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