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