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