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