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