OpenBSD portability to H323
[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
888         if ((pfmt = getenv("ASTERISK_PROMPT"))) {
889                 char *t = pfmt, *p = prompt;
890                 memset(prompt, 0, sizeof(prompt));
891                 while (*t != '\0' && *p < sizeof(prompt)) {
892                         if (*t == '%') {
893                                 t++;
894                                 switch (*t) {
895                                         char hostname[256];
896                                         struct timeval tv;
897                                         struct tm tm;
898                                         FILE *LOADAVG;
899                                         case 'd': /* date */
900                                                 memset(&tm, 0, sizeof(struct tm));
901                                                 gettimeofday(&tv, NULL);
902                                                 if (localtime_r(&(tv.tv_sec), &tm)) {
903                                                         strftime(p, sizeof(prompt) - strlen(prompt), "%Y-%m-%d", &tm);
904                                                 }
905                                                 break;
906                                         case 'h': /* hostname */
907                                                 if (!gethostname(hostname, sizeof(hostname) - 1)) {
908                                                         strncat(p, hostname, sizeof(prompt) - strlen(prompt));
909                                                 } else {
910                                                         strncat(p, "localhost", sizeof(prompt) - strlen(prompt));
911                                                 }
912                                                 break;
913 #ifdef linux
914                                         case 'l': /* load avg */
915                                                 t++;
916                                                 if ((LOADAVG = fopen("/proc/loadavg", "r"))) {
917                                                         float avg1, avg2, avg3;
918                                                         int actproc, totproc, npid, which;
919                                                         fscanf(LOADAVG, "%f %f %f %d/%d %d",
920                                                                 &avg1, &avg2, &avg3, &actproc, &totproc, &npid);
921                                                         if (sscanf(t, "%d", &which) == 1) {
922                                                                 switch (which) {
923                                                                         case 1:
924                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg1);
925                                                                                 break;
926                                                                         case 2:
927                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg2);
928                                                                                 break;
929                                                                         case 3:
930                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg3);
931                                                                                 break;
932                                                                         case 4:
933                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%d/%d", actproc, totproc);
934                                                                                 break;
935                                                                         case 5:
936                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%d", npid);
937                                                                                 break;
938                                                                 }
939                                                         }
940                                                 }
941                                                 break;
942 #endif
943                                         case 't': /* time */
944                                                 memset(&tm, 0, sizeof(struct tm));
945                                                 gettimeofday(&tv, NULL);
946                                                 if (localtime_r(&(tv.tv_sec), &tm)) {
947                                                         strftime(p, sizeof(prompt) - strlen(prompt), "%H:%M:%S", &tm);
948                                                 }
949                                                 break;
950                                         case '#': /* process console or remote? */
951                                                 if (! option_remote) {
952                                                         strncat(p, "#", sizeof(prompt) - strlen(prompt));
953                                                 } else {
954                                                         strncat(p, ">", sizeof(prompt) - strlen(prompt));
955                                                 }
956                                                 break;
957                                         case '%': /* literal % */
958                                                 strncat(p, "%", sizeof(prompt) - strlen(prompt));
959                                                 break;
960                                         case '\0': /* % is last character - prevent bug */
961                                                 t--;
962                                                 break;
963                                 }
964                                 while (*p != '\0') {
965                                         p++;
966                                 }
967                                 t++;
968                         } else {
969                                 *p = *t;
970                                 p++;
971                                 t++;
972                         }
973                 }
974         } else if (remotehostname)
975                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT2, remotehostname);
976         else
977                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT);
978
979         return(prompt); 
980 }
981
982 static char **ast_el_strtoarr(char *buf)
983 {
984         char **match_list = NULL, *retstr;
985         size_t match_list_len;
986         int matches = 0;
987
988         match_list_len = 1;
989         while ( (retstr = strsep(&buf, " ")) != NULL) {
990
991                 if (!strcmp(retstr, AST_CLI_COMPLETE_EOF))
992                         break;
993                 if (matches + 1 >= match_list_len) {
994                         match_list_len <<= 1;
995                         match_list = realloc(match_list, match_list_len * sizeof(char *));
996                 }
997
998                 match_list[matches++] = strdup(retstr);
999         }
1000
1001         if (!match_list)
1002                 return (char **) NULL;
1003
1004         if (matches>= match_list_len)
1005                 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
1006
1007         match_list[matches] = (char *) NULL;
1008
1009         return match_list;
1010 }
1011
1012 static int ast_el_sort_compare(const void *i1, const void *i2)
1013 {
1014         char *s1, *s2;
1015
1016         s1 = ((char **)i1)[0];
1017         s2 = ((char **)i2)[0];
1018
1019         return strcasecmp(s1, s2);
1020 }
1021
1022 static int ast_cli_display_match_list(char **matches, int len, int max)
1023 {
1024         int i, idx, limit, count;
1025         int screenwidth = 0;
1026         int numoutput = 0, numoutputline = 0;
1027
1028         screenwidth = ast_get_termcols(STDOUT_FILENO);
1029
1030         /* find out how many entries can be put on one line, with two spaces between strings */
1031         limit = screenwidth / (max + 2);
1032         if (limit == 0)
1033                 limit = 1;
1034
1035         /* how many lines of output */
1036         count = len / limit;
1037         if (count * limit < len)
1038                 count++;
1039
1040         idx = 1;
1041
1042         qsort(&matches[0], (size_t)(len + 1), sizeof(char *), ast_el_sort_compare);
1043
1044         for (; count > 0; count--) {
1045                 numoutputline = 0;
1046                 for (i=0; i < limit && matches[idx]; i++, idx++) {
1047
1048                         /* Don't print dupes */
1049                         if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
1050                                 i--;
1051                                 continue;
1052                         }
1053
1054                         numoutput++;  numoutputline++;
1055                         fprintf(stdout, "%-*s  ", max, matches[idx]);
1056                 }
1057                 if (numoutputline > 0)
1058                         fprintf(stdout, "\n");
1059         }
1060
1061         return numoutput;
1062 }
1063
1064
1065 static char *cli_complete(EditLine *el, int ch)
1066 {
1067         int len=0;
1068         char *ptr;
1069         int nummatches = 0;
1070         char **matches;
1071         int retval = CC_ERROR;
1072         char buf[2048];
1073         int res;
1074
1075         LineInfo *lf = (LineInfo *)el_line(el);
1076
1077         *(char *)lf->cursor = '\0';
1078         ptr = (char *)lf->cursor;
1079         if (ptr) {
1080                 while (ptr > lf->buffer) {
1081                         if (isspace(*ptr)) {
1082                                 ptr++;
1083                                 break;
1084                         }
1085                         ptr--;
1086                 }
1087         }
1088
1089         len = lf->cursor - ptr;
1090
1091         if (option_remote) {
1092                 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr); 
1093                 fdprint(ast_consock, buf);
1094                 res = read(ast_consock, buf, sizeof(buf));
1095                 buf[res] = '\0';
1096                 nummatches = atoi(buf);
1097
1098                 if (nummatches > 0) {
1099                         char *mbuf;
1100                         int mlen = 0, maxmbuf = 2048;
1101                         /* Start with a 2048 byte buffer */
1102                         mbuf = malloc(maxmbuf);
1103                         if (!mbuf)
1104                                 return (char *)(CC_ERROR);
1105                         snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr); 
1106                         fdprint(ast_consock, buf);
1107                         res = 0;
1108                         mbuf[0] = '\0';
1109                         while (!strstr(mbuf, AST_CLI_COMPLETE_EOF) && res != -1) {
1110                                 if (mlen + 1024 > maxmbuf) {
1111                                         /* Every step increment buffer 1024 bytes */
1112                                         maxmbuf += 1024;
1113                                         mbuf = realloc(mbuf, maxmbuf);
1114                                         if (!mbuf)
1115                                                 return (char *)(CC_ERROR);
1116                                 }
1117                                 /* Only read 1024 bytes at a time */
1118                                 res = read(ast_consock, mbuf + mlen, 1024);
1119                                 if (res > 0)
1120                                         mlen += res;
1121                         }
1122                         mbuf[mlen] = '\0';
1123
1124                         matches = ast_el_strtoarr(mbuf);
1125                         free(mbuf);
1126                 } else
1127                         matches = (char **) NULL;
1128
1129
1130         }  else {
1131
1132                 nummatches = ast_cli_generatornummatches((char *)lf->buffer,ptr);
1133                 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
1134         }
1135
1136         if (matches) {
1137                 int i;
1138                 int matches_num, maxlen, match_len;
1139
1140                 if (matches[0][0] != '\0') {
1141                         el_deletestr(el, (int) len);
1142                         el_insertstr(el, matches[0]);
1143                         retval = CC_REFRESH;
1144                 }
1145
1146                 if (nummatches == 1) {
1147                         /* Found an exact match */
1148                         el_insertstr(el, " ");
1149                         retval = CC_REFRESH;
1150                 } else {
1151                         /* Must be more than one match */
1152                         for (i=1, maxlen=0; matches[i]; i++) {
1153                                 match_len = strlen(matches[i]);
1154                                 if (match_len > maxlen)
1155                                         maxlen = match_len;
1156                         }
1157                         matches_num = i - 1;
1158                         if (matches_num >1) {
1159                                 fprintf(stdout, "\n");
1160                                 ast_cli_display_match_list(matches, nummatches, maxlen);
1161                                 retval = CC_REDISPLAY;
1162                         } else { 
1163                                 el_insertstr(el," ");
1164                                 retval = CC_REFRESH;
1165                         }
1166                 }
1167         free(matches);
1168         }
1169
1170         return (char *)retval;
1171 }
1172
1173 static int ast_el_initialize(void)
1174 {
1175         HistEvent ev;
1176
1177         if (el != NULL)
1178                 el_end(el);
1179         if (el_hist != NULL)
1180                 history_end(el_hist);
1181
1182         el = el_init("asterisk", stdin, stdout, stderr);
1183         el_set(el, EL_PROMPT, cli_prompt);
1184
1185         el_set(el, EL_EDITMODE, 1);             
1186         el_set(el, EL_EDITOR, "emacs");         
1187         el_hist = history_init();
1188         if (!el || !el_hist)
1189                 return -1;
1190
1191         /* setup history with 100 entries */
1192         history(el_hist, &ev, H_SETSIZE, 100);
1193
1194         el_set(el, EL_HIST, history, el_hist);
1195
1196         el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
1197         /* Bind <tab> to command completion */
1198         el_set(el, EL_BIND, "^I", "ed-complete", NULL);
1199         /* Bind ? to command completion */
1200         el_set(el, EL_BIND, "?", "ed-complete", NULL);
1201         /* Bind ^D to redisplay */
1202         el_set(el, EL_BIND, "^D", "ed-redisplay", NULL);
1203
1204         return 0;
1205 }
1206
1207 static int ast_el_add_history(char *buf)
1208 {
1209         HistEvent ev;
1210
1211         if (el_hist == NULL || el == NULL)
1212                 ast_el_initialize();
1213         if (strlen(buf) > 256)
1214                 return 0;
1215         return (history(el_hist, &ev, H_ENTER, buf));
1216 }
1217
1218 static int ast_el_write_history(char *filename)
1219 {
1220         HistEvent ev;
1221
1222         if (el_hist == NULL || el == NULL)
1223                 ast_el_initialize();
1224
1225         return (history(el_hist, &ev, H_SAVE, filename));
1226 }
1227
1228 static int ast_el_read_history(char *filename)
1229 {
1230         char buf[256];
1231         FILE *f;
1232         int ret = -1;
1233
1234         if (el_hist == NULL || el == NULL)
1235                 ast_el_initialize();
1236
1237         if ((f = fopen(filename, "r")) == NULL)
1238                 return ret;
1239
1240         while (!feof(f)) {
1241                 fgets(buf, sizeof(buf), f);
1242                 if (!strcmp(buf, "_HiStOrY_V2_\n"))
1243                         continue;
1244                 if ((ret = ast_el_add_history(buf)) == -1)
1245                         break;
1246         }
1247         fclose(f);
1248
1249         return ret;
1250 }
1251
1252 static void ast_remotecontrol(char * data)
1253 {
1254         char buf[80];
1255         int res;
1256         char filename[80] = "";
1257         char *hostname;
1258         char *cpid;
1259         char *version;
1260         int pid;
1261         char tmp[80];
1262         char *stringp=NULL;
1263
1264         char *ebuf;
1265         int num = 0;
1266
1267         read(ast_consock, buf, sizeof(buf));
1268         if (data)
1269                 write(ast_consock, data, strlen(data) + 1);
1270         stringp=buf;
1271         hostname = strsep(&stringp, "/");
1272         cpid = strsep(&stringp, "/");
1273         version = strsep(&stringp, "\n");
1274         if (!version)
1275                 version = "<Version Unknown>";
1276         stringp=hostname;
1277         strsep(&stringp, ".");
1278         if (cpid)
1279                 pid = atoi(cpid);
1280         else
1281                 pid = -1;
1282         snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
1283         fdprint(ast_consock, tmp);
1284         ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
1285         remotehostname = hostname;
1286         if (getenv("HOME")) 
1287                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1288         if (el_hist == NULL || el == NULL)
1289                 ast_el_initialize();
1290
1291         el_set(el, EL_GETCFN, ast_el_read_char);
1292
1293         if (strlen(filename))
1294                 ast_el_read_history(filename);
1295
1296         ast_cli_register(&quit);
1297         ast_cli_register(&astexit);
1298 #if 0
1299         ast_cli_register(&astshutdown);
1300 #endif  
1301         if (option_exec && data) {  /* hack to print output then exit if asterisk -rx is used */
1302                 char tempchar;
1303                 ast_el_read_char(el, &tempchar);
1304                 return;
1305         }
1306         for(;;) {
1307                 ebuf = (char *)el_gets(el, &num);
1308
1309                 if (ebuf && strlen(ebuf)) {
1310                         if (ebuf[strlen(ebuf)-1] == '\n')
1311                                 ebuf[strlen(ebuf)-1] = '\0';
1312                         if (!remoteconsolehandler(ebuf)) {
1313                                 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
1314                                 if (res < 1) {
1315                                         ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
1316                                         break;
1317                                 }
1318                         }
1319                 }
1320         }
1321         printf("\nDisconnected from Asterisk server\n");
1322 }
1323
1324 static int show_cli_help(void) {
1325         printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 2000-2002, Digium.\n");
1326         printf("Usage: asterisk [OPTIONS]\n");
1327         printf("Valid Options:\n");
1328         printf("   -h           This help screen\n");
1329         printf("   -r           Connect to Asterisk on this machine\n");
1330         printf("   -f           Do not fork\n");
1331         printf("   -n           Disable console colorization\n");
1332         printf("   -p           Run as pseudo-realtime thread\n");
1333         printf("   -v           Increase verbosity (multiple v's = more verbose)\n");
1334         printf("   -q           Quiet mode (supress output)\n");
1335         printf("   -g           Dump core in case of a crash\n");
1336         printf("   -x <cmd>     Execute command <cmd> (only valid with -r)\n");
1337         printf("   -i           Initializie crypto keys at startup\n");
1338         printf("   -c           Provide console CLI\n");
1339         printf("   -d           Enable extra debugging\n");
1340         printf("\n");
1341         return 0;
1342 }
1343
1344 static void ast_readconfig(void) {
1345         struct ast_config *cfg;
1346         struct ast_variable *v;
1347         char *config = ASTCONFPATH;
1348
1349         if (option_overrideconfig == 1) {
1350             cfg = ast_load((char *)ast_config_AST_CONFIG_FILE);
1351         } else {
1352             cfg = ast_load(config);
1353         }
1354
1355         /* init with buildtime config */
1356         strncpy((char *)ast_config_AST_CONFIG_DIR,AST_CONFIG_DIR,sizeof(ast_config_AST_CONFIG_DIR)-1);
1357         strncpy((char *)ast_config_AST_SPOOL_DIR,AST_SPOOL_DIR,sizeof(ast_config_AST_SPOOL_DIR)-1);
1358         strncpy((char *)ast_config_AST_MODULE_DIR,AST_MODULE_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1359         strncpy((char *)ast_config_AST_VAR_DIR,AST_VAR_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1360         strncpy((char *)ast_config_AST_LOG_DIR,AST_LOG_DIR,sizeof(ast_config_AST_LOG_DIR)-1);
1361         strncpy((char *)ast_config_AST_AGI_DIR,AST_AGI_DIR,sizeof(ast_config_AST_AGI_DIR)-1);
1362         strncpy((char *)ast_config_AST_DB,AST_DB,sizeof(ast_config_AST_DB)-1);
1363         strncpy((char *)ast_config_AST_KEY_DIR,AST_KEY_DIR,sizeof(ast_config_AST_KEY_DIR)-1);
1364         strncpy((char *)ast_config_AST_PID,AST_PID,sizeof(ast_config_AST_PID)-1);
1365         strncpy((char *)ast_config_AST_SOCKET,AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1);
1366         strncpy((char *)ast_config_AST_RUN_DIR,AST_RUN_DIR,sizeof(ast_config_AST_RUN_DIR)-1);
1367         
1368         /* no asterisk.conf? no problem, use buildtime config! */
1369         if (!cfg) {
1370             return;
1371         }
1372         v = ast_variable_browse(cfg, "directories");
1373         while(v) {
1374                 if (!strcasecmp(v->name, "astetcdir")) {
1375                     strncpy((char *)ast_config_AST_CONFIG_DIR,v->value,sizeof(ast_config_AST_CONFIG_DIR)-1);
1376                 } else if (!strcasecmp(v->name, "astspooldir")) {
1377                     strncpy((char *)ast_config_AST_SPOOL_DIR,v->value,sizeof(ast_config_AST_SPOOL_DIR)-1);
1378                 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1379                     strncpy((char *)ast_config_AST_VAR_DIR,v->value,sizeof(ast_config_AST_VAR_DIR)-1);
1380                     snprintf((char *)ast_config_AST_DB,sizeof(ast_config_AST_DB)-1,"%s/%s",v->value,"astdb");    
1381                 } else if (!strcasecmp(v->name, "astlogdir")) {
1382                     strncpy((char *)ast_config_AST_LOG_DIR,v->value,sizeof(ast_config_AST_LOG_DIR)-1);
1383                 } else if (!strcasecmp(v->name, "astagidir")) {
1384                     strncpy((char *)ast_config_AST_AGI_DIR,v->value,sizeof(ast_config_AST_AGI_DIR)-1);
1385                 } else if (!strcasecmp(v->name, "astrundir")) {
1386                     snprintf((char *)ast_config_AST_PID,sizeof(ast_config_AST_PID)-1,"%s/%s",v->value,"asterisk.pid");    
1387                     snprintf((char *)ast_config_AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1,"%s/%s",v->value,"asterisk.ctl");    
1388                     strncpy((char *)ast_config_AST_RUN_DIR,v->value,sizeof(ast_config_AST_RUN_DIR)-1);
1389                 } else if (!strcasecmp(v->name, "astmoddir")) {
1390                     strncpy((char *)ast_config_AST_MODULE_DIR,v->value,sizeof(ast_config_AST_MODULE_DIR)-1);
1391                 }
1392                 v = v->next;
1393         }
1394         ast_destroy(cfg);
1395 }
1396
1397 int main(int argc, char *argv[])
1398 {
1399         int c;
1400         char filename[80] = "";
1401         char hostname[256];
1402         char tmp[80];
1403         char * xarg = NULL;
1404         int x;
1405         FILE *f;
1406         sigset_t sigs;
1407         int num;
1408         char *buf;
1409
1410         /* Remember original args for restart */
1411         if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1412                 fprintf(stderr, "Truncating argument size to %d\n", sizeof(_argv) / sizeof(_argv[0]) - 1);
1413                 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1414         }
1415         for (x=0;x<argc;x++)
1416                 _argv[x] = argv[x];
1417         _argv[x] = NULL;
1418
1419         /* if the progname is rasterisk consider it a remote console */
1420         if ( argv[0] && (strstr(argv[0], "rasterisk")) != NULL)  {
1421                 option_remote++;
1422                 option_nofork++;
1423         }
1424         if (gethostname(hostname, sizeof(hostname)))
1425                 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
1426         ast_mainpid = getpid();
1427         ast_ulaw_init();
1428         ast_alaw_init();
1429         callerid_init();
1430         tdd_init();
1431         if (getenv("HOME")) 
1432                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1433         /* Check if we're root */
1434         /*
1435         if (geteuid()) {
1436                 ast_log(LOG_ERROR, "Must be run as root\n");
1437                 exit(1);
1438         }
1439         */
1440         /* Check for options */
1441         while((c=getopt(argc, argv, "hfdvqprgcinx:C:")) != -1) {
1442                 switch(c) {
1443                 case 'd':
1444                         option_debug++;
1445                         option_nofork++;
1446                         break;
1447                 case 'c':
1448                         option_console++;
1449                         option_nofork++;
1450                         break;
1451                 case 'f':
1452                         option_nofork++;
1453                         break;
1454                 case 'n':
1455                         option_nocolor++;
1456                         break;
1457                 case 'r':
1458                         option_remote++;
1459                         option_nofork++;
1460                         break;
1461                 case 'p':
1462                         option_highpriority++;
1463                         break;
1464                 case 'v':
1465                         option_verbose++;
1466                         option_nofork++;
1467                         break;
1468                 case 'q':
1469                         option_quiet++;
1470                         break;
1471                 case 'x':
1472                         option_exec++;
1473                         xarg = optarg;
1474                         break;
1475                 case 'C':
1476                         strncpy((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE));
1477                         option_overrideconfig++;
1478                         break;
1479                 case 'i':
1480                         option_initcrypto++;
1481                         break;
1482                 case'g':
1483                         option_dumpcore++;
1484                         break;
1485                 case 'h':
1486                         show_cli_help();
1487                         exit(0);
1488                 case '?':
1489                         exit(1);
1490                 }
1491         }
1492
1493         if (option_dumpcore) {
1494                 struct rlimit l;
1495                 memset(&l, 0, sizeof(l));
1496                 l.rlim_cur = RLIM_INFINITY;
1497                 l.rlim_max = RLIM_INFINITY;
1498                 if (setrlimit(RLIMIT_CORE, &l)) {
1499                         ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
1500                 }
1501         }
1502
1503         term_init();
1504         printf(term_end());
1505         fflush(stdout);
1506         if (option_console && !option_verbose) 
1507                 ast_verbose("[ Reading Master Configuration ]");
1508         ast_readconfig();
1509
1510         if (option_console) {
1511                 if (el_hist == NULL || el == NULL)
1512                         ast_el_initialize();
1513
1514                 if (strlen(filename))
1515                         ast_el_read_history(filename);
1516         }
1517
1518         if (ast_tryconnect()) {
1519                 /* One is already running */
1520                 if (option_remote) {
1521                         if (option_exec) {
1522                                 ast_remotecontrol(xarg);
1523                                 quit_handler(0, 0, 0, 0);
1524                                 exit(0);
1525                         }
1526                         printf(term_quit());
1527                         ast_register_verbose(console_verboser);
1528                         ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2004 Digium.\n");
1529                         ast_verbose( "Written by Mark Spencer <markster@digium.com>\n");
1530                         ast_verbose( "=========================================================================\n");
1531                         ast_remotecontrol(NULL);
1532                         quit_handler(0, 0, 0, 0);
1533                         exit(0);
1534                 } else {
1535                         ast_log(LOG_ERROR, "Asterisk already running on %s.  Use 'asterisk -r' to connect.\n", (char *)ast_config_AST_SOCKET);
1536                         printf(term_quit());
1537                         exit(1);
1538                 }
1539         } else if (option_remote || option_exec) {
1540                 ast_log(LOG_ERROR, "Unable to connect to remote asterisk\n");
1541                 printf(term_quit());
1542                 exit(1);
1543         }
1544         /* Blindly write pid file since we couldn't connect */
1545         unlink((char *)ast_config_AST_PID);
1546         f = fopen((char *)ast_config_AST_PID, "w");
1547         if (f) {
1548                 fprintf(f, "%d\n", getpid());
1549                 fclose(f);
1550         } else
1551                 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1552
1553         if (!option_verbose && !option_debug && !option_nofork && !option_console) {
1554                 daemon(0,0);
1555                 /* Blindly re-write pid file since we are forking */
1556                 unlink((char *)ast_config_AST_PID);
1557                 f = fopen((char *)ast_config_AST_PID, "w");
1558                 if (f) {
1559                         fprintf(f, "%d\n", getpid());
1560                         fclose(f);
1561                 } else
1562                         ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1563         }
1564
1565         ast_makesocket();
1566         sigemptyset(&sigs);
1567         sigaddset(&sigs, SIGHUP);
1568         sigaddset(&sigs, SIGTERM);
1569         sigaddset(&sigs, SIGINT);
1570         sigaddset(&sigs, SIGPIPE);
1571         sigaddset(&sigs, SIGWINCH);
1572         pthread_sigmask(SIG_BLOCK, &sigs, NULL);
1573         if (option_console || option_verbose || option_remote)
1574                 ast_register_verbose(console_verboser);
1575         /* Print a welcome message if desired */
1576         if (option_verbose || option_console) {
1577                 ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2001 Linux Support Services, Inc.\n");
1578                 ast_verbose( "Written by Mark Spencer <markster@linux-support.net>\n");
1579                 ast_verbose( "=========================================================================\n");
1580         }
1581         if (option_console && !option_verbose) 
1582                 ast_verbose("[ Booting...");
1583
1584         signal(SIGURG, urg_handler);
1585         signal(SIGINT, __quit_handler);
1586         signal(SIGTERM, __quit_handler);
1587         signal(SIGHUP, hup_handler);
1588         signal(SIGCHLD, child_handler);
1589         signal(SIGPIPE, SIG_IGN);
1590
1591         if (set_priority(option_highpriority)) {
1592                 printf(term_quit());
1593                 exit(1);
1594         }
1595         if (init_logger()) {
1596                 printf(term_quit());
1597                 exit(1);
1598         }
1599         if (init_manager()) {
1600                 printf(term_quit());
1601                 exit(1);
1602         }
1603         ast_rtp_init();
1604         if (ast_image_init()) {
1605                 printf(term_quit());
1606                 exit(1);
1607         }
1608         if (load_pbx()) {
1609                 printf(term_quit());
1610                 exit(1);
1611         }
1612         if (load_modules()) {
1613                 printf(term_quit());
1614                 exit(1);
1615         }
1616         if (init_framer()) {
1617                 printf(term_quit());
1618                 exit(1);
1619         }
1620         if (astdb_init()) {
1621                 printf(term_quit());
1622                 exit(1);
1623         }
1624         if (ast_enum_init()) {
1625                 printf(term_quit());
1626                 exit(1);
1627         }
1628         /* We might have the option of showing a console, but for now just
1629            do nothing... */
1630         if (option_console && !option_verbose)
1631                 ast_verbose(" ]\n");
1632         if (option_verbose || option_console)
1633                 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
1634         if (option_nofork)
1635                 consolethread = pthread_self();
1636         fully_booted = 1;
1637         pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
1638 #ifdef __AST_DEBUG_MALLOC
1639         __ast_mm_init();
1640 #endif  
1641         time(&ast_startuptime);
1642         ast_cli_register(&astshutdownnow);
1643         ast_cli_register(&astshutdowngracefully);
1644         ast_cli_register(&astrestartnow);
1645         ast_cli_register(&astrestartgracefully);
1646         ast_cli_register(&astrestartwhenconvenient);
1647         ast_cli_register(&astshutdownwhenconvenient);
1648         ast_cli_register(&aborthalt);
1649         ast_cli_register(&astbang);
1650         if (option_console) {
1651                 /* Console stuff now... */
1652                 /* Register our quit function */
1653                 char title[256];
1654                 set_icon("Asterisk");
1655                 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, ast_mainpid);
1656                 set_title(title);
1657             ast_cli_register(&quit);
1658             ast_cli_register(&astexit);
1659
1660                 for (;;) {
1661                         buf = (char *)el_gets(el, &num);
1662                         if (buf) {
1663                                 if (buf[strlen(buf)-1] == '\n')
1664                                         buf[strlen(buf)-1] = '\0';
1665
1666                                 consolehandler((char *)buf);
1667                         } else {
1668                                 if (option_remote)
1669                                         ast_cli(STDOUT_FILENO, "\nUse EXIT or QUIT to exit the asterisk console\n");
1670                                 else
1671                                         ast_cli(STDOUT_FILENO, "\nUse STOP NOW to shutdown Asterisk\n");
1672                         }
1673                 }
1674
1675         } else {
1676                 /* Do nothing */
1677                 poll(NULL,0, -1);
1678         }
1679         return 0;
1680 }
1681
1682
1683 #if  defined(__FreeBSD__)
1684
1685 /* duh? ERANGE value copied from web... */
1686 #define ERANGE 34
1687 #undef gethostbyname
1688
1689 int gethostbyname_r (const char *name,
1690                      struct hostent *ret,
1691                      char *buf,
1692                      size_t buflen,
1693                      struct hostent **result,
1694                      int *h_errnop);
1695
1696 int gethostbyname_r (const char *name,
1697                      struct hostent *ret,
1698                      char *buf,
1699                      size_t buflen,
1700                      struct hostent **result,
1701                      int *h_errnop) {
1702
1703   int hsave;
1704   struct hostent *ph;
1705   static ast_mutex_t __mutex = AST_MUTEX_INITIALIZER;
1706   ast_mutex_lock(&__mutex); /* begin critical area */
1707   hsave = h_errno;
1708
1709   ph = gethostbyname(name);
1710   *h_errnop = h_errno; /* copy h_errno to *h_herrnop */
1711   if (ph == NULL) {
1712     *result = NULL;
1713   } else {
1714     char **p, **q;
1715     char *pbuf;
1716     int nbytes=0;
1717     int naddr=0, naliases=0;
1718     /* determine if we have enough space in buf */
1719
1720     /* count how many addresses */
1721     for (p = ph->h_addr_list; *p != 0; p++) {
1722       nbytes += ph->h_length; /* addresses */
1723       nbytes += sizeof(*p); /* pointers */
1724       naddr++;
1725     }
1726     nbytes += sizeof(*p); /* one more for the terminating NULL */
1727
1728     /* count how many aliases, and total length of strings */
1729
1730     for (p = ph->h_aliases; *p != 0; p++) {
1731       nbytes += (strlen(*p)+1); /* aliases */
1732       nbytes += sizeof(*p);  /* pointers */
1733       naliases++;
1734     }
1735     nbytes += sizeof(*p); /* one more for the terminating NULL */
1736
1737     /* here nbytes is the number of bytes required in buffer */
1738     /* as a terminator must be there, the minimum value is ph->h_length */
1739     if(nbytes > buflen) {
1740       *result = NULL;
1741       pthread_mutex_unlock(&__mutex); /* end critical area */
1742       return ERANGE; /* not enough space in buf!! */
1743     }
1744
1745     /* There is enough space. Now we need to do a deep copy! */
1746     /* Allocation in buffer:
1747        from [0] to [(naddr-1) * sizeof(*p)]:
1748        pointers to addresses
1749        at [naddr * sizeof(*p)]:
1750        NULL
1751        from [(naddr+1) * sizeof(*p)] to [(naddr+naliases) * sizeof(*p)] :
1752        pointers to aliases
1753        at [(naddr+naliases+1) * sizeof(*p)]:
1754        NULL
1755        then naddr addresses (fixed length), and naliases aliases (asciiz).
1756     */
1757
1758     *ret = *ph;   /* copy whole structure (not its address!) */
1759
1760     /* copy addresses */
1761     q = (char **)buf; /* pointer to pointers area (type: char **) */
1762     ret->h_addr_list = q; /* update pointer to address list */
1763     pbuf = buf + ((naddr+naliases+2)*sizeof(*p)); /* skip that area */
1764     for (p = ph->h_addr_list; *p != 0; p++) {
1765       memcpy(pbuf, *p, ph->h_length); /* copy address bytes */
1766       *q++ = pbuf; /* the pointer is the one inside buf... */
1767       pbuf += ph->h_length; /* advance pbuf */
1768     }
1769     *q++ = NULL; /* address list terminator */
1770
1771     /* copy aliases */
1772
1773     ret->h_aliases = q; /* update pointer to aliases list */
1774     for (p = ph->h_aliases; *p != 0; p++) {
1775       strcpy(pbuf, *p); /* copy alias strings */
1776       *q++ = pbuf; /* the pointer is the one inside buf... */
1777       pbuf += strlen(*p); /* advance pbuf */
1778       *pbuf++ = 0; /* string terminator */
1779     }
1780     *q++ = NULL; /* terminator */
1781
1782     strcpy(pbuf, ph->h_name); /* copy alias strings */
1783     ret->h_name = pbuf;
1784     pbuf += strlen(ph->h_name); /* advance pbuf */
1785     *pbuf++ = 0; /* string terminator */
1786
1787     *result = ret;  /* and let *result point to structure */
1788
1789   }
1790   h_errno = hsave;  /* restore h_errno */
1791
1792   ast_mutex_unlock(&__mutex); /* end critical area */
1793
1794   return (*result != NULL);
1795
1796 }
1797
1798
1799 #endif
1800
1801 struct hostent *ast_gethostbyname(const char *host, struct ast_hostent *hp)
1802 {
1803         int res;
1804         int herrno;
1805         struct hostent *result = NULL;
1806
1807         res = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &result, &herrno);
1808
1809         if (res)
1810                 return NULL;
1811         return &hp->hp;
1812 }