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