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