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