Don't try to look offhook with channel banks & Loopstart (bug #2362), also make indiv...
[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-2004, Digium, Inc.
7  *
8  * Mark Spencer <markster@digium.com>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <unistd.h>
15 #include <stdlib.h>
16 #include <sys/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__) || defined( __NetBSD__ )
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(NULL);
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                 if (!cfg)
1490                         ast_log(LOG_WARNING, "Unable to open specified master config file '%s', using builtin defaults\n", ast_config_AST_CONFIG_FILE);
1491         } else {
1492             cfg = ast_load(config);
1493         }
1494
1495         /* init with buildtime config */
1496         strncpy((char *)ast_config_AST_CONFIG_DIR,AST_CONFIG_DIR,sizeof(ast_config_AST_CONFIG_DIR)-1);
1497         strncpy((char *)ast_config_AST_SPOOL_DIR,AST_SPOOL_DIR,sizeof(ast_config_AST_SPOOL_DIR)-1);
1498         strncpy((char *)ast_config_AST_MODULE_DIR,AST_MODULE_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1499         strncpy((char *)ast_config_AST_VAR_DIR,AST_VAR_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1500         strncpy((char *)ast_config_AST_LOG_DIR,AST_LOG_DIR,sizeof(ast_config_AST_LOG_DIR)-1);
1501         strncpy((char *)ast_config_AST_AGI_DIR,AST_AGI_DIR,sizeof(ast_config_AST_AGI_DIR)-1);
1502         strncpy((char *)ast_config_AST_DB,AST_DB,sizeof(ast_config_AST_DB)-1);
1503         strncpy((char *)ast_config_AST_KEY_DIR,AST_KEY_DIR,sizeof(ast_config_AST_KEY_DIR)-1);
1504         strncpy((char *)ast_config_AST_PID,AST_PID,sizeof(ast_config_AST_PID)-1);
1505         strncpy((char *)ast_config_AST_SOCKET,AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1);
1506         strncpy((char *)ast_config_AST_RUN_DIR,AST_RUN_DIR,sizeof(ast_config_AST_RUN_DIR)-1);
1507         
1508         /* no asterisk.conf? no problem, use buildtime config! */
1509         if (!cfg) {
1510             return;
1511         }
1512         v = ast_variable_browse(cfg, "directories");
1513         while(v) {
1514                 if (!strcasecmp(v->name, "astetcdir")) {
1515                     strncpy((char *)ast_config_AST_CONFIG_DIR,v->value,sizeof(ast_config_AST_CONFIG_DIR)-1);
1516                 } else if (!strcasecmp(v->name, "astspooldir")) {
1517                     strncpy((char *)ast_config_AST_SPOOL_DIR,v->value,sizeof(ast_config_AST_SPOOL_DIR)-1);
1518                 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1519                     strncpy((char *)ast_config_AST_VAR_DIR,v->value,sizeof(ast_config_AST_VAR_DIR)-1);
1520                     snprintf((char *)ast_config_AST_DB,sizeof(ast_config_AST_DB),"%s/%s",v->value,"astdb");    
1521                 } else if (!strcasecmp(v->name, "astlogdir")) {
1522                     strncpy((char *)ast_config_AST_LOG_DIR,v->value,sizeof(ast_config_AST_LOG_DIR)-1);
1523                 } else if (!strcasecmp(v->name, "astagidir")) {
1524                     strncpy((char *)ast_config_AST_AGI_DIR,v->value,sizeof(ast_config_AST_AGI_DIR)-1);
1525                 } else if (!strcasecmp(v->name, "astrundir")) {
1526                     snprintf((char *)ast_config_AST_PID,sizeof(ast_config_AST_PID),"%s/%s",v->value,"asterisk.pid");    
1527                     snprintf((char *)ast_config_AST_SOCKET,sizeof(ast_config_AST_SOCKET),"%s/%s",v->value,"asterisk.ctl");    
1528                     strncpy((char *)ast_config_AST_RUN_DIR,v->value,sizeof(ast_config_AST_RUN_DIR)-1);
1529                 } else if (!strcasecmp(v->name, "astmoddir")) {
1530                     strncpy((char *)ast_config_AST_MODULE_DIR,v->value,sizeof(ast_config_AST_MODULE_DIR)-1);
1531                 }
1532                 v = v->next;
1533         }
1534         ast_destroy(cfg);
1535 }
1536
1537 int main(int argc, char *argv[])
1538 {
1539         int c;
1540         char filename[80] = "";
1541         char hostname[256];
1542         char tmp[80];
1543         char * xarg = NULL;
1544         int x;
1545         FILE *f;
1546         sigset_t sigs;
1547         int num;
1548         char *buf;
1549         char *runuser=NULL, *rungroup=NULL;
1550
1551         /* Remember original args for restart */
1552         if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1553                 fprintf(stderr, "Truncating argument size to %d\n", (int)(sizeof(_argv) / sizeof(_argv[0])) - 1);
1554                 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1555         }
1556         for (x=0;x<argc;x++)
1557                 _argv[x] = argv[x];
1558         _argv[x] = NULL;
1559
1560         /* if the progname is rasterisk consider it a remote console */
1561         if ( argv[0] && (strstr(argv[0], "rasterisk")) != NULL)  {
1562                 option_remote++;
1563                 option_nofork++;
1564         }
1565         if (gethostname(hostname, sizeof(hostname)))
1566                 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
1567         ast_mainpid = getpid();
1568         ast_ulaw_init();
1569         ast_alaw_init();
1570         callerid_init();
1571         ast_utils_init();
1572         tdd_init();
1573         if (getenv("HOME")) 
1574                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1575         /* Check if we're root */
1576         /*
1577         if (geteuid()) {
1578                 ast_log(LOG_ERROR, "Must be run as root\n");
1579                 exit(1);
1580         }
1581         */
1582         /* Check for options */
1583         while((c=getopt(argc, argv, "hfdvVqprRgcinx:U:G:C:")) != -1) {
1584                 switch(c) {
1585                 case 'd':
1586                         option_debug++;
1587                         option_nofork++;
1588                         break;
1589                 case 'c':
1590                         option_console++;
1591                         option_nofork++;
1592                         break;
1593                 case 'f':
1594                         option_nofork++;
1595                         break;
1596                 case 'n':
1597                         option_nocolor++;
1598                         break;
1599                 case 'r':
1600                         option_remote++;
1601                         option_nofork++;
1602                         break;
1603                 case 'R':
1604                         option_remote++;
1605                         option_nofork++;
1606                         option_reconnect++;
1607                         break;
1608                 case 'p':
1609                         option_highpriority++;
1610                         break;
1611                 case 'v':
1612                         option_verbose++;
1613                         option_nofork++;
1614                         break;
1615                 case 'q':
1616                         option_quiet++;
1617                         break;
1618                 case 'x':
1619                         option_exec++;
1620                         xarg = optarg;
1621                         break;
1622                 case 'C':
1623                         strncpy((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE) - 1);
1624                         option_overrideconfig++;
1625                         break;
1626                 case 'i':
1627                         option_initcrypto++;
1628                         break;
1629                 case'g':
1630                         option_dumpcore++;
1631                         break;
1632                 case 'h':
1633                         show_cli_help();
1634                         exit(0);
1635                 case 'V':
1636                         show_version();
1637                         exit(0);
1638                 case 'U':
1639                         runuser = optarg;
1640                         break;
1641                 case 'G':
1642                         rungroup = optarg;
1643                         break;
1644                 case '?':
1645                         exit(1);
1646                 }
1647         }
1648
1649         if (option_dumpcore) {
1650                 struct rlimit l;
1651                 memset(&l, 0, sizeof(l));
1652                 l.rlim_cur = RLIM_INFINITY;
1653                 l.rlim_max = RLIM_INFINITY;
1654                 if (setrlimit(RLIMIT_CORE, &l)) {
1655                         ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
1656                 }
1657         }
1658
1659         if (rungroup) {
1660                 struct group *gr;
1661                 gr = getgrnam(rungroup);
1662                 if (!gr) {
1663                         ast_log(LOG_WARNING, "No such group '%s'!\n", rungroup);
1664                         exit(1);
1665                 }
1666                 if (setgid(gr->gr_gid)) {
1667                         ast_log(LOG_WARNING, "Unable to setgid to %d (%s)\n", gr->gr_gid, rungroup);
1668                         exit(1);
1669                 }
1670                 if (option_verbose)
1671                         ast_verbose("Running as group '%s'\n", rungroup);
1672         }
1673
1674         if (set_priority(option_highpriority)) {
1675                 exit(1);
1676         }
1677         if (runuser) {
1678                 struct passwd *pw;
1679                 pw = getpwnam(runuser);
1680                 if (!pw) {
1681                         ast_log(LOG_WARNING, "No such user '%s'!\n", runuser);
1682                         exit(1);
1683                 }
1684                 if (setuid(pw->pw_uid)) {
1685                         ast_log(LOG_WARNING, "Unable to setuid to %d (%s)\n", pw->pw_uid, runuser);
1686                         exit(1);
1687                 }
1688                 if (option_verbose)
1689                         ast_verbose("Running as user '%s'\n", runuser);
1690         }
1691
1692         term_init();
1693         printf(term_end());
1694         fflush(stdout);
1695
1696         /* Test recursive mutex locking. */
1697         if (test_for_thread_safety())
1698                 ast_verbose("Warning! Asterisk is not thread safe.\n");
1699
1700         if (option_console && !option_verbose) 
1701                 ast_verbose("[ Reading Master Configuration ]");
1702         ast_readconfig();
1703
1704         if (option_console && !option_verbose) 
1705                 ast_verbose("[ Initializing Custom Configuration Options]");
1706         /* custom config setup */
1707         register_config_cli();
1708         read_ast_cust_config();
1709         
1710
1711         if (option_console) {
1712                 if (el_hist == NULL || el == NULL)
1713                         ast_el_initialize();
1714
1715                 if (!ast_strlen_zero(filename))
1716                         ast_el_read_history(filename);
1717         }
1718
1719         if (ast_tryconnect()) {
1720                 /* One is already running */
1721                 if (option_remote) {
1722                         if (option_exec) {
1723                                 ast_remotecontrol(xarg);
1724                                 quit_handler(0, 0, 0, 0);
1725                                 exit(0);
1726                         }
1727                         printf(term_quit());
1728                         ast_register_verbose(console_verboser);
1729                         WELCOME_MESSAGE;
1730                         ast_remotecontrol(NULL);
1731                         quit_handler(0, 0, 0, 0);
1732                         exit(0);
1733                 } else {
1734                         ast_log(LOG_ERROR, "Asterisk already running on %s.  Use 'asterisk -r' to connect.\n", (char *)ast_config_AST_SOCKET);
1735                         printf(term_quit());
1736                         exit(1);
1737                 }
1738         } else if (option_remote || option_exec) {
1739                 ast_log(LOG_ERROR, "Unable to connect to remote asterisk\n");
1740                 printf(term_quit());
1741                 exit(1);
1742         }
1743         /* Blindly write pid file since we couldn't connect */
1744         unlink((char *)ast_config_AST_PID);
1745         f = fopen((char *)ast_config_AST_PID, "w");
1746         if (f) {
1747                 fprintf(f, "%d\n", getpid());
1748                 fclose(f);
1749         } else
1750                 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1751
1752         if (!option_verbose && !option_debug && !option_nofork && !option_console) {
1753                 daemon(0,0);
1754                 /* Blindly re-write pid file since we are forking */
1755                 unlink((char *)ast_config_AST_PID);
1756                 f = fopen((char *)ast_config_AST_PID, "w");
1757                 if (f) {
1758                         fprintf(f, "%d\n", getpid());
1759                         fclose(f);
1760                 } else
1761                         ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1762         }
1763
1764         ast_makesocket();
1765         sigemptyset(&sigs);
1766         sigaddset(&sigs, SIGHUP);
1767         sigaddset(&sigs, SIGTERM);
1768         sigaddset(&sigs, SIGINT);
1769         sigaddset(&sigs, SIGPIPE);
1770         sigaddset(&sigs, SIGWINCH);
1771         pthread_sigmask(SIG_BLOCK, &sigs, NULL);
1772         if (option_console || option_verbose || option_remote)
1773                 ast_register_verbose(console_verboser);
1774         /* Print a welcome message if desired */
1775         if (option_verbose || option_console) {
1776                 WELCOME_MESSAGE;
1777         }
1778         if (option_console && !option_verbose) 
1779                 ast_verbose("[ Booting...");
1780
1781         signal(SIGURG, urg_handler);
1782         signal(SIGINT, __quit_handler);
1783         signal(SIGTERM, __quit_handler);
1784         signal(SIGHUP, hup_handler);
1785         signal(SIGCHLD, child_handler);
1786         signal(SIGPIPE, SIG_IGN);
1787
1788         if (init_logger()) {
1789                 printf(term_quit());
1790                 exit(1);
1791         }
1792         if (init_manager()) {
1793                 printf(term_quit());
1794                 exit(1);
1795         }
1796         ast_rtp_init();
1797         if (ast_image_init()) {
1798                 printf(term_quit());
1799                 exit(1);
1800         }
1801         if (ast_file_init()) {
1802                 printf(term_quit());
1803                 exit(1);
1804         }
1805         if (load_pbx()) {
1806                 printf(term_quit());
1807                 exit(1);
1808         }
1809         if (load_modules()) {
1810                 printf(term_quit());
1811                 exit(1);
1812         }
1813         if (init_framer()) {
1814                 printf(term_quit());
1815                 exit(1);
1816         }
1817         if (astdb_init()) {
1818                 printf(term_quit());
1819                 exit(1);
1820         }
1821         if (ast_enum_init()) {
1822                 printf(term_quit());
1823                 exit(1);
1824         }
1825         /* reload logger in case a custom config handler binded to logger.conf*/
1826         reload_logger(0);
1827
1828         /* We might have the option of showing a console, but for now just
1829            do nothing... */
1830         if (option_console && !option_verbose)
1831                 ast_verbose(" ]\n");
1832         if (option_verbose || option_console)
1833                 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
1834         if (option_nofork)
1835                 consolethread = pthread_self();
1836         fully_booted = 1;
1837         pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
1838 #ifdef __AST_DEBUG_MALLOC
1839         __ast_mm_init();
1840 #endif  
1841         time(&ast_startuptime);
1842         ast_cli_register(&astshutdownnow);
1843         ast_cli_register(&astshutdowngracefully);
1844         ast_cli_register(&astrestartnow);
1845         ast_cli_register(&astrestartgracefully);
1846         ast_cli_register(&astrestartwhenconvenient);
1847         ast_cli_register(&astshutdownwhenconvenient);
1848         ast_cli_register(&aborthalt);
1849         ast_cli_register(&astbang);
1850         if (option_console) {
1851                 /* Console stuff now... */
1852                 /* Register our quit function */
1853                 char title[256];
1854                 set_icon("Asterisk");
1855                 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, ast_mainpid);
1856                 set_title(title);
1857             ast_cli_register(&quit);
1858             ast_cli_register(&astexit);
1859
1860                 for (;;) {
1861                         buf = (char *)el_gets(el, &num);
1862                         if (buf) {
1863                                 if (buf[strlen(buf)-1] == '\n')
1864                                         buf[strlen(buf)-1] = '\0';
1865
1866                                 consolehandler((char *)buf);
1867                         } else {
1868                                 if (option_remote)
1869                                         ast_cli(STDOUT_FILENO, "\nUse EXIT or QUIT to exit the asterisk console\n");
1870                         }
1871                 }
1872
1873         } else {
1874                 /* Do nothing */
1875                 for(;;) 
1876                         poll(NULL,0, -1);
1877         }
1878         return 0;
1879 }