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