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