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