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