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