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