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