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