2 * Asterisk -- A telephony toolkit for Linux.
4 * Top level source file for asterisk
6 * Copyright (C) 1999, Mark Spencer
8 * Mark Spencer <markster@linux-support.net>
10 * This program is free software, distributed under the terms of
11 * the GNU General Public License
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 <sys/resource.h>
34 #include <asterisk/io.h>
36 #include <sys/socket.h>
38 #include <sys/select.h>
42 #include "editline/histedit.h"
44 #include <asterisk/config.h>
46 #define AST_MAX_CONNECTS 128
54 int option_highpriority=0;
57 int option_initcrypto=0;
59 int option_dumpcore = 0;
60 int option_overrideconfig = 0;
63 static int ast_socket = -1; /* UNIX Socket for allowing remote control */
64 static int ast_consock = -1; /* UNIX Socket for controlling another asterisk */
67 int fd; /* File descriptor */
69 pthread_t t; /* Thread of handler */
72 static History *el_hist = NULL;
73 static EditLine *el = NULL;
74 static char *remotehostname;
76 struct console consoles[AST_MAX_CONNECTS];
78 char defaultlanguage[MAX_LANGUAGE] = DEFAULT_LANGUAGE;
80 static int ast_el_add_history(char *);
81 static int ast_el_read_history(char *);
82 static int ast_el_write_history(char *);
84 char ast_config_AST_CONFIG_DIR[AST_CONFIG_MAX_PATH];
85 char ast_config_AST_CONFIG_FILE[AST_CONFIG_MAX_PATH];
86 char ast_config_AST_MODULE_DIR[AST_CONFIG_MAX_PATH];
87 char ast_config_AST_SPOOL_DIR[AST_CONFIG_MAX_PATH];
88 char ast_config_AST_VAR_DIR[AST_CONFIG_MAX_PATH];
89 char ast_config_AST_LOG_DIR[AST_CONFIG_MAX_PATH];
90 char ast_config_AST_AGI_DIR[AST_CONFIG_MAX_PATH];
91 char ast_config_AST_DB[AST_CONFIG_MAX_PATH];
92 char ast_config_AST_KEY_DIR[AST_CONFIG_MAX_PATH];
93 char ast_config_AST_PID[AST_CONFIG_MAX_PATH];
94 char ast_config_AST_SOCKET[AST_CONFIG_MAX_PATH];
95 char ast_config_AST_RUN_DIR[AST_CONFIG_MAX_PATH];
97 static int fdprint(int fd, char *s)
99 return write(fd, s, strlen(s) + 1);
102 static void network_verboser(char *s, int pos, int replace, int complete)
105 for (x=0;x<AST_MAX_CONNECTS; x++) {
106 if (consoles[x].fd > -1)
107 fdprint(consoles[x].p[1], s);
111 static pthread_t lthread;
113 static void *netconsole(void *vconsole)
115 struct console *con = vconsole;
122 if (gethostname(hostname, sizeof(hostname)))
123 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
124 snprintf(tmp, sizeof(tmp), "%s/%d/%s\n", hostname, mainpid, ASTERISK_VERSION);
125 fdprint(con->fd, tmp);
128 FD_SET(con->fd, &rfds);
129 FD_SET(con->p[0], &rfds);
133 res = select(max + 1, &rfds, NULL, NULL, NULL);
135 ast_log(LOG_WARNING, "select returned < 0: %s\n", strerror(errno));
138 if (FD_ISSET(con->fd, &rfds)) {
139 res = read(con->fd, tmp, sizeof(tmp));
144 ast_cli_command(con->fd, tmp);
146 if (FD_ISSET(con->p[0], &rfds)) {
147 res = read(con->p[0], tmp, sizeof(tmp));
149 ast_log(LOG_ERROR, "read returned %d\n", res);
152 res = write(con->fd, tmp, res);
157 if (option_verbose > 2)
158 ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection disconnected\n");
167 static void *listener(void *unused)
169 struct sockaddr_un sun;
175 pthread_attr_init(&attr);
176 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
181 s = accept(ast_socket, (struct sockaddr *)&sun, &len);
183 ast_log(LOG_WARNING, "Accept retured %d: %s\n", s, strerror(errno));
185 for (x=0;x<AST_MAX_CONNECTS;x++) {
186 if (consoles[x].fd < 0) {
187 if (socketpair(AF_LOCAL, SOCK_STREAM, 0, consoles[x].p)) {
188 ast_log(LOG_ERROR, "Unable to create pipe: %s\n", strerror(errno));
190 fdprint(s, "Server failed to create pipe\n");
194 flags = fcntl(consoles[x].p[1], F_GETFL);
195 fcntl(consoles[x].p[1], F_SETFL, flags | O_NONBLOCK);
197 if (pthread_create(&consoles[x].t, &attr, netconsole, &consoles[x])) {
198 ast_log(LOG_ERROR, "Unable to spawn thread to handle connection\n");
200 fdprint(s, "Server failed to spawn thread\n");
206 if (x >= AST_MAX_CONNECTS) {
207 fdprint(s, "No more connections allowed\n");
208 ast_log(LOG_WARNING, "No more connections allowed\n");
210 } else if (consoles[x].fd > -1) {
211 if (option_verbose > 2)
212 ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection\n");
219 static int ast_makesocket(void)
221 struct sockaddr_un sun;
224 for (x=0;x<AST_MAX_CONNECTS;x++)
226 unlink((char *)ast_config_AST_SOCKET);
227 ast_socket = socket(PF_LOCAL, SOCK_STREAM, 0);
228 if (ast_socket < 0) {
229 ast_log(LOG_WARNING, "Unable to create control socket: %s\n", strerror(errno));
232 memset(&sun, 0, sizeof(sun));
233 sun.sun_family = AF_LOCAL;
234 strncpy(sun.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sun.sun_path)-1);
235 res = bind(ast_socket, (struct sockaddr *)&sun, sizeof(sun));
237 ast_log(LOG_WARNING, "Unable to bind socket to %s: %s\n", (char *)ast_config_AST_SOCKET, strerror(errno));
242 res = listen(ast_socket, 2);
244 ast_log(LOG_WARNING, "Unable to listen on socket %s: %s\n", (char *)ast_config_AST_SOCKET, strerror(errno));
249 ast_register_verbose(network_verboser);
250 pthread_create(<hread, NULL, listener, NULL);
254 static int ast_tryconnect(void)
256 struct sockaddr_un sun;
258 ast_consock = socket(PF_LOCAL, SOCK_STREAM, 0);
259 if (ast_consock < 0) {
260 ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
263 memset(&sun, 0, sizeof(sun));
264 sun.sun_family = AF_LOCAL;
265 strncpy(sun.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sun.sun_path)-1);
266 res = connect(ast_consock, (struct sockaddr *)&sun, sizeof(sun));
275 static void urg_handler(int num)
277 /* Called by soft_hangup to interrupt the select, read, or other
278 system call. We don't actually need to do anything though. */
280 ast_log(LOG_DEBUG, "Urgent handler\n");
281 signal(num, urg_handler);
285 static void hup_handler(int num)
287 if (option_verbose > 1)
288 ast_verbose(VERBOSE_PREFIX_2 "Received HUP signal -- Reloading configs\n");
293 static void pipe_handler(int num)
297 static void set_title(char *text)
299 /* Set an X-term or screen title */
300 if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
301 fprintf(stdout, "\033]2;%s\007", text);
304 static void set_icon(char *text)
306 if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
307 fprintf(stdout, "\033]1;%s\007", text);
310 static int set_priority(int pri)
312 struct sched_param sched;
313 memset(&sched, 0, sizeof(sched));
314 /* We set ourselves to a high priority, that we might pre-empt everything
315 else. If your PBX has heavy activity on it, this is a good thing. */
317 sched.sched_priority = 10;
318 if (sched_setscheduler(0, SCHED_RR, &sched)) {
319 ast_log(LOG_WARNING, "Unable to set high priority\n");
323 ast_verbose("Set to realtime thread\n");
325 sched.sched_priority = 0;
326 if (sched_setscheduler(0, SCHED_OTHER, &sched)) {
327 ast_log(LOG_WARNING, "Unable to set normal priority\n");
334 static char *_argv[256];
336 static int shuttingdown = 0;
338 static void quit_handler(int num, int nice, int safeshutdown, int restart)
340 char filename[80] = "";
346 /* Begin shutdown routine, hanging up active channels */
347 ast_begin_shutdown(1);
348 if (option_verbose && option_console)
349 ast_verbose("Beginning asterisk %s....\n", restart ? "restart" : "shutdown");
353 /* Wait up to 15 seconds for all channels to go away */
356 if (!ast_active_channels())
360 /* Sleep 1/10 of a second */
365 ast_begin_shutdown(0);
366 if (option_verbose && option_console)
367 ast_verbose("Waiting for inactivity to perform %s...\n", restart ? "restart" : "halt");
369 if (!ast_active_channels())
378 if (option_verbose && option_console)
379 ast_verbose("Asterisk %s cancelled.\n", restart ? "restart" : "shutdown");
383 if (option_console || option_remote) {
385 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
386 if (strlen(filename))
387 ast_el_write_history(filename);
391 history_end(el_hist);
394 if (option_verbose && option_console)
395 ast_verbose("Asterisk %s ending (%d).\n", ast_active_channels() ? "uncleanly" : "cleanly", num);
396 else if (option_debug)
397 ast_log(LOG_DEBUG, "Asterisk ending (%d).\n", num);
398 if (ast_socket > -1) {
402 if (ast_consock > -1)
405 unlink((char *)ast_config_AST_SOCKET);
406 unlink((char *)ast_config_AST_PID);
409 if (option_verbose || option_console)
410 ast_verbose("Preparing for Asterisk restart...\n");
411 /* Mark all FD's for closing on exec */
412 for (x=3;x<32768;x++) {
413 fcntl(x, F_SETFD, FD_CLOEXEC);
415 if (option_verbose || option_console)
416 ast_verbose("Restarting Asterisk NOW...\n");
417 execvp(_argv[0], _argv);
422 static void __quit_handler(int num)
424 quit_handler(num, 0, 1, 0);
427 static pthread_t consolethread = -1;
429 static int fix_header(char *outbuf, int maxout, char **s, char *cmp)
431 if (!strncmp(*s, cmp, strlen(cmp))) {
433 term_color(outbuf, cmp, COLOR_GRAY, 0, maxout);
439 static void console_verboser(char *s, int pos, int replace, int complete)
442 /* Return to the beginning of the line */
444 fprintf(stdout, "\r");
445 if (fix_header(tmp, sizeof(tmp), &s, VERBOSE_PREFIX_4) ||
446 fix_header(tmp, sizeof(tmp), &s, VERBOSE_PREFIX_3) ||
447 fix_header(tmp, sizeof(tmp), &s, VERBOSE_PREFIX_2) ||
448 fix_header(tmp, sizeof(tmp), &s, VERBOSE_PREFIX_1))
451 fputs(s + pos,stdout);
454 /* Wake up a select()ing console */
455 if (consolethread > -1)
456 pthread_kill(consolethread, SIGURG);
459 static void consolehandler(char *s)
463 /* Called when readline data is available */
465 ast_el_add_history(s);
466 /* Give the console access to the shell */
472 system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
474 ast_cli_command(STDOUT_FILENO, s);
475 if (!strcasecmp(s, "help"))
476 fprintf(stdout, " !<command> Executes a given shell command\n");
478 fprintf(stdout, "\nUse \"quit\" to exit\n");
481 static int remoteconsolehandler(char *s)
484 /* Called when readline data is available */
486 ast_el_add_history(s);
487 /* Give the console access to the shell */
493 system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
496 if (!strcasecmp(s, "help")) {
497 fprintf(stdout, " !<command> Executes a given shell command\n");
500 if (!strcasecmp(s, "quit")) {
501 quit_handler(0, 0, 0, 0);
504 if (!strcasecmp(s, "exit")) {
505 quit_handler(0, 0, 0, 0);
509 fprintf(stdout, "\nUse \"quit\" to exit\n");
514 static char quit_help[] =
516 " Exits Asterisk.\n";
518 static char abort_halt_help[] =
519 "Usage: abort shutdown\n"
520 " Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
521 " call operations.\n";
523 static char shutdown_now_help[] =
525 " Shuts down a running Asterisk immediately, hanging up all active calls .\n";
527 static char shutdown_gracefully_help[] =
528 "Usage: stop gracefully\n"
529 " Causes Asterisk to not accept new calls, and exit when all\n"
530 " active calls have terminated normally.\n";
532 static char restart_now_help[] =
533 "Usage: restart now\n"
534 " Causes Asterisk to hangup all calls and exec() itself performing a cold.\n"
537 static char restart_gracefully_help[] =
538 "Usage: restart gracefully\n"
539 " Causes Asterisk to stop accepting new calls and exec() itself performing a cold.\n"
540 " restart when all active calls have ended.\n";
542 static char restart_when_convenient_help[] =
543 "Usage: restart when convenient\n"
544 " Causes Asterisk to perform a cold restart when all active calls have ended.\n";
546 static int handle_quit(int fd, int argc, char *argv[])
549 return RESULT_SHOWUSAGE;
550 quit_handler(0, 0, 1, 0);
551 return RESULT_SUCCESS;
554 static int no_more_quit(int fd, int argc, char *argv[])
557 return RESULT_SHOWUSAGE;
558 ast_cli(fd, "The QUIT and EXIT commands may no longer be used to shutdown the PBX.\n"
559 "Please use STOP NOW instead, if you wish to shutdown the PBX.\n");
560 return RESULT_SUCCESS;
563 static int handle_shutdown_now(int fd, int argc, char *argv[])
566 return RESULT_SHOWUSAGE;
567 quit_handler(0, 0 /* Not nice */, 1 /* safely */, 0 /* not restart */);
568 return RESULT_SUCCESS;
571 static int handle_shutdown_gracefully(int fd, int argc, char *argv[])
574 return RESULT_SHOWUSAGE;
575 quit_handler(0, 1 /* nicely */, 1 /* safely */, 0 /* no restart */);
576 return RESULT_SUCCESS;
579 static int handle_restart_now(int fd, int argc, char *argv[])
582 return RESULT_SHOWUSAGE;
583 quit_handler(0, 0 /* not nicely */, 1 /* safely */, 1 /* restart */);
584 return RESULT_SUCCESS;
587 static int handle_restart_gracefully(int fd, int argc, char *argv[])
590 return RESULT_SHOWUSAGE;
591 quit_handler(0, 1 /* nicely */, 1 /* safely */, 1 /* restart */);
592 return RESULT_SUCCESS;
595 static int handle_restart_when_convenient(int fd, int argc, char *argv[])
598 return RESULT_SHOWUSAGE;
599 quit_handler(0, 2 /* really nicely */, 1 /* safely */, 1 /* restart */);
600 return RESULT_SUCCESS;
603 static int handle_abort_halt(int fd, int argc, char *argv[])
606 return RESULT_SHOWUSAGE;
607 ast_cancel_shutdown();
609 return RESULT_SUCCESS;
612 #define ASTERISK_PROMPT "*CLI> "
614 #define ASTERISK_PROMPT2 "%s*CLI> "
616 static struct ast_cli_entry aborthalt = { { "abort", "halt", NULL }, handle_abort_halt, "Cancel a running halt", abort_halt_help };
618 static struct ast_cli_entry quit = { { "quit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
619 static struct ast_cli_entry astexit = { { "exit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
621 static struct ast_cli_entry astshutdownnow = { { "stop", "now", NULL }, handle_shutdown_now, "Shut down Asterisk imediately", shutdown_now_help };
622 static struct ast_cli_entry astshutdowngracefully = { { "stop", "gracefully", NULL }, handle_shutdown_gracefully, "Gracefully shut down Asterisk", shutdown_gracefully_help };
623 static struct ast_cli_entry astrestartnow = { { "restart", "now", NULL }, handle_restart_now, "Restart Asterisk immediately", restart_now_help };
624 static struct ast_cli_entry astrestartgracefully = { { "restart", "gracefully", NULL }, handle_restart_gracefully, "Restart Asterisk gracefully", restart_gracefully_help };
625 static struct ast_cli_entry astrestartwhenconvenient= { { "restart", "when", "convenient", NULL }, handle_restart_when_convenient, "Restart Asterisk at empty call volume", restart_when_convenient_help };
627 static int ast_el_read_char(EditLine *el, char *cp)
638 FD_SET(ast_consock, &rfds);
639 FD_SET(STDIN_FILENO, &rfds);
641 if (STDIN_FILENO > max)
643 res = select(max+1, &rfds, NULL, NULL, NULL);
647 ast_log(LOG_ERROR, "select failed: %s\n", strerror(errno));
651 if (FD_ISSET(STDIN_FILENO, &rfds)) {
652 num_read = read(STDIN_FILENO, cp, 1);
658 if (FD_ISSET(ast_consock, &rfds)) {
659 res = read(ast_consock, buf, sizeof(buf) - 1);
660 /* if the remote side disappears exit */
662 fprintf(stderr, "\nDisconnected from Asterisk server\n");
663 quit_handler(0, 0, 0, 0);
669 write(STDOUT_FILENO, "\r", 1);
670 write(STDOUT_FILENO, buf, res);
671 if ((buf[res-1] == '\n') || (buf[res-2] == '\n')) {
683 static char *cli_prompt(EditLine *el)
688 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT2, remotehostname);
690 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT);
692 return strdup(prompt);
695 static char **ast_el_strtoarr(char *buf)
697 char **match_list = NULL, *retstr;
698 size_t match_list_len;
702 while ( (retstr = strsep(&buf, " ")) != NULL) {
704 if (matches + 1 >= match_list_len) {
705 match_list_len <<= 1;
706 match_list = realloc(match_list, match_list_len * sizeof(char *));
709 match_list[matches++] = retstr;
713 return (char **) NULL;
715 if (matches>= match_list_len)
716 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
718 match_list[matches] = (char *) NULL;
723 static int ast_el_sort_compare(const void *i1, const void *i2)
727 s1 = ((char **)i1)[0];
728 s2 = ((char **)i2)[0];
730 return strcasecmp(s1, s2);
733 static int ast_cli_display_match_list(char **matches, int len, int max)
735 int i, idx, limit, count;
737 int numoutput = 0, numoutputline = 0;
739 screenwidth = ast_get_termcols(STDOUT_FILENO);
741 /* find out how many entries can be put on one line, with two spaces between strings */
742 limit = screenwidth / (max + 2);
746 /* how many lines of output */
748 if (count * limit < len)
753 qsort(&matches[0], (size_t)(len + 1), sizeof(char *), ast_el_sort_compare);
755 for (; count > 0; count--) {
757 for (i=0; i < limit && matches[idx]; i++, idx++) {
759 /* Don't print dupes */
760 if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
765 numoutput++; numoutputline++;
766 fprintf(stdout, "%-*s ", max, matches[idx]);
768 if (numoutputline > 0)
769 fprintf(stdout, "\n");
776 static char *cli_complete(EditLine *el, int ch)
782 int retval = CC_ERROR;
786 LineInfo *lf = (LineInfo *)el_line(el);
789 ptr = (char *)lf->cursor-1;
791 while (ptr > lf->buffer) {
800 len = lf->cursor - ptr;
803 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr);
804 fdprint(ast_consock, buf);
805 res = read(ast_consock, buf, sizeof(buf));
807 nummatches = atoi(buf);
809 if (nummatches > 0) {
810 snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr);
811 fdprint(ast_consock, buf);
812 res = read(ast_consock, buf, sizeof(buf));
815 matches = ast_el_strtoarr(buf);
817 matches = (char **) NULL;
822 nummatches = ast_cli_generatornummatches((char *)lf->buffer,ptr);
823 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
828 int matches_num, maxlen, match_len;
830 if (matches[0][0] != '\0') {
831 el_deletestr(el, (int) len);
832 el_insertstr(el, matches[0]);
836 if (nummatches == 1) {
837 /* Found an exact match */
838 el_insertstr(el, strdup(" "));
841 /* Must be more than one match */
842 for (i=1, maxlen=0; matches[i]; i++) {
843 match_len = strlen(matches[i]);
844 if (match_len > maxlen)
848 if (matches_num >1) {
849 fprintf(stdout, "\n");
850 ast_cli_display_match_list(matches, nummatches, maxlen);
851 retval = CC_REDISPLAY;
853 el_insertstr(el,strdup(" "));
860 return (char *)retval;
863 static int ast_el_initialize(void)
870 history_end(el_hist);
872 el = el_init("asterisk", stdin, stdout, stderr);
873 el_set(el, EL_PROMPT, cli_prompt);
875 el_set(el, EL_EDITMODE, 1);
876 el_set(el, EL_EDITOR, "emacs");
877 el_hist = history_init();
881 /* setup history with 100 entries */
882 history(el_hist, &ev, H_SETSIZE, 100);
884 el_set(el, EL_HIST, history, el_hist);
886 el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
887 /* Bind <tab> to command completion */
888 el_set(el, EL_BIND, "^I", "ed-complete", NULL);
889 /* Bind ? to command completion */
890 el_set(el, EL_BIND, "?", "ed-complete", NULL);
895 static int ast_el_add_history(char *buf)
899 if (el_hist == NULL || el == NULL)
902 return (history(el_hist, &ev, H_ENTER, buf));
905 static int ast_el_write_history(char *filename)
909 if (el_hist == NULL || el == NULL)
912 return (history(el_hist, &ev, H_SAVE, filename));
915 static int ast_el_read_history(char *filename)
921 if (el_hist == NULL || el == NULL)
924 if ((f = fopen(filename, "r")) == NULL)
928 fgets(buf, sizeof(buf), f);
929 if (!strcmp(buf, "_HiStOrY_V2_\n"))
931 if ((ret = ast_el_add_history(buf)) == -1)
939 static void ast_remotecontrol(char * data)
943 char filename[80] = "";
954 read(ast_consock, buf, sizeof(buf));
956 write(ast_consock, data, strlen(data) + 1);
958 hostname = strsep(&stringp, "/");
959 cpid = strsep(&stringp, "/");
960 version = strsep(&stringp, "/");
962 version = "<Version Unknown>";
964 strsep(&stringp, ".");
969 snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
970 fdprint(ast_consock, tmp);
971 ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
972 remotehostname = hostname;
974 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
975 if (el_hist == NULL || el == NULL)
978 el_set(el, EL_GETCFN, ast_el_read_char);
980 if (strlen(filename))
981 ast_el_read_history(filename);
983 ast_cli_register(&quit);
984 ast_cli_register(&astexit);
986 ast_cli_register(&astshutdown);
989 ebuf = (char *)el_gets(el, &num);
991 if (data) /* hack to print output then exit if asterisk -rx is used */
992 ebuf = strdup("quit");
994 if (ebuf && strlen(ebuf)) {
995 if (ebuf[strlen(ebuf)-1] == '\n')
996 ebuf[strlen(ebuf)-1] = '\0';
997 if (!remoteconsolehandler(ebuf)) {
998 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
1000 ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
1006 printf("\nDisconnected from Asterisk server\n");
1009 static int show_cli_help(void) {
1010 printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 2000-2002, Digium.\n");
1011 printf("Usage: asterisk [OPTIONS]\n");
1012 printf("Valid Options:\n");
1013 printf(" -h This help screen\n");
1014 printf(" -r Connect to Asterisk on this machine\n");
1015 printf(" -f Do not fork\n");
1016 printf(" -n Disable console colorization\n");
1017 printf(" -p Run as pseudo-realtime thread\n");
1018 printf(" -v Increase verbosity (multiple v's = more verbose)\n");
1019 printf(" -q Quiet mode (supress output)\n");
1020 printf(" -g Dump core in case of a crash\n");
1021 printf(" -x <cmd> Execute command <cmd> (only valid with -r)\n");
1022 printf(" -i Initializie crypto keys at startup\n");
1023 printf(" -c Provide console CLI\n");
1024 printf(" -d Enable extra debugging\n");
1029 static void ast_readconfig() {
1030 struct ast_config *cfg;
1031 struct ast_variable *v;
1032 char *config = ASTCONFPATH;
1034 if (option_overrideconfig == 1) {
1035 cfg = ast_load((char *)ast_config_AST_CONFIG_FILE);
1037 cfg = ast_load(config);
1040 /* init with buildtime config */
1041 strncpy((char *)ast_config_AST_CONFIG_DIR,AST_CONFIG_DIR,sizeof(ast_config_AST_CONFIG_DIR)-1);
1042 strncpy((char *)ast_config_AST_SPOOL_DIR,AST_SPOOL_DIR,sizeof(ast_config_AST_SPOOL_DIR)-1);
1043 strncpy((char *)ast_config_AST_MODULE_DIR,AST_MODULE_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1044 strncpy((char *)ast_config_AST_VAR_DIR,AST_VAR_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1045 strncpy((char *)ast_config_AST_LOG_DIR,AST_LOG_DIR,sizeof(ast_config_AST_LOG_DIR)-1);
1046 strncpy((char *)ast_config_AST_AGI_DIR,AST_AGI_DIR,sizeof(ast_config_AST_AGI_DIR)-1);
1047 strncpy((char *)ast_config_AST_DB,AST_DB,sizeof(ast_config_AST_DB)-1);
1048 strncpy((char *)ast_config_AST_KEY_DIR,AST_KEY_DIR,sizeof(ast_config_AST_KEY_DIR)-1);
1049 strncpy((char *)ast_config_AST_PID,AST_PID,sizeof(ast_config_AST_PID)-1);
1050 strncpy((char *)ast_config_AST_SOCKET,AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1);
1051 strncpy((char *)ast_config_AST_RUN_DIR,AST_RUN_DIR,sizeof(ast_config_AST_RUN_DIR)-1);
1053 /* no asterisk.conf? no problem, use buildtime config! */
1057 v = ast_variable_browse(cfg, "directories");
1059 if (!strcasecmp(v->name, "astetcdir")) {
1060 strncpy((char *)ast_config_AST_CONFIG_DIR,v->value,sizeof(ast_config_AST_CONFIG_DIR)-1);
1061 } else if (!strcasecmp(v->name, "astspooldir")) {
1062 strncpy((char *)ast_config_AST_SPOOL_DIR,v->value,sizeof(ast_config_AST_SPOOL_DIR)-1);
1063 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1064 strncpy((char *)ast_config_AST_VAR_DIR,v->value,sizeof(ast_config_AST_VAR_DIR)-1);
1065 snprintf((char *)ast_config_AST_DB,sizeof(ast_config_AST_DB)-1,"%s/%s",v->value,"astdb");
1066 } else if (!strcasecmp(v->name, "astlogdir")) {
1067 strncpy((char *)ast_config_AST_LOG_DIR,v->value,sizeof(ast_config_AST_LOG_DIR)-1);
1068 } else if (!strcasecmp(v->name, "astagidir")) {
1069 strncpy((char *)ast_config_AST_AGI_DIR,v->value,sizeof(ast_config_AST_AGI_DIR)-1);
1070 } else if (!strcasecmp(v->name, "astrundir")) {
1071 snprintf((char *)ast_config_AST_PID,sizeof(ast_config_AST_PID)-1,"%s/%s",v->value,"asterisk.pid");
1072 snprintf((char *)ast_config_AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1,"%s/%s",v->value,"asterisk.ctl");
1073 strncpy((char *)ast_config_AST_RUN_DIR,v->value,sizeof(ast_config_AST_RUN_DIR)-1);
1074 } else if (!strcasecmp(v->name, "astmoddir")) {
1075 strncpy((char *)ast_config_AST_MODULE_DIR,v->value,sizeof(ast_config_AST_MODULE_DIR)-1);
1082 int main(int argc, char *argv[])
1085 char filename[80] = "";
1095 /* Remember original args for restart */
1096 if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1097 fprintf(stderr, "Truncating argument size to %d\n", sizeof(_argv) / sizeof(_argv[0]) - 1);
1098 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1100 for (x=0;x<argc;x++)
1104 if (gethostname(hostname, sizeof(hostname)))
1105 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
1112 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1113 /* Check if we're root */
1116 ast_log(LOG_ERROR, "Must be run as root\n");
1120 /* Check for options */
1121 while((c=getopt(argc, argv, "hfdvqprgcinx:C:")) != EOF) {
1142 option_highpriority++;
1156 strncpy((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE));
1157 option_overrideconfig++;
1160 option_initcrypto++;
1173 if (option_dumpcore) {
1175 memset(&l, 0, sizeof(l));
1176 l.rlim_cur = RLIM_INFINITY;
1177 l.rlim_max = RLIM_INFINITY;
1178 if (setrlimit(RLIMIT_CORE, &l)) {
1179 ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
1186 if (option_console && !option_verbose)
1187 ast_verbose("[ Reading Master Configuration ]");
1190 if (el_hist == NULL || el == NULL)
1191 ast_el_initialize();
1193 if (strlen(filename))
1194 ast_el_read_history(filename);
1196 if (ast_tryconnect()) {
1197 /* One is already running */
1198 if (option_remote) {
1200 ast_remotecontrol(xarg);
1201 quit_handler(0, 0, 0, 0);
1204 printf(term_quit());
1205 ast_register_verbose(console_verboser);
1206 ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2001 Linux Support Services, Inc.\n");
1207 ast_verbose( "Written by Mark Spencer <markster@linux-support.net>\n");
1208 ast_verbose( "=========================================================================\n");
1209 ast_remotecontrol(NULL);
1210 quit_handler(0, 0, 0, 0);
1213 ast_log(LOG_ERROR, "Asterisk already running on %s. Use 'asterisk -r' to connect.\n", (char *)ast_config_AST_SOCKET);
1214 printf(term_quit());
1217 } else if (option_remote || option_exec) {
1218 ast_log(LOG_ERROR, "Unable to connect to remote asterisk\n");
1219 printf(term_quit());
1222 /* Blindly write pid file since we couldn't connect */
1223 unlink((char *)ast_config_AST_PID);
1224 f = fopen((char *)ast_config_AST_PID, "w");
1226 fprintf(f, "%d\n", getpid());
1229 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1231 if (!option_verbose && !option_debug && !option_nofork && !option_console) {
1237 ast_log(LOG_ERROR, "Unable to fork(): %s\n", strerror(errno));
1238 printf(term_quit());
1248 sigaddset(&sigs, SIGHUP);
1249 sigaddset(&sigs, SIGTERM);
1250 sigaddset(&sigs, SIGINT);
1251 sigaddset(&sigs, SIGPIPE);
1252 sigaddset(&sigs, SIGWINCH);
1253 pthread_sigmask(SIG_BLOCK, &sigs, NULL);
1254 if (option_console || option_verbose || option_remote)
1255 ast_register_verbose(console_verboser);
1256 /* Print a welcome message if desired */
1257 if (option_verbose || option_console) {
1258 ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2001 Linux Support Services, Inc.\n");
1259 ast_verbose( "Written by Mark Spencer <markster@linux-support.net>\n");
1260 ast_verbose( "=========================================================================\n");
1262 if (option_console && !option_verbose)
1263 ast_verbose("[ Booting...");
1264 signal(SIGURG, urg_handler);
1265 signal(SIGINT, __quit_handler);
1266 signal(SIGTERM, __quit_handler);
1267 signal(SIGHUP, hup_handler);
1268 signal(SIGPIPE, pipe_handler);
1269 if (set_priority(option_highpriority)) {
1270 printf(term_quit());
1273 if (init_logger()) {
1274 printf(term_quit());
1277 if (init_manager()) {
1278 printf(term_quit());
1281 if (ast_image_init()) {
1282 printf(term_quit());
1286 printf(term_quit());
1289 if (load_modules()) {
1290 printf(term_quit());
1293 if (init_framer()) {
1294 printf(term_quit());
1298 printf(term_quit());
1301 /* We might have the option of showing a console, but for now just
1303 if (option_console && !option_verbose)
1304 ast_verbose(" ]\n");
1305 if (option_verbose || option_console)
1306 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
1308 pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
1309 ast_cli_register(&astshutdownnow);
1310 ast_cli_register(&astshutdowngracefully);
1311 ast_cli_register(&astrestartnow);
1312 ast_cli_register(&astrestartgracefully);
1313 ast_cli_register(&astrestartwhenconvenient);
1314 ast_cli_register(&aborthalt);
1315 if (option_console) {
1316 /* Console stuff now... */
1317 /* Register our quit function */
1319 set_icon("Asterisk");
1320 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, mainpid);
1322 ast_cli_register(&quit);
1323 ast_cli_register(&astexit);
1324 consolethread = pthread_self();
1326 while ( (buf = (char *)el_gets(el, &num) ) != NULL && num != 0) {
1328 if (buf[strlen(buf)-1] == '\n')
1329 buf[strlen(buf)-1] = '\0';
1331 consolehandler((char *)buf);
1336 select(0,NULL,NULL,NULL,NULL);