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