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