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