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