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