dd943334e492de144f9275ca575bd6a21df3c791
[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                 else
549                         execvp(_argv[0], _argv);
550         
551         }
552         exit(0);
553 }
554
555 static void __quit_handler(int num)
556 {
557         quit_handler(num, 0, 1, 0);
558 }
559
560 static const char *fix_header(char *outbuf, int maxout, const char *s, char *cmp)
561 {
562         const char *c;
563         if (!strncmp(s, cmp, strlen(cmp))) {
564                 c = s + strlen(cmp);
565                 term_color(outbuf, cmp, COLOR_GRAY, 0, maxout);
566                 return c;
567         }
568         return NULL;
569 }
570
571 static void console_verboser(const char *s, int pos, int replace, int complete)
572 {
573         char tmp[80];
574         const char *c=NULL;
575         /* Return to the beginning of the line */
576         if (!pos) {
577                 fprintf(stdout, "\r");
578                 if ((c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_4)) ||
579                         (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_3)) ||
580                         (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_2)) ||
581                         (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_1)))
582                         fputs(tmp, stdout);
583         }
584         if (c)
585                 fputs(c + pos,stdout);
586         else
587                 fputs(s + pos,stdout);
588         fflush(stdout);
589         if (complete)
590         /* Wake up a select()ing console */
591                 if (option_console && consolethread != (pthread_t) -1)
592                         pthread_kill(consolethread, SIGURG);
593 }
594
595 static void consolehandler(char *s)
596 {
597         printf(term_end());
598         fflush(stdout);
599         /* Called when readline data is available */
600         if (s && strlen(s))
601                 ast_el_add_history(s);
602         /* Give the console access to the shell */
603         if (s) {
604                 /* The real handler for bang */
605                 if (s[0] == '!') {
606                         if (s[1])
607                                 system(s+1);
608                         else
609                                 system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
610                 } else 
611                 ast_cli_command(STDOUT_FILENO, s);
612         } else
613                 fprintf(stdout, "\nUse \"quit\" to exit\n");
614 }
615
616 static int remoteconsolehandler(char *s)
617 {
618         int ret = 0;
619         /* Called when readline data is available */
620         if (s && strlen(s))
621                 ast_el_add_history(s);
622         /* Give the console access to the shell */
623         if (s) {
624                 /* The real handler for bang */
625                 if (s[0] == '!') {
626                         if (s[1])
627                                 system(s+1);
628                         else
629                                 system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
630                         ret = 1;
631                 }
632                 if ((strncasecmp(s, "quit", 4) == 0 || strncasecmp(s, "exit", 4) == 0) &&
633                     (s[4] == '\0' || isspace(s[4]))) {
634                         quit_handler(0, 0, 0, 0);
635                         ret = 1;
636                 }
637         } else
638                 fprintf(stdout, "\nUse \"quit\" to exit\n");
639
640         return ret;
641 }
642
643 static char quit_help[] = 
644 "Usage: quit\n"
645 "       Exits Asterisk.\n";
646
647 static char abort_halt_help[] = 
648 "Usage: abort shutdown\n"
649 "       Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
650 "       call operations.\n";
651
652 static char shutdown_now_help[] = 
653 "Usage: stop now\n"
654 "       Shuts down a running Asterisk immediately, hanging up all active calls .\n";
655
656 static char shutdown_gracefully_help[] = 
657 "Usage: stop gracefully\n"
658 "       Causes Asterisk to not accept new calls, and exit when all\n"
659 "       active calls have terminated normally.\n";
660
661 static char shutdown_when_convenient_help[] = 
662 "Usage: stop when convenient\n"
663 "       Causes Asterisk to perform a shutdown when all active calls have ended.\n";
664
665 static char restart_now_help[] = 
666 "Usage: restart now\n"
667 "       Causes Asterisk to hangup all calls and exec() itself performing a cold.\n"
668 "       restart.\n";
669
670 static char restart_gracefully_help[] = 
671 "Usage: restart gracefully\n"
672 "       Causes Asterisk to stop accepting new calls and exec() itself performing a cold.\n"
673 "       restart when all active calls have ended.\n";
674
675 static char restart_when_convenient_help[] = 
676 "Usage: restart when convenient\n"
677 "       Causes Asterisk to perform a cold restart when all active calls have ended.\n";
678
679 static char bang_help[] =
680 "Usage: !<command>\n"
681 "       Executes a given shell command\n";
682
683 #if 0
684 static int handle_quit(int fd, int argc, char *argv[])
685 {
686         if (argc != 1)
687                 return RESULT_SHOWUSAGE;
688         quit_handler(0, 0, 1, 0);
689         return RESULT_SUCCESS;
690 }
691 #endif
692
693 static int no_more_quit(int fd, int argc, char *argv[])
694 {
695         if (argc != 1)
696                 return RESULT_SHOWUSAGE;
697         ast_cli(fd, "The QUIT and EXIT commands may no longer be used to shutdown the PBX.\n"
698                     "Please use STOP NOW instead, if you wish to shutdown the PBX.\n");
699         return RESULT_SUCCESS;
700 }
701
702 static int handle_shutdown_now(int fd, int argc, char *argv[])
703 {
704         if (argc != 2)
705                 return RESULT_SHOWUSAGE;
706         quit_handler(0, 0 /* Not nice */, 1 /* safely */, 0 /* not restart */);
707         return RESULT_SUCCESS;
708 }
709
710 static int handle_shutdown_gracefully(int fd, int argc, char *argv[])
711 {
712         if (argc != 2)
713                 return RESULT_SHOWUSAGE;
714         quit_handler(0, 1 /* nicely */, 1 /* safely */, 0 /* no restart */);
715         return RESULT_SUCCESS;
716 }
717
718 static int handle_shutdown_when_convenient(int fd, int argc, char *argv[])
719 {
720         if (argc != 3)
721                 return RESULT_SHOWUSAGE;
722         quit_handler(0, 2 /* really nicely */, 1 /* safely */, 0 /* don't restart */);
723         return RESULT_SUCCESS;
724 }
725
726 static int handle_restart_now(int fd, int argc, char *argv[])
727 {
728         if (argc != 2)
729                 return RESULT_SHOWUSAGE;
730         quit_handler(0, 0 /* not nicely */, 1 /* safely */, 1 /* restart */);
731         return RESULT_SUCCESS;
732 }
733
734 static int handle_restart_gracefully(int fd, int argc, char *argv[])
735 {
736         if (argc != 2)
737                 return RESULT_SHOWUSAGE;
738         quit_handler(0, 1 /* nicely */, 1 /* safely */, 1 /* restart */);
739         return RESULT_SUCCESS;
740 }
741
742 static int handle_restart_when_convenient(int fd, int argc, char *argv[])
743 {
744         if (argc != 3)
745                 return RESULT_SHOWUSAGE;
746         quit_handler(0, 2 /* really nicely */, 1 /* safely */, 1 /* restart */);
747         return RESULT_SUCCESS;
748 }
749
750 static int handle_abort_halt(int fd, int argc, char *argv[])
751 {
752         if (argc != 2)
753                 return RESULT_SHOWUSAGE;
754         ast_cancel_shutdown();
755         shuttingdown = 0;
756         return RESULT_SUCCESS;
757 }
758
759 static int handle_bang(int fd, int argc, char *argv[])
760 {
761         return RESULT_SUCCESS;
762 }
763
764 #define ASTERISK_PROMPT "*CLI> "
765
766 #define ASTERISK_PROMPT2 "%s*CLI> "
767
768 static struct ast_cli_entry aborthalt = { { "abort", "halt", NULL }, handle_abort_halt, "Cancel a running halt", abort_halt_help };
769
770 static struct ast_cli_entry quit =      { { "quit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
771 static struct ast_cli_entry astexit =   { { "exit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
772
773 static struct ast_cli_entry astshutdownnow =    { { "stop", "now", NULL }, handle_shutdown_now, "Shut down Asterisk immediately", shutdown_now_help };
774 static struct ast_cli_entry astshutdowngracefully =     { { "stop", "gracefully", NULL }, handle_shutdown_gracefully, "Gracefully shut down Asterisk", shutdown_gracefully_help };
775 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 };
776 static struct ast_cli_entry astrestartnow =     { { "restart", "now", NULL }, handle_restart_now, "Restart Asterisk immediately", restart_now_help };
777 static struct ast_cli_entry astrestartgracefully =      { { "restart", "gracefully", NULL }, handle_restart_gracefully, "Restart Asterisk gracefully", restart_gracefully_help };
778 static struct ast_cli_entry astrestartwhenconvenient=   { { "restart", "when", "convenient", NULL }, handle_restart_when_convenient, "Restart Asterisk at empty call volume", restart_when_convenient_help };
779 static struct ast_cli_entry astbang = { { "!", NULL }, handle_bang, "Execute a shell command", bang_help };
780
781 static int ast_el_read_char(EditLine *el, char *cp)
782 {
783         int num_read=0;
784         int lastpos=0;
785         fd_set rfds;
786         int res;
787         int max;
788         char buf[512];
789
790         for (;;) {
791                 FD_ZERO(&rfds);
792                 FD_SET(ast_consock, &rfds);
793                 max = ast_consock;
794                 if (!option_exec) {
795                         FD_SET(STDIN_FILENO, &rfds);
796                         if (STDIN_FILENO > max)
797                                 max = STDIN_FILENO;
798                 }
799                 res = ast_select(max+1, &rfds, NULL, NULL, NULL);
800                 if (res < 0) {
801                         if (errno == EINTR)
802                                 continue;
803                         ast_log(LOG_ERROR, "select failed: %s\n", strerror(errno));
804                         break;
805                 }
806
807                 if (FD_ISSET(STDIN_FILENO, &rfds)) {
808                         num_read = read(STDIN_FILENO, cp, 1);
809                         if (num_read < 1) {
810                                 break;
811                         } else 
812                                 return (num_read);
813                 }
814                 if (FD_ISSET(ast_consock, &rfds)) {
815                         res = read(ast_consock, buf, sizeof(buf) - 1);
816                         /* if the remote side disappears exit */
817                         if (res < 1) {
818                                 fprintf(stderr, "\nDisconnected from Asterisk server\n");
819                                 quit_handler(0, 0, 0, 0);
820                         }
821
822                         buf[res] = '\0';
823
824                         if (!option_exec && !lastpos)
825                                 write(STDOUT_FILENO, "\r", 1);
826                         write(STDOUT_FILENO, buf, res);
827                         if ((buf[res-1] == '\n') || (buf[res-2] == '\n')) {
828                                 *cp = CC_REFRESH;
829                                 return(1);
830                         } else {
831                                 lastpos = 1;
832                         }
833                 }
834         }
835
836         *cp = '\0';
837         return (0);
838 }
839
840 static char *cli_prompt(EditLine *el)
841 {
842         static char prompt[80];
843
844         if (remotehostname)
845                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT2, remotehostname);
846         else
847                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT);
848
849         return(prompt); 
850 }
851
852 static char **ast_el_strtoarr(char *buf)
853 {
854         char **match_list = NULL, *retstr;
855         size_t match_list_len;
856         int matches = 0;
857
858         match_list_len = 1;
859         while ( (retstr = strsep(&buf, " ")) != NULL) {
860
861                 if (matches + 1 >= match_list_len) {
862                         match_list_len <<= 1;
863                         match_list = realloc(match_list, match_list_len * sizeof(char *));
864                 }
865
866                 match_list[matches++] = retstr;
867         }
868
869         if (!match_list)
870                 return (char **) NULL;
871
872         if (matches>= match_list_len)
873                 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
874
875         match_list[matches] = (char *) NULL;
876
877         return match_list;
878 }
879
880 static int ast_el_sort_compare(const void *i1, const void *i2)
881 {
882         char *s1, *s2;
883
884         s1 = ((char **)i1)[0];
885         s2 = ((char **)i2)[0];
886
887         return strcasecmp(s1, s2);
888 }
889
890 static int ast_cli_display_match_list(char **matches, int len, int max)
891 {
892         int i, idx, limit, count;
893         int screenwidth = 0;
894         int numoutput = 0, numoutputline = 0;
895
896         screenwidth = ast_get_termcols(STDOUT_FILENO);
897
898         /* find out how many entries can be put on one line, with two spaces between strings */
899         limit = screenwidth / (max + 2);
900         if (limit == 0)
901                 limit = 1;
902
903         /* how many lines of output */
904         count = len / limit;
905         if (count * limit < len)
906                 count++;
907
908         idx = 1;
909
910         qsort(&matches[0], (size_t)(len + 1), sizeof(char *), ast_el_sort_compare);
911
912         for (; count > 0; count--) {
913                 numoutputline = 0;
914                 for (i=0; i < limit && matches[idx]; i++, idx++) {
915
916                         /* Don't print dupes */
917                         if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
918                                 i--;
919                                 continue;
920                         }
921
922                         numoutput++;  numoutputline++;
923                         fprintf(stdout, "%-*s  ", max, matches[idx]);
924                 }
925                 if (numoutputline > 0)
926                         fprintf(stdout, "\n");
927         }
928
929         return numoutput;
930 }
931
932
933 static char *cli_complete(EditLine *el, int ch)
934 {
935         int len=0;
936         char *ptr;
937         int nummatches = 0;
938         char **matches;
939         int retval = CC_ERROR;
940         char buf[1024];
941         int res;
942
943         LineInfo *lf = (LineInfo *)el_line(el);
944
945         *(char *)lf->cursor = '\0';
946         ptr = (char *)lf->cursor;
947         if (ptr) {
948                 while (ptr > lf->buffer) {
949                         if (isspace(*ptr)) {
950                                 ptr++;
951                                 break;
952                         }
953                         ptr--;
954                 }
955         }
956
957         len = lf->cursor - ptr;
958
959         if (option_remote) {
960                 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr); 
961                 fdprint(ast_consock, buf);
962                 res = read(ast_consock, buf, sizeof(buf));
963                 buf[res] = '\0';
964                 nummatches = atoi(buf);
965
966                 if (nummatches > 0) {
967                         snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr); 
968                         fdprint(ast_consock, buf);
969                         res = read(ast_consock, buf, sizeof(buf));
970                         buf[res] = '\0';
971
972                         matches = ast_el_strtoarr(buf);
973                 } else
974                         matches = (char **) NULL;
975
976
977         }  else {
978
979                 nummatches = ast_cli_generatornummatches((char *)lf->buffer,ptr);
980                 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
981         }
982
983         if (matches) {
984                 int i;
985                 int matches_num, maxlen, match_len;
986
987                 if (matches[0][0] != '\0') {
988                         el_deletestr(el, (int) len);
989                         el_insertstr(el, matches[0]);
990                         retval = CC_REFRESH;
991                 }
992
993                 if (nummatches == 1) {
994                         /* Found an exact match */
995                         el_insertstr(el, " ");
996                         retval = CC_REFRESH;
997                 } else {
998                         /* Must be more than one match */
999                         for (i=1, maxlen=0; matches[i]; i++) {
1000                                 match_len = strlen(matches[i]);
1001                                 if (match_len > maxlen)
1002                                         maxlen = match_len;
1003                         }
1004                         matches_num = i - 1;
1005                         if (matches_num >1) {
1006                                 fprintf(stdout, "\n");
1007                                 ast_cli_display_match_list(matches, nummatches, maxlen);
1008                                 retval = CC_REDISPLAY;
1009                         } else { 
1010                                 el_insertstr(el," ");
1011                                 retval = CC_REFRESH;
1012                         }
1013                 }
1014         free(matches);
1015         }
1016
1017         return (char *)retval;
1018 }
1019
1020 static int ast_el_initialize(void)
1021 {
1022         HistEvent ev;
1023
1024         if (el != NULL)
1025                 el_end(el);
1026         if (el_hist != NULL)
1027                 history_end(el_hist);
1028
1029         el = el_init("asterisk", stdin, stdout, stderr);
1030         el_set(el, EL_PROMPT, cli_prompt);
1031
1032         el_set(el, EL_EDITMODE, 1);             
1033         el_set(el, EL_EDITOR, "emacs");         
1034         el_hist = history_init();
1035         if (!el || !el_hist)
1036                 return -1;
1037
1038         /* setup history with 100 entries */
1039         history(el_hist, &ev, H_SETSIZE, 100);
1040
1041         el_set(el, EL_HIST, history, el_hist);
1042
1043         el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
1044         /* Bind <tab> to command completion */
1045         el_set(el, EL_BIND, "^I", "ed-complete", NULL);
1046         /* Bind ? to command completion */
1047         el_set(el, EL_BIND, "?", "ed-complete", NULL);
1048
1049         return 0;
1050 }
1051
1052 static int ast_el_add_history(char *buf)
1053 {
1054         HistEvent ev;
1055
1056         if (el_hist == NULL || el == NULL)
1057                 ast_el_initialize();
1058         if (strlen(buf) > 256)
1059                 return 0;
1060         return (history(el_hist, &ev, H_ENTER, buf));
1061 }
1062
1063 static int ast_el_write_history(char *filename)
1064 {
1065         HistEvent ev;
1066
1067         if (el_hist == NULL || el == NULL)
1068                 ast_el_initialize();
1069
1070         return (history(el_hist, &ev, H_SAVE, filename));
1071 }
1072
1073 static int ast_el_read_history(char *filename)
1074 {
1075         char buf[256];
1076         FILE *f;
1077         int ret = -1;
1078
1079         if (el_hist == NULL || el == NULL)
1080                 ast_el_initialize();
1081
1082         if ((f = fopen(filename, "r")) == NULL)
1083                 return ret;
1084
1085         while (!feof(f)) {
1086                 fgets(buf, sizeof(buf), f);
1087                 if (!strcmp(buf, "_HiStOrY_V2_\n"))
1088                         continue;
1089                 if ((ret = ast_el_add_history(buf)) == -1)
1090                         break;
1091         }
1092         fclose(f);
1093
1094         return ret;
1095 }
1096
1097 static void ast_remotecontrol(char * data)
1098 {
1099         char buf[80];
1100         int res;
1101         char filename[80] = "";
1102         char *hostname;
1103         char *cpid;
1104         char *version;
1105         int pid;
1106         char tmp[80];
1107         char *stringp=NULL;
1108
1109         char *ebuf;
1110         int num = 0;
1111
1112         read(ast_consock, buf, sizeof(buf));
1113         if (data)
1114                 write(ast_consock, data, strlen(data) + 1);
1115         stringp=buf;
1116         hostname = strsep(&stringp, "/");
1117         cpid = strsep(&stringp, "/");
1118         version = strsep(&stringp, "\n");
1119         if (!version)
1120                 version = "<Version Unknown>";
1121         stringp=hostname;
1122         strsep(&stringp, ".");
1123         if (cpid)
1124                 pid = atoi(cpid);
1125         else
1126                 pid = -1;
1127         snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
1128         fdprint(ast_consock, tmp);
1129         ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
1130         remotehostname = hostname;
1131         if (getenv("HOME")) 
1132                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1133         if (el_hist == NULL || el == NULL)
1134                 ast_el_initialize();
1135
1136         el_set(el, EL_GETCFN, ast_el_read_char);
1137
1138         if (strlen(filename))
1139                 ast_el_read_history(filename);
1140
1141         ast_cli_register(&quit);
1142         ast_cli_register(&astexit);
1143 #if 0
1144         ast_cli_register(&astshutdown);
1145 #endif  
1146         if (option_exec && data) {  /* hack to print output then exit if asterisk -rx is used */
1147                 char tempchar;
1148                 ast_el_read_char(el, &tempchar);
1149                 return;
1150         }
1151         for(;;) {
1152                 ebuf = (char *)el_gets(el, &num);
1153
1154                 if (ebuf && strlen(ebuf)) {
1155                         if (ebuf[strlen(ebuf)-1] == '\n')
1156                                 ebuf[strlen(ebuf)-1] = '\0';
1157                         if (!remoteconsolehandler(ebuf)) {
1158                                 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
1159                                 if (res < 1) {
1160                                         ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
1161                                         break;
1162                                 }
1163                         }
1164                 }
1165         }
1166         printf("\nDisconnected from Asterisk server\n");
1167 }
1168
1169 static int show_cli_help(void) {
1170         printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 2000-2002, Digium.\n");
1171         printf("Usage: asterisk [OPTIONS]\n");
1172         printf("Valid Options:\n");
1173         printf("   -h           This help screen\n");
1174         printf("   -r           Connect to Asterisk on this machine\n");
1175         printf("   -f           Do not fork\n");
1176         printf("   -n           Disable console colorization\n");
1177         printf("   -p           Run as pseudo-realtime thread\n");
1178         printf("   -v           Increase verbosity (multiple v's = more verbose)\n");
1179         printf("   -q           Quiet mode (supress output)\n");
1180         printf("   -g           Dump core in case of a crash\n");
1181         printf("   -x <cmd>     Execute command <cmd> (only valid with -r)\n");
1182         printf("   -i           Initializie crypto keys at startup\n");
1183         printf("   -c           Provide console CLI\n");
1184         printf("   -d           Enable extra debugging\n");
1185         printf("\n");
1186         return 0;
1187 }
1188
1189 static void ast_readconfig(void) {
1190         struct ast_config *cfg;
1191         struct ast_variable *v;
1192         char *config = ASTCONFPATH;
1193
1194         if (option_overrideconfig == 1) {
1195             cfg = ast_load((char *)ast_config_AST_CONFIG_FILE);
1196         } else {
1197             cfg = ast_load(config);
1198         }
1199
1200         /* init with buildtime config */
1201         strncpy((char *)ast_config_AST_CONFIG_DIR,AST_CONFIG_DIR,sizeof(ast_config_AST_CONFIG_DIR)-1);
1202         strncpy((char *)ast_config_AST_SPOOL_DIR,AST_SPOOL_DIR,sizeof(ast_config_AST_SPOOL_DIR)-1);
1203         strncpy((char *)ast_config_AST_MODULE_DIR,AST_MODULE_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1204         strncpy((char *)ast_config_AST_VAR_DIR,AST_VAR_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1205         strncpy((char *)ast_config_AST_LOG_DIR,AST_LOG_DIR,sizeof(ast_config_AST_LOG_DIR)-1);
1206         strncpy((char *)ast_config_AST_AGI_DIR,AST_AGI_DIR,sizeof(ast_config_AST_AGI_DIR)-1);
1207         strncpy((char *)ast_config_AST_DB,AST_DB,sizeof(ast_config_AST_DB)-1);
1208         strncpy((char *)ast_config_AST_KEY_DIR,AST_KEY_DIR,sizeof(ast_config_AST_KEY_DIR)-1);
1209         strncpy((char *)ast_config_AST_PID,AST_PID,sizeof(ast_config_AST_PID)-1);
1210         strncpy((char *)ast_config_AST_SOCKET,AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1);
1211         strncpy((char *)ast_config_AST_RUN_DIR,AST_RUN_DIR,sizeof(ast_config_AST_RUN_DIR)-1);
1212         
1213         /* no asterisk.conf? no problem, use buildtime config! */
1214         if (!cfg) {
1215             return;
1216         }
1217         v = ast_variable_browse(cfg, "directories");
1218         while(v) {
1219                 if (!strcasecmp(v->name, "astetcdir")) {
1220                     strncpy((char *)ast_config_AST_CONFIG_DIR,v->value,sizeof(ast_config_AST_CONFIG_DIR)-1);
1221                 } else if (!strcasecmp(v->name, "astspooldir")) {
1222                     strncpy((char *)ast_config_AST_SPOOL_DIR,v->value,sizeof(ast_config_AST_SPOOL_DIR)-1);
1223                 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1224                     strncpy((char *)ast_config_AST_VAR_DIR,v->value,sizeof(ast_config_AST_VAR_DIR)-1);
1225                     snprintf((char *)ast_config_AST_DB,sizeof(ast_config_AST_DB)-1,"%s/%s",v->value,"astdb");    
1226                 } else if (!strcasecmp(v->name, "astlogdir")) {
1227                     strncpy((char *)ast_config_AST_LOG_DIR,v->value,sizeof(ast_config_AST_LOG_DIR)-1);
1228                 } else if (!strcasecmp(v->name, "astagidir")) {
1229                     strncpy((char *)ast_config_AST_AGI_DIR,v->value,sizeof(ast_config_AST_AGI_DIR)-1);
1230                 } else if (!strcasecmp(v->name, "astrundir")) {
1231                     snprintf((char *)ast_config_AST_PID,sizeof(ast_config_AST_PID)-1,"%s/%s",v->value,"asterisk.pid");    
1232                     snprintf((char *)ast_config_AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1,"%s/%s",v->value,"asterisk.ctl");    
1233                     strncpy((char *)ast_config_AST_RUN_DIR,v->value,sizeof(ast_config_AST_RUN_DIR)-1);
1234                 } else if (!strcasecmp(v->name, "astmoddir")) {
1235                     strncpy((char *)ast_config_AST_MODULE_DIR,v->value,sizeof(ast_config_AST_MODULE_DIR)-1);
1236                 }
1237                 v = v->next;
1238         }
1239         ast_destroy(cfg);
1240 }
1241
1242 int main(int argc, char *argv[])
1243 {
1244         int c;
1245         char filename[80] = "";
1246         char hostname[256];
1247         char tmp[80];
1248         char * xarg = NULL;
1249         int x;
1250         FILE *f;
1251         sigset_t sigs;
1252         int num;
1253         char *buf;
1254
1255         /* Remember original args for restart */
1256         if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1257                 fprintf(stderr, "Truncating argument size to %d\n", sizeof(_argv) / sizeof(_argv[0]) - 1);
1258                 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1259         }
1260         for (x=0;x<argc;x++)
1261                 _argv[x] = argv[x];
1262         _argv[x] = NULL;
1263
1264         if (gethostname(hostname, sizeof(hostname)))
1265                 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
1266         mainpid = getpid();
1267         ast_ulaw_init();
1268         ast_alaw_init();
1269         callerid_init();
1270         tdd_init();
1271         if (getenv("HOME")) 
1272                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1273         /* Check if we're root */
1274         /*
1275         if (geteuid()) {
1276                 ast_log(LOG_ERROR, "Must be run as root\n");
1277                 exit(1);
1278         }
1279         */
1280         /* Check for options */
1281         while((c=getopt(argc, argv, "hfdvqprgcinx:C:")) != -1) {
1282                 switch(c) {
1283                 case 'd':
1284                         option_debug++;
1285                         option_nofork++;
1286                         break;
1287                 case 'c':
1288                         option_console++;
1289                         option_nofork++;
1290                         break;
1291                 case 'f':
1292                         option_nofork++;
1293                         break;
1294                 case 'n':
1295                         option_nocolor++;
1296                         break;
1297                 case 'r':
1298                         option_remote++;
1299                         option_nofork++;
1300                         break;
1301                 case 'p':
1302                         option_highpriority++;
1303                         break;
1304                 case 'v':
1305                         option_verbose++;
1306                         option_nofork++;
1307                         break;
1308                 case 'q':
1309                         option_quiet++;
1310                         break;
1311                 case 'x':
1312                         option_exec++;
1313                         xarg = optarg;
1314                         break;
1315                 case 'C':
1316                         strncpy((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE));
1317                         option_overrideconfig++;
1318                         break;
1319                 case 'i':
1320                         option_initcrypto++;
1321                         break;
1322                 case'g':
1323                         option_dumpcore++;
1324                         break;
1325                 case 'h':
1326                         show_cli_help();
1327                         exit(0);
1328                 case '?':
1329                         exit(1);
1330                 }
1331         }
1332
1333         if (option_dumpcore) {
1334                 struct rlimit l;
1335                 memset(&l, 0, sizeof(l));
1336                 l.rlim_cur = RLIM_INFINITY;
1337                 l.rlim_max = RLIM_INFINITY;
1338                 if (setrlimit(RLIMIT_CORE, &l)) {
1339                         ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
1340                 }
1341         }
1342
1343         term_init();
1344         printf(term_end());
1345         fflush(stdout);
1346         if (option_console && !option_verbose) 
1347                 ast_verbose("[ Reading Master Configuration ]");
1348         ast_readconfig();
1349
1350         if (option_console) {
1351                 if (el_hist == NULL || el == NULL)
1352                         ast_el_initialize();
1353
1354                 if (strlen(filename))
1355                         ast_el_read_history(filename);
1356         }
1357
1358         if (ast_tryconnect()) {
1359                 /* One is already running */
1360                 if (option_remote) {
1361                         if (option_exec) {
1362                                 ast_remotecontrol(xarg);
1363                                 quit_handler(0, 0, 0, 0);
1364                                 exit(0);
1365                         }
1366                         printf(term_quit());
1367                         ast_register_verbose(console_verboser);
1368                         ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2004 Digium.\n");
1369                         ast_verbose( "Written by Mark Spencer <markster@digium.com>\n");
1370                         ast_verbose( "=========================================================================\n");
1371                         ast_remotecontrol(NULL);
1372                         quit_handler(0, 0, 0, 0);
1373                         exit(0);
1374                 } else {
1375                         ast_log(LOG_ERROR, "Asterisk already running on %s.  Use 'asterisk -r' to connect.\n", (char *)ast_config_AST_SOCKET);
1376                         printf(term_quit());
1377                         exit(1);
1378                 }
1379         } else if (option_remote || option_exec) {
1380                 ast_log(LOG_ERROR, "Unable to connect to remote asterisk\n");
1381                 printf(term_quit());
1382                 exit(1);
1383         }
1384         /* Blindly write pid file since we couldn't connect */
1385         unlink((char *)ast_config_AST_PID);
1386         f = fopen((char *)ast_config_AST_PID, "w");
1387         if (f) {
1388                 fprintf(f, "%d\n", getpid());
1389                 fclose(f);
1390         } else
1391                 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1392
1393         if (!option_verbose && !option_debug && !option_nofork && !option_console) {
1394                 daemon(0,0);
1395                 /* Blindly re-write pid file since we are forking */
1396                 unlink((char *)ast_config_AST_PID);
1397                 f = fopen((char *)ast_config_AST_PID, "w");
1398                 if (f) {
1399                         fprintf(f, "%d\n", getpid());
1400                         fclose(f);
1401                 } else
1402                         ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1403         }
1404
1405         ast_makesocket();
1406         sigemptyset(&sigs);
1407         sigaddset(&sigs, SIGHUP);
1408         sigaddset(&sigs, SIGTERM);
1409         sigaddset(&sigs, SIGINT);
1410         sigaddset(&sigs, SIGPIPE);
1411         sigaddset(&sigs, SIGWINCH);
1412         pthread_sigmask(SIG_BLOCK, &sigs, NULL);
1413         if (option_console || option_verbose || option_remote)
1414                 ast_register_verbose(console_verboser);
1415         /* Print a welcome message if desired */
1416         if (option_verbose || option_console) {
1417                 ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2001 Linux Support Services, Inc.\n");
1418                 ast_verbose( "Written by Mark Spencer <markster@linux-support.net>\n");
1419                 ast_verbose( "=========================================================================\n");
1420         }
1421         if (option_console && !option_verbose) 
1422                 ast_verbose("[ Booting...");
1423
1424         signal(SIGURG, urg_handler);
1425         signal(SIGINT, __quit_handler);
1426         signal(SIGTERM, __quit_handler);
1427         signal(SIGHUP, hup_handler);
1428         signal(SIGCHLD, child_handler);
1429         signal(SIGPIPE, SIG_IGN);
1430
1431         if (set_priority(option_highpriority)) {
1432                 printf(term_quit());
1433                 exit(1);
1434         }
1435         if (init_logger()) {
1436                 printf(term_quit());
1437                 exit(1);
1438         }
1439         if (init_manager()) {
1440                 printf(term_quit());
1441                 exit(1);
1442         }
1443         ast_rtp_init();
1444         if (ast_image_init()) {
1445                 printf(term_quit());
1446                 exit(1);
1447         }
1448         if (load_pbx()) {
1449                 printf(term_quit());
1450                 exit(1);
1451         }
1452         if (load_modules()) {
1453                 printf(term_quit());
1454                 exit(1);
1455         }
1456         if (init_framer()) {
1457                 printf(term_quit());
1458                 exit(1);
1459         }
1460         if (astdb_init()) {
1461                 printf(term_quit());
1462                 exit(1);
1463         }
1464         if (ast_enum_init()) {
1465                 printf(term_quit());
1466                 exit(1);
1467         }
1468         /* We might have the option of showing a console, but for now just
1469            do nothing... */
1470         if (option_console && !option_verbose)
1471                 ast_verbose(" ]\n");
1472         if (option_verbose || option_console)
1473                 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
1474         fully_booted = 1;
1475         pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
1476 #ifdef __AST_DEBUG_MALLOC
1477         __ast_mm_init();
1478 #endif  
1479         time(&ast_startuptime);
1480         ast_cli_register(&astshutdownnow);
1481         ast_cli_register(&astshutdowngracefully);
1482         ast_cli_register(&astrestartnow);
1483         ast_cli_register(&astrestartgracefully);
1484         ast_cli_register(&astrestartwhenconvenient);
1485         ast_cli_register(&astshutdownwhenconvenient);
1486         ast_cli_register(&aborthalt);
1487         ast_cli_register(&astbang);
1488         if (option_nofork)
1489                 consolethread = pthread_self();
1490         if (option_console) {
1491                 /* Console stuff now... */
1492                 /* Register our quit function */
1493                 char title[256];
1494                 set_icon("Asterisk");
1495                 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, mainpid);
1496                 set_title(title);
1497             ast_cli_register(&quit);
1498             ast_cli_register(&astexit);
1499
1500                 for (;;) {
1501                         buf = (char *)el_gets(el, &num);
1502                         if (buf) {
1503                                 if (buf[strlen(buf)-1] == '\n')
1504                                         buf[strlen(buf)-1] = '\0';
1505
1506                                 consolehandler((char *)buf);
1507                         } else {
1508                                 if (option_remote)
1509                                         ast_cli(STDOUT_FILENO, "\nUse EXIT or QUIT to exit the asterisk console\n");
1510                                 else
1511                                         ast_cli(STDOUT_FILENO, "\nUse STOP NOW to shutdown Asterisk\n");
1512                         }
1513                 }
1514
1515         } else {
1516                 /* Do nothing */
1517                 ast_select(0,NULL,NULL,NULL,NULL);
1518         }
1519         return 0;
1520 }