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