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