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