Fix restarting when not called from the main console (bug #830 and #864)
[asterisk/asterisk.git] / asterisk.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Top level source file for asterisk
5  * 
6  * Copyright (C) 1999, Mark Spencer
7  *
8  * Mark Spencer <markster@linux-support.net>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <unistd.h>
15 #include <stdlib.h>
16 #include <asterisk/logger.h>
17 #include <asterisk/options.h>
18 #include <asterisk/cli.h>
19 #include <asterisk/channel.h>
20 #include <asterisk/ulaw.h>
21 #include <asterisk/alaw.h>
22 #include <asterisk/callerid.h>
23 #include <asterisk/module.h>
24 #include <asterisk/image.h>
25 #include <asterisk/tdd.h>
26 #include <asterisk/term.h>
27 #include <asterisk/manager.h>
28 #include <asterisk/pbx.h>
29 #include <asterisk/enum.h>
30 #include <asterisk/rtp.h>
31 #include <sys/resource.h>
32 #include <fcntl.h>
33 #include <stdio.h>
34 #include <signal.h>
35 #include <sched.h>
36 #include <asterisk/io.h>
37 #include <pthread.h>
38 #include <sys/socket.h>
39 #include <sys/un.h>
40 #include <sys/select.h>
41 #include <sys/wait.h>
42 #include <string.h>
43 #include <errno.h>
44 #include <ctype.h>
45 #include "editline/histedit.h"
46 #include "asterisk.h"
47 #include <asterisk/config.h>
48
49 #define AST_MAX_CONNECTS 128
50 #define NUM_MSGS 64
51
52 int option_verbose=0;
53 int option_debug=0;
54 int option_nofork=0;
55 int option_quiet=0;
56 int option_console=0;
57 int option_highpriority=0;
58 int option_remote=0;
59 int option_exec=0;
60 int option_initcrypto=0;
61 int option_nocolor;
62 int option_dumpcore = 0;
63 int option_overrideconfig = 0;
64 int fully_booted = 0;
65
66 static int ast_socket = -1;             /* UNIX Socket for allowing remote control */
67 static int ast_consock = -1;            /* UNIX Socket for controlling another asterisk */
68 static int mainpid;
69 struct console {
70         int fd;                                 /* File descriptor */
71         int p[2];                               /* Pipe */
72         pthread_t t;                    /* Thread of handler */
73 };
74
75 static struct ast_atexit {
76         void (*func)(void);
77         struct ast_atexit *next;
78 } *atexits = NULL;
79 static ast_mutex_t atexitslock = AST_MUTEX_INITIALIZER;
80
81 time_t ast_startuptime;
82 time_t ast_lastreloadtime;
83
84 static History *el_hist = NULL;
85 static EditLine *el = NULL;
86 static char *remotehostname;
87
88 struct console consoles[AST_MAX_CONNECTS];
89
90 char defaultlanguage[MAX_LANGUAGE] = DEFAULT_LANGUAGE;
91
92 static int ast_el_add_history(char *);
93 static int ast_el_read_history(char *);
94 static int ast_el_write_history(char *);
95
96 char ast_config_AST_CONFIG_DIR[AST_CONFIG_MAX_PATH];
97 char ast_config_AST_CONFIG_FILE[AST_CONFIG_MAX_PATH];
98 char ast_config_AST_MODULE_DIR[AST_CONFIG_MAX_PATH];
99 char ast_config_AST_SPOOL_DIR[AST_CONFIG_MAX_PATH];
100 char ast_config_AST_VAR_DIR[AST_CONFIG_MAX_PATH];
101 char ast_config_AST_LOG_DIR[AST_CONFIG_MAX_PATH];
102 char ast_config_AST_AGI_DIR[AST_CONFIG_MAX_PATH];
103 char ast_config_AST_DB[AST_CONFIG_MAX_PATH];
104 char ast_config_AST_KEY_DIR[AST_CONFIG_MAX_PATH];
105 char ast_config_AST_PID[AST_CONFIG_MAX_PATH];
106 char ast_config_AST_SOCKET[AST_CONFIG_MAX_PATH];
107 char ast_config_AST_RUN_DIR[AST_CONFIG_MAX_PATH];
108
109 static char *_argv[256];
110 static int shuttingdown = 0;
111 static int restartnow = 0;
112 static pthread_t consolethread = (pthread_t) -1;
113
114 int ast_register_atexit(void (*func)(void))
115 {
116         int res = -1;
117         struct ast_atexit *ae;
118         ast_unregister_atexit(func);
119         ae = malloc(sizeof(struct ast_atexit));
120         ast_mutex_lock(&atexitslock);
121         if (ae) {
122                 memset(ae, 0, sizeof(struct ast_atexit));
123                 ae->next = atexits;
124                 ae->func = func;
125                 atexits = ae;
126                 res = 0;
127         }
128         ast_mutex_unlock(&atexitslock);
129         return res;
130 }
131
132 void ast_unregister_atexit(void (*func)(void))
133 {
134         struct ast_atexit *ae, *prev = NULL;
135         ast_mutex_lock(&atexitslock);
136         ae = atexits;
137         while(ae) {
138                 if (ae->func == func) {
139                         if (prev)
140                                 prev->next = ae->next;
141                         else
142                                 atexits = ae->next;
143                         break;
144                 }
145                 prev = ae;
146                 ae = ae->next;
147         }
148         ast_mutex_unlock(&atexitslock);
149 }
150
151 static int fdprint(int fd, const char *s)
152 {
153         return write(fd, s, strlen(s) + 1);
154 }
155
156 /*
157  * write the string to all attached console clients
158  */
159 static void ast_network_puts(const char *string)
160 {
161     int x;
162     for (x=0;x<AST_MAX_CONNECTS; x++) {
163         if (consoles[x].fd > -1) 
164             fdprint(consoles[x].p[1], string);
165     }
166 }
167
168
169 /*
170  * write the string to the console, and all attached
171  * console clients
172  */
173 void ast_console_puts(const char *string)
174 {
175     fputs(string, stdout);
176     fflush(stdout);
177     ast_network_puts(string);
178 }
179
180 static void network_verboser(const char *s, int pos, int replace, int complete)
181      /* ARGUSED */
182 {
183     ast_network_puts(s);
184 }
185
186 static pthread_t lthread;
187
188 static void *netconsole(void *vconsole)
189 {
190         struct console *con = vconsole;
191         char hostname[256];
192         char tmp[512];
193         int res;
194         int max;
195         fd_set rfds;
196         
197         if (gethostname(hostname, sizeof(hostname)))
198                 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
199         snprintf(tmp, sizeof(tmp), "%s/%d/%s\n", hostname, mainpid, ASTERISK_VERSION);
200         fdprint(con->fd, tmp);
201         for(;;) {
202                 FD_ZERO(&rfds); 
203                 FD_SET(con->fd, &rfds);
204                 FD_SET(con->p[0], &rfds);
205                 max = con->fd;
206                 if (con->p[0] > max)
207                         max = con->p[0];
208                 res = ast_select(max + 1, &rfds, NULL, NULL, NULL);
209                 if (res < 0) {
210                         ast_log(LOG_WARNING, "select returned < 0: %s\n", strerror(errno));
211                         continue;
212                 }
213                 if (FD_ISSET(con->fd, &rfds)) {
214                         res = read(con->fd, tmp, sizeof(tmp));
215                         if (res < 1) {
216                                 break;
217                         }
218                         tmp[res] = 0;
219                         ast_cli_command(con->fd, tmp);
220                 }
221                 if (FD_ISSET(con->p[0], &rfds)) {
222                         res = read(con->p[0], tmp, sizeof(tmp));
223                         if (res < 1) {
224                                 ast_log(LOG_ERROR, "read returned %d\n", res);
225                                 break;
226                         }
227                         res = write(con->fd, tmp, res);
228                         if (res < 1)
229                                 break;
230                 }
231         }
232         if (option_verbose > 2) 
233                 ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection disconnected\n");
234         close(con->fd);
235         close(con->p[0]);
236         close(con->p[1]);
237         con->fd = -1;
238         
239         return NULL;
240 }
241
242 static void *listener(void *unused)
243 {
244         struct sockaddr_un sun;
245         fd_set fds;
246         int s;
247         int len;
248         int x;
249         int flags;
250         pthread_attr_t attr;
251         pthread_attr_init(&attr);
252         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
253         for(;;) {
254                 if (ast_socket < 0)
255                         return NULL;
256                 FD_ZERO(&fds);
257                 FD_SET(ast_socket, &fds);
258                 s = ast_select(ast_socket + 1, &fds, NULL, NULL, NULL);
259                 if (s < 0) {
260                         ast_log(LOG_WARNING, "Select retured error: %s\n", strerror(errno));
261                         continue;
262                 }
263                 len = sizeof(sun);
264                 s = accept(ast_socket, (struct sockaddr *)&sun, &len);
265                 if (s < 0) {
266                         ast_log(LOG_WARNING, "Accept retured %d: %s\n", s, strerror(errno));
267                 } else {
268                         for (x=0;x<AST_MAX_CONNECTS;x++) {
269                                 if (consoles[x].fd < 0) {
270                                         if (socketpair(AF_LOCAL, SOCK_STREAM, 0, consoles[x].p)) {
271                                                 ast_log(LOG_ERROR, "Unable to create pipe: %s\n", strerror(errno));
272                                                 consoles[x].fd = -1;
273                                                 fdprint(s, "Server failed to create pipe\n");
274                                                 close(s);
275                                                 break;
276                                         }
277                                         flags = fcntl(consoles[x].p[1], F_GETFL);
278                                         fcntl(consoles[x].p[1], F_SETFL, flags | O_NONBLOCK);
279                                         consoles[x].fd = s;
280                                         if (pthread_create(&consoles[x].t, &attr, netconsole, &consoles[x])) {
281                                                 ast_log(LOG_ERROR, "Unable to spawn thread to handle connection\n");
282                                                 consoles[x].fd = -1;
283                                                 fdprint(s, "Server failed to spawn thread\n");
284                                                 close(s);
285                                         }
286                                         break;
287                                 }
288                         }
289                         if (x >= AST_MAX_CONNECTS) {
290                                 fdprint(s, "No more connections allowed\n");
291                                 ast_log(LOG_WARNING, "No more connections allowed\n");
292                                 close(s);
293                         } else if (consoles[x].fd > -1) {
294                                 if (option_verbose > 2) 
295                                         ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection\n");
296                         }
297                 }
298         }
299         return NULL;
300 }
301
302 static int ast_makesocket(void)
303 {
304         struct sockaddr_un sun;
305         int res;
306         int x;
307         for (x=0;x<AST_MAX_CONNECTS;x++)        
308                 consoles[x].fd = -1;
309         unlink((char *)ast_config_AST_SOCKET);
310         ast_socket = socket(PF_LOCAL, SOCK_STREAM, 0);
311         if (ast_socket < 0) {
312                 ast_log(LOG_WARNING, "Unable to create control socket: %s\n", strerror(errno));
313                 return -1;
314         }               
315         memset(&sun, 0, sizeof(sun));
316         sun.sun_family = AF_LOCAL;
317         strncpy(sun.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sun.sun_path)-1);
318         res = bind(ast_socket, (struct sockaddr *)&sun, sizeof(sun));
319         if (res) {
320                 ast_log(LOG_WARNING, "Unable to bind socket to %s: %s\n", (char *)ast_config_AST_SOCKET, strerror(errno));
321                 close(ast_socket);
322                 ast_socket = -1;
323                 return -1;
324         }
325         res = listen(ast_socket, 2);
326         if (res < 0) {
327                 ast_log(LOG_WARNING, "Unable to listen on socket %s: %s\n", (char *)ast_config_AST_SOCKET, strerror(errno));
328                 close(ast_socket);
329                 ast_socket = -1;
330                 return -1;
331         }
332         ast_register_verbose(network_verboser);
333         pthread_create(&lthread, NULL, listener, NULL);
334         return 0;
335 }
336
337 static int ast_tryconnect(void)
338 {
339         struct sockaddr_un sun;
340         int res;
341         ast_consock = socket(PF_LOCAL, SOCK_STREAM, 0);
342         if (ast_consock < 0) {
343                 ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
344                 return 0;
345         }
346         memset(&sun, 0, sizeof(sun));
347         sun.sun_family = AF_LOCAL;
348         strncpy(sun.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sun.sun_path)-1);
349         res = connect(ast_consock, (struct sockaddr *)&sun, sizeof(sun));
350         if (res) {
351                 close(ast_consock);
352                 ast_consock = -1;
353                 return 0;
354         } else
355                 return 1;
356 }
357
358 static void urg_handler(int num)
359 {
360         /* Called by soft_hangup to interrupt the select, read, or other
361            system call.  We don't actually need to do anything though.  */
362         /* Cannot EVER ast_log from within a signal handler */
363         if (option_debug) 
364                 printf("Urgent handler\n");
365         signal(num, urg_handler);
366         return;
367 }
368
369 static void hup_handler(int num)
370 {
371         if (option_verbose > 1) 
372                 printf("Received HUP signal -- Reloading configs\n");
373         if (restartnow)
374                 execvp(_argv[0], _argv);
375         /* XXX This could deadlock XXX */
376         ast_module_reload();
377 }
378
379 static void child_handler(int sig)
380 {
381         /* Must not ever ast_log or ast_verbose within signal handler */
382         int n, status;
383
384         /*
385          * Reap all dead children -- not just one
386          */
387         for (n = 0; wait4(-1, &status, WNOHANG, NULL) > 0; n++)
388                 ;
389         if (n == 0 && option_debug)     
390                 printf("Huh?  Child handler, but nobody there?\n");
391 }
392
393 static void set_title(char *text)
394 {
395         /* Set an X-term or screen title */
396         if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
397                 fprintf(stdout, "\033]2;%s\007", text);
398 }
399
400 static void set_icon(char *text)
401 {
402         if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
403                 fprintf(stdout, "\033]1;%s\007", text);
404 }
405
406 static int set_priority(int pri)
407 {
408         struct sched_param sched;
409         memset(&sched, 0, sizeof(sched));
410         /* We set ourselves to a high priority, that we might pre-empt everything
411            else.  If your PBX has heavy activity on it, this is a good thing.  */
412 #ifdef __linux__
413         if (pri) {  
414                 sched.sched_priority = 10;
415                 if (sched_setscheduler(0, SCHED_RR, &sched)) {
416                         ast_log(LOG_WARNING, "Unable to set high priority\n");
417                         return -1;
418                 } else
419                         if (option_verbose)
420                                 ast_verbose("Set to realtime thread\n");
421         } else {
422                 sched.sched_priority = 0;
423                 if (sched_setscheduler(0, SCHED_OTHER, &sched)) {
424                         ast_log(LOG_WARNING, "Unable to set normal priority\n");
425                         return -1;
426                 }
427         }
428 #else
429         if (pri) {
430                 if (setpriority(PRIO_PROCESS, 0, -10) == -1) {
431                         ast_log(LOG_WARNING, "Unable to set high priority\n");
432                         return -1;
433                 } else
434                         if (option_verbose)
435                                 ast_verbose("Set to high priority\n");
436         } else {
437                 if (setpriority(PRIO_PROCESS, 0, 0) == -1) {
438                         ast_log(LOG_WARNING, "Unable to set normal priority\n");
439                         return -1;
440                 }
441         }
442 #endif
443         return 0;
444 }
445
446 static void ast_run_atexits(void)
447 {
448         struct ast_atexit *ae;
449         ast_mutex_lock(&atexitslock);
450         ae = atexits;
451         while(ae) {
452                 if (ae->func) 
453                         ae->func();
454                 ae = ae->next;
455         }
456         ast_mutex_unlock(&atexitslock);
457 }
458
459 static void quit_handler(int num, int nice, int safeshutdown, int restart)
460 {
461         char filename[80] = "";
462         time_t s,e;
463         int x;
464         if (safeshutdown) {
465                 shuttingdown = 1;
466                 if (!nice) {
467                         /* Begin shutdown routine, hanging up active channels */
468                         ast_begin_shutdown(1);
469                         if (option_verbose && option_console)
470                                 ast_verbose("Beginning asterisk %s....\n", restart ? "restart" : "shutdown");
471                         time(&s);
472                         for(;;) {
473                                 time(&e);
474                                 /* Wait up to 15 seconds for all channels to go away */
475                                 if ((e - s) > 15)
476                                         break;
477                                 if (!ast_active_channels())
478                                         break;
479                                 if (!shuttingdown)
480                                         break;
481                                 /* Sleep 1/10 of a second */
482                                 usleep(100000);
483                         }
484                 } else {
485                         if (nice < 2)
486                                 ast_begin_shutdown(0);
487                         if (option_verbose && option_console)
488                                 ast_verbose("Waiting for inactivity to perform %s...\n", restart ? "restart" : "halt");
489                         for(;;) {
490                                 if (!ast_active_channels())
491                                         break;
492                                 if (!shuttingdown)
493                                         break;
494                                 sleep(1);
495                         }
496                 }
497
498                 if (!shuttingdown) {
499                         if (option_verbose && option_console)
500                                 ast_verbose("Asterisk %s cancelled.\n", restart ? "restart" : "shutdown");
501                         return;
502                 }
503         }
504         if (option_console || option_remote) {
505                 if (getenv("HOME")) 
506                         snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
507                 if (strlen(filename))
508                         ast_el_write_history(filename);
509                 if (el != NULL)
510                         el_end(el);
511                 if (el_hist != NULL)
512                         history_end(el_hist);
513         }
514         if (option_verbose)
515                 ast_verbose("Executing last minute cleanups\n");
516         ast_run_atexits();
517         /* Called on exit */
518         if (option_verbose && option_console)
519                 ast_verbose("Asterisk %s ending (%d).\n", ast_active_channels() ? "uncleanly" : "cleanly", num);
520         else if (option_debug)
521                 ast_log(LOG_DEBUG, "Asterisk ending (%d).\n", num);
522         manager_event(EVENT_FLAG_SYSTEM, "Shutdown", "Shutdown: %s\r\nRestart: %s\r\n", ast_active_channels() ? "Uncleanly" : "Cleanly", restart ? "True" : "False");
523         if (ast_socket > -1) {
524                 close(ast_socket);
525                 ast_socket = -1;
526         }
527         if (ast_consock > -1)
528                 close(ast_consock);
529         if (ast_socket > -1)
530                 unlink((char *)ast_config_AST_SOCKET);
531         if (!option_remote) unlink((char *)ast_config_AST_PID);
532         printf(term_quit());
533         if (restart) {
534                 if (option_verbose || option_console)
535                         ast_verbose("Preparing for Asterisk restart...\n");
536                 /* Mark all FD's for closing on exec */
537                 for (x=3;x<32768;x++) {
538                         fcntl(x, F_SETFD, FD_CLOEXEC);
539                 }
540                 if (option_verbose || option_console)
541                         ast_verbose("Restarting Asterisk NOW...\n");
542                 restartnow = 1;
543                 /* If there is a consolethread running send it a SIGHUP 
544                    so it can execvp, otherwise we can do it ourselves */
545                 if (consolethread != (pthread_t) -1)
546                         pthread_kill(consolethread, SIGHUP);
547                 else
548                         execvp(_argv[0], _argv);
549         
550         }
551         exit(0);
552 }
553
554 static void __quit_handler(int num)
555 {
556         quit_handler(num, 0, 1, 0);
557 }
558
559 static const char *fix_header(char *outbuf, int maxout, const char *s, char *cmp)
560 {
561         const char *c;
562         if (!strncmp(s, cmp, strlen(cmp))) {
563                 c = s + strlen(cmp);
564                 term_color(outbuf, cmp, COLOR_GRAY, 0, maxout);
565                 return c;
566         }
567         return NULL;
568 }
569
570 static void console_verboser(const char *s, int pos, int replace, int complete)
571 {
572         char tmp[80];
573         const char *c=NULL;
574         /* Return to the beginning of the line */
575         if (!pos) {
576                 fprintf(stdout, "\r");
577                 if ((c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_4)) ||
578                         (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_3)) ||
579                         (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_2)) ||
580                         (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_1)))
581                         fputs(tmp, stdout);
582         }
583         if (c)
584                 fputs(c + pos,stdout);
585         else
586                 fputs(s + pos,stdout);
587         fflush(stdout);
588         if (complete)
589         /* Wake up a select()ing console */
590                 if (consolethread != (pthread_t) -1)
591                         pthread_kill(consolethread, SIGURG);
592 }
593
594 static void consolehandler(char *s)
595 {
596         printf(term_end());
597         fflush(stdout);
598         /* Called when readline data is available */
599         if (s && strlen(s))
600                 ast_el_add_history(s);
601         /* Give the console access to the shell */
602         if (s) {
603                 /* The real handler for bang */
604                 if (s[0] == '!') {
605                         if (s[1])
606                                 system(s+1);
607                         else
608                                 system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
609                 } else 
610                 ast_cli_command(STDOUT_FILENO, s);
611         } else
612                 fprintf(stdout, "\nUse \"quit\" to exit\n");
613 }
614
615 static int remoteconsolehandler(char *s)
616 {
617         int ret = 0;
618         /* Called when readline data is available */
619         if (s && strlen(s))
620                 ast_el_add_history(s);
621         /* Give the console access to the shell */
622         if (s) {
623                 /* The real handler for bang */
624                 if (s[0] == '!') {
625                         if (s[1])
626                                 system(s+1);
627                         else
628                                 system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
629                         ret = 1;
630                 }
631                 if ((strncasecmp(s, "quit", 4) == 0 || strncasecmp(s, "exit", 4) == 0) &&
632                     (s[4] == '\0' || isspace(s[4]))) {
633                         quit_handler(0, 0, 0, 0);
634                         ret = 1;
635                 }
636         } else
637                 fprintf(stdout, "\nUse \"quit\" to exit\n");
638
639         return ret;
640 }
641
642 static char quit_help[] = 
643 "Usage: quit\n"
644 "       Exits Asterisk.\n";
645
646 static char abort_halt_help[] = 
647 "Usage: abort shutdown\n"
648 "       Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
649 "       call operations.\n";
650
651 static char shutdown_now_help[] = 
652 "Usage: stop now\n"
653 "       Shuts down a running Asterisk immediately, hanging up all active calls .\n";
654
655 static char shutdown_gracefully_help[] = 
656 "Usage: stop gracefully\n"
657 "       Causes Asterisk to not accept new calls, and exit when all\n"
658 "       active calls have terminated normally.\n";
659
660 static char shutdown_when_convenient_help[] = 
661 "Usage: stop when convenient\n"
662 "       Causes Asterisk to perform a shutdown when all active calls have ended.\n";
663
664 static char restart_now_help[] = 
665 "Usage: restart now\n"
666 "       Causes Asterisk to hangup all calls and exec() itself performing a cold.\n"
667 "       restart.\n";
668
669 static char restart_gracefully_help[] = 
670 "Usage: restart gracefully\n"
671 "       Causes Asterisk to stop accepting new calls and exec() itself performing a cold.\n"
672 "       restart when all active calls have ended.\n";
673
674 static char restart_when_convenient_help[] = 
675 "Usage: restart when convenient\n"
676 "       Causes Asterisk to perform a cold restart when all active calls have ended.\n";
677
678 static char bang_help[] =
679 "Usage: !<command>\n"
680 "       Executes a given shell command\n";
681
682 #if 0
683 static int handle_quit(int fd, int argc, char *argv[])
684 {
685         if (argc != 1)
686                 return RESULT_SHOWUSAGE;
687         quit_handler(0, 0, 1, 0);
688         return RESULT_SUCCESS;
689 }
690 #endif
691
692 static int no_more_quit(int fd, int argc, char *argv[])
693 {
694         if (argc != 1)
695                 return RESULT_SHOWUSAGE;
696         ast_cli(fd, "The QUIT and EXIT commands may no longer be used to shutdown the PBX.\n"
697                     "Please use STOP NOW instead, if you wish to shutdown the PBX.\n");
698         return RESULT_SUCCESS;
699 }
700
701 static int handle_shutdown_now(int fd, int argc, char *argv[])
702 {
703         if (argc != 2)
704                 return RESULT_SHOWUSAGE;
705         quit_handler(0, 0 /* Not nice */, 1 /* safely */, 0 /* not restart */);
706         return RESULT_SUCCESS;
707 }
708
709 static int handle_shutdown_gracefully(int fd, int argc, char *argv[])
710 {
711         if (argc != 2)
712                 return RESULT_SHOWUSAGE;
713         quit_handler(0, 1 /* nicely */, 1 /* safely */, 0 /* no restart */);
714         return RESULT_SUCCESS;
715 }
716
717 static int handle_shutdown_when_convenient(int fd, int argc, char *argv[])
718 {
719         if (argc != 3)
720                 return RESULT_SHOWUSAGE;
721         quit_handler(0, 2 /* really nicely */, 1 /* safely */, 0 /* don't restart */);
722         return RESULT_SUCCESS;
723 }
724
725 static int handle_restart_now(int fd, int argc, char *argv[])
726 {
727         if (argc != 2)
728                 return RESULT_SHOWUSAGE;
729         quit_handler(0, 0 /* not nicely */, 1 /* safely */, 1 /* restart */);
730         return RESULT_SUCCESS;
731 }
732
733 static int handle_restart_gracefully(int fd, int argc, char *argv[])
734 {
735         if (argc != 2)
736                 return RESULT_SHOWUSAGE;
737         quit_handler(0, 1 /* nicely */, 1 /* safely */, 1 /* restart */);
738         return RESULT_SUCCESS;
739 }
740
741 static int handle_restart_when_convenient(int fd, int argc, char *argv[])
742 {
743         if (argc != 3)
744                 return RESULT_SHOWUSAGE;
745         quit_handler(0, 2 /* really nicely */, 1 /* safely */, 1 /* restart */);
746         return RESULT_SUCCESS;
747 }
748
749 static int handle_abort_halt(int fd, int argc, char *argv[])
750 {
751         if (argc != 2)
752                 return RESULT_SHOWUSAGE;
753         ast_cancel_shutdown();
754         shuttingdown = 0;
755         return RESULT_SUCCESS;
756 }
757
758 static int handle_bang(int fd, int argc, char *argv[])
759 {
760         return RESULT_SUCCESS;
761 }
762
763 #define ASTERISK_PROMPT "*CLI> "
764
765 #define ASTERISK_PROMPT2 "%s*CLI> "
766
767 static struct ast_cli_entry aborthalt = { { "abort", "halt", NULL }, handle_abort_halt, "Cancel a running halt", abort_halt_help };
768
769 static struct ast_cli_entry quit =      { { "quit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
770 static struct ast_cli_entry astexit =   { { "exit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
771
772 static struct ast_cli_entry astshutdownnow =    { { "stop", "now", NULL }, handle_shutdown_now, "Shut down Asterisk immediately", shutdown_now_help };
773 static struct ast_cli_entry astshutdowngracefully =     { { "stop", "gracefully", NULL }, handle_shutdown_gracefully, "Gracefully shut down Asterisk", shutdown_gracefully_help };
774 static struct ast_cli_entry astshutdownwhenconvenient =         { { "stop", "when","convenient", NULL }, handle_shutdown_when_convenient, "Shut down Asterisk at empty call volume", shutdown_when_convenient_help };
775 static struct ast_cli_entry astrestartnow =     { { "restart", "now", NULL }, handle_restart_now, "Restart Asterisk immediately", restart_now_help };
776 static struct ast_cli_entry astrestartgracefully =      { { "restart", "gracefully", NULL }, handle_restart_gracefully, "Restart Asterisk gracefully", restart_gracefully_help };
777 static struct ast_cli_entry astrestartwhenconvenient=   { { "restart", "when", "convenient", NULL }, handle_restart_when_convenient, "Restart Asterisk at empty call volume", restart_when_convenient_help };
778 static struct ast_cli_entry astbang = { { "!", NULL }, handle_bang, "Execute a shell command", bang_help };
779
780 static int ast_el_read_char(EditLine *el, char *cp)
781 {
782         int num_read=0;
783         int lastpos=0;
784         fd_set rfds;
785         int res;
786         int max;
787         char buf[512];
788
789         for (;;) {
790                 FD_ZERO(&rfds);
791                 FD_SET(ast_consock, &rfds);
792                 max = ast_consock;
793                 if (!option_exec) {
794                         FD_SET(STDIN_FILENO, &rfds);
795                         if (STDIN_FILENO > max)
796                                 max = STDIN_FILENO;
797                 }
798                 res = ast_select(max+1, &rfds, NULL, NULL, NULL);
799                 if (res < 0) {
800                         if (errno == EINTR)
801                                 continue;
802                         ast_log(LOG_ERROR, "select failed: %s\n", strerror(errno));
803                         break;
804                 }
805
806                 if (FD_ISSET(STDIN_FILENO, &rfds)) {
807                         num_read = read(STDIN_FILENO, cp, 1);
808                         if (num_read < 1) {
809                                 break;
810                         } else 
811                                 return (num_read);
812                 }
813                 if (FD_ISSET(ast_consock, &rfds)) {
814                         res = read(ast_consock, buf, sizeof(buf) - 1);
815                         /* if the remote side disappears exit */
816                         if (res < 1) {
817                                 fprintf(stderr, "\nDisconnected from Asterisk server\n");
818                                 quit_handler(0, 0, 0, 0);
819                         }
820
821                         buf[res] = '\0';
822
823                         if (!option_exec && !lastpos)
824                                 write(STDOUT_FILENO, "\r", 1);
825                         write(STDOUT_FILENO, buf, res);
826                         if ((buf[res-1] == '\n') || (buf[res-2] == '\n')) {
827                                 *cp = CC_REFRESH;
828                                 return(1);
829                         } else {
830                                 lastpos = 1;
831                         }
832                 }
833         }
834
835         *cp = '\0';
836         return (0);
837 }
838
839 static char *cli_prompt(EditLine *el)
840 {
841         static char prompt[80];
842
843         if (remotehostname)
844                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT2, remotehostname);
845         else
846                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT);
847
848         return(prompt); 
849 }
850
851 static char **ast_el_strtoarr(char *buf)
852 {
853         char **match_list = NULL, *retstr;
854         size_t match_list_len;
855         int matches = 0;
856
857         match_list_len = 1;
858         while ( (retstr = strsep(&buf, " ")) != NULL) {
859
860                 if (matches + 1 >= match_list_len) {
861                         match_list_len <<= 1;
862                         match_list = realloc(match_list, match_list_len * sizeof(char *));
863                 }
864
865                 match_list[matches++] = retstr;
866         }
867
868         if (!match_list)
869                 return (char **) NULL;
870
871         if (matches>= match_list_len)
872                 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
873
874         match_list[matches] = (char *) NULL;
875
876         return match_list;
877 }
878
879 static int ast_el_sort_compare(const void *i1, const void *i2)
880 {
881         char *s1, *s2;
882
883         s1 = ((char **)i1)[0];
884         s2 = ((char **)i2)[0];
885
886         return strcasecmp(s1, s2);
887 }
888
889 static int ast_cli_display_match_list(char **matches, int len, int max)
890 {
891         int i, idx, limit, count;
892         int screenwidth = 0;
893         int numoutput = 0, numoutputline = 0;
894
895         screenwidth = ast_get_termcols(STDOUT_FILENO);
896
897         /* find out how many entries can be put on one line, with two spaces between strings */
898         limit = screenwidth / (max + 2);
899         if (limit == 0)
900                 limit = 1;
901
902         /* how many lines of output */
903         count = len / limit;
904         if (count * limit < len)
905                 count++;
906
907         idx = 1;
908
909         qsort(&matches[0], (size_t)(len + 1), sizeof(char *), ast_el_sort_compare);
910
911         for (; count > 0; count--) {
912                 numoutputline = 0;
913                 for (i=0; i < limit && matches[idx]; i++, idx++) {
914
915                         /* Don't print dupes */
916                         if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
917                                 i--;
918                                 continue;
919                         }
920
921                         numoutput++;  numoutputline++;
922                         fprintf(stdout, "%-*s  ", max, matches[idx]);
923                 }
924                 if (numoutputline > 0)
925                         fprintf(stdout, "\n");
926         }
927
928         return numoutput;
929 }
930
931
932 static char *cli_complete(EditLine *el, int ch)
933 {
934         int len=0;
935         char *ptr;
936         int nummatches = 0;
937         char **matches;
938         int retval = CC_ERROR;
939         char buf[1024];
940         int res;
941
942         LineInfo *lf = (LineInfo *)el_line(el);
943
944         *(char *)lf->cursor = '\0';
945         ptr = (char *)lf->cursor;
946         if (ptr) {
947                 while (ptr > lf->buffer) {
948                         if (isspace(*ptr)) {
949                                 ptr++;
950                                 break;
951                         }
952                         ptr--;
953                 }
954         }
955
956         len = lf->cursor - ptr;
957
958         if (option_remote) {
959                 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr); 
960                 fdprint(ast_consock, buf);
961                 res = read(ast_consock, buf, sizeof(buf));
962                 buf[res] = '\0';
963                 nummatches = atoi(buf);
964
965                 if (nummatches > 0) {
966                         snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr); 
967                         fdprint(ast_consock, buf);
968                         res = read(ast_consock, buf, sizeof(buf));
969                         buf[res] = '\0';
970
971                         matches = ast_el_strtoarr(buf);
972                 } else
973                         matches = (char **) NULL;
974
975
976         }  else {
977
978                 nummatches = ast_cli_generatornummatches((char *)lf->buffer,ptr);
979                 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
980         }
981
982         if (matches) {
983                 int i;
984                 int matches_num, maxlen, match_len;
985
986                 if (matches[0][0] != '\0') {
987                         el_deletestr(el, (int) len);
988                         el_insertstr(el, matches[0]);
989                         retval = CC_REFRESH;
990                 }
991
992                 if (nummatches == 1) {
993                         /* Found an exact match */
994                         el_insertstr(el, " ");
995                         retval = CC_REFRESH;
996                 } else {
997                         /* Must be more than one match */
998                         for (i=1, maxlen=0; matches[i]; i++) {
999                                 match_len = strlen(matches[i]);
1000                                 if (match_len > maxlen)
1001                                         maxlen = match_len;
1002                         }
1003                         matches_num = i - 1;
1004                         if (matches_num >1) {
1005                                 fprintf(stdout, "\n");
1006                                 ast_cli_display_match_list(matches, nummatches, maxlen);
1007                                 retval = CC_REDISPLAY;
1008                         } else { 
1009                                 el_insertstr(el," ");
1010                                 retval = CC_REFRESH;
1011                         }
1012                 }
1013         free(matches);
1014         }
1015
1016         return (char *)retval;
1017 }
1018
1019 static int ast_el_initialize(void)
1020 {
1021         HistEvent ev;
1022
1023         if (el != NULL)
1024                 el_end(el);
1025         if (el_hist != NULL)
1026                 history_end(el_hist);
1027
1028         el = el_init("asterisk", stdin, stdout, stderr);
1029         el_set(el, EL_PROMPT, cli_prompt);
1030
1031         el_set(el, EL_EDITMODE, 1);             
1032         el_set(el, EL_EDITOR, "emacs");         
1033         el_hist = history_init();
1034         if (!el || !el_hist)
1035                 return -1;
1036
1037         /* setup history with 100 entries */
1038         history(el_hist, &ev, H_SETSIZE, 100);
1039
1040         el_set(el, EL_HIST, history, el_hist);
1041
1042         el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
1043         /* Bind <tab> to command completion */
1044         el_set(el, EL_BIND, "^I", "ed-complete", NULL);
1045         /* Bind ? to command completion */
1046         el_set(el, EL_BIND, "?", "ed-complete", NULL);
1047
1048         return 0;
1049 }
1050
1051 static int ast_el_add_history(char *buf)
1052 {
1053         HistEvent ev;
1054
1055         if (el_hist == NULL || el == NULL)
1056                 ast_el_initialize();
1057         if (strlen(buf) > 256)
1058                 return 0;
1059         return (history(el_hist, &ev, H_ENTER, buf));
1060 }
1061
1062 static int ast_el_write_history(char *filename)
1063 {
1064         HistEvent ev;
1065
1066         if (el_hist == NULL || el == NULL)
1067                 ast_el_initialize();
1068
1069         return (history(el_hist, &ev, H_SAVE, filename));
1070 }
1071
1072 static int ast_el_read_history(char *filename)
1073 {
1074         char buf[256];
1075         FILE *f;
1076         int ret = -1;
1077
1078         if (el_hist == NULL || el == NULL)
1079                 ast_el_initialize();
1080
1081         if ((f = fopen(filename, "r")) == NULL)
1082                 return ret;
1083
1084         while (!feof(f)) {
1085                 fgets(buf, sizeof(buf), f);
1086                 if (!strcmp(buf, "_HiStOrY_V2_\n"))
1087                         continue;
1088                 if ((ret = ast_el_add_history(buf)) == -1)
1089                         break;
1090         }
1091         fclose(f);
1092
1093         return ret;
1094 }
1095
1096 static void ast_remotecontrol(char * data)
1097 {
1098         char buf[80];
1099         int res;
1100         char filename[80] = "";
1101         char *hostname;
1102         char *cpid;
1103         char *version;
1104         int pid;
1105         char tmp[80];
1106         char *stringp=NULL;
1107
1108         char *ebuf;
1109         int num = 0;
1110
1111         read(ast_consock, buf, sizeof(buf));
1112         if (data)
1113                 write(ast_consock, data, strlen(data) + 1);
1114         stringp=buf;
1115         hostname = strsep(&stringp, "/");
1116         cpid = strsep(&stringp, "/");
1117         version = strsep(&stringp, "\n");
1118         if (!version)
1119                 version = "<Version Unknown>";
1120         stringp=hostname;
1121         strsep(&stringp, ".");
1122         if (cpid)
1123                 pid = atoi(cpid);
1124         else
1125                 pid = -1;
1126         snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
1127         fdprint(ast_consock, tmp);
1128         ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
1129         remotehostname = hostname;
1130         if (getenv("HOME")) 
1131                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1132         if (el_hist == NULL || el == NULL)
1133                 ast_el_initialize();
1134
1135         el_set(el, EL_GETCFN, ast_el_read_char);
1136
1137         if (strlen(filename))
1138                 ast_el_read_history(filename);
1139
1140         ast_cli_register(&quit);
1141         ast_cli_register(&astexit);
1142 #if 0
1143         ast_cli_register(&astshutdown);
1144 #endif  
1145         if (option_exec && data) {  /* hack to print output then exit if asterisk -rx is used */
1146                 char tempchar;
1147                 ast_el_read_char(el, &tempchar);
1148                 return;
1149         }
1150         for(;;) {
1151                 ebuf = (char *)el_gets(el, &num);
1152
1153                 if (ebuf && strlen(ebuf)) {
1154                         if (ebuf[strlen(ebuf)-1] == '\n')
1155                                 ebuf[strlen(ebuf)-1] = '\0';
1156                         if (!remoteconsolehandler(ebuf)) {
1157                                 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
1158                                 if (res < 1) {
1159                                         ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
1160                                         break;
1161                                 }
1162                         }
1163                 }
1164         }
1165         printf("\nDisconnected from Asterisk server\n");
1166 }
1167
1168 static int show_cli_help(void) {
1169         printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 2000-2002, Digium.\n");
1170         printf("Usage: asterisk [OPTIONS]\n");
1171         printf("Valid Options:\n");
1172         printf("   -h           This help screen\n");
1173         printf("   -r           Connect to Asterisk on this machine\n");
1174         printf("   -f           Do not fork\n");
1175         printf("   -n           Disable console colorization\n");
1176         printf("   -p           Run as pseudo-realtime thread\n");
1177         printf("   -v           Increase verbosity (multiple v's = more verbose)\n");
1178         printf("   -q           Quiet mode (supress output)\n");
1179         printf("   -g           Dump core in case of a crash\n");
1180         printf("   -x <cmd>     Execute command <cmd> (only valid with -r)\n");
1181         printf("   -i           Initializie crypto keys at startup\n");
1182         printf("   -c           Provide console CLI\n");
1183         printf("   -d           Enable extra debugging\n");
1184         printf("\n");
1185         return 0;
1186 }
1187
1188 static void ast_readconfig(void) {
1189         struct ast_config *cfg;
1190         struct ast_variable *v;
1191         char *config = ASTCONFPATH;
1192
1193         if (option_overrideconfig == 1) {
1194             cfg = ast_load((char *)ast_config_AST_CONFIG_FILE);
1195         } else {
1196             cfg = ast_load(config);
1197         }
1198
1199         /* init with buildtime config */
1200         strncpy((char *)ast_config_AST_CONFIG_DIR,AST_CONFIG_DIR,sizeof(ast_config_AST_CONFIG_DIR)-1);
1201         strncpy((char *)ast_config_AST_SPOOL_DIR,AST_SPOOL_DIR,sizeof(ast_config_AST_SPOOL_DIR)-1);
1202         strncpy((char *)ast_config_AST_MODULE_DIR,AST_MODULE_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1203         strncpy((char *)ast_config_AST_VAR_DIR,AST_VAR_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1204         strncpy((char *)ast_config_AST_LOG_DIR,AST_LOG_DIR,sizeof(ast_config_AST_LOG_DIR)-1);
1205         strncpy((char *)ast_config_AST_AGI_DIR,AST_AGI_DIR,sizeof(ast_config_AST_AGI_DIR)-1);
1206         strncpy((char *)ast_config_AST_DB,AST_DB,sizeof(ast_config_AST_DB)-1);
1207         strncpy((char *)ast_config_AST_KEY_DIR,AST_KEY_DIR,sizeof(ast_config_AST_KEY_DIR)-1);
1208         strncpy((char *)ast_config_AST_PID,AST_PID,sizeof(ast_config_AST_PID)-1);
1209         strncpy((char *)ast_config_AST_SOCKET,AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1);
1210         strncpy((char *)ast_config_AST_RUN_DIR,AST_RUN_DIR,sizeof(ast_config_AST_RUN_DIR)-1);
1211         
1212         /* no asterisk.conf? no problem, use buildtime config! */
1213         if (!cfg) {
1214             return;
1215         }
1216         v = ast_variable_browse(cfg, "directories");
1217         while(v) {
1218                 if (!strcasecmp(v->name, "astetcdir")) {
1219                     strncpy((char *)ast_config_AST_CONFIG_DIR,v->value,sizeof(ast_config_AST_CONFIG_DIR)-1);
1220                 } else if (!strcasecmp(v->name, "astspooldir")) {
1221                     strncpy((char *)ast_config_AST_SPOOL_DIR,v->value,sizeof(ast_config_AST_SPOOL_DIR)-1);
1222                 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1223                     strncpy((char *)ast_config_AST_VAR_DIR,v->value,sizeof(ast_config_AST_VAR_DIR)-1);
1224                     snprintf((char *)ast_config_AST_DB,sizeof(ast_config_AST_DB)-1,"%s/%s",v->value,"astdb");    
1225                 } else if (!strcasecmp(v->name, "astlogdir")) {
1226                     strncpy((char *)ast_config_AST_LOG_DIR,v->value,sizeof(ast_config_AST_LOG_DIR)-1);
1227                 } else if (!strcasecmp(v->name, "astagidir")) {
1228                     strncpy((char *)ast_config_AST_AGI_DIR,v->value,sizeof(ast_config_AST_AGI_DIR)-1);
1229                 } else if (!strcasecmp(v->name, "astrundir")) {
1230                     snprintf((char *)ast_config_AST_PID,sizeof(ast_config_AST_PID)-1,"%s/%s",v->value,"asterisk.pid");    
1231                     snprintf((char *)ast_config_AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1,"%s/%s",v->value,"asterisk.ctl");    
1232                     strncpy((char *)ast_config_AST_RUN_DIR,v->value,sizeof(ast_config_AST_RUN_DIR)-1);
1233                 } else if (!strcasecmp(v->name, "astmoddir")) {
1234                     strncpy((char *)ast_config_AST_MODULE_DIR,v->value,sizeof(ast_config_AST_MODULE_DIR)-1);
1235                 }
1236                 v = v->next;
1237         }
1238         ast_destroy(cfg);
1239 }
1240
1241 int main(int argc, char *argv[])
1242 {
1243         int c;
1244         char filename[80] = "";
1245         char hostname[256];
1246         char tmp[80];
1247         char * xarg = NULL;
1248         int x;
1249         FILE *f;
1250         sigset_t sigs;
1251         int num;
1252         char *buf;
1253
1254         /* Remember original args for restart */
1255         if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1256                 fprintf(stderr, "Truncating argument size to %d\n", sizeof(_argv) / sizeof(_argv[0]) - 1);
1257                 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1258         }
1259         for (x=0;x<argc;x++)
1260                 _argv[x] = argv[x];
1261         _argv[x] = NULL;
1262
1263         if (gethostname(hostname, sizeof(hostname)))
1264                 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
1265         mainpid = getpid();
1266         ast_ulaw_init();
1267         ast_alaw_init();
1268         callerid_init();
1269         tdd_init();
1270         if (getenv("HOME")) 
1271                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1272         /* Check if we're root */
1273         /*
1274         if (geteuid()) {
1275                 ast_log(LOG_ERROR, "Must be run as root\n");
1276                 exit(1);
1277         }
1278         */
1279         /* Check for options */
1280         while((c=getopt(argc, argv, "hfdvqprgcinx:C:")) != -1) {
1281                 switch(c) {
1282                 case 'd':
1283                         option_debug++;
1284                         option_nofork++;
1285                         break;
1286                 case 'c':
1287                         option_console++;
1288                         option_nofork++;
1289                         break;
1290                 case 'f':
1291                         option_nofork++;
1292                         break;
1293                 case 'n':
1294                         option_nocolor++;
1295                         break;
1296                 case 'r':
1297                         option_remote++;
1298                         option_nofork++;
1299                         break;
1300                 case 'p':
1301                         option_highpriority++;
1302                         break;
1303                 case 'v':
1304                         option_verbose++;
1305                         option_nofork++;
1306                         break;
1307                 case 'q':
1308                         option_quiet++;
1309                         break;
1310                 case 'x':
1311                         option_exec++;
1312                         xarg = optarg;
1313                         break;
1314                 case 'C':
1315                         strncpy((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE));
1316                         option_overrideconfig++;
1317                         break;
1318                 case 'i':
1319                         option_initcrypto++;
1320                         break;
1321                 case'g':
1322                         option_dumpcore++;
1323                         break;
1324                 case 'h':
1325                         show_cli_help();
1326                         exit(0);
1327                 case '?':
1328                         exit(1);
1329                 }
1330         }
1331
1332         if (option_dumpcore) {
1333                 struct rlimit l;
1334                 memset(&l, 0, sizeof(l));
1335                 l.rlim_cur = RLIM_INFINITY;
1336                 l.rlim_max = RLIM_INFINITY;
1337                 if (setrlimit(RLIMIT_CORE, &l)) {
1338                         ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
1339                 }
1340         }
1341
1342         term_init();
1343         printf(term_end());
1344         fflush(stdout);
1345         if (option_console && !option_verbose) 
1346                 ast_verbose("[ Reading Master Configuration ]");
1347         ast_readconfig();
1348
1349         if (option_console) {
1350                 if (el_hist == NULL || el == NULL)
1351                         ast_el_initialize();
1352
1353                 if (strlen(filename))
1354                         ast_el_read_history(filename);
1355         }
1356
1357         if (ast_tryconnect()) {
1358                 /* One is already running */
1359                 if (option_remote) {
1360                         if (option_exec) {
1361                                 ast_remotecontrol(xarg);
1362                                 quit_handler(0, 0, 0, 0);
1363                                 exit(0);
1364                         }
1365                         printf(term_quit());
1366                         ast_register_verbose(console_verboser);
1367                         ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2004 Digium.\n");
1368                         ast_verbose( "Written by Mark Spencer <markster@digium.com>\n");
1369                         ast_verbose( "=========================================================================\n");
1370                         ast_remotecontrol(NULL);
1371                         quit_handler(0, 0, 0, 0);
1372                         exit(0);
1373                 } else {
1374                         ast_log(LOG_ERROR, "Asterisk already running on %s.  Use 'asterisk -r' to connect.\n", (char *)ast_config_AST_SOCKET);
1375                         printf(term_quit());
1376                         exit(1);
1377                 }
1378         } else if (option_remote || option_exec) {
1379                 ast_log(LOG_ERROR, "Unable to connect to remote asterisk\n");
1380                 printf(term_quit());
1381                 exit(1);
1382         }
1383         /* Blindly write pid file since we couldn't connect */
1384         unlink((char *)ast_config_AST_PID);
1385         f = fopen((char *)ast_config_AST_PID, "w");
1386         if (f) {
1387                 fprintf(f, "%d\n", getpid());
1388                 fclose(f);
1389         } else
1390                 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1391
1392         if (!option_verbose && !option_debug && !option_nofork && !option_console) {
1393                 daemon(0,0);
1394                 /* Blindly re-write pid file since we are forking */
1395                 unlink((char *)ast_config_AST_PID);
1396                 f = fopen((char *)ast_config_AST_PID, "w");
1397                 if (f) {
1398                         fprintf(f, "%d\n", getpid());
1399                         fclose(f);
1400                 } else
1401                         ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1402         }
1403
1404         ast_makesocket();
1405         sigemptyset(&sigs);
1406         sigaddset(&sigs, SIGHUP);
1407         sigaddset(&sigs, SIGTERM);
1408         sigaddset(&sigs, SIGINT);
1409         sigaddset(&sigs, SIGPIPE);
1410         sigaddset(&sigs, SIGWINCH);
1411         pthread_sigmask(SIG_BLOCK, &sigs, NULL);
1412         if (option_console || option_verbose || option_remote)
1413                 ast_register_verbose(console_verboser);
1414         /* Print a welcome message if desired */
1415         if (option_verbose || option_console) {
1416                 ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2001 Linux Support Services, Inc.\n");
1417                 ast_verbose( "Written by Mark Spencer <markster@linux-support.net>\n");
1418                 ast_verbose( "=========================================================================\n");
1419         }
1420         if (option_console && !option_verbose) 
1421                 ast_verbose("[ Booting...");
1422
1423         signal(SIGURG, urg_handler);
1424         signal(SIGINT, __quit_handler);
1425         signal(SIGTERM, __quit_handler);
1426         signal(SIGHUP, hup_handler);
1427         signal(SIGCHLD, child_handler);
1428         signal(SIGPIPE, SIG_IGN);
1429
1430         if (set_priority(option_highpriority)) {
1431                 printf(term_quit());
1432                 exit(1);
1433         }
1434         if (init_logger()) {
1435                 printf(term_quit());
1436                 exit(1);
1437         }
1438         if (init_manager()) {
1439                 printf(term_quit());
1440                 exit(1);
1441         }
1442         ast_rtp_init();
1443         if (ast_image_init()) {
1444                 printf(term_quit());
1445                 exit(1);
1446         }
1447         if (load_pbx()) {
1448                 printf(term_quit());
1449                 exit(1);
1450         }
1451         if (load_modules()) {
1452                 printf(term_quit());
1453                 exit(1);
1454         }
1455         if (init_framer()) {
1456                 printf(term_quit());
1457                 exit(1);
1458         }
1459         if (astdb_init()) {
1460                 printf(term_quit());
1461                 exit(1);
1462         }
1463         if (ast_enum_init()) {
1464                 printf(term_quit());
1465                 exit(1);
1466         }
1467         /* We might have the option of showing a console, but for now just
1468            do nothing... */
1469         if (option_console && !option_verbose)
1470                 ast_verbose(" ]\n");
1471         if (option_verbose || option_console)
1472                 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
1473         fully_booted = 1;
1474         pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
1475 #ifdef __AST_DEBUG_MALLOC
1476         __ast_mm_init();
1477 #endif  
1478         time(&ast_startuptime);
1479         ast_cli_register(&astshutdownnow);
1480         ast_cli_register(&astshutdowngracefully);
1481         ast_cli_register(&astrestartnow);
1482         ast_cli_register(&astrestartgracefully);
1483         ast_cli_register(&astrestartwhenconvenient);
1484         ast_cli_register(&astshutdownwhenconvenient);
1485         ast_cli_register(&aborthalt);
1486         ast_cli_register(&astbang);
1487         if (option_nofork)
1488                 consolethread = pthread_self();
1489         if (option_console) {
1490                 /* Console stuff now... */
1491                 /* Register our quit function */
1492                 char title[256];
1493                 set_icon("Asterisk");
1494                 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, mainpid);
1495                 set_title(title);
1496             ast_cli_register(&quit);
1497             ast_cli_register(&astexit);
1498
1499                 for (;;) {
1500                         buf = (char *)el_gets(el, &num);
1501                         if (buf) {
1502                                 if (buf[strlen(buf)-1] == '\n')
1503                                         buf[strlen(buf)-1] = '\0';
1504
1505                                 consolehandler((char *)buf);
1506                         } else {
1507                                 if (option_remote)
1508                                         ast_cli(STDOUT_FILENO, "\nUse EXIT or QUIT to exit the asterisk console\n");
1509                                 else
1510                                         ast_cli(STDOUT_FILENO, "\nUse STOP NOW to shutdown Asterisk\n");
1511                         }
1512                 }
1513
1514         } else {
1515                 /* Do nothing */
1516                 ast_select(0,NULL,NULL,NULL,NULL);
1517         }
1518         return 0;
1519 }