ensure that needed headers are included for chmod() and mkdir() (bug #3937)
[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 - 2005, Digium, Inc.
7  *
8  * Mark Spencer <markster@digium.com>
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 <asterisk/enum.h>
30 #include <asterisk/rtp.h>
31 #include <asterisk/app.h>
32 #include <asterisk/lock.h>
33 #include <asterisk/utils.h>
34 #include <asterisk/file.h>
35 #include <sys/resource.h>
36 #include <fcntl.h>
37 #include <stdio.h>
38 #include <signal.h>
39 #include <sched.h>
40 #include <asterisk/io.h>
41 #include <asterisk/lock.h>
42 #include <sys/socket.h>
43 #include <sys/un.h>
44 #include <sys/wait.h>
45 #include <string.h>
46 #include <errno.h>
47 #include <ctype.h>
48 #include "editline/histedit.h"
49 #include "asterisk.h"
50 #include <asterisk/config.h>
51 #include <sys/resource.h>
52 #include <grp.h>
53 #include <pwd.h>
54 #include <sys/stat.h>
55
56 #if  defined(__FreeBSD__) || defined( __NetBSD__ ) || defined(SOLARIS)
57 #include <netdb.h>
58 #endif
59
60 #ifndef AF_LOCAL
61 #define AF_LOCAL AF_UNIX
62 #define PF_LOCAL PF_UNIX
63 #endif
64
65 #define AST_MAX_CONNECTS 128
66 #define NUM_MSGS 64
67
68 #define WELCOME_MESSAGE ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999 - 2005 Digium.\n"); \
69                 ast_verbose( "Written by Mark Spencer <markster@digium.com>\n"); \
70                 ast_verbose( "=========================================================================\n")
71
72 int option_verbose=0;
73 int option_debug=0;
74 int option_exec_includes=0;
75 int option_nofork=0;
76 int option_quiet=0;
77 int option_console=0;
78 int option_highpriority=0;
79 int option_remote=0;
80 int option_exec=0;
81 int option_initcrypto=0;
82 int option_nocolor;
83 int option_dumpcore = 0;
84 int option_cache_record_files = 0;
85 int option_timestamp = 0;
86 int option_overrideconfig = 0;
87 int option_reconnect = 0;
88 int fully_booted = 0;
89 char record_cache_dir[AST_CACHE_DIR_LEN] = AST_TMP_DIR;
90 char debug_filename[AST_FILENAME_MAX] = "";
91
92 static int ast_socket = -1;             /* UNIX Socket for allowing remote control */
93 static int ast_consock = -1;            /* UNIX Socket for controlling another asterisk */
94 int ast_mainpid;
95 struct console {
96         int fd;                                 /* File descriptor */
97         int p[2];                               /* Pipe */
98         pthread_t t;                    /* Thread of handler */
99 };
100
101 static struct ast_atexit {
102         void (*func)(void);
103         struct ast_atexit *next;
104 } *atexits = NULL;
105 AST_MUTEX_DEFINE_STATIC(atexitslock);
106
107 time_t ast_startuptime;
108 time_t ast_lastreloadtime;
109
110 static History *el_hist = NULL;
111 static EditLine *el = NULL;
112 static char *remotehostname;
113
114 struct console consoles[AST_MAX_CONNECTS];
115
116 char defaultlanguage[MAX_LANGUAGE] = DEFAULT_LANGUAGE;
117
118 static int ast_el_add_history(char *);
119 static int ast_el_read_history(char *);
120 static int ast_el_write_history(char *);
121
122 char ast_config_AST_CONFIG_DIR[AST_CONFIG_MAX_PATH];
123 char ast_config_AST_CONFIG_FILE[AST_CONFIG_MAX_PATH];
124 char ast_config_AST_MODULE_DIR[AST_CONFIG_MAX_PATH];
125 char ast_config_AST_SPOOL_DIR[AST_CONFIG_MAX_PATH];
126 char ast_config_AST_VAR_DIR[AST_CONFIG_MAX_PATH];
127 char ast_config_AST_LOG_DIR[AST_CONFIG_MAX_PATH];
128 char ast_config_AST_AGI_DIR[AST_CONFIG_MAX_PATH];
129 char ast_config_AST_DB[AST_CONFIG_MAX_PATH];
130 char ast_config_AST_KEY_DIR[AST_CONFIG_MAX_PATH];
131 char ast_config_AST_PID[AST_CONFIG_MAX_PATH];
132 char ast_config_AST_SOCKET[AST_CONFIG_MAX_PATH];
133 char ast_config_AST_RUN_DIR[AST_CONFIG_MAX_PATH];
134
135 static char *_argv[256];
136 static int shuttingdown = 0;
137 static int restartnow = 0;
138 static pthread_t consolethread = AST_PTHREADT_NULL;
139
140 int ast_register_atexit(void (*func)(void))
141 {
142         int res = -1;
143         struct ast_atexit *ae;
144         ast_unregister_atexit(func);
145         ae = malloc(sizeof(struct ast_atexit));
146         ast_mutex_lock(&atexitslock);
147         if (ae) {
148                 memset(ae, 0, sizeof(struct ast_atexit));
149                 ae->next = atexits;
150                 ae->func = func;
151                 atexits = ae;
152                 res = 0;
153         }
154         ast_mutex_unlock(&atexitslock);
155         return res;
156 }
157
158 void ast_unregister_atexit(void (*func)(void))
159 {
160         struct ast_atexit *ae, *prev = NULL;
161         ast_mutex_lock(&atexitslock);
162         ae = atexits;
163         while(ae) {
164                 if (ae->func == func) {
165                         if (prev)
166                                 prev->next = ae->next;
167                         else
168                                 atexits = ae->next;
169                         break;
170                 }
171                 prev = ae;
172                 ae = ae->next;
173         }
174         ast_mutex_unlock(&atexitslock);
175 }
176
177 static int fdprint(int fd, const char *s)
178 {
179         return write(fd, s, strlen(s) + 1);
180 }
181
182 /* NULL handler so we can collect the child exit status */
183 static void null_sig_handler(int signal)
184 {
185
186 }
187
188 int ast_safe_system(const char *s)
189 {
190         /* XXX This function needs some optimization work XXX */
191         pid_t pid;
192         int x;
193         int res;
194         struct rusage rusage;
195         int status;
196         void (*prev_handler) = signal(SIGCHLD, null_sig_handler);
197         pid = fork();
198         if (pid == 0) {
199                 /* Close file descriptors and launch system command */
200                 for (x=STDERR_FILENO + 1; x<4096;x++) {
201                         close(x);
202                 }
203                 res = execl("/bin/sh", "/bin/sh", "-c", s, NULL);
204                 exit(1);
205         } else if (pid > 0) {
206                 for(;;) {
207                         res = wait4(pid, &status, 0, &rusage);
208                         if (res > -1) {
209                                 if (WIFEXITED(status))
210                                         res = WEXITSTATUS(status);
211                                 else
212                                         res = -1;
213                                 break;
214                         } else {
215                                 if (errno != EINTR) 
216                                         break;
217                         }
218                 }
219         } else {
220                 ast_log(LOG_WARNING, "Fork failed: %s\n", strerror(errno));
221                 res = -1;
222         }
223         signal(SIGCHLD, prev_handler);
224         return res;
225 }
226
227 /*
228  * write the string to all attached console clients
229  */
230 static void ast_network_puts(const char *string)
231 {
232         int x;
233         for (x=0;x<AST_MAX_CONNECTS; x++) {
234                 if (consoles[x].fd > -1) 
235                         fdprint(consoles[x].p[1], string);
236         }
237 }
238
239 /*
240  * write the string to the console, and all attached
241  * console clients
242  */
243 void ast_console_puts(const char *string)
244 {
245         fputs(string, stdout);
246         fflush(stdout);
247         ast_network_puts(string);
248 }
249
250 static void network_verboser(const char *s, int pos, int replace, int complete)
251         /* ARGUSED */
252 {
253         if (replace) {
254                 char *t = alloca(strlen(s) + 2);
255                 if (t) {
256                         sprintf(t, "\r%s", s);
257                         if (complete)
258                                 ast_network_puts(t);
259                 } else {
260                         ast_log(LOG_ERROR, "Out of memory\n");
261                         ast_network_puts(s);
262                 }
263         } else {
264                 if (complete)
265                         ast_network_puts(s);
266         }
267 }
268
269 static pthread_t lthread;
270
271 static void *netconsole(void *vconsole)
272 {
273         struct console *con = vconsole;
274         char hostname[256];
275         char tmp[512];
276         int res;
277         struct pollfd fds[2];
278         
279         if (gethostname(hostname, sizeof(hostname)))
280                 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
281         snprintf(tmp, sizeof(tmp), "%s/%d/%s\n", hostname, ast_mainpid, ASTERISK_VERSION);
282         fdprint(con->fd, tmp);
283         for(;;) {
284                 fds[0].fd = con->fd;
285                 fds[0].events = POLLIN;
286                 fds[1].fd = con->p[0];
287                 fds[1].events = POLLIN;
288
289                 res = poll(fds, 2, -1);
290                 if (res < 0) {
291                         if (errno != EINTR)
292                                 ast_log(LOG_WARNING, "poll returned < 0: %s\n", strerror(errno));
293                         continue;
294                 }
295                 if (fds[0].revents) {
296                         res = read(con->fd, tmp, sizeof(tmp));
297                         if (res < 1) {
298                                 break;
299                         }
300                         tmp[res] = 0;
301                         ast_cli_command(con->fd, tmp);
302                 }
303                 if (fds[1].revents) {
304                         res = read(con->p[0], tmp, sizeof(tmp));
305                         if (res < 1) {
306                                 ast_log(LOG_ERROR, "read returned %d\n", res);
307                                 break;
308                         }
309                         res = write(con->fd, tmp, res);
310                         if (res < 1)
311                                 break;
312                 }
313         }
314         if (option_verbose > 2) 
315                 ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection disconnected\n");
316         close(con->fd);
317         close(con->p[0]);
318         close(con->p[1]);
319         con->fd = -1;
320         
321         return NULL;
322 }
323
324 static void *listener(void *unused)
325 {
326         struct sockaddr_un sunaddr;
327         int s;
328         int len;
329         int x;
330         int flags;
331         struct pollfd fds[1];
332         pthread_attr_t attr;
333         pthread_attr_init(&attr);
334         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
335         for(;;) {
336                 if (ast_socket < 0)
337                         return NULL;
338                 fds[0].fd = ast_socket;
339                 fds[0].events= POLLIN;
340                 s = poll(fds, 1, -1);
341                 if (s < 0) {
342                         if (errno != EINTR)
343                                 ast_log(LOG_WARNING, "poll returned error: %s\n", strerror(errno));
344                         continue;
345                 }
346                 len = sizeof(sunaddr);
347                 s = accept(ast_socket, (struct sockaddr *)&sunaddr, &len);
348                 if (s < 0) {
349                         if (errno != EINTR)
350                                 ast_log(LOG_WARNING, "Accept returned %d: %s\n", s, strerror(errno));
351                 } else {
352                         for (x=0;x<AST_MAX_CONNECTS;x++) {
353                                 if (consoles[x].fd < 0) {
354                                         if (socketpair(AF_LOCAL, SOCK_STREAM, 0, consoles[x].p)) {
355                                                 ast_log(LOG_ERROR, "Unable to create pipe: %s\n", strerror(errno));
356                                                 consoles[x].fd = -1;
357                                                 fdprint(s, "Server failed to create pipe\n");
358                                                 close(s);
359                                                 break;
360                                         }
361                                         flags = fcntl(consoles[x].p[1], F_GETFL);
362                                         fcntl(consoles[x].p[1], F_SETFL, flags | O_NONBLOCK);
363                                         consoles[x].fd = s;
364                                         if (ast_pthread_create(&consoles[x].t, &attr, netconsole, &consoles[x])) {
365                                                 ast_log(LOG_ERROR, "Unable to spawn thread to handle connection: %s\n", strerror(errno));
366                                                 consoles[x].fd = -1;
367                                                 fdprint(s, "Server failed to spawn thread\n");
368                                                 close(s);
369                                         }
370                                         break;
371                                 }
372                         }
373                         if (x >= AST_MAX_CONNECTS) {
374                                 fdprint(s, "No more connections allowed\n");
375                                 ast_log(LOG_WARNING, "No more connections allowed\n");
376                                 close(s);
377                         } else if (consoles[x].fd > -1) {
378                                 if (option_verbose > 2) 
379                                         ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection\n");
380                         }
381                 }
382         }
383         return NULL;
384 }
385
386 static int ast_makesocket(void)
387 {
388         struct sockaddr_un sunaddr;
389         int res;
390         int x;
391
392         struct ast_config *cfg;
393         char *config = ASTCONFPATH;
394         char *owner;
395         char *group;
396         char *perms;
397         uid_t uid;
398         gid_t gid;
399
400
401         for (x=0;x<AST_MAX_CONNECTS;x++)        
402                 consoles[x].fd = -1;
403         unlink((char *)ast_config_AST_SOCKET);
404         ast_socket = socket(PF_LOCAL, SOCK_STREAM, 0);
405         if (ast_socket < 0) {
406                 ast_log(LOG_WARNING, "Unable to create control socket: %s\n", strerror(errno));
407                 return -1;
408         }               
409         memset(&sunaddr, 0, sizeof(sunaddr));
410         sunaddr.sun_family = AF_LOCAL;
411         strncpy(sunaddr.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sunaddr.sun_path)-1);
412         res = bind(ast_socket, (struct sockaddr *)&sunaddr, sizeof(sunaddr));
413         if (res) {
414                 ast_log(LOG_WARNING, "Unable to bind socket to %s: %s\n", (char *)ast_config_AST_SOCKET, strerror(errno));
415                 close(ast_socket);
416                 ast_socket = -1;
417                 return -1;
418         }
419         res = listen(ast_socket, 2);
420         if (res < 0) {
421                 ast_log(LOG_WARNING, "Unable to listen on socket %s: %s\n", (char *)ast_config_AST_SOCKET, strerror(errno));
422                 close(ast_socket);
423                 ast_socket = -1;
424                 return -1;
425         }
426         ast_register_verbose(network_verboser);
427         ast_pthread_create(&lthread, NULL, listener, NULL);
428
429         /* Load the options for owner, group and permissions from
430            asterisk.conf. if the file doesn't exist (????) just skip
431            this part.
432         */
433         if (option_overrideconfig == 1) {
434                 cfg = ast_config_load((char *)ast_config_AST_CONFIG_FILE);
435         } else {
436                 cfg = ast_config_load(config);
437         }
438         if (!cfg) return 0;
439
440         gid=-1;
441         uid=-1;
442         group = ast_variable_retrieve(cfg, "files", "astctlgroup");
443         owner = ast_variable_retrieve(cfg, "files", "astctlowner");
444         perms = ast_variable_retrieve(cfg, "files", "astctlpermissions");
445
446         if (owner!=NULL) {
447                 struct passwd *pw;
448                 if ((pw=getpwnam(owner))==NULL)
449                         ast_log(LOG_WARNING, "Unable to find uid of user %s\n", owner);
450                 else
451                         uid=pw->pw_uid;
452         }
453         if (group!=NULL) {
454                 struct group *grp;
455                 if ((grp=getgrnam(group))==NULL)
456                         ast_log(LOG_WARNING, "Unable to find gid of group %s\n", group);
457                 else
458                         gid=grp->gr_gid;
459         }
460         if (chown(ast_config_AST_SOCKET,uid,gid)<0)
461                 ast_log(LOG_WARNING, "Unable to change ownership of %s: %s\n", ast_config_AST_SOCKET,strerror(errno));
462
463         if (perms!=NULL) {
464                 mode_t p;
465                 sscanf(perms,"%o",&p);
466                 if ((chmod(ast_config_AST_SOCKET,p))<0)
467                         ast_log(LOG_WARNING, "Unable to change file permissions of %s: %s\n", ast_config_AST_SOCKET,strerror(errno));
468         }
469
470         return 0;
471 }
472
473 static int ast_tryconnect(void)
474 {
475         struct sockaddr_un sunaddr;
476         int res;
477         ast_consock = socket(PF_LOCAL, SOCK_STREAM, 0);
478         if (ast_consock < 0) {
479                 ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
480                 return 0;
481         }
482         memset(&sunaddr, 0, sizeof(sunaddr));
483         sunaddr.sun_family = AF_LOCAL;
484         strncpy(sunaddr.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sunaddr.sun_path)-1);
485         res = connect(ast_consock, (struct sockaddr *)&sunaddr, sizeof(sunaddr));
486         if (res) {
487                 close(ast_consock);
488                 ast_consock = -1;
489                 return 0;
490         } else
491                 return 1;
492 }
493
494 static void urg_handler(int num)
495 {
496         /* Called by soft_hangup to interrupt the poll, read, or other
497            system call.  We don't actually need to do anything though.  */
498         /* Cannot EVER ast_log from within a signal handler */
499         if (option_debug) 
500                 printf("Urgent handler\n");
501         signal(num, urg_handler);
502         return;
503 }
504
505 static void hup_handler(int num)
506 {
507         if (option_verbose > 1) 
508                 printf("Received HUP signal -- Reloading configs\n");
509         if (restartnow)
510                 execvp(_argv[0], _argv);
511         /* XXX This could deadlock XXX */
512         ast_module_reload(NULL);
513 }
514
515 static void child_handler(int sig)
516 {
517         /* Must not ever ast_log or ast_verbose within signal handler */
518         int n, status;
519
520         /*
521          * Reap all dead children -- not just one
522          */
523         for (n = 0; wait4(-1, &status, WNOHANG, NULL) > 0; n++)
524                 ;
525         if (n == 0 && option_debug)     
526                 printf("Huh?  Child handler, but nobody there?\n");
527 }
528
529 static void set_title(char *text)
530 {
531         /* Set an X-term or screen title */
532         if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
533                 fprintf(stdout, "\033]2;%s\007", text);
534 }
535
536 static void set_icon(char *text)
537 {
538         if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
539                 fprintf(stdout, "\033]1;%s\007", text);
540 }
541
542 static int set_priority(int pri)
543 {
544         struct sched_param sched;
545         memset(&sched, 0, sizeof(sched));
546         /* We set ourselves to a high priority, that we might pre-empt everything
547            else.  If your PBX has heavy activity on it, this is a good thing.  */
548 #ifdef __linux__
549         if (pri) {  
550                 sched.sched_priority = 10;
551                 if (sched_setscheduler(0, SCHED_RR, &sched)) {
552                         ast_log(LOG_WARNING, "Unable to set high priority\n");
553                         return -1;
554                 } else
555                         if (option_verbose)
556                                 ast_verbose("Set to realtime thread\n");
557         } else {
558                 sched.sched_priority = 0;
559                 if (sched_setscheduler(0, SCHED_OTHER, &sched)) {
560                         ast_log(LOG_WARNING, "Unable to set normal priority\n");
561                         return -1;
562                 }
563         }
564 #else
565         if (pri) {
566                 if (setpriority(PRIO_PROCESS, 0, -10) == -1) {
567                         ast_log(LOG_WARNING, "Unable to set high priority\n");
568                         return -1;
569                 } else
570                         if (option_verbose)
571                                 ast_verbose("Set to high priority\n");
572         } else {
573                 if (setpriority(PRIO_PROCESS, 0, 0) == -1) {
574                         ast_log(LOG_WARNING, "Unable to set normal priority\n");
575                         return -1;
576                 }
577         }
578 #endif
579         return 0;
580 }
581
582 static void ast_run_atexits(void)
583 {
584         struct ast_atexit *ae;
585         ast_mutex_lock(&atexitslock);
586         ae = atexits;
587         while(ae) {
588                 if (ae->func) 
589                         ae->func();
590                 ae = ae->next;
591         }
592         ast_mutex_unlock(&atexitslock);
593 }
594
595 static void quit_handler(int num, int nice, int safeshutdown, int restart)
596 {
597         char filename[80] = "";
598         time_t s,e;
599         int x;
600         if (safeshutdown) {
601                 shuttingdown = 1;
602                 if (!nice) {
603                         /* Begin shutdown routine, hanging up active channels */
604                         ast_begin_shutdown(1);
605                         if (option_verbose && option_console)
606                                 ast_verbose("Beginning asterisk %s....\n", restart ? "restart" : "shutdown");
607                         time(&s);
608                         for(;;) {
609                                 time(&e);
610                                 /* Wait up to 15 seconds for all channels to go away */
611                                 if ((e - s) > 15)
612                                         break;
613                                 if (!ast_active_channels())
614                                         break;
615                                 if (!shuttingdown)
616                                         break;
617                                 /* Sleep 1/10 of a second */
618                                 usleep(100000);
619                         }
620                 } else {
621                         if (nice < 2)
622                                 ast_begin_shutdown(0);
623                         if (option_verbose && option_console)
624                                 ast_verbose("Waiting for inactivity to perform %s...\n", restart ? "restart" : "halt");
625                         for(;;) {
626                                 if (!ast_active_channels())
627                                         break;
628                                 if (!shuttingdown)
629                                         break;
630                                 sleep(1);
631                         }
632                 }
633
634                 if (!shuttingdown) {
635                         if (option_verbose && option_console)
636                                 ast_verbose("Asterisk %s cancelled.\n", restart ? "restart" : "shutdown");
637                         return;
638                 }
639         }
640         if (option_console || option_remote) {
641                 if (getenv("HOME")) 
642                         snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
643                 if (!ast_strlen_zero(filename))
644                         ast_el_write_history(filename);
645                 if (el != NULL)
646                         el_end(el);
647                 if (el_hist != NULL)
648                         history_end(el_hist);
649         }
650         if (option_verbose)
651                 ast_verbose("Executing last minute cleanups\n");
652         ast_run_atexits();
653         /* Called on exit */
654         if (option_verbose && option_console)
655                 ast_verbose("Asterisk %s ending (%d).\n", ast_active_channels() ? "uncleanly" : "cleanly", num);
656         else if (option_debug)
657                 ast_log(LOG_DEBUG, "Asterisk ending (%d).\n", num);
658         manager_event(EVENT_FLAG_SYSTEM, "Shutdown", "Shutdown: %s\r\nRestart: %s\r\n", ast_active_channels() ? "Uncleanly" : "Cleanly", restart ? "True" : "False");
659         if (ast_socket > -1) {
660                 close(ast_socket);
661                 ast_socket = -1;
662         }
663         if (ast_consock > -1)
664                 close(ast_consock);
665         if (ast_socket > -1)
666                 unlink((char *)ast_config_AST_SOCKET);
667         if (!option_remote) unlink((char *)ast_config_AST_PID);
668         printf(term_quit());
669         if (restart) {
670                 if (option_verbose || option_console)
671                         ast_verbose("Preparing for Asterisk restart...\n");
672                 /* Mark all FD's for closing on exec */
673                 for (x=3;x<32768;x++) {
674                         fcntl(x, F_SETFD, FD_CLOEXEC);
675                 }
676                 if (option_verbose || option_console)
677                         ast_verbose("Restarting Asterisk NOW...\n");
678                 restartnow = 1;
679
680                 /* close logger */
681                 close_logger();
682
683                 /* If there is a consolethread running send it a SIGHUP 
684                    so it can execvp, otherwise we can do it ourselves */
685                 if (consolethread != AST_PTHREADT_NULL) {
686                         pthread_kill(consolethread, SIGHUP);
687                         /* Give the signal handler some time to complete */
688                         sleep(2);
689                 } else
690                         execvp(_argv[0], _argv);
691         
692         } else {
693                 /* close logger */
694                 close_logger();
695         }
696         exit(0);
697 }
698
699 static void __quit_handler(int num)
700 {
701         quit_handler(num, 0, 1, 0);
702 }
703
704 static const char *fix_header(char *outbuf, int maxout, const char *s, char *cmp)
705 {
706         const char *c;
707         if (!strncmp(s, cmp, strlen(cmp))) {
708                 c = s + strlen(cmp);
709                 term_color(outbuf, cmp, COLOR_GRAY, 0, maxout);
710                 return c;
711         }
712         return NULL;
713 }
714
715 static void console_verboser(const char *s, int pos, int replace, int complete)
716 {
717         char tmp[80];
718         const char *c=NULL;
719         /* Return to the beginning of the line */
720         if (!pos) {
721                 fprintf(stdout, "\r");
722                 if ((c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_4)) ||
723                         (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_3)) ||
724                         (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_2)) ||
725                         (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_1)))
726                         fputs(tmp, stdout);
727         }
728         if (c)
729                 fputs(c + pos,stdout);
730         else
731                 fputs(s + pos,stdout);
732         fflush(stdout);
733         if (complete) {
734                 /* Wake up a poll()ing console */
735                 if (option_console && consolethread != AST_PTHREADT_NULL)
736                         pthread_kill(consolethread, SIGURG);
737         }
738 }
739
740 static int ast_all_zeros(char *s)
741 {
742         while(*s) {
743                 if (*s > 32)
744                         return 0;
745                 s++;  
746         }
747         return 1;
748 }
749
750 static void consolehandler(char *s)
751 {
752         printf(term_end());
753         fflush(stdout);
754         /* Called when readline data is available */
755         if (s && !ast_all_zeros(s))
756                 ast_el_add_history(s);
757         /* Give the console access to the shell */
758         if (s) {
759                 /* The real handler for bang */
760                 if (s[0] == '!') {
761                         if (s[1])
762                                 ast_safe_system(s+1);
763                         else
764                                 ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
765                 } else 
766                 ast_cli_command(STDOUT_FILENO, s);
767         } else
768                 fprintf(stdout, "\nUse \"quit\" to exit\n");
769 }
770
771 static int remoteconsolehandler(char *s)
772 {
773         int ret = 0;
774         /* Called when readline data is available */
775         if (s && !ast_all_zeros(s))
776                 ast_el_add_history(s);
777         /* Give the console access to the shell */
778         if (s) {
779                 /* The real handler for bang */
780                 if (s[0] == '!') {
781                         if (s[1])
782                                 ast_safe_system(s+1);
783                         else
784                                 ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
785                         ret = 1;
786                 }
787                 if ((strncasecmp(s, "quit", 4) == 0 || strncasecmp(s, "exit", 4) == 0) &&
788                     (s[4] == '\0' || isspace(s[4]))) {
789                         quit_handler(0, 0, 0, 0);
790                         ret = 1;
791                 }
792         } else
793                 fprintf(stdout, "\nUse \"quit\" to exit\n");
794
795         return ret;
796 }
797
798 static char quit_help[] = 
799 "Usage: quit\n"
800 "       Exits Asterisk.\n";
801
802 static char abort_halt_help[] = 
803 "Usage: abort shutdown\n"
804 "       Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
805 "       call operations.\n";
806
807 static char shutdown_now_help[] = 
808 "Usage: stop now\n"
809 "       Shuts down a running Asterisk immediately, hanging up all active calls .\n";
810
811 static char shutdown_gracefully_help[] = 
812 "Usage: stop gracefully\n"
813 "       Causes Asterisk to not accept new calls, and exit when all\n"
814 "       active calls have terminated normally.\n";
815
816 static char shutdown_when_convenient_help[] = 
817 "Usage: stop when convenient\n"
818 "       Causes Asterisk to perform a shutdown when all active calls have ended.\n";
819
820 static char restart_now_help[] = 
821 "Usage: restart now\n"
822 "       Causes Asterisk to hangup all calls and exec() itself performing a cold\n"
823 "       restart.\n";
824
825 static char restart_gracefully_help[] = 
826 "Usage: restart gracefully\n"
827 "       Causes Asterisk to stop accepting new calls and exec() itself performing a cold\n"
828 "       restart when all active calls have ended.\n";
829
830 static char restart_when_convenient_help[] = 
831 "Usage: restart when convenient\n"
832 "       Causes Asterisk to perform a cold restart when all active calls have ended.\n";
833
834 static char bang_help[] =
835 "Usage: !<command>\n"
836 "       Executes a given shell command\n";
837
838 #if 0
839 static int handle_quit(int fd, int argc, char *argv[])
840 {
841         if (argc != 1)
842                 return RESULT_SHOWUSAGE;
843         quit_handler(0, 0, 1, 0);
844         return RESULT_SUCCESS;
845 }
846 #endif
847
848 static int no_more_quit(int fd, int argc, char *argv[])
849 {
850         if (argc != 1)
851                 return RESULT_SHOWUSAGE;
852         ast_cli(fd, "The QUIT and EXIT commands may no longer be used to shutdown the PBX.\n"
853                     "Please use STOP NOW instead, if you wish to shutdown the PBX.\n");
854         return RESULT_SUCCESS;
855 }
856
857 static int handle_shutdown_now(int fd, int argc, char *argv[])
858 {
859         if (argc != 2)
860                 return RESULT_SHOWUSAGE;
861         quit_handler(0, 0 /* Not nice */, 1 /* safely */, 0 /* not restart */);
862         return RESULT_SUCCESS;
863 }
864
865 static int handle_shutdown_gracefully(int fd, int argc, char *argv[])
866 {
867         if (argc != 2)
868                 return RESULT_SHOWUSAGE;
869         quit_handler(0, 1 /* nicely */, 1 /* safely */, 0 /* no restart */);
870         return RESULT_SUCCESS;
871 }
872
873 static int handle_shutdown_when_convenient(int fd, int argc, char *argv[])
874 {
875         if (argc != 3)
876                 return RESULT_SHOWUSAGE;
877         quit_handler(0, 2 /* really nicely */, 1 /* safely */, 0 /* don't restart */);
878         return RESULT_SUCCESS;
879 }
880
881 static int handle_restart_now(int fd, int argc, char *argv[])
882 {
883         if (argc != 2)
884                 return RESULT_SHOWUSAGE;
885         quit_handler(0, 0 /* not nicely */, 1 /* safely */, 1 /* restart */);
886         return RESULT_SUCCESS;
887 }
888
889 static int handle_restart_gracefully(int fd, int argc, char *argv[])
890 {
891         if (argc != 2)
892                 return RESULT_SHOWUSAGE;
893         quit_handler(0, 1 /* nicely */, 1 /* safely */, 1 /* restart */);
894         return RESULT_SUCCESS;
895 }
896
897 static int handle_restart_when_convenient(int fd, int argc, char *argv[])
898 {
899         if (argc != 3)
900                 return RESULT_SHOWUSAGE;
901         quit_handler(0, 2 /* really nicely */, 1 /* safely */, 1 /* restart */);
902         return RESULT_SUCCESS;
903 }
904
905 static int handle_abort_halt(int fd, int argc, char *argv[])
906 {
907         if (argc != 2)
908                 return RESULT_SHOWUSAGE;
909         ast_cancel_shutdown();
910         shuttingdown = 0;
911         return RESULT_SUCCESS;
912 }
913
914 static int handle_bang(int fd, int argc, char *argv[])
915 {
916         return RESULT_SUCCESS;
917 }
918
919 #define ASTERISK_PROMPT "*CLI> "
920
921 #define ASTERISK_PROMPT2 "%s*CLI> "
922
923 static struct ast_cli_entry aborthalt = { { "abort", "halt", NULL }, handle_abort_halt, "Cancel a running halt", abort_halt_help };
924
925 static struct ast_cli_entry quit =      { { "quit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
926 static struct ast_cli_entry astexit =   { { "exit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
927
928 static struct ast_cli_entry astshutdownnow =    { { "stop", "now", NULL }, handle_shutdown_now, "Shut down Asterisk immediately", shutdown_now_help };
929 static struct ast_cli_entry astshutdowngracefully =     { { "stop", "gracefully", NULL }, handle_shutdown_gracefully, "Gracefully shut down Asterisk", shutdown_gracefully_help };
930 static struct ast_cli_entry astshutdownwhenconvenient =         { { "stop", "when","convenient", NULL }, handle_shutdown_when_convenient, "Shut down Asterisk at empty call volume", shutdown_when_convenient_help };
931 static struct ast_cli_entry astrestartnow =     { { "restart", "now", NULL }, handle_restart_now, "Restart Asterisk immediately", restart_now_help };
932 static struct ast_cli_entry astrestartgracefully =      { { "restart", "gracefully", NULL }, handle_restart_gracefully, "Restart Asterisk gracefully", restart_gracefully_help };
933 static struct ast_cli_entry astrestartwhenconvenient=   { { "restart", "when", "convenient", NULL }, handle_restart_when_convenient, "Restart Asterisk at empty call volume", restart_when_convenient_help };
934 static struct ast_cli_entry astbang = { { "!", NULL }, handle_bang, "Execute a shell command", bang_help };
935
936 static int ast_el_read_char(EditLine *el, char *cp)
937 {
938         int num_read=0;
939         int lastpos=0;
940         struct pollfd fds[2];
941         int res;
942         int max;
943         char buf[512];
944
945         for (;;) {
946                 max = 1;
947                 fds[0].fd = ast_consock;
948                 fds[0].events = POLLIN;
949                 if (!option_exec) {
950                         fds[1].fd = STDIN_FILENO;
951                         fds[1].events = POLLIN;
952                         max++;
953                 }
954                 res = poll(fds, max, -1);
955                 if (res < 0) {
956                         if (errno == EINTR)
957                                 continue;
958                         ast_log(LOG_ERROR, "poll failed: %s\n", strerror(errno));
959                         break;
960                 }
961
962                 if (!option_exec && fds[1].revents) {
963                         num_read = read(STDIN_FILENO, cp, 1);
964                         if (num_read < 1) {
965                                 break;
966                         } else 
967                                 return (num_read);
968                 }
969                 if (fds[0].revents) {
970                         res = read(ast_consock, buf, sizeof(buf) - 1);
971                         /* if the remote side disappears exit */
972                         if (res < 1) {
973                                 fprintf(stderr, "\nDisconnected from Asterisk server\n");
974                                 if (!option_reconnect) {
975                                         quit_handler(0, 0, 0, 0);
976                                 } else {
977                                         int tries;
978                                         int reconnects_per_second = 20;
979                                         fprintf(stderr, "Attempting to reconnect for 30 seconds\n");
980                                         for (tries=0;tries<30 * reconnects_per_second;tries++) {
981                                                 if (ast_tryconnect()) {
982                                                         fprintf(stderr, "Reconnect succeeded after %.3f seconds\n", 1.0 / reconnects_per_second * tries);
983                                                         printf(term_quit());
984                                                         WELCOME_MESSAGE;
985                                                         break;
986                                                 } else {
987                                                         usleep(1000000 / reconnects_per_second);
988                                                 }
989                                         }
990                                         if (tries >= 30 * reconnects_per_second) {
991                                                 fprintf(stderr, "Failed to reconnect for 30 seconds.  Quitting.\n");
992                                                 quit_handler(0, 0, 0, 0);
993                                         }
994                                 }
995                         }
996
997                         buf[res] = '\0';
998
999                         if (!option_exec && !lastpos)
1000                                 write(STDOUT_FILENO, "\r", 1);
1001                         write(STDOUT_FILENO, buf, res);
1002                         if ((buf[res-1] == '\n') || (buf[res-2] == '\n')) {
1003                                 *cp = CC_REFRESH;
1004                                 return(1);
1005                         } else {
1006                                 lastpos = 1;
1007                         }
1008                 }
1009         }
1010
1011         *cp = '\0';
1012         return (0);
1013 }
1014
1015 static char *cli_prompt(EditLine *el)
1016 {
1017         static char prompt[200];
1018         char *pfmt;
1019         int color_used=0;
1020         char term_code[20];
1021
1022         if ((pfmt = getenv("ASTERISK_PROMPT"))) {
1023                 char *t = pfmt, *p = prompt;
1024                 memset(prompt, 0, sizeof(prompt));
1025                 while (*t != '\0' && *p < sizeof(prompt)) {
1026                         if (*t == '%') {
1027                                 char hostname[256];
1028                                 int i;
1029                                 struct timeval tv;
1030                                 struct tm tm;
1031 #ifdef linux
1032                                 FILE *LOADAVG;
1033 #endif
1034                                 int fgcolor = COLOR_WHITE, bgcolor = COLOR_BLACK;
1035
1036                                 t++;
1037                                 switch (*t) {
1038                                         case 'C': /* color */
1039                                                 t++;
1040                                                 if (sscanf(t, "%d;%d%n", &fgcolor, &bgcolor, &i) == 2) {
1041                                                         strncat(p, term_color_code(term_code, fgcolor, bgcolor, sizeof(term_code)),sizeof(prompt) - strlen(prompt) - 1);
1042                                                         t += i - 1;
1043                                                 } else if (sscanf(t, "%d%n", &fgcolor, &i) == 1) {
1044                                                         strncat(p, term_color_code(term_code, fgcolor, 0, sizeof(term_code)),sizeof(prompt) - strlen(prompt) - 1);
1045                                                         t += i - 1;
1046                                                 }
1047
1048                                                 /* If the color has been reset correctly, then there's no need to reset it later */
1049                                                 if ((fgcolor == COLOR_WHITE) && (bgcolor == COLOR_BLACK)) {
1050                                                         color_used = 0;
1051                                                 } else {
1052                                                         color_used = 1;
1053                                                 }
1054                                                 break;
1055                                         case 'd': /* date */
1056                                                 memset(&tm, 0, sizeof(struct tm));
1057                                                 gettimeofday(&tv, NULL);
1058                                                 if (localtime_r(&(tv.tv_sec), &tm)) {
1059                                                         strftime(p, sizeof(prompt) - strlen(prompt), "%Y-%m-%d", &tm);
1060                                                 }
1061                                                 break;
1062                                         case 'h': /* hostname */
1063                                                 if (!gethostname(hostname, sizeof(hostname) - 1)) {
1064                                                         strncat(p, hostname, sizeof(prompt) - strlen(prompt) - 1);
1065                                                 } else {
1066                                                         strncat(p, "localhost", sizeof(prompt) - strlen(prompt) - 1);
1067                                                 }
1068                                                 break;
1069                                         case 'H': /* short hostname */
1070                                                 if (!gethostname(hostname, sizeof(hostname) - 1)) {
1071                                                         for (i=0;i<sizeof(hostname);i++) {
1072                                                                 if (hostname[i] == '.') {
1073                                                                         hostname[i] = '\0';
1074                                                                         break;
1075                                                                 }
1076                                                         }
1077                                                         strncat(p, hostname, sizeof(prompt) - strlen(prompt) - 1);
1078                                                 } else {
1079                                                         strncat(p, "localhost", sizeof(prompt) - strlen(prompt) - 1);
1080                                                 }
1081                                                 break;
1082 #ifdef linux
1083                                         case 'l': /* load avg */
1084                                                 t++;
1085                                                 if ((LOADAVG = fopen("/proc/loadavg", "r"))) {
1086                                                         float avg1, avg2, avg3;
1087                                                         int actproc, totproc, npid, which;
1088                                                         fscanf(LOADAVG, "%f %f %f %d/%d %d",
1089                                                                 &avg1, &avg2, &avg3, &actproc, &totproc, &npid);
1090                                                         if (sscanf(t, "%d", &which) == 1) {
1091                                                                 switch (which) {
1092                                                                         case 1:
1093                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg1);
1094                                                                                 break;
1095                                                                         case 2:
1096                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg2);
1097                                                                                 break;
1098                                                                         case 3:
1099                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg3);
1100                                                                                 break;
1101                                                                         case 4:
1102                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%d/%d", actproc, totproc);
1103                                                                                 break;
1104                                                                         case 5:
1105                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%d", npid);
1106                                                                                 break;
1107                                                                 }
1108                                                         }
1109                                                 }
1110                                                 break;
1111 #endif
1112                                         case 't': /* time */
1113                                                 memset(&tm, 0, sizeof(struct tm));
1114                                                 gettimeofday(&tv, NULL);
1115                                                 if (localtime_r(&(tv.tv_sec), &tm)) {
1116                                                         strftime(p, sizeof(prompt) - strlen(prompt), "%H:%M:%S", &tm);
1117                                                 }
1118                                                 break;
1119                                         case '#': /* process console or remote? */
1120                                                 if (! option_remote) {
1121                                                         strncat(p, "#", sizeof(prompt) - strlen(prompt) - 1);
1122                                                 } else {
1123                                                         strncat(p, ">", sizeof(prompt) - strlen(prompt) - 1);
1124                                                 }
1125                                                 break;
1126                                         case '%': /* literal % */
1127                                                 strncat(p, "%", sizeof(prompt) - strlen(prompt) - 1);
1128                                                 break;
1129                                         case '\0': /* % is last character - prevent bug */
1130                                                 t--;
1131                                                 break;
1132                                 }
1133                                 while (*p != '\0') {
1134                                         p++;
1135                                 }
1136                                 t++;
1137                         } else {
1138                                 *p = *t;
1139                                 p++;
1140                                 t++;
1141                         }
1142                 }
1143                 if (color_used) {
1144                         /* Force colors back to normal at end */
1145                         term_color_code(term_code, COLOR_WHITE, COLOR_BLACK, sizeof(term_code));
1146                         if (strlen(term_code) > sizeof(prompt) - strlen(prompt)) {
1147                                 strncat(prompt + sizeof(prompt) - strlen(term_code) - 1, term_code, strlen(term_code));
1148                         } else {
1149                                 strncat(p, term_code, sizeof(term_code));
1150                         }
1151                 }
1152         } else if (remotehostname)
1153                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT2, remotehostname);
1154         else
1155                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT);
1156
1157         return(prompt); 
1158 }
1159
1160 static char **ast_el_strtoarr(char *buf)
1161 {
1162         char **match_list = NULL, *retstr;
1163         size_t match_list_len;
1164         int matches = 0;
1165
1166         match_list_len = 1;
1167         while ( (retstr = strsep(&buf, " ")) != NULL) {
1168
1169                 if (!strcmp(retstr, AST_CLI_COMPLETE_EOF))
1170                         break;
1171                 if (matches + 1 >= match_list_len) {
1172                         match_list_len <<= 1;
1173                         match_list = realloc(match_list, match_list_len * sizeof(char *));
1174                 }
1175
1176                 match_list[matches++] = strdup(retstr);
1177         }
1178
1179         if (!match_list)
1180                 return (char **) NULL;
1181
1182         if (matches>= match_list_len)
1183                 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
1184
1185         match_list[matches] = (char *) NULL;
1186
1187         return match_list;
1188 }
1189
1190 static int ast_el_sort_compare(const void *i1, const void *i2)
1191 {
1192         char *s1, *s2;
1193
1194         s1 = ((char **)i1)[0];
1195         s2 = ((char **)i2)[0];
1196
1197         return strcasecmp(s1, s2);
1198 }
1199
1200 static int ast_cli_display_match_list(char **matches, int len, int max)
1201 {
1202         int i, idx, limit, count;
1203         int screenwidth = 0;
1204         int numoutput = 0, numoutputline = 0;
1205
1206         screenwidth = ast_get_termcols(STDOUT_FILENO);
1207
1208         /* find out how many entries can be put on one line, with two spaces between strings */
1209         limit = screenwidth / (max + 2);
1210         if (limit == 0)
1211                 limit = 1;
1212
1213         /* how many lines of output */
1214         count = len / limit;
1215         if (count * limit < len)
1216                 count++;
1217
1218         idx = 1;
1219
1220         qsort(&matches[0], (size_t)(len + 1), sizeof(char *), ast_el_sort_compare);
1221
1222         for (; count > 0; count--) {
1223                 numoutputline = 0;
1224                 for (i=0; i < limit && matches[idx]; i++, idx++) {
1225
1226                         /* Don't print dupes */
1227                         if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
1228                                 i--;
1229                                 free(matches[idx]);
1230                                 matches[idx] = NULL;
1231                                 continue;
1232                         }
1233
1234                         numoutput++;
1235                         numoutputline++;
1236                         fprintf(stdout, "%-*s  ", max, matches[idx]);
1237                         free(matches[idx]);
1238                         matches[idx] = NULL;
1239                 }
1240                 if (numoutputline > 0)
1241                         fprintf(stdout, "\n");
1242         }
1243
1244         return numoutput;
1245 }
1246
1247
1248 static char *cli_complete(EditLine *el, int ch)
1249 {
1250         int len=0;
1251         char *ptr;
1252         int nummatches = 0;
1253         char **matches;
1254         int retval = CC_ERROR;
1255         char buf[2048];
1256         int res;
1257
1258         LineInfo *lf = (LineInfo *)el_line(el);
1259
1260         *(char *)lf->cursor = '\0';
1261         ptr = (char *)lf->cursor;
1262         if (ptr) {
1263                 while (ptr > lf->buffer) {
1264                         if (isspace(*ptr)) {
1265                                 ptr++;
1266                                 break;
1267                         }
1268                         ptr--;
1269                 }
1270         }
1271
1272         len = lf->cursor - ptr;
1273
1274         if (option_remote) {
1275                 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr); 
1276                 fdprint(ast_consock, buf);
1277                 res = read(ast_consock, buf, sizeof(buf));
1278                 buf[res] = '\0';
1279                 nummatches = atoi(buf);
1280
1281                 if (nummatches > 0) {
1282                         char *mbuf;
1283                         int mlen = 0, maxmbuf = 2048;
1284                         /* Start with a 2048 byte buffer */
1285                         mbuf = malloc(maxmbuf);
1286                         if (!mbuf)
1287                                 return (char *)(CC_ERROR);
1288                         snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr); 
1289                         fdprint(ast_consock, buf);
1290                         res = 0;
1291                         mbuf[0] = '\0';
1292                         while (!strstr(mbuf, AST_CLI_COMPLETE_EOF) && res != -1) {
1293                                 if (mlen + 1024 > maxmbuf) {
1294                                         /* Every step increment buffer 1024 bytes */
1295                                         maxmbuf += 1024;
1296                                         mbuf = realloc(mbuf, maxmbuf);
1297                                         if (!mbuf)
1298                                                 return (char *)(CC_ERROR);
1299                                 }
1300                                 /* Only read 1024 bytes at a time */
1301                                 res = read(ast_consock, mbuf + mlen, 1024);
1302                                 if (res > 0)
1303                                         mlen += res;
1304                         }
1305                         mbuf[mlen] = '\0';
1306
1307                         matches = ast_el_strtoarr(mbuf);
1308                         free(mbuf);
1309                 } else
1310                         matches = (char **) NULL;
1311
1312
1313         } else {
1314
1315                 nummatches = ast_cli_generatornummatches((char *)lf->buffer,ptr);
1316                 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
1317         }
1318
1319         if (matches) {
1320                 int i;
1321                 int matches_num, maxlen, match_len;
1322
1323                 if (matches[0][0] != '\0') {
1324                         el_deletestr(el, (int) len);
1325                         el_insertstr(el, matches[0]);
1326                         retval = CC_REFRESH;
1327                 }
1328
1329                 if (nummatches == 1) {
1330                         /* Found an exact match */
1331                         el_insertstr(el, " ");
1332                         retval = CC_REFRESH;
1333                 } else {
1334                         /* Must be more than one match */
1335                         for (i=1, maxlen=0; matches[i]; i++) {
1336                                 match_len = strlen(matches[i]);
1337                                 if (match_len > maxlen)
1338                                         maxlen = match_len;
1339                         }
1340                         matches_num = i - 1;
1341                         if (matches_num >1) {
1342                                 fprintf(stdout, "\n");
1343                                 ast_cli_display_match_list(matches, nummatches, maxlen);
1344                                 retval = CC_REDISPLAY;
1345                         } else { 
1346                                 el_insertstr(el," ");
1347                                 retval = CC_REFRESH;
1348                         }
1349                 }
1350         free(matches);
1351         }
1352
1353         return (char *)(long)retval;
1354 }
1355
1356 static int ast_el_initialize(void)
1357 {
1358         HistEvent ev;
1359         char *editor = getenv("AST_EDITOR");
1360
1361         if (el != NULL)
1362                 el_end(el);
1363         if (el_hist != NULL)
1364                 history_end(el_hist);
1365
1366         el = el_init("asterisk", stdin, stdout, stderr);
1367         el_set(el, EL_PROMPT, cli_prompt);
1368
1369         el_set(el, EL_EDITMODE, 1);             
1370         el_set(el, EL_EDITOR, editor ? editor : "emacs");               
1371         el_hist = history_init();
1372         if (!el || !el_hist)
1373                 return -1;
1374
1375         /* setup history with 100 entries */
1376         history(el_hist, &ev, H_SETSIZE, 100);
1377
1378         el_set(el, EL_HIST, history, el_hist);
1379
1380         el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
1381         /* Bind <tab> to command completion */
1382         el_set(el, EL_BIND, "^I", "ed-complete", NULL);
1383         /* Bind ? to command completion */
1384         el_set(el, EL_BIND, "?", "ed-complete", NULL);
1385         /* Bind ^D to redisplay */
1386         el_set(el, EL_BIND, "^D", "ed-redisplay", NULL);
1387
1388         return 0;
1389 }
1390
1391 static int ast_el_add_history(char *buf)
1392 {
1393         HistEvent ev;
1394
1395         if (el_hist == NULL || el == NULL)
1396                 ast_el_initialize();
1397         if (strlen(buf) > 256)
1398                 return 0;
1399         return (history(el_hist, &ev, H_ENTER, buf));
1400 }
1401
1402 static int ast_el_write_history(char *filename)
1403 {
1404         HistEvent ev;
1405
1406         if (el_hist == NULL || el == NULL)
1407                 ast_el_initialize();
1408
1409         return (history(el_hist, &ev, H_SAVE, filename));
1410 }
1411
1412 static int ast_el_read_history(char *filename)
1413 {
1414         char buf[256];
1415         FILE *f;
1416         int ret = -1;
1417
1418         if (el_hist == NULL || el == NULL)
1419                 ast_el_initialize();
1420
1421         if ((f = fopen(filename, "r")) == NULL)
1422                 return ret;
1423
1424         while (!feof(f)) {
1425                 fgets(buf, sizeof(buf), f);
1426                 if (!strcmp(buf, "_HiStOrY_V2_\n"))
1427                         continue;
1428                 if (ast_all_zeros(buf))
1429                         continue;
1430                 if ((ret = ast_el_add_history(buf)) == -1)
1431                         break;
1432         }
1433         fclose(f);
1434
1435         return ret;
1436 }
1437
1438 static void ast_remotecontrol(char * data)
1439 {
1440         char buf[80];
1441         int res;
1442         char filename[80] = "";
1443         char *hostname;
1444         char *cpid;
1445         char *version;
1446         int pid;
1447         char tmp[80];
1448         char *stringp=NULL;
1449
1450         char *ebuf;
1451         int num = 0;
1452
1453         read(ast_consock, buf, sizeof(buf));
1454         if (data)
1455                 write(ast_consock, data, strlen(data) + 1);
1456         stringp=buf;
1457         hostname = strsep(&stringp, "/");
1458         cpid = strsep(&stringp, "/");
1459         version = strsep(&stringp, "\n");
1460         if (!version)
1461                 version = "<Version Unknown>";
1462         stringp=hostname;
1463         strsep(&stringp, ".");
1464         if (cpid)
1465                 pid = atoi(cpid);
1466         else
1467                 pid = -1;
1468         snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
1469         fdprint(ast_consock, tmp);
1470         snprintf(tmp, sizeof(tmp), "set debug atleast %d", option_debug);
1471         fdprint(ast_consock, tmp);
1472         ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
1473         remotehostname = hostname;
1474         if (getenv("HOME")) 
1475                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1476         if (el_hist == NULL || el == NULL)
1477                 ast_el_initialize();
1478
1479         el_set(el, EL_GETCFN, ast_el_read_char);
1480
1481         if (!ast_strlen_zero(filename))
1482                 ast_el_read_history(filename);
1483
1484         ast_cli_register(&quit);
1485         ast_cli_register(&astexit);
1486 #if 0
1487         ast_cli_register(&astshutdown);
1488 #endif  
1489         if (option_exec && data) {  /* hack to print output then exit if asterisk -rx is used */
1490                 char tempchar;
1491                 struct pollfd fds[0];
1492                 fds[0].fd = ast_consock;
1493                 fds[0].events = POLLIN;
1494                 fds[0].revents = 0;
1495                 while(poll(fds, 1, 100) > 0) {
1496                         ast_el_read_char(el, &tempchar);
1497                 }
1498                 return;
1499         }
1500         for(;;) {
1501                 ebuf = (char *)el_gets(el, &num);
1502
1503                 if (ebuf && !ast_strlen_zero(ebuf)) {
1504                         if (ebuf[strlen(ebuf)-1] == '\n')
1505                                 ebuf[strlen(ebuf)-1] = '\0';
1506                         if (!remoteconsolehandler(ebuf)) {
1507                                 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
1508                                 if (res < 1) {
1509                                         ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
1510                                         break;
1511                                 }
1512                         }
1513                 }
1514         }
1515         printf("\nDisconnected from Asterisk server\n");
1516 }
1517
1518 static int show_version(void)
1519 {
1520         printf("Asterisk " ASTERISK_VERSION "\n");
1521         return 0;
1522 }
1523
1524 static int show_cli_help(void) {
1525         printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 2000 - 2005, Digium.\n");
1526         printf("Usage: asterisk [OPTIONS]\n");
1527         printf("Valid Options:\n");
1528         printf("   -V              Display version number and exit\n");
1529         printf("   -C <configfile> Use an alternate configuration file\n");
1530         printf("   -G <group>      Run as a group other than the caller\n");
1531         printf("   -U <user>       Run as a user other than the caller\n");
1532         printf("   -c              Provide console CLI\n");
1533         printf("   -d              Enable extra debugging\n");
1534         printf("   -f              Do not fork\n");
1535         printf("   -g              Dump core in case of a crash\n");
1536         printf("   -h              This help screen\n");
1537         printf("   -i              Initialize crypto keys at startup\n");
1538         printf("   -n              Disable console colorization\n");
1539         printf("   -p              Run as pseudo-realtime thread\n");
1540         printf("   -q              Quiet mode (suppress output)\n");
1541         printf("   -r              Connect to Asterisk on this machine\n");
1542         printf("   -R              Connect to Asterisk, and attempt to reconnect if disconnected\n");
1543         printf("   -t              Record soundfiles in /var/tmp and move them where they belong after they are done.\n");
1544         printf("   -T              Display the time in [Mmm dd hh:mm:ss] format for each line of output to the CLI.\n");
1545         printf("   -v              Increase verbosity (multiple v's = more verbose)\n");
1546         printf("   -x <cmd>        Execute command <cmd> (only valid with -r)\n");
1547         printf("\n");
1548         return 0;
1549 }
1550
1551 static void ast_readconfig(void) {
1552         struct ast_config *cfg;
1553         struct ast_variable *v;
1554         struct ast_variable *v_ctlfile;
1555         char *config = ASTCONFPATH;
1556
1557         if (option_overrideconfig == 1) {
1558                 cfg = ast_config_load((char *)ast_config_AST_CONFIG_FILE);
1559                 if (!cfg)
1560                         ast_log(LOG_WARNING, "Unable to open specified master config file '%s', using builtin defaults\n", ast_config_AST_CONFIG_FILE);
1561         } else {
1562                 cfg = ast_config_load(config);
1563         }
1564
1565         /* init with buildtime config */
1566         strncpy((char *)ast_config_AST_CONFIG_DIR,AST_CONFIG_DIR,sizeof(ast_config_AST_CONFIG_DIR)-1);
1567         strncpy((char *)ast_config_AST_SPOOL_DIR,AST_SPOOL_DIR,sizeof(ast_config_AST_SPOOL_DIR)-1);
1568         strncpy((char *)ast_config_AST_MODULE_DIR,AST_MODULE_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1569         strncpy((char *)ast_config_AST_VAR_DIR,AST_VAR_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1570         strncpy((char *)ast_config_AST_LOG_DIR,AST_LOG_DIR,sizeof(ast_config_AST_LOG_DIR)-1);
1571         strncpy((char *)ast_config_AST_AGI_DIR,AST_AGI_DIR,sizeof(ast_config_AST_AGI_DIR)-1);
1572         strncpy((char *)ast_config_AST_DB,AST_DB,sizeof(ast_config_AST_DB)-1);
1573         strncpy((char *)ast_config_AST_KEY_DIR,AST_KEY_DIR,sizeof(ast_config_AST_KEY_DIR)-1);
1574         strncpy((char *)ast_config_AST_PID,AST_PID,sizeof(ast_config_AST_PID)-1);
1575         strncpy((char *)ast_config_AST_SOCKET,AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1);
1576         strncpy((char *)ast_config_AST_RUN_DIR,AST_RUN_DIR,sizeof(ast_config_AST_RUN_DIR)-1);
1577         
1578         /* no asterisk.conf? no problem, use buildtime config! */
1579         if (!cfg) {
1580                 return;
1581         }
1582
1583         v_ctlfile = ast_variable_browse(cfg, "files");
1584         while (v_ctlfile!=NULL) {
1585                 if (strcmp(v_ctlfile->name,"astctl")==0)
1586                         break;
1587                 v_ctlfile=v_ctlfile->next;
1588         }
1589
1590         v = ast_variable_browse(cfg, "directories");
1591         while(v) {
1592                 if (!strcasecmp(v->name, "astetcdir")) {
1593                         strncpy((char *)ast_config_AST_CONFIG_DIR,v->value,sizeof(ast_config_AST_CONFIG_DIR)-1);
1594                 } else if (!strcasecmp(v->name, "astspooldir")) {
1595                         strncpy((char *)ast_config_AST_SPOOL_DIR,v->value,sizeof(ast_config_AST_SPOOL_DIR)-1);
1596                 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1597                         strncpy((char *)ast_config_AST_VAR_DIR,v->value,sizeof(ast_config_AST_VAR_DIR)-1);
1598                         snprintf((char *)ast_config_AST_DB,sizeof(ast_config_AST_DB),"%s/%s",v->value,"astdb");    
1599                 } else if (!strcasecmp(v->name, "astlogdir")) {
1600                         strncpy((char *)ast_config_AST_LOG_DIR,v->value,sizeof(ast_config_AST_LOG_DIR)-1);
1601                 } else if (!strcasecmp(v->name, "astagidir")) {
1602                         strncpy((char *)ast_config_AST_AGI_DIR,v->value,sizeof(ast_config_AST_AGI_DIR)-1);
1603                 } else if (!strcasecmp(v->name, "astrundir")) {
1604                         snprintf((char *)ast_config_AST_PID,sizeof(ast_config_AST_PID),"%s/%s",v->value,"asterisk.pid");
1605                         snprintf((char *)ast_config_AST_SOCKET,sizeof(ast_config_AST_SOCKET),"%s/%s",v->value,v_ctlfile==NULL?"asterisk.ctl":v_ctlfile->value);
1606                         strncpy((char *)ast_config_AST_RUN_DIR,v->value,sizeof(ast_config_AST_RUN_DIR)-1);
1607                 } else if (!strcasecmp(v->name, "astmoddir")) {
1608                         strncpy((char *)ast_config_AST_MODULE_DIR,v->value,sizeof(ast_config_AST_MODULE_DIR)-1);
1609                 }
1610                 v = v->next;
1611         }
1612         v = ast_variable_browse(cfg, "options");
1613         while(v) {
1614                 /* verbose level (-v at startup) */
1615                 if (!strcasecmp(v->name, "verbose")) {
1616                         option_verbose= atoi(v->value);
1617                 /* whether or not to force timestamping. (-T at startup) */
1618                 } else if (!strcasecmp(v->name, "timestamp")) {
1619                         option_timestamp = ast_true(v->value);
1620                 /* whether or not to support #exec in config files */
1621                 } else if (!strcasecmp(v->name, "execincludes")) {
1622                         option_exec_includes = ast_true(v->value);
1623                 /* debug level (-d at startup) */
1624                 } else if (!strcasecmp(v->name, "debug")) {
1625                         option_debug = 0;
1626                         if (sscanf(v->value, "%d", &option_debug) != 1) {
1627                                 option_debug = ast_true(v->value);
1628                         }
1629                 /* Disable forking (-f at startup) */
1630                 } else if (!strcasecmp(v->name, "nofork")) {
1631                         option_nofork = ast_true(v->value);
1632                 /* Run quietly (-q at startup ) */
1633                 } else if (!strcasecmp(v->name, "quiet")) {
1634                         option_quiet = ast_true(v->value);
1635                 /* Run as console (-c at startup, implies nofork) */
1636                 } else if (!strcasecmp(v->name, "console")) {
1637                         option_console = ast_true(v->value);
1638                 /* Run with highg priority if the O/S permits (-p at startup) */
1639                 } else if (!strcasecmp(v->name, "highpriority")) {
1640                         option_highpriority = ast_true(v->value);
1641                 /* Initialize RSA auth keys (IAX2) (-i at startup) */
1642                 } else if (!strcasecmp(v->name, "initcrypto")) {
1643                         option_initcrypto = ast_true(v->value);
1644                 /* Disable ANSI colors for console (-c at startup) */
1645                 } else if (!strcasecmp(v->name, "nocolor")) {
1646                         option_nocolor = ast_true(v->value);
1647                 /* Dump core in case of crash (-g) */
1648                 } else if (!strcasecmp(v->name, "dumpcore")) {
1649                         option_dumpcore = ast_true(v->value);
1650                 /* Cache recorded sound files to another directory during recording */
1651                 } else if (!strcasecmp(v->name, "cache_record_files")) {
1652                         option_cache_record_files = ast_true(v->value);
1653                 /* Specify cache directory */
1654                 }  else if (!strcasecmp(v->name, "record_cache_dir")) {
1655                         strncpy(record_cache_dir,v->value,AST_CACHE_DIR_LEN);
1656                 }
1657                 v = v->next;
1658         }
1659         ast_config_destroy(cfg);
1660 }
1661
1662 int main(int argc, char *argv[])
1663 {
1664         int c;
1665         char filename[80] = "";
1666         char hostname[256];
1667         char tmp[80];
1668         char * xarg = NULL;
1669         int x;
1670         FILE *f;
1671         sigset_t sigs;
1672         int num;
1673         char *buf;
1674         char *runuser=NULL, *rungroup=NULL;
1675         struct pollfd silly_macos[1];   
1676
1677         /* Remember original args for restart */
1678         if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1679                 fprintf(stderr, "Truncating argument size to %d\n", (int)(sizeof(_argv) / sizeof(_argv[0])) - 1);
1680                 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1681         }
1682         for (x=0;x<argc;x++)
1683                 _argv[x] = argv[x];
1684         _argv[x] = NULL;
1685
1686         /* if the progname is rasterisk consider it a remote console */
1687         if (argv[0] && (strstr(argv[0], "rasterisk")) != NULL) {
1688                 option_remote++;
1689                 option_nofork++;
1690         }
1691         if (gethostname(hostname, sizeof(hostname)))
1692                 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
1693         ast_mainpid = getpid();
1694         ast_ulaw_init();
1695         ast_alaw_init();
1696         callerid_init();
1697         ast_utils_init();
1698         tdd_init();
1699         if (getenv("HOME")) 
1700                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1701         /* Check if we're root */
1702         /*
1703         if (geteuid()) {
1704                 ast_log(LOG_ERROR, "Must be run as root\n");
1705                 exit(1);
1706         }
1707         */
1708         /* Check for options */
1709         while((c=getopt(argc, argv, "tThfdvVqprRgcinx:U:G:C:")) != -1) {
1710                 switch(c) {
1711                 case 'd':
1712                         option_debug++;
1713                         option_nofork++;
1714                         break;
1715                 case 'c':
1716                         option_console++;
1717                         option_nofork++;
1718                         break;
1719                 case 'f':
1720                         option_nofork++;
1721                         break;
1722                 case 'n':
1723                         option_nocolor++;
1724                         break;
1725                 case 'r':
1726                         option_remote++;
1727                         option_nofork++;
1728                         break;
1729                 case 'R':
1730                         option_remote++;
1731                         option_nofork++;
1732                         option_reconnect++;
1733                         break;
1734                 case 'p':
1735                         option_highpriority++;
1736                         break;
1737                 case 'v':
1738                         option_verbose++;
1739                         option_nofork++;
1740                         break;
1741                 case 'q':
1742                         option_quiet++;
1743                         break;
1744                 case 't':
1745                         option_cache_record_files++;
1746                         break;
1747                 case 'T':
1748                         option_timestamp++;
1749                         break;
1750                 case 'x':
1751                         option_exec++;
1752                         xarg = optarg;
1753                         break;
1754                 case 'C':
1755                         strncpy((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE) - 1);
1756                         option_overrideconfig++;
1757                         break;
1758                 case 'i':
1759                         option_initcrypto++;
1760                         break;
1761                 case'g':
1762                         option_dumpcore++;
1763                         break;
1764                 case 'h':
1765                         show_cli_help();
1766                         exit(0);
1767                 case 'V':
1768                         show_version();
1769                         exit(0);
1770                 case 'U':
1771                         runuser = optarg;
1772                         break;
1773                 case 'G':
1774                         rungroup = optarg;
1775                         break;
1776                 case '?':
1777                         exit(1);
1778                 }
1779         }
1780
1781         if (option_dumpcore) {
1782                 struct rlimit l;
1783                 memset(&l, 0, sizeof(l));
1784                 l.rlim_cur = RLIM_INFINITY;
1785                 l.rlim_max = RLIM_INFINITY;
1786                 if (setrlimit(RLIMIT_CORE, &l)) {
1787                         ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
1788                 }
1789         }
1790
1791         if (option_console && !option_verbose) 
1792                 ast_verbose("[ Reading Master Configuration ]");
1793         ast_readconfig();
1794
1795         if (set_priority(option_highpriority)) {
1796                 exit(1);
1797         }
1798
1799         if (rungroup) {
1800                 struct group *gr;
1801                 gr = getgrnam(rungroup);
1802                 if (!gr) {
1803                         ast_log(LOG_WARNING, "No such group '%s'!\n", rungroup);
1804                         exit(1);
1805                 }
1806                 if (setgid(gr->gr_gid)) {
1807                         ast_log(LOG_WARNING, "Unable to setgid to %d (%s)\n", gr->gr_gid, rungroup);
1808                         exit(1);
1809                 }
1810                 if (option_verbose)
1811                         ast_verbose("Running as group '%s'\n", rungroup);
1812         }
1813
1814         if (runuser) {
1815                 struct passwd *pw;
1816                 pw = getpwnam(runuser);
1817                 if (!pw) {
1818                         ast_log(LOG_WARNING, "No such user '%s'!\n", runuser);
1819                         exit(1);
1820                 }
1821                 if (setuid(pw->pw_uid)) {
1822                         ast_log(LOG_WARNING, "Unable to setuid to %d (%s)\n", pw->pw_uid, runuser);
1823                         exit(1);
1824                 }
1825                 if (option_verbose)
1826                         ast_verbose("Running as user '%s'\n", runuser);
1827         }
1828
1829         term_init();
1830         printf(term_end());
1831         fflush(stdout);
1832
1833         if (option_console && !option_verbose) 
1834                 ast_verbose("[ Initializing Custom Configuration Options ]");
1835         /* custom config setup */
1836         register_config_cli();
1837         read_config_maps();
1838         
1839
1840         if (option_console) {
1841                 if (el_hist == NULL || el == NULL)
1842                         ast_el_initialize();
1843
1844                 if (!ast_strlen_zero(filename))
1845                         ast_el_read_history(filename);
1846         }
1847
1848         if (ast_tryconnect()) {
1849                 /* One is already running */
1850                 if (option_remote) {
1851                         if (option_exec) {
1852                                 ast_remotecontrol(xarg);
1853                                 quit_handler(0, 0, 0, 0);
1854                                 exit(0);
1855                         }
1856                         printf(term_quit());
1857                         ast_register_verbose(console_verboser);
1858                         WELCOME_MESSAGE;
1859                         ast_remotecontrol(NULL);
1860                         quit_handler(0, 0, 0, 0);
1861                         exit(0);
1862                 } else {
1863                         ast_log(LOG_ERROR, "Asterisk already running on %s.  Use 'asterisk -r' to connect.\n", (char *)ast_config_AST_SOCKET);
1864                         printf(term_quit());
1865                         exit(1);
1866                 }
1867         } else if (option_remote || option_exec) {
1868                 ast_log(LOG_ERROR, "Unable to connect to remote asterisk (does %s exist?)\n",ast_config_AST_SOCKET);
1869                 printf(term_quit());
1870                 exit(1);
1871         }
1872         /* Blindly write pid file since we couldn't connect */
1873         unlink((char *)ast_config_AST_PID);
1874         f = fopen((char *)ast_config_AST_PID, "w");
1875         if (f) {
1876                 fprintf(f, "%d\n", getpid());
1877                 fclose(f);
1878         } else
1879                 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1880
1881         if (!option_verbose && !option_debug && !option_nofork && !option_console) {
1882                 daemon(0,0);
1883                 /* Blindly re-write pid file since we are forking */
1884                 unlink((char *)ast_config_AST_PID);
1885                 f = fopen((char *)ast_config_AST_PID, "w");
1886                 if (f) {
1887                         fprintf(f, "%d\n", getpid());
1888                         fclose(f);
1889                 } else
1890                         ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1891         }
1892
1893         /* Test recursive mutex locking. */
1894         if (test_for_thread_safety())
1895                 ast_verbose("Warning! Asterisk is not thread safe.\n");
1896
1897         ast_makesocket();
1898         sigemptyset(&sigs);
1899         sigaddset(&sigs, SIGHUP);
1900         sigaddset(&sigs, SIGTERM);
1901         sigaddset(&sigs, SIGINT);
1902         sigaddset(&sigs, SIGPIPE);
1903         sigaddset(&sigs, SIGWINCH);
1904         pthread_sigmask(SIG_BLOCK, &sigs, NULL);
1905         if (option_console || option_verbose || option_remote)
1906                 ast_register_verbose(console_verboser);
1907         /* Print a welcome message if desired */
1908         if (option_verbose || option_console) {
1909                 WELCOME_MESSAGE;
1910         }
1911         if (option_console && !option_verbose) 
1912                 ast_verbose("[ Booting...");
1913
1914         signal(SIGURG, urg_handler);
1915         signal(SIGINT, __quit_handler);
1916         signal(SIGTERM, __quit_handler);
1917         signal(SIGHUP, hup_handler);
1918         signal(SIGCHLD, child_handler);
1919         signal(SIGPIPE, SIG_IGN);
1920
1921         if (init_logger()) {
1922                 printf(term_quit());
1923                 exit(1);
1924         }
1925         ast_channels_init();
1926         if (init_manager()) {
1927                 printf(term_quit());
1928                 exit(1);
1929         }
1930         ast_rtp_init();
1931         if (ast_image_init()) {
1932                 printf(term_quit());
1933                 exit(1);
1934         }
1935         if (ast_file_init()) {
1936                 printf(term_quit());
1937                 exit(1);
1938         }
1939         if (load_pbx()) {
1940                 printf(term_quit());
1941                 exit(1);
1942         }
1943         if (load_modules()) {
1944                 printf(term_quit());
1945                 exit(1);
1946         }
1947         if (init_framer()) {
1948                 printf(term_quit());
1949                 exit(1);
1950         }
1951         if (astdb_init()) {
1952                 printf(term_quit());
1953                 exit(1);
1954         }
1955         if (ast_enum_init()) {
1956                 printf(term_quit());
1957                 exit(1);
1958         }
1959 #if 0
1960         /* This should no longer be necessary */
1961         /* sync cust config and reload some internals in case a custom config handler binded to them */
1962         read_ast_cust_config();
1963         reload_logger(0);
1964         reload_manager();
1965         ast_enum_reload();
1966         ast_rtp_reload();
1967 #endif
1968
1969
1970         /* We might have the option of showing a console, but for now just
1971            do nothing... */
1972         if (option_console && !option_verbose)
1973                 ast_verbose(" ]\n");
1974         if (option_verbose || option_console)
1975                 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
1976         if (option_nofork)
1977                 consolethread = pthread_self();
1978         fully_booted = 1;
1979         pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
1980 #ifdef __AST_DEBUG_MALLOC
1981         __ast_mm_init();
1982 #endif  
1983         time(&ast_startuptime);
1984         ast_cli_register(&astshutdownnow);
1985         ast_cli_register(&astshutdowngracefully);
1986         ast_cli_register(&astrestartnow);
1987         ast_cli_register(&astrestartgracefully);
1988         ast_cli_register(&astrestartwhenconvenient);
1989         ast_cli_register(&astshutdownwhenconvenient);
1990         ast_cli_register(&aborthalt);
1991         ast_cli_register(&astbang);
1992         if (option_console) {
1993                 /* Console stuff now... */
1994                 /* Register our quit function */
1995                 char title[256];
1996                 set_icon("Asterisk");
1997                 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, ast_mainpid);
1998                 set_title(title);
1999                 ast_cli_register(&quit);
2000                 ast_cli_register(&astexit);
2001
2002                 for (;;) {
2003                         buf = (char *)el_gets(el, &num);
2004                         if (buf) {
2005                                 if (buf[strlen(buf)-1] == '\n')
2006                                         buf[strlen(buf)-1] = '\0';
2007
2008                                 consolehandler((char *)buf);
2009                         } else {
2010                                 if (write(STDOUT_FILENO, "\nUse EXIT or QUIT to exit the asterisk console\n",
2011                                                                   strlen("\nUse EXIT or QUIT to exit the asterisk console\n")) < 0) {
2012                                         /* Whoa, stdout disappeared from under us... Make /dev/null's */
2013                                         int fd;
2014                                         fd = open("/dev/null", O_RDWR);
2015                                         if (fd > -1) {
2016                                                 dup2(fd, STDOUT_FILENO);
2017                                                 dup2(fd, STDIN_FILENO);
2018                                         } else
2019                                                 ast_log(LOG_WARNING, "Failed to open /dev/null to recover from dead console.  Bad things will happen!\n");
2020                                         break;
2021                                 }
2022                         }
2023                 }
2024
2025         }
2026         /* Do nothing */
2027         for(;;) 
2028                 poll(silly_macos,0, -1);
2029         return 0;
2030 }