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