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