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