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