Update chanelog
[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] = AST_TMP_DIR;
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
679 static int ast_all_zeros(char *s)
680 {
681         while(*s) {
682                 if (*s > 32)
683                         return 0;
684                 s++;  
685         }
686         return 1;
687 }
688
689 static void consolehandler(char *s)
690 {
691         printf(term_end());
692         fflush(stdout);
693         /* Called when readline data is available */
694         if (s && !ast_all_zeros(s))
695                 ast_el_add_history(s);
696         /* Give the console access to the shell */
697         if (s) {
698                 /* The real handler for bang */
699                 if (s[0] == '!') {
700                         if (s[1])
701                                 ast_safe_system(s+1);
702                         else
703                                 ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
704                 } else 
705                 ast_cli_command(STDOUT_FILENO, s);
706         } else
707                 fprintf(stdout, "\nUse \"quit\" to exit\n");
708 }
709
710 static int remoteconsolehandler(char *s)
711 {
712         int ret = 0;
713         /* Called when readline data is available */
714         if (s && !ast_all_zeros(s))
715                 ast_el_add_history(s);
716         /* Give the console access to the shell */
717         if (s) {
718                 /* The real handler for bang */
719                 if (s[0] == '!') {
720                         if (s[1])
721                                 ast_safe_system(s+1);
722                         else
723                                 ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
724                         ret = 1;
725                 }
726                 if ((strncasecmp(s, "quit", 4) == 0 || strncasecmp(s, "exit", 4) == 0) &&
727                     (s[4] == '\0' || isspace(s[4]))) {
728                         quit_handler(0, 0, 0, 0);
729                         ret = 1;
730                 }
731         } else
732                 fprintf(stdout, "\nUse \"quit\" to exit\n");
733
734         return ret;
735 }
736
737 static char quit_help[] = 
738 "Usage: quit\n"
739 "       Exits Asterisk.\n";
740
741 static char abort_halt_help[] = 
742 "Usage: abort shutdown\n"
743 "       Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
744 "       call operations.\n";
745
746 static char shutdown_now_help[] = 
747 "Usage: stop now\n"
748 "       Shuts down a running Asterisk immediately, hanging up all active calls .\n";
749
750 static char shutdown_gracefully_help[] = 
751 "Usage: stop gracefully\n"
752 "       Causes Asterisk to not accept new calls, and exit when all\n"
753 "       active calls have terminated normally.\n";
754
755 static char shutdown_when_convenient_help[] = 
756 "Usage: stop when convenient\n"
757 "       Causes Asterisk to perform a shutdown when all active calls have ended.\n";
758
759 static char restart_now_help[] = 
760 "Usage: restart now\n"
761 "       Causes Asterisk to hangup all calls and exec() itself performing a cold.\n"
762 "       restart.\n";
763
764 static char restart_gracefully_help[] = 
765 "Usage: restart gracefully\n"
766 "       Causes Asterisk to stop accepting new calls and exec() itself performing a cold.\n"
767 "       restart when all active calls have ended.\n";
768
769 static char restart_when_convenient_help[] = 
770 "Usage: restart when convenient\n"
771 "       Causes Asterisk to perform a cold restart when all active calls have ended.\n";
772
773 static char bang_help[] =
774 "Usage: !<command>\n"
775 "       Executes a given shell command\n";
776
777 #if 0
778 static int handle_quit(int fd, int argc, char *argv[])
779 {
780         if (argc != 1)
781                 return RESULT_SHOWUSAGE;
782         quit_handler(0, 0, 1, 0);
783         return RESULT_SUCCESS;
784 }
785 #endif
786
787 static int no_more_quit(int fd, int argc, char *argv[])
788 {
789         if (argc != 1)
790                 return RESULT_SHOWUSAGE;
791         ast_cli(fd, "The QUIT and EXIT commands may no longer be used to shutdown the PBX.\n"
792                     "Please use STOP NOW instead, if you wish to shutdown the PBX.\n");
793         return RESULT_SUCCESS;
794 }
795
796 static int handle_shutdown_now(int fd, int argc, char *argv[])
797 {
798         if (argc != 2)
799                 return RESULT_SHOWUSAGE;
800         quit_handler(0, 0 /* Not nice */, 1 /* safely */, 0 /* not restart */);
801         return RESULT_SUCCESS;
802 }
803
804 static int handle_shutdown_gracefully(int fd, int argc, char *argv[])
805 {
806         if (argc != 2)
807                 return RESULT_SHOWUSAGE;
808         quit_handler(0, 1 /* nicely */, 1 /* safely */, 0 /* no restart */);
809         return RESULT_SUCCESS;
810 }
811
812 static int handle_shutdown_when_convenient(int fd, int argc, char *argv[])
813 {
814         if (argc != 3)
815                 return RESULT_SHOWUSAGE;
816         quit_handler(0, 2 /* really nicely */, 1 /* safely */, 0 /* don't restart */);
817         return RESULT_SUCCESS;
818 }
819
820 static int handle_restart_now(int fd, int argc, char *argv[])
821 {
822         if (argc != 2)
823                 return RESULT_SHOWUSAGE;
824         quit_handler(0, 0 /* not nicely */, 1 /* safely */, 1 /* restart */);
825         return RESULT_SUCCESS;
826 }
827
828 static int handle_restart_gracefully(int fd, int argc, char *argv[])
829 {
830         if (argc != 2)
831                 return RESULT_SHOWUSAGE;
832         quit_handler(0, 1 /* nicely */, 1 /* safely */, 1 /* restart */);
833         return RESULT_SUCCESS;
834 }
835
836 static int handle_restart_when_convenient(int fd, int argc, char *argv[])
837 {
838         if (argc != 3)
839                 return RESULT_SHOWUSAGE;
840         quit_handler(0, 2 /* really nicely */, 1 /* safely */, 1 /* restart */);
841         return RESULT_SUCCESS;
842 }
843
844 static int handle_abort_halt(int fd, int argc, char *argv[])
845 {
846         if (argc != 2)
847                 return RESULT_SHOWUSAGE;
848         ast_cancel_shutdown();
849         shuttingdown = 0;
850         return RESULT_SUCCESS;
851 }
852
853 static int handle_bang(int fd, int argc, char *argv[])
854 {
855         return RESULT_SUCCESS;
856 }
857
858 #define ASTERISK_PROMPT "*CLI> "
859
860 #define ASTERISK_PROMPT2 "%s*CLI> "
861
862 static struct ast_cli_entry aborthalt = { { "abort", "halt", NULL }, handle_abort_halt, "Cancel a running halt", abort_halt_help };
863
864 static struct ast_cli_entry quit =      { { "quit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
865 static struct ast_cli_entry astexit =   { { "exit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
866
867 static struct ast_cli_entry astshutdownnow =    { { "stop", "now", NULL }, handle_shutdown_now, "Shut down Asterisk immediately", shutdown_now_help };
868 static struct ast_cli_entry astshutdowngracefully =     { { "stop", "gracefully", NULL }, handle_shutdown_gracefully, "Gracefully shut down Asterisk", shutdown_gracefully_help };
869 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 };
870 static struct ast_cli_entry astrestartnow =     { { "restart", "now", NULL }, handle_restart_now, "Restart Asterisk immediately", restart_now_help };
871 static struct ast_cli_entry astrestartgracefully =      { { "restart", "gracefully", NULL }, handle_restart_gracefully, "Restart Asterisk gracefully", restart_gracefully_help };
872 static struct ast_cli_entry astrestartwhenconvenient=   { { "restart", "when", "convenient", NULL }, handle_restart_when_convenient, "Restart Asterisk at empty call volume", restart_when_convenient_help };
873 static struct ast_cli_entry astbang = { { "!", NULL }, handle_bang, "Execute a shell command", bang_help };
874
875 static int ast_el_read_char(EditLine *el, char *cp)
876 {
877         int num_read=0;
878         int lastpos=0;
879         struct pollfd fds[2];
880         int res;
881         int max;
882         char buf[512];
883
884         for (;;) {
885                 max = 1;
886                 fds[0].fd = ast_consock;
887                 fds[0].events = POLLIN;
888                 if (!option_exec) {
889                         fds[1].fd = STDIN_FILENO;
890                         fds[1].events = POLLIN;
891                         max++;
892                 }
893                 res = poll(fds, max, -1);
894                 if (res < 0) {
895                         if (errno == EINTR)
896                                 continue;
897                         ast_log(LOG_ERROR, "poll failed: %s\n", strerror(errno));
898                         break;
899                 }
900
901                 if (!option_exec && fds[1].revents) {
902                         num_read = read(STDIN_FILENO, cp, 1);
903                         if (num_read < 1) {
904                                 break;
905                         } else 
906                                 return (num_read);
907                 }
908                 if (fds[0].revents) {
909                         res = read(ast_consock, buf, sizeof(buf) - 1);
910                         /* if the remote side disappears exit */
911                         if (res < 1) {
912                                 fprintf(stderr, "\nDisconnected from Asterisk server\n");
913                                 if (!option_reconnect) {
914                                         quit_handler(0, 0, 0, 0);
915                                 } else {
916                                         int tries;
917                                         int reconnects_per_second = 20;
918                                         fprintf(stderr, "Attempting to reconnect for 30 seconds\n");
919                                         for (tries=0;tries<30 * reconnects_per_second;tries++) {
920                                                 if (ast_tryconnect()) {
921                                                         fprintf(stderr, "Reconnect succeeded after %.3f seconds\n", 1.0 / reconnects_per_second * tries);
922                                                         printf(term_quit());
923                                                         WELCOME_MESSAGE;
924                                                         break;
925                                                 } else {
926                                                         usleep(1000000 / reconnects_per_second);
927                                                 }
928                                         }
929                                         if (tries >= 30) {
930                                                 fprintf(stderr, "Failed to reconnect for 30 seconds.  Quitting.\n");
931                                                 quit_handler(0, 0, 0, 0);
932                                         }
933                                 }
934                         }
935
936                         buf[res] = '\0';
937
938                         if (!option_exec && !lastpos)
939                                 write(STDOUT_FILENO, "\r", 1);
940                         write(STDOUT_FILENO, buf, res);
941                         if ((buf[res-1] == '\n') || (buf[res-2] == '\n')) {
942                                 *cp = CC_REFRESH;
943                                 return(1);
944                         } else {
945                                 lastpos = 1;
946                         }
947                 }
948         }
949
950         *cp = '\0';
951         return (0);
952 }
953
954 static char *cli_prompt(EditLine *el)
955 {
956         static char prompt[200];
957         char *pfmt;
958         int color_used=0;
959         char term_code[20];
960
961         if ((pfmt = getenv("ASTERISK_PROMPT"))) {
962                 char *t = pfmt, *p = prompt;
963                 memset(prompt, 0, sizeof(prompt));
964                 while (*t != '\0' && *p < sizeof(prompt)) {
965                         if (*t == '%') {
966                                 char hostname[256];
967                                 int i;
968                                 struct timeval tv;
969                                 struct tm tm;
970 #ifdef linux
971                                 FILE *LOADAVG;
972 #endif
973                                 int fgcolor = COLOR_WHITE, bgcolor = COLOR_BLACK;
974
975                                 t++;
976                                 switch (*t) {
977                                         case 'C': /* color */
978                                                 t++;
979                                                 if (sscanf(t, "%d;%d%n", &fgcolor, &bgcolor, &i) == 2) {
980                                                         strncat(p, term_color_code(term_code, fgcolor, bgcolor, sizeof(term_code)),sizeof(prompt) - strlen(prompt) - 1);
981                                                         t += i - 1;
982                                                 } else if (sscanf(t, "%d%n", &fgcolor, &i) == 1) {
983                                                         strncat(p, term_color_code(term_code, fgcolor, 0, sizeof(term_code)),sizeof(prompt) - strlen(prompt) - 1);
984                                                         t += i - 1;
985                                                 }
986
987                                                 /* If the color has been reset correctly, then there's no need to reset it later */
988                                                 if ((fgcolor == COLOR_WHITE) && (bgcolor == COLOR_BLACK)) {
989                                                         color_used = 0;
990                                                 } else {
991                                                         color_used = 1;
992                                                 }
993                                                 break;
994                                         case 'd': /* date */
995                                                 memset(&tm, 0, sizeof(struct tm));
996                                                 gettimeofday(&tv, NULL);
997                                                 if (localtime_r(&(tv.tv_sec), &tm)) {
998                                                         strftime(p, sizeof(prompt) - strlen(prompt), "%Y-%m-%d", &tm);
999                                                 }
1000                                                 break;
1001                                         case 'h': /* hostname */
1002                                                 if (!gethostname(hostname, sizeof(hostname) - 1)) {
1003                                                         strncat(p, hostname, sizeof(prompt) - strlen(prompt) - 1);
1004                                                 } else {
1005                                                         strncat(p, "localhost", sizeof(prompt) - strlen(prompt) - 1);
1006                                                 }
1007                                                 break;
1008                                         case 'H': /* short hostname */
1009                                                 if (!gethostname(hostname, sizeof(hostname) - 1)) {
1010                                                         for (i=0;i<sizeof(hostname);i++) {
1011                                                                 if (hostname[i] == '.') {
1012                                                                         hostname[i] = '\0';
1013                                                                         break;
1014                                                                 }
1015                                                         }
1016                                                         strncat(p, hostname, sizeof(prompt) - strlen(prompt) - 1);
1017                                                 } else {
1018                                                         strncat(p, "localhost", sizeof(prompt) - strlen(prompt) - 1);
1019                                                 }
1020                                                 break;
1021 #ifdef linux
1022                                         case 'l': /* load avg */
1023                                                 t++;
1024                                                 if ((LOADAVG = fopen("/proc/loadavg", "r"))) {
1025                                                         float avg1, avg2, avg3;
1026                                                         int actproc, totproc, npid, which;
1027                                                         fscanf(LOADAVG, "%f %f %f %d/%d %d",
1028                                                                 &avg1, &avg2, &avg3, &actproc, &totproc, &npid);
1029                                                         if (sscanf(t, "%d", &which) == 1) {
1030                                                                 switch (which) {
1031                                                                         case 1:
1032                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg1);
1033                                                                                 break;
1034                                                                         case 2:
1035                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg2);
1036                                                                                 break;
1037                                                                         case 3:
1038                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg3);
1039                                                                                 break;
1040                                                                         case 4:
1041                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%d/%d", actproc, totproc);
1042                                                                                 break;
1043                                                                         case 5:
1044                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%d", npid);
1045                                                                                 break;
1046                                                                 }
1047                                                         }
1048                                                 }
1049                                                 break;
1050 #endif
1051                                         case 't': /* time */
1052                                                 memset(&tm, 0, sizeof(struct tm));
1053                                                 gettimeofday(&tv, NULL);
1054                                                 if (localtime_r(&(tv.tv_sec), &tm)) {
1055                                                         strftime(p, sizeof(prompt) - strlen(prompt), "%H:%M:%S", &tm);
1056                                                 }
1057                                                 break;
1058                                         case '#': /* process console or remote? */
1059                                                 if (! option_remote) {
1060                                                         strncat(p, "#", sizeof(prompt) - strlen(prompt) - 1);
1061                                                 } else {
1062                                                         strncat(p, ">", sizeof(prompt) - strlen(prompt) - 1);
1063                                                 }
1064                                                 break;
1065                                         case '%': /* literal % */
1066                                                 strncat(p, "%", sizeof(prompt) - strlen(prompt) - 1);
1067                                                 break;
1068                                         case '\0': /* % is last character - prevent bug */
1069                                                 t--;
1070                                                 break;
1071                                 }
1072                                 while (*p != '\0') {
1073                                         p++;
1074                                 }
1075                                 t++;
1076                         } else {
1077                                 *p = *t;
1078                                 p++;
1079                                 t++;
1080                         }
1081                 }
1082                 if (color_used) {
1083                         /* Force colors back to normal at end */
1084                         term_color_code(term_code, COLOR_WHITE, COLOR_BLACK, sizeof(term_code));
1085                         if (strlen(term_code) > sizeof(prompt) - strlen(prompt)) {
1086                                 strncat(prompt + sizeof(prompt) - strlen(term_code) - 1, term_code, strlen(term_code));
1087                         } else {
1088                                 strncat(p, term_code, sizeof(term_code));
1089                         }
1090                 }
1091         } else if (remotehostname)
1092                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT2, remotehostname);
1093         else
1094                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT);
1095
1096         return(prompt); 
1097 }
1098
1099 static char **ast_el_strtoarr(char *buf)
1100 {
1101         char **match_list = NULL, *retstr;
1102         size_t match_list_len;
1103         int matches = 0;
1104
1105         match_list_len = 1;
1106         while ( (retstr = strsep(&buf, " ")) != NULL) {
1107
1108                 if (!strcmp(retstr, AST_CLI_COMPLETE_EOF))
1109                         break;
1110                 if (matches + 1 >= match_list_len) {
1111                         match_list_len <<= 1;
1112                         match_list = realloc(match_list, match_list_len * sizeof(char *));
1113                 }
1114
1115                 match_list[matches++] = strdup(retstr);
1116         }
1117
1118         if (!match_list)
1119                 return (char **) NULL;
1120
1121         if (matches>= match_list_len)
1122                 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
1123
1124         match_list[matches] = (char *) NULL;
1125
1126         return match_list;
1127 }
1128
1129 static int ast_el_sort_compare(const void *i1, const void *i2)
1130 {
1131         char *s1, *s2;
1132
1133         s1 = ((char **)i1)[0];
1134         s2 = ((char **)i2)[0];
1135
1136         return strcasecmp(s1, s2);
1137 }
1138
1139 static int ast_cli_display_match_list(char **matches, int len, int max)
1140 {
1141         int i, idx, limit, count;
1142         int screenwidth = 0;
1143         int numoutput = 0, numoutputline = 0;
1144
1145         screenwidth = ast_get_termcols(STDOUT_FILENO);
1146
1147         /* find out how many entries can be put on one line, with two spaces between strings */
1148         limit = screenwidth / (max + 2);
1149         if (limit == 0)
1150                 limit = 1;
1151
1152         /* how many lines of output */
1153         count = len / limit;
1154         if (count * limit < len)
1155                 count++;
1156
1157         idx = 1;
1158
1159         qsort(&matches[0], (size_t)(len + 1), sizeof(char *), ast_el_sort_compare);
1160
1161         for (; count > 0; count--) {
1162                 numoutputline = 0;
1163                 for (i=0; i < limit && matches[idx]; i++, idx++) {
1164
1165                         /* Don't print dupes */
1166                         if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
1167                                 i--;
1168                                 free(matches[idx]);
1169                                 matches[idx] = NULL;
1170                                 continue;
1171                         }
1172
1173                         numoutput++;
1174                         numoutputline++;
1175                         fprintf(stdout, "%-*s  ", max, matches[idx]);
1176                         free(matches[idx]);
1177                         matches[idx] = NULL;
1178                 }
1179                 if (numoutputline > 0)
1180                         fprintf(stdout, "\n");
1181         }
1182
1183         return numoutput;
1184 }
1185
1186
1187 static char *cli_complete(EditLine *el, int ch)
1188 {
1189         int len=0;
1190         char *ptr;
1191         int nummatches = 0;
1192         char **matches;
1193         int retval = CC_ERROR;
1194         char buf[2048];
1195         int res;
1196
1197         LineInfo *lf = (LineInfo *)el_line(el);
1198
1199         *(char *)lf->cursor = '\0';
1200         ptr = (char *)lf->cursor;
1201         if (ptr) {
1202                 while (ptr > lf->buffer) {
1203                         if (isspace(*ptr)) {
1204                                 ptr++;
1205                                 break;
1206                         }
1207                         ptr--;
1208                 }
1209         }
1210
1211         len = lf->cursor - ptr;
1212
1213         if (option_remote) {
1214                 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr); 
1215                 fdprint(ast_consock, buf);
1216                 res = read(ast_consock, buf, sizeof(buf));
1217                 buf[res] = '\0';
1218                 nummatches = atoi(buf);
1219
1220                 if (nummatches > 0) {
1221                         char *mbuf;
1222                         int mlen = 0, maxmbuf = 2048;
1223                         /* Start with a 2048 byte buffer */
1224                         mbuf = malloc(maxmbuf);
1225                         if (!mbuf)
1226                                 return (char *)(CC_ERROR);
1227                         snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr); 
1228                         fdprint(ast_consock, buf);
1229                         res = 0;
1230                         mbuf[0] = '\0';
1231                         while (!strstr(mbuf, AST_CLI_COMPLETE_EOF) && res != -1) {
1232                                 if (mlen + 1024 > maxmbuf) {
1233                                         /* Every step increment buffer 1024 bytes */
1234                                         maxmbuf += 1024;
1235                                         mbuf = realloc(mbuf, maxmbuf);
1236                                         if (!mbuf)
1237                                                 return (char *)(CC_ERROR);
1238                                 }
1239                                 /* Only read 1024 bytes at a time */
1240                                 res = read(ast_consock, mbuf + mlen, 1024);
1241                                 if (res > 0)
1242                                         mlen += res;
1243                         }
1244                         mbuf[mlen] = '\0';
1245
1246                         matches = ast_el_strtoarr(mbuf);
1247                         free(mbuf);
1248                 } else
1249                         matches = (char **) NULL;
1250
1251
1252         } else {
1253
1254                 nummatches = ast_cli_generatornummatches((char *)lf->buffer,ptr);
1255                 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
1256         }
1257
1258         if (matches) {
1259                 int i;
1260                 int matches_num, maxlen, match_len;
1261
1262                 if (matches[0][0] != '\0') {
1263                         el_deletestr(el, (int) len);
1264                         el_insertstr(el, matches[0]);
1265                         retval = CC_REFRESH;
1266                 }
1267
1268                 if (nummatches == 1) {
1269                         /* Found an exact match */
1270                         el_insertstr(el, " ");
1271                         retval = CC_REFRESH;
1272                 } else {
1273                         /* Must be more than one match */
1274                         for (i=1, maxlen=0; matches[i]; i++) {
1275                                 match_len = strlen(matches[i]);
1276                                 if (match_len > maxlen)
1277                                         maxlen = match_len;
1278                         }
1279                         matches_num = i - 1;
1280                         if (matches_num >1) {
1281                                 fprintf(stdout, "\n");
1282                                 ast_cli_display_match_list(matches, nummatches, maxlen);
1283                                 retval = CC_REDISPLAY;
1284                         } else { 
1285                                 el_insertstr(el," ");
1286                                 retval = CC_REFRESH;
1287                         }
1288                 }
1289         free(matches);
1290         }
1291
1292         return (char *)(long)retval;
1293 }
1294
1295 static int ast_el_initialize(void)
1296 {
1297         HistEvent ev;
1298         char *editor = getenv("AST_EDITOR");
1299
1300         if (el != NULL)
1301                 el_end(el);
1302         if (el_hist != NULL)
1303                 history_end(el_hist);
1304
1305         el = el_init("asterisk", stdin, stdout, stderr);
1306         el_set(el, EL_PROMPT, cli_prompt);
1307
1308         el_set(el, EL_EDITMODE, 1);             
1309         el_set(el, EL_EDITOR, editor ? editor : "emacs");               
1310         el_hist = history_init();
1311         if (!el || !el_hist)
1312                 return -1;
1313
1314         /* setup history with 100 entries */
1315         history(el_hist, &ev, H_SETSIZE, 100);
1316
1317         el_set(el, EL_HIST, history, el_hist);
1318
1319         el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
1320         /* Bind <tab> to command completion */
1321         el_set(el, EL_BIND, "^I", "ed-complete", NULL);
1322         /* Bind ? to command completion */
1323         el_set(el, EL_BIND, "?", "ed-complete", NULL);
1324         /* Bind ^D to redisplay */
1325         el_set(el, EL_BIND, "^D", "ed-redisplay", NULL);
1326
1327         return 0;
1328 }
1329
1330 static int ast_el_add_history(char *buf)
1331 {
1332         HistEvent ev;
1333
1334         if (el_hist == NULL || el == NULL)
1335                 ast_el_initialize();
1336         if (strlen(buf) > 256)
1337                 return 0;
1338         return (history(el_hist, &ev, H_ENTER, buf));
1339 }
1340
1341 static int ast_el_write_history(char *filename)
1342 {
1343         HistEvent ev;
1344
1345         if (el_hist == NULL || el == NULL)
1346                 ast_el_initialize();
1347
1348         return (history(el_hist, &ev, H_SAVE, filename));
1349 }
1350
1351 static int ast_el_read_history(char *filename)
1352 {
1353         char buf[256];
1354         FILE *f;
1355         int ret = -1;
1356
1357         if (el_hist == NULL || el == NULL)
1358                 ast_el_initialize();
1359
1360         if ((f = fopen(filename, "r")) == NULL)
1361                 return ret;
1362
1363         while (!feof(f)) {
1364                 fgets(buf, sizeof(buf), f);
1365                 if (!strcmp(buf, "_HiStOrY_V2_\n"))
1366                         continue;
1367                 if (ast_all_zeros(buf))
1368                         continue;
1369                 if ((ret = ast_el_add_history(buf)) == -1)
1370                         break;
1371         }
1372         fclose(f);
1373
1374         return ret;
1375 }
1376
1377 static void ast_remotecontrol(char * data)
1378 {
1379         char buf[80];
1380         int res;
1381         char filename[80] = "";
1382         char *hostname;
1383         char *cpid;
1384         char *version;
1385         int pid;
1386         char tmp[80];
1387         char *stringp=NULL;
1388
1389         char *ebuf;
1390         int num = 0;
1391
1392         read(ast_consock, buf, sizeof(buf));
1393         if (data)
1394                 write(ast_consock, data, strlen(data) + 1);
1395         stringp=buf;
1396         hostname = strsep(&stringp, "/");
1397         cpid = strsep(&stringp, "/");
1398         version = strsep(&stringp, "\n");
1399         if (!version)
1400                 version = "<Version Unknown>";
1401         stringp=hostname;
1402         strsep(&stringp, ".");
1403         if (cpid)
1404                 pid = atoi(cpid);
1405         else
1406                 pid = -1;
1407         snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
1408         fdprint(ast_consock, tmp);
1409         snprintf(tmp, sizeof(tmp), "set debug atleast %d", option_debug);
1410         fdprint(ast_consock, tmp);
1411         ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
1412         remotehostname = hostname;
1413         if (getenv("HOME")) 
1414                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1415         if (el_hist == NULL || el == NULL)
1416                 ast_el_initialize();
1417
1418         el_set(el, EL_GETCFN, ast_el_read_char);
1419
1420         if (!ast_strlen_zero(filename))
1421                 ast_el_read_history(filename);
1422
1423         ast_cli_register(&quit);
1424         ast_cli_register(&astexit);
1425 #if 0
1426         ast_cli_register(&astshutdown);
1427 #endif  
1428         if (option_exec && data) {  /* hack to print output then exit if asterisk -rx is used */
1429                 char tempchar;
1430                 struct pollfd fds[0];
1431                 fds[0].fd = ast_consock;
1432                 fds[0].events = POLLIN;
1433                 fds[0].revents = 0;
1434                 while(poll(fds, 1, 100) > 0) {
1435                         ast_el_read_char(el, &tempchar);
1436                 }
1437                 return;
1438         }
1439         for(;;) {
1440                 ebuf = (char *)el_gets(el, &num);
1441
1442                 if (ebuf && !ast_strlen_zero(ebuf)) {
1443                         if (ebuf[strlen(ebuf)-1] == '\n')
1444                                 ebuf[strlen(ebuf)-1] = '\0';
1445                         if (!remoteconsolehandler(ebuf)) {
1446                                 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
1447                                 if (res < 1) {
1448                                         ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
1449                                         break;
1450                                 }
1451                         }
1452                 }
1453         }
1454         printf("\nDisconnected from Asterisk server\n");
1455 }
1456
1457 static int show_version(void)
1458 {
1459         printf("Asterisk " ASTERISK_VERSION "\n");
1460         return 0;
1461 }
1462
1463 static int show_cli_help(void) {
1464         printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 2000-2004, Digium.\n");
1465         printf("Usage: asterisk [OPTIONS]\n");
1466         printf("Valid Options:\n");
1467         printf("   -V              Display version number and exit\n");
1468         printf("   -C <configfile> Use an alternate configuration file\n");
1469         printf("   -G <group>      Run as a group other than the caller\n");
1470         printf("   -U <user>       Run as a user other than the caller\n");
1471         printf("   -c              Provide console CLI\n");
1472         printf("   -d              Enable extra debugging\n");
1473         printf("   -f              Do not fork\n");
1474         printf("   -g              Dump core in case of a crash\n");
1475         printf("   -h              This help screen\n");
1476         printf("   -i              Initializie crypto keys at startup\n");
1477         printf("   -n              Disable console colorization\n");
1478         printf("   -p              Run as pseudo-realtime thread\n");
1479         printf("   -q              Quiet mode (supress output)\n");
1480         printf("   -r              Connect to Asterisk on this machine\n");
1481         printf("   -R              Connect to Asterisk, and attempt to reconnect if disconnected\n");
1482         printf("   -t              Record soundfiles in /tmp and move them where they belong after they are done.\n");
1483         printf("   -v              Increase verbosity (multiple v's = more verbose)\n");
1484         printf("   -x <cmd>        Execute command <cmd> (only valid with -r)\n");
1485         printf("\n");
1486         return 0;
1487 }
1488
1489 static void ast_readconfig(void) {
1490         struct ast_config *cfg;
1491         struct ast_variable *v;
1492         char *config = ASTCONFPATH;
1493
1494         if (option_overrideconfig == 1) {
1495                 cfg = ast_load((char *)ast_config_AST_CONFIG_FILE);
1496                 if (!cfg)
1497                         ast_log(LOG_WARNING, "Unable to open specified master config file '%s', using builtin defaults\n", ast_config_AST_CONFIG_FILE);
1498         } else {
1499                 cfg = ast_load(config);
1500         }
1501
1502         /* init with buildtime config */
1503         strncpy((char *)ast_config_AST_CONFIG_DIR,AST_CONFIG_DIR,sizeof(ast_config_AST_CONFIG_DIR)-1);
1504         strncpy((char *)ast_config_AST_SPOOL_DIR,AST_SPOOL_DIR,sizeof(ast_config_AST_SPOOL_DIR)-1);
1505         strncpy((char *)ast_config_AST_MODULE_DIR,AST_MODULE_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1506         strncpy((char *)ast_config_AST_VAR_DIR,AST_VAR_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1507         strncpy((char *)ast_config_AST_LOG_DIR,AST_LOG_DIR,sizeof(ast_config_AST_LOG_DIR)-1);
1508         strncpy((char *)ast_config_AST_AGI_DIR,AST_AGI_DIR,sizeof(ast_config_AST_AGI_DIR)-1);
1509         strncpy((char *)ast_config_AST_DB,AST_DB,sizeof(ast_config_AST_DB)-1);
1510         strncpy((char *)ast_config_AST_KEY_DIR,AST_KEY_DIR,sizeof(ast_config_AST_KEY_DIR)-1);
1511         strncpy((char *)ast_config_AST_PID,AST_PID,sizeof(ast_config_AST_PID)-1);
1512         strncpy((char *)ast_config_AST_SOCKET,AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1);
1513         strncpy((char *)ast_config_AST_RUN_DIR,AST_RUN_DIR,sizeof(ast_config_AST_RUN_DIR)-1);
1514         
1515         /* no asterisk.conf? no problem, use buildtime config! */
1516         if (!cfg) {
1517                 return;
1518         }
1519         v = ast_variable_browse(cfg, "directories");
1520         while(v) {
1521                 if (!strcasecmp(v->name, "astetcdir")) {
1522                         strncpy((char *)ast_config_AST_CONFIG_DIR,v->value,sizeof(ast_config_AST_CONFIG_DIR)-1);
1523                 } else if (!strcasecmp(v->name, "astspooldir")) {
1524                         strncpy((char *)ast_config_AST_SPOOL_DIR,v->value,sizeof(ast_config_AST_SPOOL_DIR)-1);
1525                 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1526                         strncpy((char *)ast_config_AST_VAR_DIR,v->value,sizeof(ast_config_AST_VAR_DIR)-1);
1527                         snprintf((char *)ast_config_AST_DB,sizeof(ast_config_AST_DB),"%s/%s",v->value,"astdb");    
1528                 } else if (!strcasecmp(v->name, "astlogdir")) {
1529                         strncpy((char *)ast_config_AST_LOG_DIR,v->value,sizeof(ast_config_AST_LOG_DIR)-1);
1530                 } else if (!strcasecmp(v->name, "astagidir")) {
1531                         strncpy((char *)ast_config_AST_AGI_DIR,v->value,sizeof(ast_config_AST_AGI_DIR)-1);
1532                 } else if (!strcasecmp(v->name, "astrundir")) {
1533                         snprintf((char *)ast_config_AST_PID,sizeof(ast_config_AST_PID),"%s/%s",v->value,"asterisk.pid");    
1534                         snprintf((char *)ast_config_AST_SOCKET,sizeof(ast_config_AST_SOCKET),"%s/%s",v->value,"asterisk.ctl");    
1535                         strncpy((char *)ast_config_AST_RUN_DIR,v->value,sizeof(ast_config_AST_RUN_DIR)-1);
1536                 } else if (!strcasecmp(v->name, "astmoddir")) {
1537                         strncpy((char *)ast_config_AST_MODULE_DIR,v->value,sizeof(ast_config_AST_MODULE_DIR)-1);
1538                 }
1539                 v = v->next;
1540         }
1541         v = ast_variable_browse(cfg, "options");
1542         while(v) {
1543                 if (!strcasecmp(v->name, "verbose")) {
1544                         option_verbose= atoi(v->value);
1545                 } else if (!strcasecmp(v->name, "debug")) {
1546                         option_debug= ast_true(v->value);
1547                 } else if (!strcasecmp(v->name, "nofork")) {
1548                         option_nofork = ast_true(v->value);
1549                 } else if (!strcasecmp(v->name, "quiet")) {
1550                         option_quiet = ast_true(v->value);
1551                 } else if (!strcasecmp(v->name, "console")) {
1552                         option_console = ast_true(v->value);
1553                 } else if (!strcasecmp(v->name, "highpriority")) {
1554                         option_highpriority = ast_true(v->value);
1555                 } else if (!strcasecmp(v->name, "initcrypto")) {
1556                         option_initcrypto = ast_true(v->value);
1557                 } else if (!strcasecmp(v->name, "nocolor")) {
1558                         option_nocolor = ast_true(v->value);
1559                 } else if (!strcasecmp(v->name, "dumpcore")) {
1560                         option_dumpcore = ast_true(v->value);
1561                 } else if (!strcasecmp(v->name, "cache_record_files")) {
1562                         option_cache_record_files = ast_true(v->value);
1563                 }  else if (!strcasecmp(v->name, "record_cache_dir")) {
1564                         strncpy(record_cache_dir,v->value,AST_CACHE_DIR_LEN);
1565                 }
1566                 v = v->next;
1567         }
1568         ast_destroy(cfg);
1569 }
1570
1571 int main(int argc, char *argv[])
1572 {
1573         int c;
1574         char filename[80] = "";
1575         char hostname[256];
1576         char tmp[80];
1577         char * xarg = NULL;
1578         int x;
1579         FILE *f;
1580         sigset_t sigs;
1581         int num;
1582         char *buf;
1583         char *runuser=NULL, *rungroup=NULL;
1584
1585         /* Remember original args for restart */
1586         if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1587                 fprintf(stderr, "Truncating argument size to %d\n", (int)(sizeof(_argv) / sizeof(_argv[0])) - 1);
1588                 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1589         }
1590         for (x=0;x<argc;x++)
1591                 _argv[x] = argv[x];
1592         _argv[x] = NULL;
1593
1594         /* if the progname is rasterisk consider it a remote console */
1595         if (argv[0] && (strstr(argv[0], "rasterisk")) != NULL) {
1596                 option_remote++;
1597                 option_nofork++;
1598         }
1599         if (gethostname(hostname, sizeof(hostname)))
1600                 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
1601         ast_mainpid = getpid();
1602         ast_ulaw_init();
1603         ast_alaw_init();
1604         callerid_init();
1605         ast_utils_init();
1606         tdd_init();
1607         if (getenv("HOME")) 
1608                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1609         /* Check if we're root */
1610         /*
1611         if (geteuid()) {
1612                 ast_log(LOG_ERROR, "Must be run as root\n");
1613                 exit(1);
1614         }
1615         */
1616         /* Check for options */
1617         while((c=getopt(argc, argv, "thfdvVqprRgcinx:U:G:C:")) != -1) {
1618                 switch(c) {
1619                 case 'd':
1620                         option_debug++;
1621                         option_nofork++;
1622                         break;
1623                 case 'c':
1624                         option_console++;
1625                         option_nofork++;
1626                         break;
1627                 case 'f':
1628                         option_nofork++;
1629                         break;
1630                 case 'n':
1631                         option_nocolor++;
1632                         break;
1633                 case 'r':
1634                         option_remote++;
1635                         option_nofork++;
1636                         break;
1637                 case 'R':
1638                         option_remote++;
1639                         option_nofork++;
1640                         option_reconnect++;
1641                         break;
1642                 case 'p':
1643                         option_highpriority++;
1644                         break;
1645                 case 'v':
1646                         option_verbose++;
1647                         option_nofork++;
1648                         break;
1649                 case 'q':
1650                         option_quiet++;
1651                         break;
1652                 case 't':
1653                         option_cache_record_files++;
1654                         break;
1655                 case 'x':
1656                         option_exec++;
1657                         xarg = optarg;
1658                         break;
1659                 case 'C':
1660                         strncpy((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE) - 1);
1661                         option_overrideconfig++;
1662                         break;
1663                 case 'i':
1664                         option_initcrypto++;
1665                         break;
1666                 case'g':
1667                         option_dumpcore++;
1668                         break;
1669                 case 'h':
1670                         show_cli_help();
1671                         exit(0);
1672                 case 'V':
1673                         show_version();
1674                         exit(0);
1675                 case 'U':
1676                         runuser = optarg;
1677                         break;
1678                 case 'G':
1679                         rungroup = optarg;
1680                         break;
1681                 case '?':
1682                         exit(1);
1683                 }
1684         }
1685
1686         if (option_dumpcore) {
1687                 struct rlimit l;
1688                 memset(&l, 0, sizeof(l));
1689                 l.rlim_cur = RLIM_INFINITY;
1690                 l.rlim_max = RLIM_INFINITY;
1691                 if (setrlimit(RLIMIT_CORE, &l)) {
1692                         ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
1693                 }
1694         }
1695
1696         if (rungroup) {
1697                 struct group *gr;
1698                 gr = getgrnam(rungroup);
1699                 if (!gr) {
1700                         ast_log(LOG_WARNING, "No such group '%s'!\n", rungroup);
1701                         exit(1);
1702                 }
1703                 if (setgid(gr->gr_gid)) {
1704                         ast_log(LOG_WARNING, "Unable to setgid to %d (%s)\n", gr->gr_gid, rungroup);
1705                         exit(1);
1706                 }
1707                 if (option_verbose)
1708                         ast_verbose("Running as group '%s'\n", rungroup);
1709         }
1710
1711         if (set_priority(option_highpriority)) {
1712                 exit(1);
1713         }
1714         if (runuser) {
1715                 struct passwd *pw;
1716                 pw = getpwnam(runuser);
1717                 if (!pw) {
1718                         ast_log(LOG_WARNING, "No such user '%s'!\n", runuser);
1719                         exit(1);
1720                 }
1721                 if (setuid(pw->pw_uid)) {
1722                         ast_log(LOG_WARNING, "Unable to setuid to %d (%s)\n", pw->pw_uid, runuser);
1723                         exit(1);
1724                 }
1725                 if (option_verbose)
1726                         ast_verbose("Running as user '%s'\n", runuser);
1727         }
1728
1729         term_init();
1730         printf(term_end());
1731         fflush(stdout);
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         /* Test recursive mutex locking. */
1798         if (test_for_thread_safety())
1799                 ast_verbose("Warning! Asterisk is not thread safe.\n");
1800
1801         ast_makesocket();
1802         sigemptyset(&sigs);
1803         sigaddset(&sigs, SIGHUP);
1804         sigaddset(&sigs, SIGTERM);
1805         sigaddset(&sigs, SIGINT);
1806         sigaddset(&sigs, SIGPIPE);
1807         sigaddset(&sigs, SIGWINCH);
1808         pthread_sigmask(SIG_BLOCK, &sigs, NULL);
1809         if (option_console || option_verbose || option_remote)
1810                 ast_register_verbose(console_verboser);
1811         /* Print a welcome message if desired */
1812         if (option_verbose || option_console) {
1813                 WELCOME_MESSAGE;
1814         }
1815         if (option_console && !option_verbose) 
1816                 ast_verbose("[ Booting...");
1817
1818         signal(SIGURG, urg_handler);
1819         signal(SIGINT, __quit_handler);
1820         signal(SIGTERM, __quit_handler);
1821         signal(SIGHUP, hup_handler);
1822         signal(SIGCHLD, child_handler);
1823         signal(SIGPIPE, SIG_IGN);
1824
1825         if (init_logger()) {
1826                 printf(term_quit());
1827                 exit(1);
1828         }
1829         if (init_manager()) {
1830                 printf(term_quit());
1831                 exit(1);
1832         }
1833         ast_rtp_init();
1834         if (ast_image_init()) {
1835                 printf(term_quit());
1836                 exit(1);
1837         }
1838         if (ast_file_init()) {
1839                 printf(term_quit());
1840                 exit(1);
1841         }
1842         if (load_pbx()) {
1843                 printf(term_quit());
1844                 exit(1);
1845         }
1846         if (load_modules()) {
1847                 printf(term_quit());
1848                 exit(1);
1849         }
1850         if (init_framer()) {
1851                 printf(term_quit());
1852                 exit(1);
1853         }
1854         if (astdb_init()) {
1855                 printf(term_quit());
1856                 exit(1);
1857         }
1858         if (ast_enum_init()) {
1859                 printf(term_quit());
1860                 exit(1);
1861         }
1862         /* sync cust config and reload some internals in case a custom config handler binded to them */
1863         read_ast_cust_config();
1864         reload_logger(0);
1865         reload_manager();
1866         ast_enum_reload();
1867         ast_rtp_reload();
1868
1869
1870         /* We might have the option of showing a console, but for now just
1871            do nothing... */
1872         if (option_console && !option_verbose)
1873                 ast_verbose(" ]\n");
1874         if (option_verbose || option_console)
1875                 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
1876         if (option_nofork)
1877                 consolethread = pthread_self();
1878         fully_booted = 1;
1879         pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
1880 #ifdef __AST_DEBUG_MALLOC
1881         __ast_mm_init();
1882 #endif  
1883         time(&ast_startuptime);
1884         ast_cli_register(&astshutdownnow);
1885         ast_cli_register(&astshutdowngracefully);
1886         ast_cli_register(&astrestartnow);
1887         ast_cli_register(&astrestartgracefully);
1888         ast_cli_register(&astrestartwhenconvenient);
1889         ast_cli_register(&astshutdownwhenconvenient);
1890         ast_cli_register(&aborthalt);
1891         ast_cli_register(&astbang);
1892         if (option_console) {
1893                 /* Console stuff now... */
1894                 /* Register our quit function */
1895                 char title[256];
1896                 set_icon("Asterisk");
1897                 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, ast_mainpid);
1898                 set_title(title);
1899                 ast_cli_register(&quit);
1900                 ast_cli_register(&astexit);
1901
1902                 for (;;) {
1903                         buf = (char *)el_gets(el, &num);
1904                         if (buf) {
1905                                 if (buf[strlen(buf)-1] == '\n')
1906                                         buf[strlen(buf)-1] = '\0';
1907
1908                                 consolehandler((char *)buf);
1909                         } else {
1910                                 if (option_remote)
1911                                         ast_cli(STDOUT_FILENO, "\nUse EXIT or QUIT to exit the asterisk console\n");
1912                         }
1913                 }
1914
1915         } else {
1916                 /* Do nothing */
1917                 for(;;) 
1918                         poll(NULL,0, -1);
1919         }
1920         return 0;
1921 }