Remove size restiction on remote console command completion (bug 1360)
[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 = execl("/bin/sh", "/bin/sh", "-c", s, NULL);
172                 exit(1);
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[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++] = 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 (CC_ERROR);
1102                         snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr); 
1103                         fdprint(ast_consock, buf);
1104                         res = 0;
1105                         while (!strstr(mbuf, AST_CLI_COMPLETE_EOF) && res != -1) {
1106                                 if (mlen + 1024 > maxmbuf) {
1107                                         /* Every step increment buffer 1024 bytes */
1108                                         maxmbuf += 1024;
1109                                         mbuf = realloc(mbuf, maxmbuf);
1110                                         if (!mbuf)
1111                                                 return (CC_ERROR);
1112                                 }
1113                                 /* Only read 1024 bytes at a time */
1114                                 res = read(ast_consock, mbuf + mlen, 1024);
1115                                 if (res > 0)
1116                                         mlen += res;
1117                         }
1118                         mbuf[mlen] = '\0';
1119
1120                         matches = ast_el_strtoarr(mbuf);
1121                         free(mbuf);
1122                 } else
1123                         matches = (char **) NULL;
1124
1125
1126         }  else {
1127
1128                 nummatches = ast_cli_generatornummatches((char *)lf->buffer,ptr);
1129                 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
1130         }
1131
1132         if (matches) {
1133                 int i;
1134                 int matches_num, maxlen, match_len;
1135
1136                 if (matches[0][0] != '\0') {
1137                         el_deletestr(el, (int) len);
1138                         el_insertstr(el, matches[0]);
1139                         retval = CC_REFRESH;
1140                 }
1141
1142                 if (nummatches == 1) {
1143                         /* Found an exact match */
1144                         el_insertstr(el, " ");
1145                         retval = CC_REFRESH;
1146                 } else {
1147                         /* Must be more than one match */
1148                         for (i=1, maxlen=0; matches[i]; i++) {
1149                                 match_len = strlen(matches[i]);
1150                                 if (match_len > maxlen)
1151                                         maxlen = match_len;
1152                         }
1153                         matches_num = i - 1;
1154                         if (matches_num >1) {
1155                                 fprintf(stdout, "\n");
1156                                 ast_cli_display_match_list(matches, nummatches, maxlen);
1157                                 retval = CC_REDISPLAY;
1158                         } else { 
1159                                 el_insertstr(el," ");
1160                                 retval = CC_REFRESH;
1161                         }
1162                 }
1163         free(matches);
1164         }
1165
1166         return (char *)retval;
1167 }
1168
1169 static int ast_el_initialize(void)
1170 {
1171         HistEvent ev;
1172
1173         if (el != NULL)
1174                 el_end(el);
1175         if (el_hist != NULL)
1176                 history_end(el_hist);
1177
1178         el = el_init("asterisk", stdin, stdout, stderr);
1179         el_set(el, EL_PROMPT, cli_prompt);
1180
1181         el_set(el, EL_EDITMODE, 1);             
1182         el_set(el, EL_EDITOR, "emacs");         
1183         el_hist = history_init();
1184         if (!el || !el_hist)
1185                 return -1;
1186
1187         /* setup history with 100 entries */
1188         history(el_hist, &ev, H_SETSIZE, 100);
1189
1190         el_set(el, EL_HIST, history, el_hist);
1191
1192         el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
1193         /* Bind <tab> to command completion */
1194         el_set(el, EL_BIND, "^I", "ed-complete", NULL);
1195         /* Bind ? to command completion */
1196         el_set(el, EL_BIND, "?", "ed-complete", NULL);
1197         /* Bind ^D to redisplay */
1198         el_set(el, EL_BIND, "^D", "ed-redisplay", NULL);
1199
1200         return 0;
1201 }
1202
1203 static int ast_el_add_history(char *buf)
1204 {
1205         HistEvent ev;
1206
1207         if (el_hist == NULL || el == NULL)
1208                 ast_el_initialize();
1209         if (strlen(buf) > 256)
1210                 return 0;
1211         return (history(el_hist, &ev, H_ENTER, buf));
1212 }
1213
1214 static int ast_el_write_history(char *filename)
1215 {
1216         HistEvent ev;
1217
1218         if (el_hist == NULL || el == NULL)
1219                 ast_el_initialize();
1220
1221         return (history(el_hist, &ev, H_SAVE, filename));
1222 }
1223
1224 static int ast_el_read_history(char *filename)
1225 {
1226         char buf[256];
1227         FILE *f;
1228         int ret = -1;
1229
1230         if (el_hist == NULL || el == NULL)
1231                 ast_el_initialize();
1232
1233         if ((f = fopen(filename, "r")) == NULL)
1234                 return ret;
1235
1236         while (!feof(f)) {
1237                 fgets(buf, sizeof(buf), f);
1238                 if (!strcmp(buf, "_HiStOrY_V2_\n"))
1239                         continue;
1240                 if ((ret = ast_el_add_history(buf)) == -1)
1241                         break;
1242         }
1243         fclose(f);
1244
1245         return ret;
1246 }
1247
1248 static void ast_remotecontrol(char * data)
1249 {
1250         char buf[80];
1251         int res;
1252         char filename[80] = "";
1253         char *hostname;
1254         char *cpid;
1255         char *version;
1256         int pid;
1257         char tmp[80];
1258         char *stringp=NULL;
1259
1260         char *ebuf;
1261         int num = 0;
1262
1263         read(ast_consock, buf, sizeof(buf));
1264         if (data)
1265                 write(ast_consock, data, strlen(data) + 1);
1266         stringp=buf;
1267         hostname = strsep(&stringp, "/");
1268         cpid = strsep(&stringp, "/");
1269         version = strsep(&stringp, "\n");
1270         if (!version)
1271                 version = "<Version Unknown>";
1272         stringp=hostname;
1273         strsep(&stringp, ".");
1274         if (cpid)
1275                 pid = atoi(cpid);
1276         else
1277                 pid = -1;
1278         snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
1279         fdprint(ast_consock, tmp);
1280         ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
1281         remotehostname = hostname;
1282         if (getenv("HOME")) 
1283                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1284         if (el_hist == NULL || el == NULL)
1285                 ast_el_initialize();
1286
1287         el_set(el, EL_GETCFN, ast_el_read_char);
1288
1289         if (strlen(filename))
1290                 ast_el_read_history(filename);
1291
1292         ast_cli_register(&quit);
1293         ast_cli_register(&astexit);
1294 #if 0
1295         ast_cli_register(&astshutdown);
1296 #endif  
1297         if (option_exec && data) {  /* hack to print output then exit if asterisk -rx is used */
1298                 char tempchar;
1299                 ast_el_read_char(el, &tempchar);
1300                 return;
1301         }
1302         for(;;) {
1303                 ebuf = (char *)el_gets(el, &num);
1304
1305                 if (ebuf && strlen(ebuf)) {
1306                         if (ebuf[strlen(ebuf)-1] == '\n')
1307                                 ebuf[strlen(ebuf)-1] = '\0';
1308                         if (!remoteconsolehandler(ebuf)) {
1309                                 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
1310                                 if (res < 1) {
1311                                         ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
1312                                         break;
1313                                 }
1314                         }
1315                 }
1316         }
1317         printf("\nDisconnected from Asterisk server\n");
1318 }
1319
1320 static int show_cli_help(void) {
1321         printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 2000-2002, Digium.\n");
1322         printf("Usage: asterisk [OPTIONS]\n");
1323         printf("Valid Options:\n");
1324         printf("   -h           This help screen\n");
1325         printf("   -r           Connect to Asterisk on this machine\n");
1326         printf("   -f           Do not fork\n");
1327         printf("   -n           Disable console colorization\n");
1328         printf("   -p           Run as pseudo-realtime thread\n");
1329         printf("   -v           Increase verbosity (multiple v's = more verbose)\n");
1330         printf("   -q           Quiet mode (supress output)\n");
1331         printf("   -g           Dump core in case of a crash\n");
1332         printf("   -x <cmd>     Execute command <cmd> (only valid with -r)\n");
1333         printf("   -i           Initializie crypto keys at startup\n");
1334         printf("   -c           Provide console CLI\n");
1335         printf("   -d           Enable extra debugging\n");
1336         printf("\n");
1337         return 0;
1338 }
1339
1340 static void ast_readconfig(void) {
1341         struct ast_config *cfg;
1342         struct ast_variable *v;
1343         char *config = ASTCONFPATH;
1344
1345         if (option_overrideconfig == 1) {
1346             cfg = ast_load((char *)ast_config_AST_CONFIG_FILE);
1347         } else {
1348             cfg = ast_load(config);
1349         }
1350
1351         /* init with buildtime config */
1352         strncpy((char *)ast_config_AST_CONFIG_DIR,AST_CONFIG_DIR,sizeof(ast_config_AST_CONFIG_DIR)-1);
1353         strncpy((char *)ast_config_AST_SPOOL_DIR,AST_SPOOL_DIR,sizeof(ast_config_AST_SPOOL_DIR)-1);
1354         strncpy((char *)ast_config_AST_MODULE_DIR,AST_MODULE_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1355         strncpy((char *)ast_config_AST_VAR_DIR,AST_VAR_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1356         strncpy((char *)ast_config_AST_LOG_DIR,AST_LOG_DIR,sizeof(ast_config_AST_LOG_DIR)-1);
1357         strncpy((char *)ast_config_AST_AGI_DIR,AST_AGI_DIR,sizeof(ast_config_AST_AGI_DIR)-1);
1358         strncpy((char *)ast_config_AST_DB,AST_DB,sizeof(ast_config_AST_DB)-1);
1359         strncpy((char *)ast_config_AST_KEY_DIR,AST_KEY_DIR,sizeof(ast_config_AST_KEY_DIR)-1);
1360         strncpy((char *)ast_config_AST_PID,AST_PID,sizeof(ast_config_AST_PID)-1);
1361         strncpy((char *)ast_config_AST_SOCKET,AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1);
1362         strncpy((char *)ast_config_AST_RUN_DIR,AST_RUN_DIR,sizeof(ast_config_AST_RUN_DIR)-1);
1363         
1364         /* no asterisk.conf? no problem, use buildtime config! */
1365         if (!cfg) {
1366             return;
1367         }
1368         v = ast_variable_browse(cfg, "directories");
1369         while(v) {
1370                 if (!strcasecmp(v->name, "astetcdir")) {
1371                     strncpy((char *)ast_config_AST_CONFIG_DIR,v->value,sizeof(ast_config_AST_CONFIG_DIR)-1);
1372                 } else if (!strcasecmp(v->name, "astspooldir")) {
1373                     strncpy((char *)ast_config_AST_SPOOL_DIR,v->value,sizeof(ast_config_AST_SPOOL_DIR)-1);
1374                 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1375                     strncpy((char *)ast_config_AST_VAR_DIR,v->value,sizeof(ast_config_AST_VAR_DIR)-1);
1376                     snprintf((char *)ast_config_AST_DB,sizeof(ast_config_AST_DB)-1,"%s/%s",v->value,"astdb");    
1377                 } else if (!strcasecmp(v->name, "astlogdir")) {
1378                     strncpy((char *)ast_config_AST_LOG_DIR,v->value,sizeof(ast_config_AST_LOG_DIR)-1);
1379                 } else if (!strcasecmp(v->name, "astagidir")) {
1380                     strncpy((char *)ast_config_AST_AGI_DIR,v->value,sizeof(ast_config_AST_AGI_DIR)-1);
1381                 } else if (!strcasecmp(v->name, "astrundir")) {
1382                     snprintf((char *)ast_config_AST_PID,sizeof(ast_config_AST_PID)-1,"%s/%s",v->value,"asterisk.pid");    
1383                     snprintf((char *)ast_config_AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1,"%s/%s",v->value,"asterisk.ctl");    
1384                     strncpy((char *)ast_config_AST_RUN_DIR,v->value,sizeof(ast_config_AST_RUN_DIR)-1);
1385                 } else if (!strcasecmp(v->name, "astmoddir")) {
1386                     strncpy((char *)ast_config_AST_MODULE_DIR,v->value,sizeof(ast_config_AST_MODULE_DIR)-1);
1387                 }
1388                 v = v->next;
1389         }
1390         ast_destroy(cfg);
1391 }
1392
1393 int main(int argc, char *argv[])
1394 {
1395         int c;
1396         char filename[80] = "";
1397         char hostname[256];
1398         char tmp[80];
1399         char * xarg = NULL;
1400         int x;
1401         FILE *f;
1402         sigset_t sigs;
1403         int num;
1404         char *buf;
1405
1406         /* Remember original args for restart */
1407         if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1408                 fprintf(stderr, "Truncating argument size to %d\n", sizeof(_argv) / sizeof(_argv[0]) - 1);
1409                 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1410         }
1411         for (x=0;x<argc;x++)
1412                 _argv[x] = argv[x];
1413         _argv[x] = NULL;
1414
1415         /* if the progname is rasterisk consider it a remote console */
1416         if ( argv[0] && (strstr(argv[0], "rasterisk")) != NULL)  {
1417                 option_remote++;
1418                 option_nofork++;
1419         }
1420         if (gethostname(hostname, sizeof(hostname)))
1421                 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
1422         ast_mainpid = getpid();
1423         ast_ulaw_init();
1424         ast_alaw_init();
1425         callerid_init();
1426         tdd_init();
1427         if (getenv("HOME")) 
1428                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1429         /* Check if we're root */
1430         /*
1431         if (geteuid()) {
1432                 ast_log(LOG_ERROR, "Must be run as root\n");
1433                 exit(1);
1434         }
1435         */
1436         /* Check for options */
1437         while((c=getopt(argc, argv, "hfdvqprgcinx:C:")) != -1) {
1438                 switch(c) {
1439                 case 'd':
1440                         option_debug++;
1441                         option_nofork++;
1442                         break;
1443                 case 'c':
1444                         option_console++;
1445                         option_nofork++;
1446                         break;
1447                 case 'f':
1448                         option_nofork++;
1449                         break;
1450                 case 'n':
1451                         option_nocolor++;
1452                         break;
1453                 case 'r':
1454                         option_remote++;
1455                         option_nofork++;
1456                         break;
1457                 case 'p':
1458                         option_highpriority++;
1459                         break;
1460                 case 'v':
1461                         option_verbose++;
1462                         option_nofork++;
1463                         break;
1464                 case 'q':
1465                         option_quiet++;
1466                         break;
1467                 case 'x':
1468                         option_exec++;
1469                         xarg = optarg;
1470                         break;
1471                 case 'C':
1472                         strncpy((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE));
1473                         option_overrideconfig++;
1474                         break;
1475                 case 'i':
1476                         option_initcrypto++;
1477                         break;
1478                 case'g':
1479                         option_dumpcore++;
1480                         break;
1481                 case 'h':
1482                         show_cli_help();
1483                         exit(0);
1484                 case '?':
1485                         exit(1);
1486                 }
1487         }
1488
1489         if (option_dumpcore) {
1490                 struct rlimit l;
1491                 memset(&l, 0, sizeof(l));
1492                 l.rlim_cur = RLIM_INFINITY;
1493                 l.rlim_max = RLIM_INFINITY;
1494                 if (setrlimit(RLIMIT_CORE, &l)) {
1495                         ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
1496                 }
1497         }
1498
1499         term_init();
1500         printf(term_end());
1501         fflush(stdout);
1502         if (option_console && !option_verbose) 
1503                 ast_verbose("[ Reading Master Configuration ]");
1504         ast_readconfig();
1505
1506         if (option_console) {
1507                 if (el_hist == NULL || el == NULL)
1508                         ast_el_initialize();
1509
1510                 if (strlen(filename))
1511                         ast_el_read_history(filename);
1512         }
1513
1514         if (ast_tryconnect()) {
1515                 /* One is already running */
1516                 if (option_remote) {
1517                         if (option_exec) {
1518                                 ast_remotecontrol(xarg);
1519                                 quit_handler(0, 0, 0, 0);
1520                                 exit(0);
1521                         }
1522                         printf(term_quit());
1523                         ast_register_verbose(console_verboser);
1524                         ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2004 Digium.\n");
1525                         ast_verbose( "Written by Mark Spencer <markster@digium.com>\n");
1526                         ast_verbose( "=========================================================================\n");
1527                         ast_remotecontrol(NULL);
1528                         quit_handler(0, 0, 0, 0);
1529                         exit(0);
1530                 } else {
1531                         ast_log(LOG_ERROR, "Asterisk already running on %s.  Use 'asterisk -r' to connect.\n", (char *)ast_config_AST_SOCKET);
1532                         printf(term_quit());
1533                         exit(1);
1534                 }
1535         } else if (option_remote || option_exec) {
1536                 ast_log(LOG_ERROR, "Unable to connect to remote asterisk\n");
1537                 printf(term_quit());
1538                 exit(1);
1539         }
1540         /* Blindly write pid file since we couldn't connect */
1541         unlink((char *)ast_config_AST_PID);
1542         f = fopen((char *)ast_config_AST_PID, "w");
1543         if (f) {
1544                 fprintf(f, "%d\n", getpid());
1545                 fclose(f);
1546         } else
1547                 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1548
1549         if (!option_verbose && !option_debug && !option_nofork && !option_console) {
1550                 daemon(0,0);
1551                 /* Blindly re-write pid file since we are forking */
1552                 unlink((char *)ast_config_AST_PID);
1553                 f = fopen((char *)ast_config_AST_PID, "w");
1554                 if (f) {
1555                         fprintf(f, "%d\n", getpid());
1556                         fclose(f);
1557                 } else
1558                         ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1559         }
1560
1561         ast_makesocket();
1562         sigemptyset(&sigs);
1563         sigaddset(&sigs, SIGHUP);
1564         sigaddset(&sigs, SIGTERM);
1565         sigaddset(&sigs, SIGINT);
1566         sigaddset(&sigs, SIGPIPE);
1567         sigaddset(&sigs, SIGWINCH);
1568         pthread_sigmask(SIG_BLOCK, &sigs, NULL);
1569         if (option_console || option_verbose || option_remote)
1570                 ast_register_verbose(console_verboser);
1571         /* Print a welcome message if desired */
1572         if (option_verbose || option_console) {
1573                 ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2001 Linux Support Services, Inc.\n");
1574                 ast_verbose( "Written by Mark Spencer <markster@linux-support.net>\n");
1575                 ast_verbose( "=========================================================================\n");
1576         }
1577         if (option_console && !option_verbose) 
1578                 ast_verbose("[ Booting...");
1579
1580         signal(SIGURG, urg_handler);
1581         signal(SIGINT, __quit_handler);
1582         signal(SIGTERM, __quit_handler);
1583         signal(SIGHUP, hup_handler);
1584         signal(SIGCHLD, child_handler);
1585         signal(SIGPIPE, SIG_IGN);
1586
1587         if (set_priority(option_highpriority)) {
1588                 printf(term_quit());
1589                 exit(1);
1590         }
1591         if (init_logger()) {
1592                 printf(term_quit());
1593                 exit(1);
1594         }
1595         if (init_manager()) {
1596                 printf(term_quit());
1597                 exit(1);
1598         }
1599         ast_rtp_init();
1600         if (ast_image_init()) {
1601                 printf(term_quit());
1602                 exit(1);
1603         }
1604         if (load_pbx()) {
1605                 printf(term_quit());
1606                 exit(1);
1607         }
1608         if (load_modules()) {
1609                 printf(term_quit());
1610                 exit(1);
1611         }
1612         if (init_framer()) {
1613                 printf(term_quit());
1614                 exit(1);
1615         }
1616         if (astdb_init()) {
1617                 printf(term_quit());
1618                 exit(1);
1619         }
1620         if (ast_enum_init()) {
1621                 printf(term_quit());
1622                 exit(1);
1623         }
1624         /* We might have the option of showing a console, but for now just
1625            do nothing... */
1626         if (option_console && !option_verbose)
1627                 ast_verbose(" ]\n");
1628         if (option_verbose || option_console)
1629                 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
1630         if (option_nofork)
1631                 consolethread = pthread_self();
1632         fully_booted = 1;
1633         pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
1634 #ifdef __AST_DEBUG_MALLOC
1635         __ast_mm_init();
1636 #endif  
1637         time(&ast_startuptime);
1638         ast_cli_register(&astshutdownnow);
1639         ast_cli_register(&astshutdowngracefully);
1640         ast_cli_register(&astrestartnow);
1641         ast_cli_register(&astrestartgracefully);
1642         ast_cli_register(&astrestartwhenconvenient);
1643         ast_cli_register(&astshutdownwhenconvenient);
1644         ast_cli_register(&aborthalt);
1645         ast_cli_register(&astbang);
1646         if (option_console) {
1647                 /* Console stuff now... */
1648                 /* Register our quit function */
1649                 char title[256];
1650                 set_icon("Asterisk");
1651                 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, ast_mainpid);
1652                 set_title(title);
1653             ast_cli_register(&quit);
1654             ast_cli_register(&astexit);
1655
1656                 for (;;) {
1657                         buf = (char *)el_gets(el, &num);
1658                         if (buf) {
1659                                 if (buf[strlen(buf)-1] == '\n')
1660                                         buf[strlen(buf)-1] = '\0';
1661
1662                                 consolehandler((char *)buf);
1663                         } else {
1664                                 if (option_remote)
1665                                         ast_cli(STDOUT_FILENO, "\nUse EXIT or QUIT to exit the asterisk console\n");
1666                                 else
1667                                         ast_cli(STDOUT_FILENO, "\nUse STOP NOW to shutdown Asterisk\n");
1668                         }
1669                 }
1670
1671         } else {
1672                 /* Do nothing */
1673                 ast_select(0,NULL,NULL,NULL,NULL);
1674         }
1675         return 0;
1676 }