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