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