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