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