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