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