don't tell people to exit/quit when it's not a valid command anymore
[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 = -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 > -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 (!strcasecmp(s, "help")) {
583                         fprintf(stdout, "          !<command>   Executes a given shell command\n");
584                         ret = 0;
585                 }
586                 if (!strcasecmp(s, "quit")) {
587                         quit_handler(0, 0, 0, 0);
588                         ret = 1;
589                 }
590                 if (!strcasecmp(s, "exit")) {
591                         quit_handler(0, 0, 0, 0);
592                         ret = 1;
593                 }
594         } else
595                 fprintf(stdout, "\nUse \"quit\" to exit\n");
596
597         return ret;
598 }
599
600 static char quit_help[] = 
601 "Usage: quit\n"
602 "       Exits Asterisk.\n";
603
604 static char abort_halt_help[] = 
605 "Usage: abort shutdown\n"
606 "       Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
607 "       call operations.\n";
608
609 static char shutdown_now_help[] = 
610 "Usage: stop now\n"
611 "       Shuts down a running Asterisk immediately, hanging up all active calls .\n";
612
613 static char shutdown_gracefully_help[] = 
614 "Usage: stop gracefully\n"
615 "       Causes Asterisk to not accept new calls, and exit when all\n"
616 "       active calls have terminated normally.\n";
617
618 static char shutdown_when_convenient_help[] = 
619 "Usage: stop when convenient\n"
620 "       Causes Asterisk to perform a shutdown when all active calls have ended.\n";
621
622 static char restart_now_help[] = 
623 "Usage: restart now\n"
624 "       Causes Asterisk to hangup all calls and exec() itself performing a cold.\n"
625 "       restart.\n";
626
627 static char restart_gracefully_help[] = 
628 "Usage: restart gracefully\n"
629 "       Causes Asterisk to stop accepting new calls and exec() itself performing a cold.\n"
630 "       restart when all active calls have ended.\n";
631
632 static char restart_when_convenient_help[] = 
633 "Usage: restart when convenient\n"
634 "       Causes Asterisk to perform a cold restart when all active calls have ended.\n";
635
636 #if 0
637 static int handle_quit(int fd, int argc, char *argv[])
638 {
639         if (argc != 1)
640                 return RESULT_SHOWUSAGE;
641         quit_handler(0, 0, 1, 0);
642         return RESULT_SUCCESS;
643 }
644 #endif
645
646 static int no_more_quit(int fd, int argc, char *argv[])
647 {
648         if (argc != 1)
649                 return RESULT_SHOWUSAGE;
650         ast_cli(fd, "The QUIT and EXIT commands may no longer be used to shutdown the PBX.\n"
651                     "Please use STOP NOW instead, if you wish to shutdown the PBX.\n");
652         return RESULT_SUCCESS;
653 }
654
655 static int handle_shutdown_now(int fd, int argc, char *argv[])
656 {
657         if (argc != 2)
658                 return RESULT_SHOWUSAGE;
659         quit_handler(0, 0 /* Not nice */, 1 /* safely */, 0 /* not restart */);
660         return RESULT_SUCCESS;
661 }
662
663 static int handle_shutdown_gracefully(int fd, int argc, char *argv[])
664 {
665         if (argc != 2)
666                 return RESULT_SHOWUSAGE;
667         quit_handler(0, 1 /* nicely */, 1 /* safely */, 0 /* no restart */);
668         return RESULT_SUCCESS;
669 }
670
671 static int handle_shutdown_when_convenient(int fd, int argc, char *argv[])
672 {
673         if (argc != 3)
674                 return RESULT_SHOWUSAGE;
675         quit_handler(0, 2 /* really nicely */, 1 /* safely */, 0 /* don't restart */);
676         return RESULT_SUCCESS;
677 }
678
679 static int handle_restart_now(int fd, int argc, char *argv[])
680 {
681         if (argc != 2)
682                 return RESULT_SHOWUSAGE;
683         quit_handler(0, 0 /* not nicely */, 1 /* safely */, 1 /* restart */);
684         return RESULT_SUCCESS;
685 }
686
687 static int handle_restart_gracefully(int fd, int argc, char *argv[])
688 {
689         if (argc != 2)
690                 return RESULT_SHOWUSAGE;
691         quit_handler(0, 1 /* nicely */, 1 /* safely */, 1 /* restart */);
692         return RESULT_SUCCESS;
693 }
694
695 static int handle_restart_when_convenient(int fd, int argc, char *argv[])
696 {
697         if (argc != 3)
698                 return RESULT_SHOWUSAGE;
699         quit_handler(0, 2 /* really nicely */, 1 /* safely */, 1 /* restart */);
700         return RESULT_SUCCESS;
701 }
702
703 static int handle_abort_halt(int fd, int argc, char *argv[])
704 {
705         if (argc != 2)
706                 return RESULT_SHOWUSAGE;
707         ast_cancel_shutdown();
708         shuttingdown = 0;
709         return RESULT_SUCCESS;
710 }
711
712 #define ASTERISK_PROMPT "*CLI> "
713
714 #define ASTERISK_PROMPT2 "%s*CLI> "
715
716 static struct ast_cli_entry aborthalt = { { "abort", "halt", NULL }, handle_abort_halt, "Cancel a running halt", abort_halt_help };
717
718 static struct ast_cli_entry quit =      { { "quit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
719 static struct ast_cli_entry astexit =   { { "exit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
720
721 static struct ast_cli_entry astshutdownnow =    { { "stop", "now", NULL }, handle_shutdown_now, "Shut down Asterisk imediately", shutdown_now_help };
722 static struct ast_cli_entry astshutdowngracefully =     { { "stop", "gracefully", NULL }, handle_shutdown_gracefully, "Gracefully shut down Asterisk", shutdown_gracefully_help };
723 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 };
724 static struct ast_cli_entry astrestartnow =     { { "restart", "now", NULL }, handle_restart_now, "Restart Asterisk immediately", restart_now_help };
725 static struct ast_cli_entry astrestartgracefully =      { { "restart", "gracefully", NULL }, handle_restart_gracefully, "Restart Asterisk gracefully", restart_gracefully_help };
726 static struct ast_cli_entry astrestartwhenconvenient=   { { "restart", "when", "convenient", NULL }, handle_restart_when_convenient, "Restart Asterisk at empty call volume", restart_when_convenient_help };
727
728 static int ast_el_read_char(EditLine *el, char *cp)
729 {
730         int num_read=0;
731         int lastpos=0;
732         fd_set rfds;
733         int res;
734         int max;
735         char buf[512];
736
737         for (;;) {
738                 FD_ZERO(&rfds);
739                 FD_SET(ast_consock, &rfds);
740                 max = ast_consock;
741                 if (!option_exec) {
742                         FD_SET(STDIN_FILENO, &rfds);
743                         if (STDIN_FILENO > max)
744                                 max = STDIN_FILENO;
745                 }
746                 res = ast_select(max+1, &rfds, NULL, NULL, NULL);
747                 if (res < 0) {
748                         if (errno == EINTR)
749                                 continue;
750                         ast_log(LOG_ERROR, "select failed: %s\n", strerror(errno));
751                         break;
752                 }
753
754                 if (FD_ISSET(STDIN_FILENO, &rfds)) {
755                         num_read = read(STDIN_FILENO, cp, 1);
756                         if (num_read < 1) {
757                                 break;
758                         } else 
759                                 return (num_read);
760                 }
761                 if (FD_ISSET(ast_consock, &rfds)) {
762                         res = read(ast_consock, buf, sizeof(buf) - 1);
763                         /* if the remote side disappears exit */
764                         if (res < 1) {
765                                 fprintf(stderr, "\nDisconnected from Asterisk server\n");
766                                 quit_handler(0, 0, 0, 0);
767                         }
768
769                         buf[res] = '\0';
770
771                         if (!option_exec && !lastpos)
772                                 write(STDOUT_FILENO, "\r", 1);
773                         write(STDOUT_FILENO, buf, res);
774                         if ((buf[res-1] == '\n') || (buf[res-2] == '\n')) {
775                                 *cp = CC_REFRESH;
776                                 return(1);
777                         } else {
778                                 lastpos = 1;
779                         }
780                 }
781         }
782
783         *cp = '\0';
784         return (0);
785 }
786
787 static char *cli_prompt(EditLine *el)
788 {
789         static char prompt[80];
790
791         if (remotehostname)
792                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT2, remotehostname);
793         else
794                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT);
795
796         return(prompt); 
797 }
798
799 static char **ast_el_strtoarr(char *buf)
800 {
801         char **match_list = NULL, *retstr;
802         size_t match_list_len;
803         int matches = 0;
804
805         match_list_len = 1;
806         while ( (retstr = strsep(&buf, " ")) != NULL) {
807
808                 if (matches + 1 >= match_list_len) {
809                         match_list_len <<= 1;
810                         match_list = realloc(match_list, match_list_len * sizeof(char *));
811                 }
812
813                 match_list[matches++] = retstr;
814         }
815
816         if (!match_list)
817                 return (char **) NULL;
818
819         if (matches>= match_list_len)
820                 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
821
822         match_list[matches] = (char *) NULL;
823
824         return match_list;
825 }
826
827 static int ast_el_sort_compare(const void *i1, const void *i2)
828 {
829         char *s1, *s2;
830
831         s1 = ((char **)i1)[0];
832         s2 = ((char **)i2)[0];
833
834         return strcasecmp(s1, s2);
835 }
836
837 static int ast_cli_display_match_list(char **matches, int len, int max)
838 {
839         int i, idx, limit, count;
840         int screenwidth = 0;
841         int numoutput = 0, numoutputline = 0;
842
843         screenwidth = ast_get_termcols(STDOUT_FILENO);
844
845         /* find out how many entries can be put on one line, with two spaces between strings */
846         limit = screenwidth / (max + 2);
847         if (limit == 0)
848                 limit = 1;
849
850         /* how many lines of output */
851         count = len / limit;
852         if (count * limit < len)
853                 count++;
854
855         idx = 1;
856
857         qsort(&matches[0], (size_t)(len + 1), sizeof(char *), ast_el_sort_compare);
858
859         for (; count > 0; count--) {
860                 numoutputline = 0;
861                 for (i=0; i < limit && matches[idx]; i++, idx++) {
862
863                         /* Don't print dupes */
864                         if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
865                                 i--;
866                                 continue;
867                         }
868
869                         numoutput++;  numoutputline++;
870                         fprintf(stdout, "%-*s  ", max, matches[idx]);
871                 }
872                 if (numoutputline > 0)
873                         fprintf(stdout, "\n");
874         }
875
876         return numoutput;
877 }
878
879
880 static char *cli_complete(EditLine *el, int ch)
881 {
882         int len=0;
883         char *ptr;
884         int nummatches = 0;
885         char **matches;
886         int retval = CC_ERROR;
887         char buf[1024];
888         int res;
889
890         LineInfo *lf = (LineInfo *)el_line(el);
891
892         *lf->cursor = '\0';
893         ptr = (char *)lf->cursor;
894         if (ptr) {
895                 while (ptr > lf->buffer) {
896                         if (isspace(*ptr)) {
897                                 ptr++;
898                                 break;
899                         }
900                         ptr--;
901                 }
902         }
903
904         len = lf->cursor - ptr;
905
906         if (option_remote) {
907                 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr); 
908                 fdprint(ast_consock, buf);
909                 res = read(ast_consock, buf, sizeof(buf));
910                 buf[res] = '\0';
911                 nummatches = atoi(buf);
912
913                 if (nummatches > 0) {
914                         snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr); 
915                         fdprint(ast_consock, buf);
916                         res = read(ast_consock, buf, sizeof(buf));
917                         buf[res] = '\0';
918
919                         matches = ast_el_strtoarr(buf);
920                 } else
921                         matches = (char **) NULL;
922
923
924         }  else {
925
926                 nummatches = ast_cli_generatornummatches((char *)lf->buffer,ptr);
927                 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
928         }
929
930         if (matches) {
931                 int i;
932                 int matches_num, maxlen, match_len;
933
934                 if (matches[0][0] != '\0') {
935                         el_deletestr(el, (int) len);
936                         el_insertstr(el, matches[0]);
937                         retval = CC_REFRESH;
938                 }
939
940                 if (nummatches == 1) {
941                         /* Found an exact match */
942                         el_insertstr(el, " ");
943                         retval = CC_REFRESH;
944                 } else {
945                         /* Must be more than one match */
946                         for (i=1, maxlen=0; matches[i]; i++) {
947                                 match_len = strlen(matches[i]);
948                                 if (match_len > maxlen)
949                                         maxlen = match_len;
950                         }
951                         matches_num = i - 1;
952                         if (matches_num >1) {
953                                 fprintf(stdout, "\n");
954                                 ast_cli_display_match_list(matches, nummatches, maxlen);
955                                 retval = CC_REDISPLAY;
956                         } else { 
957                                 el_insertstr(el," ");
958                                 retval = CC_REFRESH;
959                         }
960                 }
961         free(matches);
962         }
963
964         return (char *)retval;
965 }
966
967 static int ast_el_initialize(void)
968 {
969         HistEvent ev;
970
971         if (el != NULL)
972                 el_end(el);
973         if (el_hist != NULL)
974                 history_end(el_hist);
975
976         el = el_init("asterisk", stdin, stdout, stderr);
977         el_set(el, EL_PROMPT, cli_prompt);
978
979         el_set(el, EL_EDITMODE, 1);             
980         el_set(el, EL_EDITOR, "emacs");         
981         el_hist = history_init();
982         if (!el || !el_hist)
983                 return -1;
984
985         /* setup history with 100 entries */
986         history(el_hist, &ev, H_SETSIZE, 100);
987
988         el_set(el, EL_HIST, history, el_hist);
989
990         el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
991         /* Bind <tab> to command completion */
992         el_set(el, EL_BIND, "^I", "ed-complete", NULL);
993         /* Bind ? to command completion */
994         el_set(el, EL_BIND, "?", "ed-complete", NULL);
995
996         return 0;
997 }
998
999 static int ast_el_add_history(char *buf)
1000 {
1001         HistEvent ev;
1002
1003         if (el_hist == NULL || el == NULL)
1004                 ast_el_initialize();
1005
1006         return (history(el_hist, &ev, H_ENTER, buf));
1007 }
1008
1009 static int ast_el_write_history(char *filename)
1010 {
1011         HistEvent ev;
1012
1013         if (el_hist == NULL || el == NULL)
1014                 ast_el_initialize();
1015
1016         return (history(el_hist, &ev, H_SAVE, filename));
1017 }
1018
1019 static int ast_el_read_history(char *filename)
1020 {
1021         char buf[256];
1022         FILE *f;
1023         int ret = -1;
1024
1025         if (el_hist == NULL || el == NULL)
1026                 ast_el_initialize();
1027
1028         if ((f = fopen(filename, "r")) == NULL)
1029                 return ret;
1030
1031         while (!feof(f)) {
1032                 fgets(buf, sizeof(buf), f);
1033                 if (!strcmp(buf, "_HiStOrY_V2_\n"))
1034                         continue;
1035                 if ((ret = ast_el_add_history(buf)) == -1)
1036                         break;
1037         }
1038         fclose(f);
1039
1040         return ret;
1041 }
1042
1043 static void ast_remotecontrol(char * data)
1044 {
1045         char buf[80];
1046         int res;
1047         char filename[80] = "";
1048         char *hostname;
1049         char *cpid;
1050         char *version;
1051         int pid;
1052         char tmp[80];
1053         char *stringp=NULL;
1054
1055         char *ebuf;
1056         int num = 0;
1057
1058         read(ast_consock, buf, sizeof(buf));
1059         if (data)
1060                 write(ast_consock, data, strlen(data) + 1);
1061         stringp=buf;
1062         hostname = strsep(&stringp, "/");
1063         cpid = strsep(&stringp, "/");
1064         version = strsep(&stringp, "/");
1065         if (!version)
1066                 version = "<Version Unknown>";
1067         stringp=hostname;
1068         strsep(&stringp, ".");
1069         if (cpid)
1070                 pid = atoi(cpid);
1071         else
1072                 pid = -1;
1073         snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
1074         fdprint(ast_consock, tmp);
1075         ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
1076         remotehostname = hostname;
1077         if (getenv("HOME")) 
1078                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1079         if (el_hist == NULL || el == NULL)
1080                 ast_el_initialize();
1081
1082         el_set(el, EL_GETCFN, ast_el_read_char);
1083
1084         if (strlen(filename))
1085                 ast_el_read_history(filename);
1086
1087         ast_cli_register(&quit);
1088         ast_cli_register(&astexit);
1089 #if 0
1090         ast_cli_register(&astshutdown);
1091 #endif  
1092         if (option_exec && data) {  /* hack to print output then exit if asterisk -rx is used */
1093                 char tempchar;
1094                 ast_el_read_char(el, &tempchar);
1095                 return;
1096         }
1097         for(;;) {
1098                 ebuf = (char *)el_gets(el, &num);
1099
1100                 if (ebuf && strlen(ebuf)) {
1101                         if (ebuf[strlen(ebuf)-1] == '\n')
1102                                 ebuf[strlen(ebuf)-1] = '\0';
1103                         if (!remoteconsolehandler(ebuf)) {
1104                                 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
1105                                 if (res < 1) {
1106                                         ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
1107                                         break;
1108                                 }
1109                         }
1110                 }
1111         }
1112         printf("\nDisconnected from Asterisk server\n");
1113 }
1114
1115 static int show_cli_help(void) {
1116         printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 2000-2002, Digium.\n");
1117         printf("Usage: asterisk [OPTIONS]\n");
1118         printf("Valid Options:\n");
1119         printf("   -h           This help screen\n");
1120         printf("   -r           Connect to Asterisk on this machine\n");
1121         printf("   -f           Do not fork\n");
1122         printf("   -n           Disable console colorization\n");
1123         printf("   -p           Run as pseudo-realtime thread\n");
1124         printf("   -v           Increase verbosity (multiple v's = more verbose)\n");
1125         printf("   -q           Quiet mode (supress output)\n");
1126         printf("   -g           Dump core in case of a crash\n");
1127         printf("   -x <cmd>     Execute command <cmd> (only valid with -r)\n");
1128         printf("   -i           Initializie crypto keys at startup\n");
1129         printf("   -c           Provide console CLI\n");
1130         printf("   -d           Enable extra debugging\n");
1131         printf("\n");
1132         return 0;
1133 }
1134
1135 static void ast_readconfig(void) {
1136         struct ast_config *cfg;
1137         struct ast_variable *v;
1138         char *config = ASTCONFPATH;
1139
1140         if (option_overrideconfig == 1) {
1141             cfg = ast_load((char *)ast_config_AST_CONFIG_FILE);
1142         } else {
1143             cfg = ast_load(config);
1144         }
1145
1146         /* init with buildtime config */
1147         strncpy((char *)ast_config_AST_CONFIG_DIR,AST_CONFIG_DIR,sizeof(ast_config_AST_CONFIG_DIR)-1);
1148         strncpy((char *)ast_config_AST_SPOOL_DIR,AST_SPOOL_DIR,sizeof(ast_config_AST_SPOOL_DIR)-1);
1149         strncpy((char *)ast_config_AST_MODULE_DIR,AST_MODULE_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1150         strncpy((char *)ast_config_AST_VAR_DIR,AST_VAR_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1151         strncpy((char *)ast_config_AST_LOG_DIR,AST_LOG_DIR,sizeof(ast_config_AST_LOG_DIR)-1);
1152         strncpy((char *)ast_config_AST_AGI_DIR,AST_AGI_DIR,sizeof(ast_config_AST_AGI_DIR)-1);
1153         strncpy((char *)ast_config_AST_DB,AST_DB,sizeof(ast_config_AST_DB)-1);
1154         strncpy((char *)ast_config_AST_KEY_DIR,AST_KEY_DIR,sizeof(ast_config_AST_KEY_DIR)-1);
1155         strncpy((char *)ast_config_AST_PID,AST_PID,sizeof(ast_config_AST_PID)-1);
1156         strncpy((char *)ast_config_AST_SOCKET,AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1);
1157         strncpy((char *)ast_config_AST_RUN_DIR,AST_RUN_DIR,sizeof(ast_config_AST_RUN_DIR)-1);
1158         
1159         /* no asterisk.conf? no problem, use buildtime config! */
1160         if (!cfg) {
1161             return;
1162         }
1163         v = ast_variable_browse(cfg, "directories");
1164         while(v) {
1165                 if (!strcasecmp(v->name, "astetcdir")) {
1166                     strncpy((char *)ast_config_AST_CONFIG_DIR,v->value,sizeof(ast_config_AST_CONFIG_DIR)-1);
1167                 } else if (!strcasecmp(v->name, "astspooldir")) {
1168                     strncpy((char *)ast_config_AST_SPOOL_DIR,v->value,sizeof(ast_config_AST_SPOOL_DIR)-1);
1169                 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1170                     strncpy((char *)ast_config_AST_VAR_DIR,v->value,sizeof(ast_config_AST_VAR_DIR)-1);
1171                     snprintf((char *)ast_config_AST_DB,sizeof(ast_config_AST_DB)-1,"%s/%s",v->value,"astdb");    
1172                 } else if (!strcasecmp(v->name, "astlogdir")) {
1173                     strncpy((char *)ast_config_AST_LOG_DIR,v->value,sizeof(ast_config_AST_LOG_DIR)-1);
1174                 } else if (!strcasecmp(v->name, "astagidir")) {
1175                     strncpy((char *)ast_config_AST_AGI_DIR,v->value,sizeof(ast_config_AST_AGI_DIR)-1);
1176                 } else if (!strcasecmp(v->name, "astrundir")) {
1177                     snprintf((char *)ast_config_AST_PID,sizeof(ast_config_AST_PID)-1,"%s/%s",v->value,"asterisk.pid");    
1178                     snprintf((char *)ast_config_AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1,"%s/%s",v->value,"asterisk.ctl");    
1179                     strncpy((char *)ast_config_AST_RUN_DIR,v->value,sizeof(ast_config_AST_RUN_DIR)-1);
1180                 } else if (!strcasecmp(v->name, "astmoddir")) {
1181                     strncpy((char *)ast_config_AST_MODULE_DIR,v->value,sizeof(ast_config_AST_MODULE_DIR)-1);
1182                 }
1183                 v = v->next;
1184         }
1185         ast_destroy(cfg);
1186 }
1187
1188 int main(int argc, char *argv[])
1189 {
1190         char c;
1191         char filename[80] = "";
1192         char hostname[256];
1193         char tmp[80];
1194         char * xarg = NULL;
1195         int x;
1196         FILE *f;
1197         sigset_t sigs;
1198         int num;
1199         char *buf;
1200
1201         /* Remember original args for restart */
1202         if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1203                 fprintf(stderr, "Truncating argument size to %d\n", sizeof(_argv) / sizeof(_argv[0]) - 1);
1204                 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1205         }
1206         for (x=0;x<argc;x++)
1207                 _argv[x] = argv[x];
1208         _argv[x] = NULL;
1209
1210         if (gethostname(hostname, sizeof(hostname)))
1211                 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
1212         mainpid = getpid();
1213         ast_ulaw_init();
1214         ast_alaw_init();
1215         callerid_init();
1216         tdd_init();
1217         if (getenv("HOME")) 
1218                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1219         /* Check if we're root */
1220         /*
1221         if (geteuid()) {
1222                 ast_log(LOG_ERROR, "Must be run as root\n");
1223                 exit(1);
1224         }
1225         */
1226         /* Check for options */
1227         while((c=getopt(argc, argv, "hfdvqprgcinx:C:")) != EOF) {
1228                 switch(c) {
1229                 case 'd':
1230                         option_debug++;
1231                         option_nofork++;
1232                         break;
1233                 case 'c':
1234                         option_console++;
1235                         option_nofork++;
1236                         break;
1237                 case 'f':
1238                         option_nofork++;
1239                         break;
1240                 case 'n':
1241                         option_nocolor++;
1242                         break;
1243                 case 'r':
1244                         option_remote++;
1245                         option_nofork++;
1246                         break;
1247                 case 'p':
1248                         option_highpriority++;
1249                         break;
1250                 case 'v':
1251                         option_verbose++;
1252                         option_nofork++;
1253                         break;
1254                 case 'q':
1255                         option_quiet++;
1256                         break;
1257                 case 'x':
1258                         option_exec++;
1259                         xarg = optarg;
1260                         break;
1261                 case 'C':
1262                         strncpy((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE));
1263                         option_overrideconfig++;
1264                         break;
1265                 case 'i':
1266                         option_initcrypto++;
1267                         break;
1268                 case'g':
1269                         option_dumpcore++;
1270                         break;
1271                 case 'h':
1272                         show_cli_help();
1273                         exit(0);
1274                 case '?':
1275                         exit(1);
1276                 }
1277         }
1278
1279         if (option_dumpcore) {
1280                 struct rlimit l;
1281                 memset(&l, 0, sizeof(l));
1282                 l.rlim_cur = RLIM_INFINITY;
1283                 l.rlim_max = RLIM_INFINITY;
1284                 if (setrlimit(RLIMIT_CORE, &l)) {
1285                         ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
1286                 }
1287         }
1288
1289         term_init();
1290         printf(term_end());
1291         fflush(stdout);
1292         if (option_console && !option_verbose) 
1293                 ast_verbose("[ Reading Master Configuration ]");
1294         ast_readconfig();
1295
1296         if (option_console) {
1297                 if (el_hist == NULL || el == NULL)
1298                         ast_el_initialize();
1299
1300                 if (strlen(filename))
1301                         ast_el_read_history(filename);
1302         }
1303
1304         if (ast_tryconnect()) {
1305                 /* One is already running */
1306                 if (option_remote) {
1307                         if (option_exec) {
1308                                 ast_remotecontrol(xarg);
1309                                 quit_handler(0, 0, 0, 0);
1310                                 exit(0);
1311                         }
1312                         printf(term_quit());
1313                         ast_register_verbose(console_verboser);
1314                         ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2001 Linux Support Services, Inc.\n");
1315                         ast_verbose( "Written by Mark Spencer <markster@linux-support.net>\n");
1316                         ast_verbose( "=========================================================================\n");
1317                         ast_remotecontrol(NULL);
1318                         quit_handler(0, 0, 0, 0);
1319                         exit(0);
1320                 } else {
1321                         ast_log(LOG_ERROR, "Asterisk already running on %s.  Use 'asterisk -r' to connect.\n", (char *)ast_config_AST_SOCKET);
1322                         printf(term_quit());
1323                         exit(1);
1324                 }
1325         } else if (option_remote || option_exec) {
1326                 ast_log(LOG_ERROR, "Unable to connect to remote asterisk\n");
1327                 printf(term_quit());
1328                 exit(1);
1329         }
1330         /* Blindly write pid file since we couldn't connect */
1331         unlink((char *)ast_config_AST_PID);
1332         f = fopen((char *)ast_config_AST_PID, "w");
1333         if (f) {
1334                 fprintf(f, "%d\n", getpid());
1335                 fclose(f);
1336         } else
1337                 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1338
1339         if (!option_verbose && !option_debug && !option_nofork && !option_console) {
1340 #if 1
1341                 daemon(0,0);
1342 #else   
1343                 pid = fork();
1344                 if (pid < 0) {
1345                         ast_log(LOG_ERROR, "Unable to fork(): %s\n", strerror(errno));
1346                         printf(term_quit());
1347                         exit(1);
1348                 }
1349                 if (pid) 
1350                         exit(0);
1351 #endif                  
1352         }
1353
1354         ast_makesocket();
1355         sigemptyset(&sigs);
1356         sigaddset(&sigs, SIGHUP);
1357         sigaddset(&sigs, SIGTERM);
1358         sigaddset(&sigs, SIGINT);
1359         sigaddset(&sigs, SIGPIPE);
1360         sigaddset(&sigs, SIGWINCH);
1361         pthread_sigmask(SIG_BLOCK, &sigs, NULL);
1362         if (option_console || option_verbose || option_remote)
1363                 ast_register_verbose(console_verboser);
1364         /* Print a welcome message if desired */
1365         if (option_verbose || option_console) {
1366                 ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2001 Linux Support Services, Inc.\n");
1367                 ast_verbose( "Written by Mark Spencer <markster@linux-support.net>\n");
1368                 ast_verbose( "=========================================================================\n");
1369         }
1370         if (option_console && !option_verbose) 
1371                 ast_verbose("[ Booting...");
1372         signal(SIGURG, urg_handler);
1373         signal(SIGINT, __quit_handler);
1374         signal(SIGTERM, __quit_handler);
1375         signal(SIGHUP, hup_handler);
1376         signal(SIGPIPE, pipe_handler);
1377         if (set_priority(option_highpriority)) {
1378                 printf(term_quit());
1379                 exit(1);
1380         }
1381         if (init_logger()) {
1382                 printf(term_quit());
1383                 exit(1);
1384         }
1385         if (init_manager()) {
1386                 printf(term_quit());
1387                 exit(1);
1388         }
1389         ast_rtp_init();
1390         if (ast_image_init()) {
1391                 printf(term_quit());
1392                 exit(1);
1393         }
1394         if (load_pbx()) {
1395                 printf(term_quit());
1396                 exit(1);
1397         }
1398         if (load_modules()) {
1399                 printf(term_quit());
1400                 exit(1);
1401         }
1402         if (init_framer()) {
1403                 printf(term_quit());
1404                 exit(1);
1405         }
1406         if (astdb_init()) {
1407                 printf(term_quit());
1408                 exit(1);
1409         }
1410         if (ast_enum_init()) {
1411                 printf(term_quit());
1412                 exit(1);
1413         }
1414         /* We might have the option of showing a console, but for now just
1415            do nothing... */
1416         if (option_console && !option_verbose)
1417                 ast_verbose(" ]\n");
1418         if (option_verbose || option_console)
1419                 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
1420         fully_booted = 1;
1421         pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
1422 #ifdef __AST_DEBUG_MALLOC
1423         __ast_mm_init();
1424 #endif  
1425         time(&ast_startuptime);
1426         ast_cli_register(&astshutdownnow);
1427         ast_cli_register(&astshutdowngracefully);
1428         ast_cli_register(&astrestartnow);
1429         ast_cli_register(&astrestartgracefully);
1430         ast_cli_register(&astrestartwhenconvenient);
1431         ast_cli_register(&astshutdownwhenconvenient);
1432         ast_cli_register(&aborthalt);
1433         if (option_console) {
1434                 /* Console stuff now... */
1435                 /* Register our quit function */
1436                 char title[256];
1437                 set_icon("Asterisk");
1438                 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, mainpid);
1439                 set_title(title);
1440             ast_cli_register(&quit);
1441             ast_cli_register(&astexit);
1442                 consolethread = pthread_self();
1443
1444                 for (;;) {
1445                         buf = (char *)el_gets(el, &num);
1446                         if (buf) {
1447                                 if (buf[strlen(buf)-1] == '\n')
1448                                         buf[strlen(buf)-1] = '\0';
1449
1450                                 consolehandler((char *)buf);
1451                         } else {
1452                                 if (option_remote)
1453                                         ast_cli(STDOUT_FILENO, "\nUse EXIT or QUIT to exit the asterisk console\n");
1454                                 else
1455                                         ast_cli(STDOUT_FILENO, "\nUse STOP NOW to shutdown Asterisk\n");
1456                         }
1457                 }
1458
1459         } else {
1460                 /* Do nothing */
1461                 ast_select(0,NULL,NULL,NULL,NULL);
1462         }
1463         return 0;
1464 }