Add peercontext parameter for default outbound context (bug #1929)
[asterisk/asterisk.git] / asterisk.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Top level source file for asterisk
5  * 
6  * Copyright (C) 1999, Mark Spencer
7  *
8  * Mark Spencer <markster@linux-support.net>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <unistd.h>
15 #include <stdlib.h>
16 #include <sys/poll.h>
17 #include <asterisk/logger.h>
18 #include <asterisk/options.h>
19 #include <asterisk/cli.h>
20 #include <asterisk/channel.h>
21 #include <asterisk/ulaw.h>
22 #include <asterisk/alaw.h>
23 #include <asterisk/callerid.h>
24 #include <asterisk/module.h>
25 #include <asterisk/image.h>
26 #include <asterisk/tdd.h>
27 #include <asterisk/term.h>
28 #include <asterisk/manager.h>
29 #include <asterisk/pbx.h>
30 #include <asterisk/enum.h>
31 #include <asterisk/rtp.h>
32 #include <asterisk/app.h>
33 #include <asterisk/lock.h>
34 #include <asterisk/utils.h>
35 #include <sys/resource.h>
36 #include <fcntl.h>
37 #include <stdio.h>
38 #include <signal.h>
39 #include <sched.h>
40 #include <asterisk/io.h>
41 #include <asterisk/lock.h>
42 #include <sys/socket.h>
43 #include <sys/un.h>
44 #include <sys/wait.h>
45 #include <string.h>
46 #include <errno.h>
47 #include <ctype.h>
48 #include "editline/histedit.h"
49 #include "asterisk.h"
50 #include <asterisk/config.h>
51 #include <asterisk/config_pvt.h>
52 #include <sys/resource.h>
53
54 #if  defined(__FreeBSD__)
55 #include <netdb.h>
56 #endif
57
58 #define AST_MAX_CONNECTS 128
59 #define NUM_MSGS 64
60
61 #define WELCOME_MESSAGE ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2004 Digium.\n"); \
62                 ast_verbose( "Written by Mark Spencer <markster@digium.com>\n"); \
63                 ast_verbose( "=========================================================================\n")
64
65 int option_verbose=0;
66 int option_debug=0;
67 int option_nofork=0;
68 int option_quiet=0;
69 int option_console=0;
70 int option_highpriority=0;
71 int option_remote=0;
72 int option_exec=0;
73 int option_initcrypto=0;
74 int option_nocolor;
75 int option_dumpcore = 0;
76 int option_overrideconfig = 0;
77 int option_reconnect = 0;
78 int fully_booted = 0;
79
80 static int ast_socket = -1;             /* UNIX Socket for allowing remote control */
81 static int ast_consock = -1;            /* UNIX Socket for controlling another asterisk */
82 int ast_mainpid;
83 struct console {
84         int fd;                                 /* File descriptor */
85         int p[2];                               /* Pipe */
86         pthread_t t;                    /* Thread of handler */
87 };
88
89 static struct ast_atexit {
90         void (*func)(void);
91         struct ast_atexit *next;
92 } *atexits = NULL;
93 AST_MUTEX_DEFINE_STATIC(atexitslock);
94
95 time_t ast_startuptime;
96 time_t ast_lastreloadtime;
97
98 static History *el_hist = NULL;
99 static EditLine *el = NULL;
100 static char *remotehostname;
101
102 struct console consoles[AST_MAX_CONNECTS];
103
104 char defaultlanguage[MAX_LANGUAGE] = DEFAULT_LANGUAGE;
105
106 static int ast_el_add_history(char *);
107 static int ast_el_read_history(char *);
108 static int ast_el_write_history(char *);
109
110 char ast_config_AST_CONFIG_DIR[AST_CONFIG_MAX_PATH];
111 char ast_config_AST_CONFIG_FILE[AST_CONFIG_MAX_PATH];
112 char ast_config_AST_MODULE_DIR[AST_CONFIG_MAX_PATH];
113 char ast_config_AST_SPOOL_DIR[AST_CONFIG_MAX_PATH];
114 char ast_config_AST_VAR_DIR[AST_CONFIG_MAX_PATH];
115 char ast_config_AST_LOG_DIR[AST_CONFIG_MAX_PATH];
116 char ast_config_AST_AGI_DIR[AST_CONFIG_MAX_PATH];
117 char ast_config_AST_DB[AST_CONFIG_MAX_PATH];
118 char ast_config_AST_KEY_DIR[AST_CONFIG_MAX_PATH];
119 char ast_config_AST_PID[AST_CONFIG_MAX_PATH];
120 char ast_config_AST_SOCKET[AST_CONFIG_MAX_PATH];
121 char ast_config_AST_RUN_DIR[AST_CONFIG_MAX_PATH];
122
123 static char *_argv[256];
124 static int shuttingdown = 0;
125 static int restartnow = 0;
126 static pthread_t consolethread = AST_PTHREADT_NULL;
127
128 int ast_register_atexit(void (*func)(void))
129 {
130         int res = -1;
131         struct ast_atexit *ae;
132         ast_unregister_atexit(func);
133         ae = malloc(sizeof(struct ast_atexit));
134         ast_mutex_lock(&atexitslock);
135         if (ae) {
136                 memset(ae, 0, sizeof(struct ast_atexit));
137                 ae->next = atexits;
138                 ae->func = func;
139                 atexits = ae;
140                 res = 0;
141         }
142         ast_mutex_unlock(&atexitslock);
143         return res;
144 }
145
146 void ast_unregister_atexit(void (*func)(void))
147 {
148         struct ast_atexit *ae, *prev = NULL;
149         ast_mutex_lock(&atexitslock);
150         ae = atexits;
151         while(ae) {
152                 if (ae->func == func) {
153                         if (prev)
154                                 prev->next = ae->next;
155                         else
156                                 atexits = ae->next;
157                         break;
158                 }
159                 prev = ae;
160                 ae = ae->next;
161         }
162         ast_mutex_unlock(&atexitslock);
163 }
164
165 static int fdprint(int fd, const char *s)
166 {
167         return write(fd, s, strlen(s) + 1);
168 }
169
170 int ast_safe_system(const char *s)
171 {
172         /* XXX This function needs some optimization work XXX */
173         pid_t pid;
174         int x;
175         int res;
176         struct rusage rusage;
177         int status;
178         pid = fork();
179         if (pid == 0) {
180                 /* Close file descriptors and launch system command */
181                 for (x=STDERR_FILENO + 1; x<4096;x++) {
182                         close(x);
183                 }
184                 res = execl("/bin/sh", "/bin/sh", "-c", s, NULL);
185                 exit(1);
186         } else if (pid > 0) {
187                 for(;;) {
188                         res = wait4(pid, &status, 0, &rusage);
189                         if (res > -1) {
190                                 if (WIFEXITED(status))
191                                         res = WEXITSTATUS(status);
192                                 else
193                                         res = -1;
194                                 break;
195                         } else {
196                                 if (errno != EINTR) 
197                                         break;
198                         }
199                 }
200         } else {
201                 ast_log(LOG_WARNING, "Fork failed: %s\n", strerror(errno));
202                 res = -1;
203         }
204         return res;
205 }
206
207 /*
208  * write the string to all attached console clients
209  */
210 static void ast_network_puts(const char *string)
211 {
212     int x;
213     for (x=0;x<AST_MAX_CONNECTS; x++) {
214         if (consoles[x].fd > -1) 
215             fdprint(consoles[x].p[1], string);
216     }
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));
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));
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));
970                                                 } else {
971                                                         strncat(p, "localhost", sizeof(prompt) - strlen(prompt));
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));
983                                                 } else {
984                                                         strncat(p, "localhost", sizeof(prompt) - strlen(prompt));
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));
1027                                                 } else {
1028                                                         strncat(p, ">", sizeof(prompt) - strlen(prompt));
1029                                                 }
1030                                                 break;
1031                                         case '%': /* literal % */
1032                                                 strncat(p, "%", sizeof(prompt) - strlen(prompt));
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                                 continue;
1135                         }
1136
1137                         numoutput++;  numoutputline++;
1138                         fprintf(stdout, "%-*s  ", max, matches[idx]);
1139                 }
1140                 if (numoutputline > 0)
1141                         fprintf(stdout, "\n");
1142         }
1143
1144         return numoutput;
1145 }
1146
1147
1148 static char *cli_complete(EditLine *el, int ch)
1149 {
1150         int len=0;
1151         char *ptr;
1152         int nummatches = 0;
1153         char **matches;
1154         int retval = CC_ERROR;
1155         char buf[2048];
1156         int res;
1157
1158         LineInfo *lf = (LineInfo *)el_line(el);
1159
1160         *(char *)lf->cursor = '\0';
1161         ptr = (char *)lf->cursor;
1162         if (ptr) {
1163                 while (ptr > lf->buffer) {
1164                         if (isspace(*ptr)) {
1165                                 ptr++;
1166                                 break;
1167                         }
1168                         ptr--;
1169                 }
1170         }
1171
1172         len = lf->cursor - ptr;
1173
1174         if (option_remote) {
1175                 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr); 
1176                 fdprint(ast_consock, buf);
1177                 res = read(ast_consock, buf, sizeof(buf));
1178                 buf[res] = '\0';
1179                 nummatches = atoi(buf);
1180
1181                 if (nummatches > 0) {
1182                         char *mbuf;
1183                         int mlen = 0, maxmbuf = 2048;
1184                         /* Start with a 2048 byte buffer */
1185                         mbuf = malloc(maxmbuf);
1186                         if (!mbuf)
1187                                 return (char *)(CC_ERROR);
1188                         snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr); 
1189                         fdprint(ast_consock, buf);
1190                         res = 0;
1191                         mbuf[0] = '\0';
1192                         while (!strstr(mbuf, AST_CLI_COMPLETE_EOF) && res != -1) {
1193                                 if (mlen + 1024 > maxmbuf) {
1194                                         /* Every step increment buffer 1024 bytes */
1195                                         maxmbuf += 1024;
1196                                         mbuf = realloc(mbuf, maxmbuf);
1197                                         if (!mbuf)
1198                                                 return (char *)(CC_ERROR);
1199                                 }
1200                                 /* Only read 1024 bytes at a time */
1201                                 res = read(ast_consock, mbuf + mlen, 1024);
1202                                 if (res > 0)
1203                                         mlen += res;
1204                         }
1205                         mbuf[mlen] = '\0';
1206
1207                         matches = ast_el_strtoarr(mbuf);
1208                         free(mbuf);
1209                 } else
1210                         matches = (char **) NULL;
1211
1212
1213         }  else {
1214
1215                 nummatches = ast_cli_generatornummatches((char *)lf->buffer,ptr);
1216                 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
1217         }
1218
1219         if (matches) {
1220                 int i;
1221                 int matches_num, maxlen, match_len;
1222
1223                 if (matches[0][0] != '\0') {
1224                         el_deletestr(el, (int) len);
1225                         el_insertstr(el, matches[0]);
1226                         retval = CC_REFRESH;
1227                 }
1228
1229                 if (nummatches == 1) {
1230                         /* Found an exact match */
1231                         el_insertstr(el, " ");
1232                         retval = CC_REFRESH;
1233                 } else {
1234                         /* Must be more than one match */
1235                         for (i=1, maxlen=0; matches[i]; i++) {
1236                                 match_len = strlen(matches[i]);
1237                                 if (match_len > maxlen)
1238                                         maxlen = match_len;
1239                         }
1240                         matches_num = i - 1;
1241                         if (matches_num >1) {
1242                                 fprintf(stdout, "\n");
1243                                 ast_cli_display_match_list(matches, nummatches, maxlen);
1244                                 retval = CC_REDISPLAY;
1245                         } else { 
1246                                 el_insertstr(el," ");
1247                                 retval = CC_REFRESH;
1248                         }
1249                 }
1250         free(matches);
1251         }
1252
1253         return (char *)(long)retval;
1254 }
1255
1256 static int ast_el_initialize(void)
1257 {
1258         HistEvent ev;
1259
1260         if (el != NULL)
1261                 el_end(el);
1262         if (el_hist != NULL)
1263                 history_end(el_hist);
1264
1265         el = el_init("asterisk", stdin, stdout, stderr);
1266         el_set(el, EL_PROMPT, cli_prompt);
1267
1268         el_set(el, EL_EDITMODE, 1);             
1269         el_set(el, EL_EDITOR, "emacs");         
1270         el_hist = history_init();
1271         if (!el || !el_hist)
1272                 return -1;
1273
1274         /* setup history with 100 entries */
1275         history(el_hist, &ev, H_SETSIZE, 100);
1276
1277         el_set(el, EL_HIST, history, el_hist);
1278
1279         el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
1280         /* Bind <tab> to command completion */
1281         el_set(el, EL_BIND, "^I", "ed-complete", NULL);
1282         /* Bind ? to command completion */
1283         el_set(el, EL_BIND, "?", "ed-complete", NULL);
1284         /* Bind ^D to redisplay */
1285         el_set(el, EL_BIND, "^D", "ed-redisplay", NULL);
1286
1287         return 0;
1288 }
1289
1290 static int ast_el_add_history(char *buf)
1291 {
1292         HistEvent ev;
1293
1294         if (el_hist == NULL || el == NULL)
1295                 ast_el_initialize();
1296         if (strlen(buf) > 256)
1297                 return 0;
1298         return (history(el_hist, &ev, H_ENTER, buf));
1299 }
1300
1301 static int ast_el_write_history(char *filename)
1302 {
1303         HistEvent ev;
1304
1305         if (el_hist == NULL || el == NULL)
1306                 ast_el_initialize();
1307
1308         return (history(el_hist, &ev, H_SAVE, filename));
1309 }
1310
1311 static int ast_el_read_history(char *filename)
1312 {
1313         char buf[256];
1314         FILE *f;
1315         int ret = -1;
1316
1317         if (el_hist == NULL || el == NULL)
1318                 ast_el_initialize();
1319
1320         if ((f = fopen(filename, "r")) == NULL)
1321                 return ret;
1322
1323         while (!feof(f)) {
1324                 fgets(buf, sizeof(buf), f);
1325                 if (!strcmp(buf, "_HiStOrY_V2_\n"))
1326                         continue;
1327                 if ((ret = ast_el_add_history(buf)) == -1)
1328                         break;
1329         }
1330         fclose(f);
1331
1332         return ret;
1333 }
1334
1335 static void ast_remotecontrol(char * data)
1336 {
1337         char buf[80];
1338         int res;
1339         char filename[80] = "";
1340         char *hostname;
1341         char *cpid;
1342         char *version;
1343         int pid;
1344         char tmp[80];
1345         char *stringp=NULL;
1346
1347         char *ebuf;
1348         int num = 0;
1349
1350         read(ast_consock, buf, sizeof(buf));
1351         if (data)
1352                 write(ast_consock, data, strlen(data) + 1);
1353         stringp=buf;
1354         hostname = strsep(&stringp, "/");
1355         cpid = strsep(&stringp, "/");
1356         version = strsep(&stringp, "\n");
1357         if (!version)
1358                 version = "<Version Unknown>";
1359         stringp=hostname;
1360         strsep(&stringp, ".");
1361         if (cpid)
1362                 pid = atoi(cpid);
1363         else
1364                 pid = -1;
1365         snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
1366         fdprint(ast_consock, tmp);
1367         ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
1368         remotehostname = hostname;
1369         if (getenv("HOME")) 
1370                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1371         if (el_hist == NULL || el == NULL)
1372                 ast_el_initialize();
1373
1374         el_set(el, EL_GETCFN, ast_el_read_char);
1375
1376         if (!ast_strlen_zero(filename))
1377                 ast_el_read_history(filename);
1378
1379         ast_cli_register(&quit);
1380         ast_cli_register(&astexit);
1381 #if 0
1382         ast_cli_register(&astshutdown);
1383 #endif  
1384         if (option_exec && data) {  /* hack to print output then exit if asterisk -rx is used */
1385                 char tempchar;
1386                 ast_el_read_char(el, &tempchar);
1387                 return;
1388         }
1389         for(;;) {
1390                 ebuf = (char *)el_gets(el, &num);
1391
1392                 if (ebuf && !ast_strlen_zero(ebuf)) {
1393                         if (ebuf[strlen(ebuf)-1] == '\n')
1394                                 ebuf[strlen(ebuf)-1] = '\0';
1395                         if (!remoteconsolehandler(ebuf)) {
1396                                 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
1397                                 if (res < 1) {
1398                                         ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
1399                                         break;
1400                                 }
1401                         }
1402                 }
1403         }
1404         printf("\nDisconnected from Asterisk server\n");
1405 }
1406
1407 static int show_cli_help(void) {
1408         printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 2000-2004, Digium.\n");
1409         printf("Usage: asterisk [OPTIONS]\n");
1410         printf("Valid Options:\n");
1411         printf("   -C <configfile> Use an alternate configuration file\n");
1412         printf("   -c              Provide console CLI\n");
1413         printf("   -d              Enable extra debugging\n");
1414         printf("   -f              Do not fork\n");
1415         printf("   -g              Dump core in case of a crash\n");
1416         printf("   -h              This help screen\n");
1417         printf("   -i              Initializie crypto keys at startup\n");
1418         printf("   -n              Disable console colorization\n");
1419         printf("   -p              Run as pseudo-realtime thread\n");
1420         printf("   -q              Quiet mode (supress output)\n");
1421         printf("   -r              Connect to Asterisk on this machine\n");
1422         printf("   -R              Connect to Asterisk, and attempt to reconnect if disconnected\n");
1423         printf("   -v              Increase verbosity (multiple v's = more verbose)\n");
1424         printf("   -x <cmd>        Execute command <cmd> (only valid with -r)\n");
1425         printf("\n");
1426         return 0;
1427 }
1428
1429 static void ast_readconfig(void) {
1430         struct ast_config *cfg;
1431         struct ast_variable *v;
1432         char *config = ASTCONFPATH;
1433
1434         if (option_overrideconfig == 1) {
1435             cfg = ast_load((char *)ast_config_AST_CONFIG_FILE);
1436         } else {
1437             cfg = ast_load(config);
1438         }
1439
1440         /* init with buildtime config */
1441         strncpy((char *)ast_config_AST_CONFIG_DIR,AST_CONFIG_DIR,sizeof(ast_config_AST_CONFIG_DIR)-1);
1442         strncpy((char *)ast_config_AST_SPOOL_DIR,AST_SPOOL_DIR,sizeof(ast_config_AST_SPOOL_DIR)-1);
1443         strncpy((char *)ast_config_AST_MODULE_DIR,AST_MODULE_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1444         strncpy((char *)ast_config_AST_VAR_DIR,AST_VAR_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1445         strncpy((char *)ast_config_AST_LOG_DIR,AST_LOG_DIR,sizeof(ast_config_AST_LOG_DIR)-1);
1446         strncpy((char *)ast_config_AST_AGI_DIR,AST_AGI_DIR,sizeof(ast_config_AST_AGI_DIR)-1);
1447         strncpy((char *)ast_config_AST_DB,AST_DB,sizeof(ast_config_AST_DB)-1);
1448         strncpy((char *)ast_config_AST_KEY_DIR,AST_KEY_DIR,sizeof(ast_config_AST_KEY_DIR)-1);
1449         strncpy((char *)ast_config_AST_PID,AST_PID,sizeof(ast_config_AST_PID)-1);
1450         strncpy((char *)ast_config_AST_SOCKET,AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1);
1451         strncpy((char *)ast_config_AST_RUN_DIR,AST_RUN_DIR,sizeof(ast_config_AST_RUN_DIR)-1);
1452         
1453         /* no asterisk.conf? no problem, use buildtime config! */
1454         if (!cfg) {
1455             return;
1456         }
1457         v = ast_variable_browse(cfg, "directories");
1458         while(v) {
1459                 if (!strcasecmp(v->name, "astetcdir")) {
1460                     strncpy((char *)ast_config_AST_CONFIG_DIR,v->value,sizeof(ast_config_AST_CONFIG_DIR)-1);
1461                 } else if (!strcasecmp(v->name, "astspooldir")) {
1462                     strncpy((char *)ast_config_AST_SPOOL_DIR,v->value,sizeof(ast_config_AST_SPOOL_DIR)-1);
1463                 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1464                     strncpy((char *)ast_config_AST_VAR_DIR,v->value,sizeof(ast_config_AST_VAR_DIR)-1);
1465                     snprintf((char *)ast_config_AST_DB,sizeof(ast_config_AST_DB)-1,"%s/%s",v->value,"astdb");    
1466                 } else if (!strcasecmp(v->name, "astlogdir")) {
1467                     strncpy((char *)ast_config_AST_LOG_DIR,v->value,sizeof(ast_config_AST_LOG_DIR)-1);
1468                 } else if (!strcasecmp(v->name, "astagidir")) {
1469                     strncpy((char *)ast_config_AST_AGI_DIR,v->value,sizeof(ast_config_AST_AGI_DIR)-1);
1470                 } else if (!strcasecmp(v->name, "astrundir")) {
1471                     snprintf((char *)ast_config_AST_PID,sizeof(ast_config_AST_PID)-1,"%s/%s",v->value,"asterisk.pid");    
1472                     snprintf((char *)ast_config_AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1,"%s/%s",v->value,"asterisk.ctl");    
1473                     strncpy((char *)ast_config_AST_RUN_DIR,v->value,sizeof(ast_config_AST_RUN_DIR)-1);
1474                 } else if (!strcasecmp(v->name, "astmoddir")) {
1475                     strncpy((char *)ast_config_AST_MODULE_DIR,v->value,sizeof(ast_config_AST_MODULE_DIR)-1);
1476                 }
1477                 v = v->next;
1478         }
1479         ast_destroy(cfg);
1480 }
1481
1482 int main(int argc, char *argv[])
1483 {
1484         int c;
1485         char filename[80] = "";
1486         char hostname[256];
1487         char tmp[80];
1488         char * xarg = NULL;
1489         int x;
1490         FILE *f;
1491         sigset_t sigs;
1492         int num;
1493         char *buf;
1494
1495         /* Remember original args for restart */
1496         if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1497                 fprintf(stderr, "Truncating argument size to %d\n", (int)(sizeof(_argv) / sizeof(_argv[0])) - 1);
1498                 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1499         }
1500         for (x=0;x<argc;x++)
1501                 _argv[x] = argv[x];
1502         _argv[x] = NULL;
1503
1504         /* if the progname is rasterisk consider it a remote console */
1505         if ( argv[0] && (strstr(argv[0], "rasterisk")) != NULL)  {
1506                 option_remote++;
1507                 option_nofork++;
1508         }
1509         if (gethostname(hostname, sizeof(hostname)))
1510                 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
1511         ast_mainpid = getpid();
1512         ast_ulaw_init();
1513         ast_alaw_init();
1514         callerid_init();
1515         ast_utils_init();
1516         tdd_init();
1517         if (getenv("HOME")) 
1518                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1519         /* Check if we're root */
1520         /*
1521         if (geteuid()) {
1522                 ast_log(LOG_ERROR, "Must be run as root\n");
1523                 exit(1);
1524         }
1525         */
1526         /* Check for options */
1527         while((c=getopt(argc, argv, "hfdvqprRgcinx:C:")) != -1) {
1528                 switch(c) {
1529                 case 'd':
1530                         option_debug++;
1531                         option_nofork++;
1532                         break;
1533                 case 'c':
1534                         option_console++;
1535                         option_nofork++;
1536                         break;
1537                 case 'f':
1538                         option_nofork++;
1539                         break;
1540                 case 'n':
1541                         option_nocolor++;
1542                         break;
1543                 case 'r':
1544                         option_remote++;
1545                         option_nofork++;
1546                         break;
1547                 case 'R':
1548                         option_remote++;
1549                         option_nofork++;
1550                         option_reconnect++;
1551                         break;
1552                 case 'p':
1553                         option_highpriority++;
1554                         break;
1555                 case 'v':
1556                         option_verbose++;
1557                         option_nofork++;
1558                         break;
1559                 case 'q':
1560                         option_quiet++;
1561                         break;
1562                 case 'x':
1563                         option_exec++;
1564                         xarg = optarg;
1565                         break;
1566                 case 'C':
1567                         strncpy((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE));
1568                         option_overrideconfig++;
1569                         break;
1570                 case 'i':
1571                         option_initcrypto++;
1572                         break;
1573                 case'g':
1574                         option_dumpcore++;
1575                         break;
1576                 case 'h':
1577                         show_cli_help();
1578                         exit(0);
1579                 case '?':
1580                         exit(1);
1581                 }
1582         }
1583
1584         if (option_dumpcore) {
1585                 struct rlimit l;
1586                 memset(&l, 0, sizeof(l));
1587                 l.rlim_cur = RLIM_INFINITY;
1588                 l.rlim_max = RLIM_INFINITY;
1589                 if (setrlimit(RLIMIT_CORE, &l)) {
1590                         ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
1591                 }
1592         }
1593
1594         term_init();
1595         printf(term_end());
1596         fflush(stdout);
1597
1598         /* Test recursive mutex locking. */
1599         if(test_for_thread_safety())
1600                 ast_verbose("Warning! Asterisk is not thread safe.\n");
1601
1602         if (option_console && !option_verbose) 
1603                 ast_verbose("[ Reading Master Configuration ]");
1604         ast_readconfig();
1605
1606         if (option_console && !option_verbose) 
1607                 ast_verbose("[ Initializing Custom Configuration Options]");
1608         /* custom config setup */
1609         register_config_cli();
1610         read_ast_cust_config();
1611         
1612
1613         if (option_console) {
1614                 if (el_hist == NULL || el == NULL)
1615                         ast_el_initialize();
1616
1617                 if (!ast_strlen_zero(filename))
1618                         ast_el_read_history(filename);
1619         }
1620
1621         if (ast_tryconnect()) {
1622                 /* One is already running */
1623                 if (option_remote) {
1624                         if (option_exec) {
1625                                 ast_remotecontrol(xarg);
1626                                 quit_handler(0, 0, 0, 0);
1627                                 exit(0);
1628                         }
1629                         printf(term_quit());
1630                         ast_register_verbose(console_verboser);
1631                         WELCOME_MESSAGE;
1632                         ast_remotecontrol(NULL);
1633                         quit_handler(0, 0, 0, 0);
1634                         exit(0);
1635                 } else {
1636                         ast_log(LOG_ERROR, "Asterisk already running on %s.  Use 'asterisk -r' to connect.\n", (char *)ast_config_AST_SOCKET);
1637                         printf(term_quit());
1638                         exit(1);
1639                 }
1640         } else if (option_remote || option_exec) {
1641                 ast_log(LOG_ERROR, "Unable to connect to remote asterisk\n");
1642                 printf(term_quit());
1643                 exit(1);
1644         }
1645         /* Blindly write pid file since we couldn't connect */
1646         unlink((char *)ast_config_AST_PID);
1647         f = fopen((char *)ast_config_AST_PID, "w");
1648         if (f) {
1649                 fprintf(f, "%d\n", getpid());
1650                 fclose(f);
1651         } else
1652                 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1653
1654         if (!option_verbose && !option_debug && !option_nofork && !option_console) {
1655                 daemon(0,0);
1656                 /* Blindly re-write pid file since we are forking */
1657                 unlink((char *)ast_config_AST_PID);
1658                 f = fopen((char *)ast_config_AST_PID, "w");
1659                 if (f) {
1660                         fprintf(f, "%d\n", getpid());
1661                         fclose(f);
1662                 } else
1663                         ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1664         }
1665
1666         ast_makesocket();
1667         sigemptyset(&sigs);
1668         sigaddset(&sigs, SIGHUP);
1669         sigaddset(&sigs, SIGTERM);
1670         sigaddset(&sigs, SIGINT);
1671         sigaddset(&sigs, SIGPIPE);
1672         sigaddset(&sigs, SIGWINCH);
1673         pthread_sigmask(SIG_BLOCK, &sigs, NULL);
1674         if (option_console || option_verbose || option_remote)
1675                 ast_register_verbose(console_verboser);
1676         /* Print a welcome message if desired */
1677         if (option_verbose || option_console) {
1678                 WELCOME_MESSAGE;
1679         }
1680         if (option_console && !option_verbose) 
1681                 ast_verbose("[ Booting...");
1682
1683         signal(SIGURG, urg_handler);
1684         signal(SIGINT, __quit_handler);
1685         signal(SIGTERM, __quit_handler);
1686         signal(SIGHUP, hup_handler);
1687         signal(SIGCHLD, child_handler);
1688         signal(SIGPIPE, SIG_IGN);
1689
1690         if (set_priority(option_highpriority)) {
1691                 printf(term_quit());
1692                 exit(1);
1693         }
1694         if (init_logger()) {
1695                 printf(term_quit());
1696                 exit(1);
1697         }
1698         if (init_manager()) {
1699                 printf(term_quit());
1700                 exit(1);
1701         }
1702         ast_rtp_init();
1703         if (ast_image_init()) {
1704                 printf(term_quit());
1705                 exit(1);
1706         }
1707         if (load_pbx()) {
1708                 printf(term_quit());
1709                 exit(1);
1710         }
1711         if (load_modules()) {
1712                 printf(term_quit());
1713                 exit(1);
1714         }
1715         if (init_framer()) {
1716                 printf(term_quit());
1717                 exit(1);
1718         }
1719         if (astdb_init()) {
1720                 printf(term_quit());
1721                 exit(1);
1722         }
1723         if (ast_enum_init()) {
1724                 printf(term_quit());
1725                 exit(1);
1726         }
1727         /* reload logger in case a custom config handler binded to logger.conf*/
1728         reload_logger(0);
1729
1730         /* We might have the option of showing a console, but for now just
1731            do nothing... */
1732         if (option_console && !option_verbose)
1733                 ast_verbose(" ]\n");
1734         if (option_verbose || option_console)
1735                 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
1736         if (option_nofork)
1737                 consolethread = pthread_self();
1738         fully_booted = 1;
1739         pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
1740 #ifdef __AST_DEBUG_MALLOC
1741         __ast_mm_init();
1742 #endif  
1743         time(&ast_startuptime);
1744         ast_cli_register(&astshutdownnow);
1745         ast_cli_register(&astshutdowngracefully);
1746         ast_cli_register(&astrestartnow);
1747         ast_cli_register(&astrestartgracefully);
1748         ast_cli_register(&astrestartwhenconvenient);
1749         ast_cli_register(&astshutdownwhenconvenient);
1750         ast_cli_register(&aborthalt);
1751         ast_cli_register(&astbang);
1752         if (option_console) {
1753                 /* Console stuff now... */
1754                 /* Register our quit function */
1755                 char title[256];
1756                 set_icon("Asterisk");
1757                 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, ast_mainpid);
1758                 set_title(title);
1759             ast_cli_register(&quit);
1760             ast_cli_register(&astexit);
1761
1762                 for (;;) {
1763                         buf = (char *)el_gets(el, &num);
1764                         if (buf) {
1765                                 if (buf[strlen(buf)-1] == '\n')
1766                                         buf[strlen(buf)-1] = '\0';
1767
1768                                 consolehandler((char *)buf);
1769                         } else {
1770                                 if (option_remote)
1771                                         ast_cli(STDOUT_FILENO, "\nUse EXIT or QUIT to exit the asterisk console\n");
1772                         }
1773                 }
1774
1775         } else {
1776                 /* Do nothing */
1777                 for(;;) 
1778                         poll(NULL,0, -1);
1779         }
1780         return 0;
1781 }