Properly migrate from select to poll for core asterisk.
[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 <sys/poll.h>
17 #include <asterisk/logger.h>
18 #include <asterisk/options.h>
19 #include <asterisk/cli.h>
20 #include <asterisk/channel.h>
21 #include <asterisk/ulaw.h>
22 #include <asterisk/alaw.h>
23 #include <asterisk/callerid.h>
24 #include <asterisk/module.h>
25 #include <asterisk/image.h>
26 #include <asterisk/tdd.h>
27 #include <asterisk/term.h>
28 #include <asterisk/manager.h>
29 #include <asterisk/pbx.h>
30 #include <asterisk/enum.h>
31 #include <asterisk/rtp.h>
32 #include <asterisk/app.h>
33 #include <asterisk/lock.h>
34 #include <sys/resource.h>
35 #include <fcntl.h>
36 #include <stdio.h>
37 #include <signal.h>
38 #include <sched.h>
39 #include <asterisk/io.h>
40 #include <asterisk/lock.h>
41 #include <sys/socket.h>
42 #include <sys/un.h>
43 #include <sys/select.h>
44 #include <sys/wait.h>
45 #include <string.h>
46 #include <errno.h>
47 #include <ctype.h>
48 #include "editline/histedit.h"
49 #include "asterisk.h"
50 #include <asterisk/config.h>
51
52 #define AST_MAX_CONNECTS 128
53 #define NUM_MSGS 64
54
55 int option_verbose=0;
56 int option_debug=0;
57 int option_nofork=0;
58 int option_quiet=0;
59 int option_console=0;
60 int option_highpriority=0;
61 int option_remote=0;
62 int option_exec=0;
63 int option_initcrypto=0;
64 int option_nocolor;
65 int option_dumpcore = 0;
66 int option_overrideconfig = 0;
67 int fully_booted = 0;
68
69 static int ast_socket = -1;             /* UNIX Socket for allowing remote control */
70 static int ast_consock = -1;            /* UNIX Socket for controlling another asterisk */
71 int ast_mainpid;
72 struct console {
73         int fd;                                 /* File descriptor */
74         int p[2];                               /* Pipe */
75         pthread_t t;                    /* Thread of handler */
76 };
77
78 static struct ast_atexit {
79         void (*func)(void);
80         struct ast_atexit *next;
81 } *atexits = NULL;
82 static ast_mutex_t atexitslock = AST_MUTEX_INITIALIZER;
83
84 time_t ast_startuptime;
85 time_t ast_lastreloadtime;
86
87 static History *el_hist = NULL;
88 static EditLine *el = NULL;
89 static char *remotehostname;
90
91 struct console consoles[AST_MAX_CONNECTS];
92
93 char defaultlanguage[MAX_LANGUAGE] = DEFAULT_LANGUAGE;
94
95 static int ast_el_add_history(char *);
96 static int ast_el_read_history(char *);
97 static int ast_el_write_history(char *);
98
99 char ast_config_AST_CONFIG_DIR[AST_CONFIG_MAX_PATH];
100 char ast_config_AST_CONFIG_FILE[AST_CONFIG_MAX_PATH];
101 char ast_config_AST_MODULE_DIR[AST_CONFIG_MAX_PATH];
102 char ast_config_AST_SPOOL_DIR[AST_CONFIG_MAX_PATH];
103 char ast_config_AST_VAR_DIR[AST_CONFIG_MAX_PATH];
104 char ast_config_AST_LOG_DIR[AST_CONFIG_MAX_PATH];
105 char ast_config_AST_AGI_DIR[AST_CONFIG_MAX_PATH];
106 char ast_config_AST_DB[AST_CONFIG_MAX_PATH];
107 char ast_config_AST_KEY_DIR[AST_CONFIG_MAX_PATH];
108 char ast_config_AST_PID[AST_CONFIG_MAX_PATH];
109 char ast_config_AST_SOCKET[AST_CONFIG_MAX_PATH];
110 char ast_config_AST_RUN_DIR[AST_CONFIG_MAX_PATH];
111
112 static char *_argv[256];
113 static int shuttingdown = 0;
114 static int restartnow = 0;
115 static pthread_t consolethread = AST_PTHREADT_NULL;
116
117 int ast_register_atexit(void (*func)(void))
118 {
119         int res = -1;
120         struct ast_atexit *ae;
121         ast_unregister_atexit(func);
122         ae = malloc(sizeof(struct ast_atexit));
123         ast_mutex_lock(&atexitslock);
124         if (ae) {
125                 memset(ae, 0, sizeof(struct ast_atexit));
126                 ae->next = atexits;
127                 ae->func = func;
128                 atexits = ae;
129                 res = 0;
130         }
131         ast_mutex_unlock(&atexitslock);
132         return res;
133 }
134
135 void ast_unregister_atexit(void (*func)(void))
136 {
137         struct ast_atexit *ae, *prev = NULL;
138         ast_mutex_lock(&atexitslock);
139         ae = atexits;
140         while(ae) {
141                 if (ae->func == func) {
142                         if (prev)
143                                 prev->next = ae->next;
144                         else
145                                 atexits = ae->next;
146                         break;
147                 }
148                 prev = ae;
149                 ae = ae->next;
150         }
151         ast_mutex_unlock(&atexitslock);
152 }
153
154 static int fdprint(int fd, const char *s)
155 {
156         return write(fd, s, strlen(s) + 1);
157 }
158
159 int ast_safe_system(const char *s)
160 {
161         /* XXX This function needs some optimization work XXX */
162         pid_t pid;
163         int x;
164         int res;
165         struct rusage rusage;
166         int status;
167         pid = fork();
168         if (pid == 0) {
169                 /* Close file descriptors and launch system command */
170                 for (x=STDERR_FILENO + 1; x<4096;x++) {
171                         close(x);
172                 }
173                 res = execl("/bin/sh", "/bin/sh", "-c", s, NULL);
174                 exit(1);
175         } else if (pid > 0) {
176                 for(;;) {
177                         res = wait4(pid, &status, 0, &rusage);
178                         if (res > -1) {
179                                 if (WIFEXITED(status))
180                                         res = WEXITSTATUS(status);
181                                 else
182                                         res = -1;
183                         } else {
184                                 if (errno != EINTR) 
185                                         break;
186                         }
187                 }
188         } else {
189                 ast_log(LOG_WARNING, "Fork failed: %s\n", strerror(errno));
190                 res = -1;
191         }
192         return res;
193 }
194
195 /*
196  * write the string to all attached console clients
197  */
198 static void ast_network_puts(const char *string)
199 {
200     int x;
201     for (x=0;x<AST_MAX_CONNECTS; x++) {
202         if (consoles[x].fd > -1) 
203             fdprint(consoles[x].p[1], string);
204     }
205 }
206
207
208 /*
209  * write the string to the console, and all attached
210  * console clients
211  */
212 void ast_console_puts(const char *string)
213 {
214     fputs(string, stdout);
215     fflush(stdout);
216     ast_network_puts(string);
217 }
218
219 static void network_verboser(const char *s, int pos, int replace, int complete)
220      /* ARGUSED */
221 {
222     ast_network_puts(s);
223 }
224
225 static pthread_t lthread;
226
227 static void *netconsole(void *vconsole)
228 {
229         struct console *con = vconsole;
230         char hostname[256];
231         char tmp[512];
232         int res;
233         struct pollfd fds[2];
234         
235         if (gethostname(hostname, sizeof(hostname)))
236                 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
237         snprintf(tmp, sizeof(tmp), "%s/%d/%s\n", hostname, ast_mainpid, ASTERISK_VERSION);
238         fdprint(con->fd, tmp);
239         for(;;) {
240                 fds[0].fd = con->fd;
241                 fds[0].events = POLLIN;
242                 fds[1].fd = con->p[0];
243                 fds[1].events = POLLIN;
244
245                 res = poll(fds, 2, -1);
246                 if (res < 0) {
247                         ast_log(LOG_WARNING, "poll returned < 0: %s\n", strerror(errno));
248                         continue;
249                 }
250                 if (fds[0].revents) {
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 (fds[1].revents) {
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         int s;
283         int len;
284         int x;
285         int flags;
286         struct pollfd fds[1];
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                 fds[0].fd = ast_socket;
294                 fds[0].events= POLLIN;
295                 s = poll(fds, 1, -1);
296                 if (s < 0) {
297                         if (errno != EINTR)
298                                 ast_log(LOG_WARNING, "poll 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 poll, 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 poll()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         struct pollfd fds[2];
826         int res;
827         int max;
828         char buf[512];
829
830         for (;;) {
831                 max = 1;
832                 fds[0].fd = ast_consock;
833                 fds[0].events = POLLIN;
834                 if (!option_exec) {
835                         fds[1].fd = STDIN_FILENO;
836                         fds[1].events = POLLIN;
837                         max++;
838                 }
839                 res = poll(fds, max, -1);
840                 if (res < 0) {
841                         if (errno == EINTR)
842                                 continue;
843                         ast_log(LOG_ERROR, "poll failed: %s\n", strerror(errno));
844                         break;
845                 }
846
847                 if (!option_exec && fds[1].revents) {
848                         num_read = read(STDIN_FILENO, cp, 1);
849                         if (num_read < 1) {
850                                 break;
851                         } else 
852                                 return (num_read);
853                 }
854                 if (fds[0].revents) {
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[200];
883         char *pfmt;
884
885         if ((pfmt = getenv("ASTERISK_PROMPT"))) {
886                 char *t = pfmt, *p = prompt;
887                 memset(prompt, 0, sizeof(prompt));
888                 while (*t != '\0' && *p < sizeof(prompt)) {
889                         if (*t == '%') {
890                                 t++;
891                                 switch (*t) {
892                                         char hostname[256];
893                                         struct timeval tv;
894                                         struct tm tm;
895                                         FILE *LOADAVG;
896                                         case 'd': /* date */
897                                                 memset(&tm, 0, sizeof(struct tm));
898                                                 gettimeofday(&tv, NULL);
899                                                 if (localtime_r(&(tv.tv_sec), &tm)) {
900                                                         strftime(p, sizeof(prompt) - strlen(prompt), "%Y-%m-%d", &tm);
901                                                 }
902                                                 break;
903                                         case 'h': /* hostname */
904                                                 if (!gethostname(hostname, sizeof(hostname) - 1)) {
905                                                         strncat(p, hostname, sizeof(prompt) - strlen(prompt));
906                                                 } else {
907                                                         strncat(p, "localhost", sizeof(prompt) - strlen(prompt));
908                                                 }
909                                                 break;
910 #ifdef linux
911                                         case 'l': /* load avg */
912                                                 t++;
913                                                 if ((LOADAVG = fopen("/proc/loadavg", "r"))) {
914                                                         float avg1, avg2, avg3;
915                                                         int actproc, totproc, npid, which;
916                                                         fscanf(LOADAVG, "%f %f %f %d/%d %d",
917                                                                 &avg1, &avg2, &avg3, &actproc, &totproc, &npid);
918                                                         if (sscanf(t, "%d", &which) == 1) {
919                                                                 switch (which) {
920                                                                         case 1:
921                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg1);
922                                                                                 break;
923                                                                         case 2:
924                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg2);
925                                                                                 break;
926                                                                         case 3:
927                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg3);
928                                                                                 break;
929                                                                         case 4:
930                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%d/%d", actproc, totproc);
931                                                                                 break;
932                                                                         case 5:
933                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%d", npid);
934                                                                                 break;
935                                                                 }
936                                                         }
937                                                 }
938                                                 break;
939 #endif
940                                         case 't': /* time */
941                                                 memset(&tm, 0, sizeof(struct tm));
942                                                 gettimeofday(&tv, NULL);
943                                                 if (localtime_r(&(tv.tv_sec), &tm)) {
944                                                         strftime(p, sizeof(prompt) - strlen(prompt), "%H:%M:%S", &tm);
945                                                 }
946                                                 break;
947                                         case '#': /* process console or remote? */
948                                                 if (! option_remote) {
949                                                         strncat(p, "#", sizeof(prompt) - strlen(prompt));
950                                                 } else {
951                                                         strncat(p, ">", sizeof(prompt) - strlen(prompt));
952                                                 }
953                                                 break;
954                                         case '%': /* literal % */
955                                                 strncat(p, "%", sizeof(prompt) - strlen(prompt));
956                                                 break;
957                                         case '\0': /* % is last character - prevent bug */
958                                                 t--;
959                                                 break;
960                                 }
961                                 while (*p != '\0') {
962                                         p++;
963                                 }
964                                 t++;
965                         } else {
966                                 *p = *t;
967                                 p++;
968                                 t++;
969                         }
970                 }
971         } else if (remotehostname)
972                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT2, remotehostname);
973         else
974                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT);
975
976         return(prompt); 
977 }
978
979 static char **ast_el_strtoarr(char *buf)
980 {
981         char **match_list = NULL, *retstr;
982         size_t match_list_len;
983         int matches = 0;
984
985         match_list_len = 1;
986         while ( (retstr = strsep(&buf, " ")) != NULL) {
987
988                 if (!strcmp(retstr, AST_CLI_COMPLETE_EOF))
989                         break;
990                 if (matches + 1 >= match_list_len) {
991                         match_list_len <<= 1;
992                         match_list = realloc(match_list, match_list_len * sizeof(char *));
993                 }
994
995                 match_list[matches++] = strdup(retstr);
996         }
997
998         if (!match_list)
999                 return (char **) NULL;
1000
1001         if (matches>= match_list_len)
1002                 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
1003
1004         match_list[matches] = (char *) NULL;
1005
1006         return match_list;
1007 }
1008
1009 static int ast_el_sort_compare(const void *i1, const void *i2)
1010 {
1011         char *s1, *s2;
1012
1013         s1 = ((char **)i1)[0];
1014         s2 = ((char **)i2)[0];
1015
1016         return strcasecmp(s1, s2);
1017 }
1018
1019 static int ast_cli_display_match_list(char **matches, int len, int max)
1020 {
1021         int i, idx, limit, count;
1022         int screenwidth = 0;
1023         int numoutput = 0, numoutputline = 0;
1024
1025         screenwidth = ast_get_termcols(STDOUT_FILENO);
1026
1027         /* find out how many entries can be put on one line, with two spaces between strings */
1028         limit = screenwidth / (max + 2);
1029         if (limit == 0)
1030                 limit = 1;
1031
1032         /* how many lines of output */
1033         count = len / limit;
1034         if (count * limit < len)
1035                 count++;
1036
1037         idx = 1;
1038
1039         qsort(&matches[0], (size_t)(len + 1), sizeof(char *), ast_el_sort_compare);
1040
1041         for (; count > 0; count--) {
1042                 numoutputline = 0;
1043                 for (i=0; i < limit && matches[idx]; i++, idx++) {
1044
1045                         /* Don't print dupes */
1046                         if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
1047                                 i--;
1048                                 continue;
1049                         }
1050
1051                         numoutput++;  numoutputline++;
1052                         fprintf(stdout, "%-*s  ", max, matches[idx]);
1053                 }
1054                 if (numoutputline > 0)
1055                         fprintf(stdout, "\n");
1056         }
1057
1058         return numoutput;
1059 }
1060
1061
1062 static char *cli_complete(EditLine *el, int ch)
1063 {
1064         int len=0;
1065         char *ptr;
1066         int nummatches = 0;
1067         char **matches;
1068         int retval = CC_ERROR;
1069         char buf[2048];
1070         int res;
1071
1072         LineInfo *lf = (LineInfo *)el_line(el);
1073
1074         *(char *)lf->cursor = '\0';
1075         ptr = (char *)lf->cursor;
1076         if (ptr) {
1077                 while (ptr > lf->buffer) {
1078                         if (isspace(*ptr)) {
1079                                 ptr++;
1080                                 break;
1081                         }
1082                         ptr--;
1083                 }
1084         }
1085
1086         len = lf->cursor - ptr;
1087
1088         if (option_remote) {
1089                 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr); 
1090                 fdprint(ast_consock, buf);
1091                 res = read(ast_consock, buf, sizeof(buf));
1092                 buf[res] = '\0';
1093                 nummatches = atoi(buf);
1094
1095                 if (nummatches > 0) {
1096                         char *mbuf;
1097                         int mlen = 0, maxmbuf = 2048;
1098                         /* Start with a 2048 byte buffer */
1099                         mbuf = malloc(maxmbuf);
1100                         if (!mbuf)
1101                                 return (char *)(CC_ERROR);
1102                         snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr); 
1103                         fdprint(ast_consock, buf);
1104                         res = 0;
1105                         mbuf[0] = '\0';
1106                         while (!strstr(mbuf, AST_CLI_COMPLETE_EOF) && res != -1) {
1107                                 if (mlen + 1024 > maxmbuf) {
1108                                         /* Every step increment buffer 1024 bytes */
1109                                         maxmbuf += 1024;
1110                                         mbuf = realloc(mbuf, maxmbuf);
1111                                         if (!mbuf)
1112                                                 return (char *)(CC_ERROR);
1113                                 }
1114                                 /* Only read 1024 bytes at a time */
1115                                 res = read(ast_consock, mbuf + mlen, 1024);
1116                                 if (res > 0)
1117                                         mlen += res;
1118                         }
1119                         mbuf[mlen] = '\0';
1120
1121                         matches = ast_el_strtoarr(mbuf);
1122                         free(mbuf);
1123                 } else
1124                         matches = (char **) NULL;
1125
1126
1127         }  else {
1128
1129                 nummatches = ast_cli_generatornummatches((char *)lf->buffer,ptr);
1130                 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
1131         }
1132
1133         if (matches) {
1134                 int i;
1135                 int matches_num, maxlen, match_len;
1136
1137                 if (matches[0][0] != '\0') {
1138                         el_deletestr(el, (int) len);
1139                         el_insertstr(el, matches[0]);
1140                         retval = CC_REFRESH;
1141                 }
1142
1143                 if (nummatches == 1) {
1144                         /* Found an exact match */
1145                         el_insertstr(el, " ");
1146                         retval = CC_REFRESH;
1147                 } else {
1148                         /* Must be more than one match */
1149                         for (i=1, maxlen=0; matches[i]; i++) {
1150                                 match_len = strlen(matches[i]);
1151                                 if (match_len > maxlen)
1152                                         maxlen = match_len;
1153                         }
1154                         matches_num = i - 1;
1155                         if (matches_num >1) {
1156                                 fprintf(stdout, "\n");
1157                                 ast_cli_display_match_list(matches, nummatches, maxlen);
1158                                 retval = CC_REDISPLAY;
1159                         } else { 
1160                                 el_insertstr(el," ");
1161                                 retval = CC_REFRESH;
1162                         }
1163                 }
1164         free(matches);
1165         }
1166
1167         return (char *)retval;
1168 }
1169
1170 static int ast_el_initialize(void)
1171 {
1172         HistEvent ev;
1173
1174         if (el != NULL)
1175                 el_end(el);
1176         if (el_hist != NULL)
1177                 history_end(el_hist);
1178
1179         el = el_init("asterisk", stdin, stdout, stderr);
1180         el_set(el, EL_PROMPT, cli_prompt);
1181
1182         el_set(el, EL_EDITMODE, 1);             
1183         el_set(el, EL_EDITOR, "emacs");         
1184         el_hist = history_init();
1185         if (!el || !el_hist)
1186                 return -1;
1187
1188         /* setup history with 100 entries */
1189         history(el_hist, &ev, H_SETSIZE, 100);
1190
1191         el_set(el, EL_HIST, history, el_hist);
1192
1193         el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
1194         /* Bind <tab> to command completion */
1195         el_set(el, EL_BIND, "^I", "ed-complete", NULL);
1196         /* Bind ? to command completion */
1197         el_set(el, EL_BIND, "?", "ed-complete", NULL);
1198         /* Bind ^D to redisplay */
1199         el_set(el, EL_BIND, "^D", "ed-redisplay", NULL);
1200
1201         return 0;
1202 }
1203
1204 static int ast_el_add_history(char *buf)
1205 {
1206         HistEvent ev;
1207
1208         if (el_hist == NULL || el == NULL)
1209                 ast_el_initialize();
1210         if (strlen(buf) > 256)
1211                 return 0;
1212         return (history(el_hist, &ev, H_ENTER, buf));
1213 }
1214
1215 static int ast_el_write_history(char *filename)
1216 {
1217         HistEvent ev;
1218
1219         if (el_hist == NULL || el == NULL)
1220                 ast_el_initialize();
1221
1222         return (history(el_hist, &ev, H_SAVE, filename));
1223 }
1224
1225 static int ast_el_read_history(char *filename)
1226 {
1227         char buf[256];
1228         FILE *f;
1229         int ret = -1;
1230
1231         if (el_hist == NULL || el == NULL)
1232                 ast_el_initialize();
1233
1234         if ((f = fopen(filename, "r")) == NULL)
1235                 return ret;
1236
1237         while (!feof(f)) {
1238                 fgets(buf, sizeof(buf), f);
1239                 if (!strcmp(buf, "_HiStOrY_V2_\n"))
1240                         continue;
1241                 if ((ret = ast_el_add_history(buf)) == -1)
1242                         break;
1243         }
1244         fclose(f);
1245
1246         return ret;
1247 }
1248
1249 static void ast_remotecontrol(char * data)
1250 {
1251         char buf[80];
1252         int res;
1253         char filename[80] = "";
1254         char *hostname;
1255         char *cpid;
1256         char *version;
1257         int pid;
1258         char tmp[80];
1259         char *stringp=NULL;
1260
1261         char *ebuf;
1262         int num = 0;
1263
1264         read(ast_consock, buf, sizeof(buf));
1265         if (data)
1266                 write(ast_consock, data, strlen(data) + 1);
1267         stringp=buf;
1268         hostname = strsep(&stringp, "/");
1269         cpid = strsep(&stringp, "/");
1270         version = strsep(&stringp, "\n");
1271         if (!version)
1272                 version = "<Version Unknown>";
1273         stringp=hostname;
1274         strsep(&stringp, ".");
1275         if (cpid)
1276                 pid = atoi(cpid);
1277         else
1278                 pid = -1;
1279         snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
1280         fdprint(ast_consock, tmp);
1281         ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
1282         remotehostname = hostname;
1283         if (getenv("HOME")) 
1284                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1285         if (el_hist == NULL || el == NULL)
1286                 ast_el_initialize();
1287
1288         el_set(el, EL_GETCFN, ast_el_read_char);
1289
1290         if (strlen(filename))
1291                 ast_el_read_history(filename);
1292
1293         ast_cli_register(&quit);
1294         ast_cli_register(&astexit);
1295 #if 0
1296         ast_cli_register(&astshutdown);
1297 #endif  
1298         if (option_exec && data) {  /* hack to print output then exit if asterisk -rx is used */
1299                 char tempchar;
1300                 ast_el_read_char(el, &tempchar);
1301                 return;
1302         }
1303         for(;;) {
1304                 ebuf = (char *)el_gets(el, &num);
1305
1306                 if (ebuf && strlen(ebuf)) {
1307                         if (ebuf[strlen(ebuf)-1] == '\n')
1308                                 ebuf[strlen(ebuf)-1] = '\0';
1309                         if (!remoteconsolehandler(ebuf)) {
1310                                 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
1311                                 if (res < 1) {
1312                                         ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
1313                                         break;
1314                                 }
1315                         }
1316                 }
1317         }
1318         printf("\nDisconnected from Asterisk server\n");
1319 }
1320
1321 static int show_cli_help(void) {
1322         printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 2000-2002, Digium.\n");
1323         printf("Usage: asterisk [OPTIONS]\n");
1324         printf("Valid Options:\n");
1325         printf("   -h           This help screen\n");
1326         printf("   -r           Connect to Asterisk on this machine\n");
1327         printf("   -f           Do not fork\n");
1328         printf("   -n           Disable console colorization\n");
1329         printf("   -p           Run as pseudo-realtime thread\n");
1330         printf("   -v           Increase verbosity (multiple v's = more verbose)\n");
1331         printf("   -q           Quiet mode (supress output)\n");
1332         printf("   -g           Dump core in case of a crash\n");
1333         printf("   -x <cmd>     Execute command <cmd> (only valid with -r)\n");
1334         printf("   -i           Initializie crypto keys at startup\n");
1335         printf("   -c           Provide console CLI\n");
1336         printf("   -d           Enable extra debugging\n");
1337         printf("\n");
1338         return 0;
1339 }
1340
1341 static void ast_readconfig(void) {
1342         struct ast_config *cfg;
1343         struct ast_variable *v;
1344         char *config = ASTCONFPATH;
1345
1346         if (option_overrideconfig == 1) {
1347             cfg = ast_load((char *)ast_config_AST_CONFIG_FILE);
1348         } else {
1349             cfg = ast_load(config);
1350         }
1351
1352         /* init with buildtime config */
1353         strncpy((char *)ast_config_AST_CONFIG_DIR,AST_CONFIG_DIR,sizeof(ast_config_AST_CONFIG_DIR)-1);
1354         strncpy((char *)ast_config_AST_SPOOL_DIR,AST_SPOOL_DIR,sizeof(ast_config_AST_SPOOL_DIR)-1);
1355         strncpy((char *)ast_config_AST_MODULE_DIR,AST_MODULE_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1356         strncpy((char *)ast_config_AST_VAR_DIR,AST_VAR_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1357         strncpy((char *)ast_config_AST_LOG_DIR,AST_LOG_DIR,sizeof(ast_config_AST_LOG_DIR)-1);
1358         strncpy((char *)ast_config_AST_AGI_DIR,AST_AGI_DIR,sizeof(ast_config_AST_AGI_DIR)-1);
1359         strncpy((char *)ast_config_AST_DB,AST_DB,sizeof(ast_config_AST_DB)-1);
1360         strncpy((char *)ast_config_AST_KEY_DIR,AST_KEY_DIR,sizeof(ast_config_AST_KEY_DIR)-1);
1361         strncpy((char *)ast_config_AST_PID,AST_PID,sizeof(ast_config_AST_PID)-1);
1362         strncpy((char *)ast_config_AST_SOCKET,AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1);
1363         strncpy((char *)ast_config_AST_RUN_DIR,AST_RUN_DIR,sizeof(ast_config_AST_RUN_DIR)-1);
1364         
1365         /* no asterisk.conf? no problem, use buildtime config! */
1366         if (!cfg) {
1367             return;
1368         }
1369         v = ast_variable_browse(cfg, "directories");
1370         while(v) {
1371                 if (!strcasecmp(v->name, "astetcdir")) {
1372                     strncpy((char *)ast_config_AST_CONFIG_DIR,v->value,sizeof(ast_config_AST_CONFIG_DIR)-1);
1373                 } else if (!strcasecmp(v->name, "astspooldir")) {
1374                     strncpy((char *)ast_config_AST_SPOOL_DIR,v->value,sizeof(ast_config_AST_SPOOL_DIR)-1);
1375                 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1376                     strncpy((char *)ast_config_AST_VAR_DIR,v->value,sizeof(ast_config_AST_VAR_DIR)-1);
1377                     snprintf((char *)ast_config_AST_DB,sizeof(ast_config_AST_DB)-1,"%s/%s",v->value,"astdb");    
1378                 } else if (!strcasecmp(v->name, "astlogdir")) {
1379                     strncpy((char *)ast_config_AST_LOG_DIR,v->value,sizeof(ast_config_AST_LOG_DIR)-1);
1380                 } else if (!strcasecmp(v->name, "astagidir")) {
1381                     strncpy((char *)ast_config_AST_AGI_DIR,v->value,sizeof(ast_config_AST_AGI_DIR)-1);
1382                 } else if (!strcasecmp(v->name, "astrundir")) {
1383                     snprintf((char *)ast_config_AST_PID,sizeof(ast_config_AST_PID)-1,"%s/%s",v->value,"asterisk.pid");    
1384                     snprintf((char *)ast_config_AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1,"%s/%s",v->value,"asterisk.ctl");    
1385                     strncpy((char *)ast_config_AST_RUN_DIR,v->value,sizeof(ast_config_AST_RUN_DIR)-1);
1386                 } else if (!strcasecmp(v->name, "astmoddir")) {
1387                     strncpy((char *)ast_config_AST_MODULE_DIR,v->value,sizeof(ast_config_AST_MODULE_DIR)-1);
1388                 }
1389                 v = v->next;
1390         }
1391         ast_destroy(cfg);
1392 }
1393
1394 int main(int argc, char *argv[])
1395 {
1396         int c;
1397         char filename[80] = "";
1398         char hostname[256];
1399         char tmp[80];
1400         char * xarg = NULL;
1401         int x;
1402         FILE *f;
1403         sigset_t sigs;
1404         int num;
1405         char *buf;
1406
1407         /* Remember original args for restart */
1408         if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1409                 fprintf(stderr, "Truncating argument size to %d\n", sizeof(_argv) / sizeof(_argv[0]) - 1);
1410                 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1411         }
1412         for (x=0;x<argc;x++)
1413                 _argv[x] = argv[x];
1414         _argv[x] = NULL;
1415
1416         /* if the progname is rasterisk consider it a remote console */
1417         if ( argv[0] && (strstr(argv[0], "rasterisk")) != NULL)  {
1418                 option_remote++;
1419                 option_nofork++;
1420         }
1421         if (gethostname(hostname, sizeof(hostname)))
1422                 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
1423         ast_mainpid = getpid();
1424         ast_ulaw_init();
1425         ast_alaw_init();
1426         callerid_init();
1427         tdd_init();
1428         if (getenv("HOME")) 
1429                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1430         /* Check if we're root */
1431         /*
1432         if (geteuid()) {
1433                 ast_log(LOG_ERROR, "Must be run as root\n");
1434                 exit(1);
1435         }
1436         */
1437         /* Check for options */
1438         while((c=getopt(argc, argv, "hfdvqprgcinx:C:")) != -1) {
1439                 switch(c) {
1440                 case 'd':
1441                         option_debug++;
1442                         option_nofork++;
1443                         break;
1444                 case 'c':
1445                         option_console++;
1446                         option_nofork++;
1447                         break;
1448                 case 'f':
1449                         option_nofork++;
1450                         break;
1451                 case 'n':
1452                         option_nocolor++;
1453                         break;
1454                 case 'r':
1455                         option_remote++;
1456                         option_nofork++;
1457                         break;
1458                 case 'p':
1459                         option_highpriority++;
1460                         break;
1461                 case 'v':
1462                         option_verbose++;
1463                         option_nofork++;
1464                         break;
1465                 case 'q':
1466                         option_quiet++;
1467                         break;
1468                 case 'x':
1469                         option_exec++;
1470                         xarg = optarg;
1471                         break;
1472                 case 'C':
1473                         strncpy((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE));
1474                         option_overrideconfig++;
1475                         break;
1476                 case 'i':
1477                         option_initcrypto++;
1478                         break;
1479                 case'g':
1480                         option_dumpcore++;
1481                         break;
1482                 case 'h':
1483                         show_cli_help();
1484                         exit(0);
1485                 case '?':
1486                         exit(1);
1487                 }
1488         }
1489
1490         if (option_dumpcore) {
1491                 struct rlimit l;
1492                 memset(&l, 0, sizeof(l));
1493                 l.rlim_cur = RLIM_INFINITY;
1494                 l.rlim_max = RLIM_INFINITY;
1495                 if (setrlimit(RLIMIT_CORE, &l)) {
1496                         ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
1497                 }
1498         }
1499
1500         term_init();
1501         printf(term_end());
1502         fflush(stdout);
1503         if (option_console && !option_verbose) 
1504                 ast_verbose("[ Reading Master Configuration ]");
1505         ast_readconfig();
1506
1507         if (option_console) {
1508                 if (el_hist == NULL || el == NULL)
1509                         ast_el_initialize();
1510
1511                 if (strlen(filename))
1512                         ast_el_read_history(filename);
1513         }
1514
1515         if (ast_tryconnect()) {
1516                 /* One is already running */
1517                 if (option_remote) {
1518                         if (option_exec) {
1519                                 ast_remotecontrol(xarg);
1520                                 quit_handler(0, 0, 0, 0);
1521                                 exit(0);
1522                         }
1523                         printf(term_quit());
1524                         ast_register_verbose(console_verboser);
1525                         ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2004 Digium.\n");
1526                         ast_verbose( "Written by Mark Spencer <markster@digium.com>\n");
1527                         ast_verbose( "=========================================================================\n");
1528                         ast_remotecontrol(NULL);
1529                         quit_handler(0, 0, 0, 0);
1530                         exit(0);
1531                 } else {
1532                         ast_log(LOG_ERROR, "Asterisk already running on %s.  Use 'asterisk -r' to connect.\n", (char *)ast_config_AST_SOCKET);
1533                         printf(term_quit());
1534                         exit(1);
1535                 }
1536         } else if (option_remote || option_exec) {
1537                 ast_log(LOG_ERROR, "Unable to connect to remote asterisk\n");
1538                 printf(term_quit());
1539                 exit(1);
1540         }
1541         /* Blindly write pid file since we couldn't connect */
1542         unlink((char *)ast_config_AST_PID);
1543         f = fopen((char *)ast_config_AST_PID, "w");
1544         if (f) {
1545                 fprintf(f, "%d\n", getpid());
1546                 fclose(f);
1547         } else
1548                 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1549
1550         if (!option_verbose && !option_debug && !option_nofork && !option_console) {
1551                 daemon(0,0);
1552                 /* Blindly re-write pid file since we are forking */
1553                 unlink((char *)ast_config_AST_PID);
1554                 f = fopen((char *)ast_config_AST_PID, "w");
1555                 if (f) {
1556                         fprintf(f, "%d\n", getpid());
1557                         fclose(f);
1558                 } else
1559                         ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1560         }
1561
1562         ast_makesocket();
1563         sigemptyset(&sigs);
1564         sigaddset(&sigs, SIGHUP);
1565         sigaddset(&sigs, SIGTERM);
1566         sigaddset(&sigs, SIGINT);
1567         sigaddset(&sigs, SIGPIPE);
1568         sigaddset(&sigs, SIGWINCH);
1569         pthread_sigmask(SIG_BLOCK, &sigs, NULL);
1570         if (option_console || option_verbose || option_remote)
1571                 ast_register_verbose(console_verboser);
1572         /* Print a welcome message if desired */
1573         if (option_verbose || option_console) {
1574                 ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2001 Linux Support Services, Inc.\n");
1575                 ast_verbose( "Written by Mark Spencer <markster@linux-support.net>\n");
1576                 ast_verbose( "=========================================================================\n");
1577         }
1578         if (option_console && !option_verbose) 
1579                 ast_verbose("[ Booting...");
1580
1581         signal(SIGURG, urg_handler);
1582         signal(SIGINT, __quit_handler);
1583         signal(SIGTERM, __quit_handler);
1584         signal(SIGHUP, hup_handler);
1585         signal(SIGCHLD, child_handler);
1586         signal(SIGPIPE, SIG_IGN);
1587
1588         if (set_priority(option_highpriority)) {
1589                 printf(term_quit());
1590                 exit(1);
1591         }
1592         if (init_logger()) {
1593                 printf(term_quit());
1594                 exit(1);
1595         }
1596         if (init_manager()) {
1597                 printf(term_quit());
1598                 exit(1);
1599         }
1600         ast_rtp_init();
1601         if (ast_image_init()) {
1602                 printf(term_quit());
1603                 exit(1);
1604         }
1605         if (load_pbx()) {
1606                 printf(term_quit());
1607                 exit(1);
1608         }
1609         if (load_modules()) {
1610                 printf(term_quit());
1611                 exit(1);
1612         }
1613         if (init_framer()) {
1614                 printf(term_quit());
1615                 exit(1);
1616         }
1617         if (astdb_init()) {
1618                 printf(term_quit());
1619                 exit(1);
1620         }
1621         if (ast_enum_init()) {
1622                 printf(term_quit());
1623                 exit(1);
1624         }
1625         /* We might have the option of showing a console, but for now just
1626            do nothing... */
1627         if (option_console && !option_verbose)
1628                 ast_verbose(" ]\n");
1629         if (option_verbose || option_console)
1630                 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
1631         if (option_nofork)
1632                 consolethread = pthread_self();
1633         fully_booted = 1;
1634         pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
1635 #ifdef __AST_DEBUG_MALLOC
1636         __ast_mm_init();
1637 #endif  
1638         time(&ast_startuptime);
1639         ast_cli_register(&astshutdownnow);
1640         ast_cli_register(&astshutdowngracefully);
1641         ast_cli_register(&astrestartnow);
1642         ast_cli_register(&astrestartgracefully);
1643         ast_cli_register(&astrestartwhenconvenient);
1644         ast_cli_register(&astshutdownwhenconvenient);
1645         ast_cli_register(&aborthalt);
1646         ast_cli_register(&astbang);
1647         if (option_console) {
1648                 /* Console stuff now... */
1649                 /* Register our quit function */
1650                 char title[256];
1651                 set_icon("Asterisk");
1652                 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, ast_mainpid);
1653                 set_title(title);
1654             ast_cli_register(&quit);
1655             ast_cli_register(&astexit);
1656
1657                 for (;;) {
1658                         buf = (char *)el_gets(el, &num);
1659                         if (buf) {
1660                                 if (buf[strlen(buf)-1] == '\n')
1661                                         buf[strlen(buf)-1] = '\0';
1662
1663                                 consolehandler((char *)buf);
1664                         } else {
1665                                 if (option_remote)
1666                                         ast_cli(STDOUT_FILENO, "\nUse EXIT or QUIT to exit the asterisk console\n");
1667                                 else
1668                                         ast_cli(STDOUT_FILENO, "\nUse STOP NOW to shutdown Asterisk\n");
1669                         }
1670                 }
1671
1672         } else {
1673                 /* Do nothing */
1674                 poll(NULL,0, -1);
1675         }
1676         return 0;
1677 }
1678
1679 struct hostent *ast_gethostbyname(const char *host, struct ast_hostent *hp)
1680 {
1681         int res;
1682         int herrno;
1683         struct hostent *result = NULL;
1684         /* XXX Does BSD do this differently? XXX */
1685         res = gethostbyname_r(host, &hp->hp, hp->buf, sizeof(hp->buf), &result, &herrno);
1686         if (res)
1687                 return NULL;
1688         return &hp->hp;
1689 }