8b4ae4504cc26866b2a79ee69fb82afb9557cea7
[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 restart_now_help[] = 
534 "Usage: restart now\n"
535 "       Causes Asterisk to hangup all calls and exec() itself performing a cold.\n"
536 "       restart.\n";
537
538 static char restart_gracefully_help[] = 
539 "Usage: restart gracefully\n"
540 "       Causes Asterisk to stop accepting new calls and exec() itself performing a cold.\n"
541 "       restart when all active calls have ended.\n";
542
543 static char restart_when_convenient_help[] = 
544 "Usage: restart when convenient\n"
545 "       Causes Asterisk to perform a cold restart when all active calls have ended.\n";
546
547 #if 0
548 static int handle_quit(int fd, int argc, char *argv[])
549 {
550         if (argc != 1)
551                 return RESULT_SHOWUSAGE;
552         quit_handler(0, 0, 1, 0);
553         return RESULT_SUCCESS;
554 }
555 #endif
556
557 static int no_more_quit(int fd, int argc, char *argv[])
558 {
559         if (argc != 1)
560                 return RESULT_SHOWUSAGE;
561         ast_cli(fd, "The QUIT and EXIT commands may no longer be used to shutdown the PBX.\n"
562                     "Please use STOP NOW instead, if you wish to shutdown the PBX.\n");
563         return RESULT_SUCCESS;
564 }
565
566 static int handle_shutdown_now(int fd, int argc, char *argv[])
567 {
568         if (argc != 2)
569                 return RESULT_SHOWUSAGE;
570         quit_handler(0, 0 /* Not nice */, 1 /* safely */, 0 /* not restart */);
571         return RESULT_SUCCESS;
572 }
573
574 static int handle_shutdown_gracefully(int fd, int argc, char *argv[])
575 {
576         if (argc != 2)
577                 return RESULT_SHOWUSAGE;
578         quit_handler(0, 1 /* nicely */, 1 /* safely */, 0 /* no restart */);
579         return RESULT_SUCCESS;
580 }
581
582 static int handle_restart_now(int fd, int argc, char *argv[])
583 {
584         if (argc != 2)
585                 return RESULT_SHOWUSAGE;
586         quit_handler(0, 0 /* not nicely */, 1 /* safely */, 1 /* restart */);
587         return RESULT_SUCCESS;
588 }
589
590 static int handle_restart_gracefully(int fd, int argc, char *argv[])
591 {
592         if (argc != 2)
593                 return RESULT_SHOWUSAGE;
594         quit_handler(0, 1 /* nicely */, 1 /* safely */, 1 /* restart */);
595         return RESULT_SUCCESS;
596 }
597
598 static int handle_restart_when_convenient(int fd, int argc, char *argv[])
599 {
600         if (argc != 3)
601                 return RESULT_SHOWUSAGE;
602         quit_handler(0, 2 /* really nicely */, 1 /* safely */, 1 /* restart */);
603         return RESULT_SUCCESS;
604 }
605
606 static int handle_abort_halt(int fd, int argc, char *argv[])
607 {
608         if (argc != 2)
609                 return RESULT_SHOWUSAGE;
610         ast_cancel_shutdown();
611         shuttingdown = 0;
612         return RESULT_SUCCESS;
613 }
614
615 #define ASTERISK_PROMPT "*CLI> "
616
617 #define ASTERISK_PROMPT2 "%s*CLI> "
618
619 static struct ast_cli_entry aborthalt = { { "abort", "halt", NULL }, handle_abort_halt, "Cancel a running halt", abort_halt_help };
620
621 static struct ast_cli_entry quit =      { { "quit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
622 static struct ast_cli_entry astexit =   { { "exit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
623
624 static struct ast_cli_entry astshutdownnow =    { { "stop", "now", NULL }, handle_shutdown_now, "Shut down Asterisk imediately", shutdown_now_help };
625 static struct ast_cli_entry astshutdowngracefully =     { { "stop", "gracefully", NULL }, handle_shutdown_gracefully, "Gracefully shut down Asterisk", shutdown_gracefully_help };
626 static struct ast_cli_entry astrestartnow =     { { "restart", "now", NULL }, handle_restart_now, "Restart Asterisk immediately", restart_now_help };
627 static struct ast_cli_entry astrestartgracefully =      { { "restart", "gracefully", NULL }, handle_restart_gracefully, "Restart Asterisk gracefully", restart_gracefully_help };
628 static struct ast_cli_entry astrestartwhenconvenient=   { { "restart", "when", "convenient", NULL }, handle_restart_when_convenient, "Restart Asterisk at empty call volume", restart_when_convenient_help };
629
630 static int ast_el_read_char(EditLine *el, char *cp)
631 {
632         int num_read=0;
633         int lastpos=0;
634         fd_set rfds;
635         int res;
636         int max;
637         char buf[512];
638
639         for (;;) {
640                 FD_ZERO(&rfds);
641                 FD_SET(ast_consock, &rfds);
642                 FD_SET(STDIN_FILENO, &rfds);
643                 max = ast_consock;
644                 if (STDIN_FILENO > max)
645                         max = STDIN_FILENO;
646                 res = select(max+1, &rfds, NULL, NULL, NULL);
647                 if (res < 0) {
648                         if (errno == EINTR)
649                                 continue;
650                         ast_log(LOG_ERROR, "select failed: %s\n", strerror(errno));
651                         break;
652                 }
653
654                 if (FD_ISSET(STDIN_FILENO, &rfds)) {
655                         num_read = read(STDIN_FILENO, cp, 1);
656                         if (num_read < 1) {
657                                 break;
658                         } else 
659                                 return (num_read);
660                 }
661                 if (FD_ISSET(ast_consock, &rfds)) {
662                         res = read(ast_consock, buf, sizeof(buf) - 1);
663                         /* if the remote side disappears exit */
664                         if (res < 1) {
665                                 fprintf(stderr, "\nDisconnected from Asterisk server\n");
666                                 quit_handler(0, 0, 0, 0);
667                         }
668
669                         buf[res] = '\0';
670
671                         if (!lastpos)
672                                 write(STDOUT_FILENO, "\r", 1);
673                         write(STDOUT_FILENO, buf, res);
674                         if ((buf[res-1] == '\n') || (buf[res-2] == '\n')) {
675                                 *cp = CC_REFRESH;
676                                 return(1);
677                         } else {
678                                 lastpos = 1;
679                         }
680                 }
681         }
682
683         *cp = '\0';
684         return (0);
685 }
686
687 static char *cli_prompt(EditLine *el)
688 {
689         char prompt[80];
690
691         if (remotehostname)
692                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT2, remotehostname);
693         else
694                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT);
695
696         return strdup(prompt);
697 }
698
699 static char **ast_el_strtoarr(char *buf)
700 {
701         char **match_list = NULL, *retstr;
702         size_t match_list_len;
703         int matches = 0;
704
705         match_list_len = 1;
706         while ( (retstr = strsep(&buf, " ")) != NULL) {
707
708                 if (matches + 1 >= match_list_len) {
709                         match_list_len <<= 1;
710                         match_list = realloc(match_list, match_list_len * sizeof(char *));
711                 }
712
713                 match_list[matches++] = retstr;
714         }
715
716         if (!match_list)
717                 return (char **) NULL;
718
719         if (matches>= match_list_len)
720                 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
721
722         match_list[matches] = (char *) NULL;
723
724         return match_list;
725 }
726
727 static int ast_el_sort_compare(const void *i1, const void *i2)
728 {
729         char *s1, *s2;
730
731         s1 = ((char **)i1)[0];
732         s2 = ((char **)i2)[0];
733
734         return strcasecmp(s1, s2);
735 }
736
737 static int ast_cli_display_match_list(char **matches, int len, int max)
738 {
739         int i, idx, limit, count;
740         int screenwidth = 0;
741         int numoutput = 0, numoutputline = 0;
742
743         screenwidth = ast_get_termcols(STDOUT_FILENO);
744
745         /* find out how many entries can be put on one line, with two spaces between strings */
746         limit = screenwidth / (max + 2);
747         if (limit == 0)
748                 limit = 1;
749
750         /* how many lines of output */
751         count = len / limit;
752         if (count * limit < len)
753                 count++;
754
755         idx = 1;
756
757         qsort(&matches[0], (size_t)(len + 1), sizeof(char *), ast_el_sort_compare);
758
759         for (; count > 0; count--) {
760                 numoutputline = 0;
761                 for (i=0; i < limit && matches[idx]; i++, idx++) {
762
763                         /* Don't print dupes */
764                         if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
765                                 i--;
766                                 continue;
767                         }
768
769                         numoutput++;  numoutputline++;
770                         fprintf(stdout, "%-*s  ", max, matches[idx]);
771                 }
772                 if (numoutputline > 0)
773                         fprintf(stdout, "\n");
774         }
775
776         return numoutput;
777 }
778
779
780 static char *cli_complete(EditLine *el, int ch)
781 {
782         int len=0;
783         char *ptr;
784         int nummatches = 0;
785         char **matches;
786         int retval = CC_ERROR;
787         char buf[1024];
788         int res;
789
790         LineInfo *lf = (LineInfo *)el_line(el);
791
792         *lf->cursor = '\0';
793         ptr = (char *)lf->cursor;
794         if (ptr) {
795                 while (ptr > lf->buffer) {
796                         if (isspace(*ptr)) {
797                                 ptr++;
798                                 break;
799                         }
800                         ptr--;
801                 }
802         }
803
804         len = lf->cursor - ptr;
805
806         if (option_remote) {
807                 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr); 
808                 fdprint(ast_consock, buf);
809                 res = read(ast_consock, buf, sizeof(buf));
810                 buf[res] = '\0';
811                 nummatches = atoi(buf);
812
813                 if (nummatches > 0) {
814                         snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr); 
815                         fdprint(ast_consock, buf);
816                         res = read(ast_consock, buf, sizeof(buf));
817                         buf[res] = '\0';
818
819                         matches = ast_el_strtoarr(buf);
820                 } else
821                         matches = (char **) NULL;
822
823
824         }  else {
825
826                 nummatches = ast_cli_generatornummatches((char *)lf->buffer,ptr);
827                 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
828         }
829
830         if (matches) {
831                 int i;
832                 int matches_num, maxlen, match_len;
833
834                 if (matches[0][0] != '\0') {
835                         el_deletestr(el, (int) len);
836                         el_insertstr(el, matches[0]);
837                         retval = CC_REFRESH;
838                 }
839
840                 if (nummatches == 1) {
841                         /* Found an exact match */
842                         el_insertstr(el, strdup(" "));
843                         retval = CC_REFRESH;
844                 } else {
845                         /* Must be more than one match */
846                         for (i=1, maxlen=0; matches[i]; i++) {
847                                 match_len = strlen(matches[i]);
848                                 if (match_len > maxlen)
849                                         maxlen = match_len;
850                         }
851                         matches_num = i - 1;
852                         if (matches_num >1) {
853                                 fprintf(stdout, "\n");
854                                 ast_cli_display_match_list(matches, nummatches, maxlen);
855                                 retval = CC_REDISPLAY;
856                         } else { 
857                                 el_insertstr(el,strdup(" "));
858                                 retval = CC_REFRESH;
859                         }
860                 }
861
862         }
863
864         return (char *)retval;
865 }
866
867 static int ast_el_initialize(void)
868 {
869         HistEvent ev;
870
871         if (el != NULL)
872                 el_end(el);
873         if (el_hist != NULL)
874                 history_end(el_hist);
875
876         el = el_init("asterisk", stdin, stdout, stderr);
877         el_set(el, EL_PROMPT, cli_prompt);
878
879         el_set(el, EL_EDITMODE, 1);             
880         el_set(el, EL_EDITOR, "emacs");         
881         el_hist = history_init();
882         if (!el || !el_hist)
883                 return -1;
884
885         /* setup history with 100 entries */
886         history(el_hist, &ev, H_SETSIZE, 100);
887
888         el_set(el, EL_HIST, history, el_hist);
889
890         el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
891         /* Bind <tab> to command completion */
892         el_set(el, EL_BIND, "^I", "ed-complete", NULL);
893         /* Bind ? to command completion */
894         el_set(el, EL_BIND, "?", "ed-complete", NULL);
895
896         return 0;
897 }
898
899 static int ast_el_add_history(char *buf)
900 {
901         HistEvent ev;
902
903         if (el_hist == NULL || el == NULL)
904                 ast_el_initialize();
905
906         return (history(el_hist, &ev, H_ENTER, buf));
907 }
908
909 static int ast_el_write_history(char *filename)
910 {
911         HistEvent ev;
912
913         if (el_hist == NULL || el == NULL)
914                 ast_el_initialize();
915
916         return (history(el_hist, &ev, H_SAVE, filename));
917 }
918
919 static int ast_el_read_history(char *filename)
920 {
921         char buf[256];
922         FILE *f;
923         int ret = -1;
924
925         if (el_hist == NULL || el == NULL)
926                 ast_el_initialize();
927
928         if ((f = fopen(filename, "r")) == NULL)
929                 return ret;
930
931         while (!feof(f)) {
932                 fgets(buf, sizeof(buf), f);
933                 if (!strcmp(buf, "_HiStOrY_V2_\n"))
934                         continue;
935                 if ((ret = ast_el_add_history(buf)) == -1)
936                         break;
937         }
938         fclose(f);
939
940         return ret;
941 }
942
943 static void ast_remotecontrol(char * data)
944 {
945         char buf[80];
946         int res;
947         char filename[80] = "";
948         char *hostname;
949         char *cpid;
950         char *version;
951         int pid;
952         char tmp[80];
953         char *stringp=NULL;
954
955         char *ebuf;
956         int num = 0;
957
958         read(ast_consock, buf, sizeof(buf));
959         if (data)
960                 write(ast_consock, data, strlen(data) + 1);
961         stringp=buf;
962         hostname = strsep(&stringp, "/");
963         cpid = strsep(&stringp, "/");
964         version = strsep(&stringp, "/");
965         if (!version)
966                 version = "<Version Unknown>";
967         stringp=hostname;
968         strsep(&stringp, ".");
969         if (cpid)
970                 pid = atoi(cpid);
971         else
972                 pid = -1;
973         snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
974         fdprint(ast_consock, tmp);
975         ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
976         remotehostname = hostname;
977         if (getenv("HOME")) 
978                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
979         if (el_hist == NULL || el == NULL)
980                 ast_el_initialize();
981
982         el_set(el, EL_GETCFN, ast_el_read_char);
983
984         if (strlen(filename))
985                 ast_el_read_history(filename);
986
987         ast_cli_register(&quit);
988         ast_cli_register(&astexit);
989 #if 0
990         ast_cli_register(&astshutdown);
991 #endif  
992         for(;;) {
993                 ebuf = (char *)el_gets(el, &num);
994
995                 if (data)       /* hack to print output then exit if asterisk -rx is used */
996                         ebuf = strdup("quit");
997
998                 if (ebuf && strlen(ebuf)) {
999                         if (ebuf[strlen(ebuf)-1] == '\n')
1000                                 ebuf[strlen(ebuf)-1] = '\0';
1001                         if (!remoteconsolehandler(ebuf)) {
1002                                 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
1003                                 if (res < 1) {
1004                                         ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
1005                                         break;
1006                                 }
1007                         }
1008                 }
1009         }
1010         printf("\nDisconnected from Asterisk server\n");
1011 }
1012
1013 static int show_cli_help(void) {
1014         printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 2000-2002, Digium.\n");
1015         printf("Usage: asterisk [OPTIONS]\n");
1016         printf("Valid Options:\n");
1017         printf("   -h           This help screen\n");
1018         printf("   -r           Connect to Asterisk on this machine\n");
1019         printf("   -f           Do not fork\n");
1020         printf("   -n           Disable console colorization\n");
1021         printf("   -p           Run as pseudo-realtime thread\n");
1022         printf("   -v           Increase verbosity (multiple v's = more verbose)\n");
1023         printf("   -q           Quiet mode (supress output)\n");
1024         printf("   -g           Dump core in case of a crash\n");
1025         printf("   -x <cmd>     Execute command <cmd> (only valid with -r)\n");
1026         printf("   -i           Initializie crypto keys at startup\n");
1027         printf("   -c           Provide console CLI\n");
1028         printf("   -d           Enable extra debugging\n");
1029         printf("\n");
1030         return 0;
1031 }
1032
1033 static void ast_readconfig(void) {
1034         struct ast_config *cfg;
1035         struct ast_variable *v;
1036         char *config = ASTCONFPATH;
1037
1038         if (option_overrideconfig == 1) {
1039             cfg = ast_load((char *)ast_config_AST_CONFIG_FILE);
1040         } else {
1041             cfg = ast_load(config);
1042         }
1043
1044         /* init with buildtime config */
1045         strncpy((char *)ast_config_AST_CONFIG_DIR,AST_CONFIG_DIR,sizeof(ast_config_AST_CONFIG_DIR)-1);
1046         strncpy((char *)ast_config_AST_SPOOL_DIR,AST_SPOOL_DIR,sizeof(ast_config_AST_SPOOL_DIR)-1);
1047         strncpy((char *)ast_config_AST_MODULE_DIR,AST_MODULE_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1048         strncpy((char *)ast_config_AST_VAR_DIR,AST_VAR_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1049         strncpy((char *)ast_config_AST_LOG_DIR,AST_LOG_DIR,sizeof(ast_config_AST_LOG_DIR)-1);
1050         strncpy((char *)ast_config_AST_AGI_DIR,AST_AGI_DIR,sizeof(ast_config_AST_AGI_DIR)-1);
1051         strncpy((char *)ast_config_AST_DB,AST_DB,sizeof(ast_config_AST_DB)-1);
1052         strncpy((char *)ast_config_AST_KEY_DIR,AST_KEY_DIR,sizeof(ast_config_AST_KEY_DIR)-1);
1053         strncpy((char *)ast_config_AST_PID,AST_PID,sizeof(ast_config_AST_PID)-1);
1054         strncpy((char *)ast_config_AST_SOCKET,AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1);
1055         strncpy((char *)ast_config_AST_RUN_DIR,AST_RUN_DIR,sizeof(ast_config_AST_RUN_DIR)-1);
1056         
1057         /* no asterisk.conf? no problem, use buildtime config! */
1058         if (!cfg) {
1059             return;
1060         }
1061         v = ast_variable_browse(cfg, "directories");
1062         while(v) {
1063                 if (!strcasecmp(v->name, "astetcdir")) {
1064                     strncpy((char *)ast_config_AST_CONFIG_DIR,v->value,sizeof(ast_config_AST_CONFIG_DIR)-1);
1065                 } else if (!strcasecmp(v->name, "astspooldir")) {
1066                     strncpy((char *)ast_config_AST_SPOOL_DIR,v->value,sizeof(ast_config_AST_SPOOL_DIR)-1);
1067                 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1068                     strncpy((char *)ast_config_AST_VAR_DIR,v->value,sizeof(ast_config_AST_VAR_DIR)-1);
1069                     snprintf((char *)ast_config_AST_DB,sizeof(ast_config_AST_DB)-1,"%s/%s",v->value,"astdb");    
1070                 } else if (!strcasecmp(v->name, "astlogdir")) {
1071                     strncpy((char *)ast_config_AST_LOG_DIR,v->value,sizeof(ast_config_AST_LOG_DIR)-1);
1072                 } else if (!strcasecmp(v->name, "astagidir")) {
1073                     strncpy((char *)ast_config_AST_AGI_DIR,v->value,sizeof(ast_config_AST_AGI_DIR)-1);
1074                 } else if (!strcasecmp(v->name, "astrundir")) {
1075                     snprintf((char *)ast_config_AST_PID,sizeof(ast_config_AST_PID)-1,"%s/%s",v->value,"asterisk.pid");    
1076                     snprintf((char *)ast_config_AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1,"%s/%s",v->value,"asterisk.ctl");    
1077                     strncpy((char *)ast_config_AST_RUN_DIR,v->value,sizeof(ast_config_AST_RUN_DIR)-1);
1078                 } else if (!strcasecmp(v->name, "astmoddir")) {
1079                     strncpy((char *)ast_config_AST_MODULE_DIR,v->value,sizeof(ast_config_AST_MODULE_DIR)-1);
1080                 }
1081                 v = v->next;
1082         }
1083         ast_destroy(cfg);
1084 }
1085
1086 int main(int argc, char *argv[])
1087 {
1088         char c;
1089         char filename[80] = "";
1090         char hostname[256];
1091         char tmp[80];
1092         char * xarg = NULL;
1093         int x;
1094         FILE *f;
1095         sigset_t sigs;
1096         int num;
1097         char *buf;
1098
1099         /* Remember original args for restart */
1100         if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1101                 fprintf(stderr, "Truncating argument size to %d\n", sizeof(_argv) / sizeof(_argv[0]) - 1);
1102                 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1103         }
1104         for (x=0;x<argc;x++)
1105                 _argv[x] = argv[x];
1106         _argv[x] = NULL;
1107
1108         if (gethostname(hostname, sizeof(hostname)))
1109                 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
1110         mainpid = getpid();
1111         ast_ulaw_init();
1112         ast_alaw_init();
1113         callerid_init();
1114         tdd_init();
1115         if (getenv("HOME")) 
1116                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1117         /* Check if we're root */
1118         /*
1119         if (geteuid()) {
1120                 ast_log(LOG_ERROR, "Must be run as root\n");
1121                 exit(1);
1122         }
1123         */
1124         /* Check for options */
1125         while((c=getopt(argc, argv, "hfdvqprgcinx:C:")) != EOF) {
1126                 switch(c) {
1127                 case 'd':
1128                         option_debug++;
1129                         option_nofork++;
1130                         break;
1131                 case 'c':
1132                         option_console++;
1133                         option_nofork++;
1134                         break;
1135                 case 'f':
1136                         option_nofork++;
1137                         break;
1138                 case 'n':
1139                         option_nocolor++;
1140                         break;
1141                 case 'r':
1142                         option_remote++;
1143                         option_nofork++;
1144                         break;
1145                 case 'p':
1146                         option_highpriority++;
1147                         break;
1148                 case 'v':
1149                         option_verbose++;
1150                         option_nofork++;
1151                         break;
1152                 case 'q':
1153                         option_quiet++;
1154                         break;
1155                 case 'x':
1156                         option_exec++;
1157                         xarg = optarg;
1158                         break;
1159                 case 'C':
1160                         strncpy((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE));
1161                         option_overrideconfig++;
1162                         break;
1163                 case 'i':
1164                         option_initcrypto++;
1165                         break;
1166                 case'g':
1167                         option_dumpcore++;
1168                         break;
1169                 case 'h':
1170                         show_cli_help();
1171                         exit(0);
1172                 case '?':
1173                         exit(1);
1174                 }
1175         }
1176
1177         if (option_dumpcore) {
1178                 struct rlimit l;
1179                 memset(&l, 0, sizeof(l));
1180                 l.rlim_cur = RLIM_INFINITY;
1181                 l.rlim_max = RLIM_INFINITY;
1182                 if (setrlimit(RLIMIT_CORE, &l)) {
1183                         ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
1184                 }
1185         }
1186
1187         term_init();
1188         printf(term_end());
1189         fflush(stdout);
1190         if (option_console && !option_verbose) 
1191                 ast_verbose("[ Reading Master Configuration ]");
1192         ast_readconfig();
1193
1194         if (el_hist == NULL || el == NULL)
1195                 ast_el_initialize();
1196
1197         if (strlen(filename))
1198                 ast_el_read_history(filename);
1199
1200         if (ast_tryconnect()) {
1201                 /* One is already running */
1202                 if (option_remote) {
1203                         if (option_exec) {
1204                                 ast_remotecontrol(xarg);
1205                                 quit_handler(0, 0, 0, 0);
1206                                 exit(0);
1207                         }
1208                         printf(term_quit());
1209                         ast_register_verbose(console_verboser);
1210                         ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2001 Linux Support Services, Inc.\n");
1211                         ast_verbose( "Written by Mark Spencer <markster@linux-support.net>\n");
1212                         ast_verbose( "=========================================================================\n");
1213                         ast_remotecontrol(NULL);
1214                         quit_handler(0, 0, 0, 0);
1215                         exit(0);
1216                 } else {
1217                         ast_log(LOG_ERROR, "Asterisk already running on %s.  Use 'asterisk -r' to connect.\n", (char *)ast_config_AST_SOCKET);
1218                         printf(term_quit());
1219                         exit(1);
1220                 }
1221         } else if (option_remote || option_exec) {
1222                 ast_log(LOG_ERROR, "Unable to connect to remote asterisk\n");
1223                 printf(term_quit());
1224                 exit(1);
1225         }
1226         /* Blindly write pid file since we couldn't connect */
1227         unlink((char *)ast_config_AST_PID);
1228         f = fopen((char *)ast_config_AST_PID, "w");
1229         if (f) {
1230                 fprintf(f, "%d\n", getpid());
1231                 fclose(f);
1232         } else
1233                 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1234
1235         if (!option_verbose && !option_debug && !option_nofork && !option_console) {
1236 #if 1
1237                 daemon(0,0);
1238 #else   
1239                 pid = fork();
1240                 if (pid < 0) {
1241                         ast_log(LOG_ERROR, "Unable to fork(): %s\n", strerror(errno));
1242                         printf(term_quit());
1243                         exit(1);
1244                 }
1245                 if (pid) 
1246                         exit(0);
1247 #endif                  
1248         }
1249
1250         ast_makesocket();
1251         sigemptyset(&sigs);
1252         sigaddset(&sigs, SIGHUP);
1253         sigaddset(&sigs, SIGTERM);
1254         sigaddset(&sigs, SIGINT);
1255         sigaddset(&sigs, SIGPIPE);
1256         sigaddset(&sigs, SIGWINCH);
1257         pthread_sigmask(SIG_BLOCK, &sigs, NULL);
1258         if (option_console || option_verbose || option_remote)
1259                 ast_register_verbose(console_verboser);
1260         /* Print a welcome message if desired */
1261         if (option_verbose || option_console) {
1262                 ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2001 Linux Support Services, Inc.\n");
1263                 ast_verbose( "Written by Mark Spencer <markster@linux-support.net>\n");
1264                 ast_verbose( "=========================================================================\n");
1265         }
1266         if (option_console && !option_verbose) 
1267                 ast_verbose("[ Booting...");
1268         signal(SIGURG, urg_handler);
1269         signal(SIGINT, __quit_handler);
1270         signal(SIGTERM, __quit_handler);
1271         signal(SIGHUP, hup_handler);
1272         signal(SIGPIPE, pipe_handler);
1273         if (set_priority(option_highpriority)) {
1274                 printf(term_quit());
1275                 exit(1);
1276         }
1277         if (init_logger()) {
1278                 printf(term_quit());
1279                 exit(1);
1280         }
1281         if (init_manager()) {
1282                 printf(term_quit());
1283                 exit(1);
1284         }
1285         if (ast_image_init()) {
1286                 printf(term_quit());
1287                 exit(1);
1288         }
1289         if (load_pbx()) {
1290                 printf(term_quit());
1291                 exit(1);
1292         }
1293         if (load_modules()) {
1294                 printf(term_quit());
1295                 exit(1);
1296         }
1297         if (init_framer()) {
1298                 printf(term_quit());
1299                 exit(1);
1300         }
1301         if (astdb_init()) {
1302                 printf(term_quit());
1303                 exit(1);
1304         }
1305         /* We might have the option of showing a console, but for now just
1306            do nothing... */
1307         if (option_console && !option_verbose)
1308                 ast_verbose(" ]\n");
1309         if (option_verbose || option_console)
1310                 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
1311         fully_booted = 1;
1312         pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
1313         ast_cli_register(&astshutdownnow);
1314         ast_cli_register(&astshutdowngracefully);
1315         ast_cli_register(&astrestartnow);
1316         ast_cli_register(&astrestartgracefully);
1317         ast_cli_register(&astrestartwhenconvenient);
1318         ast_cli_register(&aborthalt);
1319         if (option_console) {
1320                 /* Console stuff now... */
1321                 /* Register our quit function */
1322                 char title[256];
1323                 set_icon("Asterisk");
1324                 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, mainpid);
1325                 set_title(title);
1326             ast_cli_register(&quit);
1327             ast_cli_register(&astexit);
1328                 consolethread = pthread_self();
1329
1330                 while ( (buf = (char *)el_gets(el, &num) ) != NULL && num != 0) {
1331
1332                         if (buf[strlen(buf)-1] == '\n')
1333                                 buf[strlen(buf)-1] = '\0';
1334
1335                         consolehandler((char *)buf);
1336                 }
1337
1338         } else {
1339                 /* Do nothing */
1340                 select(0,NULL,NULL,NULL,NULL);
1341         }
1342         return 0;
1343 }