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 manager_event(EVENT_FLAG_SYSTEM, "Shutdown", "Shutdown: %s\r\nRestart: %s\r\n", ast_active_channels() ? "Uncleanly" : "Cleanly", restart ? "True" : "False");
399 if (ast_socket > -1) {
403 if (ast_consock > -1)
406 unlink((char *)ast_config_AST_SOCKET);
407 unlink((char *)ast_config_AST_PID);
410 if (option_verbose || option_console)
411 ast_verbose("Preparing for Asterisk restart...\n");
412 /* Mark all FD's for closing on exec */
413 for (x=3;x<32768;x++) {
414 fcntl(x, F_SETFD, FD_CLOEXEC);
416 if (option_verbose || option_console)
417 ast_verbose("Restarting Asterisk NOW...\n");
418 execvp(_argv[0], _argv);
423 static void __quit_handler(int num)
425 quit_handler(num, 0, 1, 0);
428 static pthread_t consolethread = -1;
430 static int fix_header(char *outbuf, int maxout, char **s, char *cmp)
432 if (!strncmp(*s, cmp, strlen(cmp))) {
434 term_color(outbuf, cmp, COLOR_GRAY, 0, maxout);
440 static void console_verboser(char *s, int pos, int replace, int complete)
443 /* Return to the beginning of the line */
445 fprintf(stdout, "\r");
446 if (fix_header(tmp, sizeof(tmp), &s, VERBOSE_PREFIX_4) ||
447 fix_header(tmp, sizeof(tmp), &s, VERBOSE_PREFIX_3) ||
448 fix_header(tmp, sizeof(tmp), &s, VERBOSE_PREFIX_2) ||
449 fix_header(tmp, sizeof(tmp), &s, VERBOSE_PREFIX_1))
452 fputs(s + pos,stdout);
455 /* Wake up a select()ing console */
456 if (consolethread > -1)
457 pthread_kill(consolethread, SIGURG);
460 static void consolehandler(char *s)
464 /* Called when readline data is available */
466 ast_el_add_history(s);
467 /* Give the console access to the shell */
473 system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
475 ast_cli_command(STDOUT_FILENO, s);
476 if (!strcasecmp(s, "help"))
477 fprintf(stdout, " !<command> Executes a given shell command\n");
479 fprintf(stdout, "\nUse \"quit\" to exit\n");
482 static int remoteconsolehandler(char *s)
485 /* Called when readline data is available */
487 ast_el_add_history(s);
488 /* Give the console access to the shell */
494 system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
497 if (!strcasecmp(s, "help")) {
498 fprintf(stdout, " !<command> Executes a given shell command\n");
501 if (!strcasecmp(s, "quit")) {
502 quit_handler(0, 0, 0, 0);
505 if (!strcasecmp(s, "exit")) {
506 quit_handler(0, 0, 0, 0);
510 fprintf(stdout, "\nUse \"quit\" to exit\n");
515 static char quit_help[] =
517 " Exits Asterisk.\n";
519 static char abort_halt_help[] =
520 "Usage: abort shutdown\n"
521 " Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
522 " call operations.\n";
524 static char shutdown_now_help[] =
526 " Shuts down a running Asterisk immediately, hanging up all active calls .\n";
528 static char shutdown_gracefully_help[] =
529 "Usage: stop gracefully\n"
530 " Causes Asterisk to not accept new calls, and exit when all\n"
531 " active calls have terminated normally.\n";
533 static char restart_now_help[] =
534 "Usage: restart now\n"
535 " Causes Asterisk to hangup all calls and exec() itself performing a cold.\n"
538 static char restart_gracefully_help[] =
539 "Usage: restart gracefully\n"
540 " Causes Asterisk to stop accepting new calls and exec() itself performing a cold.\n"
541 " restart when all active calls have ended.\n";
543 static char restart_when_convenient_help[] =
544 "Usage: restart when convenient\n"
545 " Causes Asterisk to perform a cold restart when all active calls have ended.\n";
547 static int handle_quit(int fd, int argc, char *argv[])
550 return RESULT_SHOWUSAGE;
551 quit_handler(0, 0, 1, 0);
552 return RESULT_SUCCESS;
555 static int no_more_quit(int fd, int argc, char *argv[])
558 return RESULT_SHOWUSAGE;
559 ast_cli(fd, "The QUIT and EXIT commands may no longer be used to shutdown the PBX.\n"
560 "Please use STOP NOW instead, if you wish to shutdown the PBX.\n");
561 return RESULT_SUCCESS;
564 static int handle_shutdown_now(int fd, int argc, char *argv[])
567 return RESULT_SHOWUSAGE;
568 quit_handler(0, 0 /* Not nice */, 1 /* safely */, 0 /* not restart */);
569 return RESULT_SUCCESS;
572 static int handle_shutdown_gracefully(int fd, int argc, char *argv[])
575 return RESULT_SHOWUSAGE;
576 quit_handler(0, 1 /* nicely */, 1 /* safely */, 0 /* no restart */);
577 return RESULT_SUCCESS;
580 static int handle_restart_now(int fd, int argc, char *argv[])
583 return RESULT_SHOWUSAGE;
584 quit_handler(0, 0 /* not nicely */, 1 /* safely */, 1 /* restart */);
585 return RESULT_SUCCESS;
588 static int handle_restart_gracefully(int fd, int argc, char *argv[])
591 return RESULT_SHOWUSAGE;
592 quit_handler(0, 1 /* nicely */, 1 /* safely */, 1 /* restart */);
593 return RESULT_SUCCESS;
596 static int handle_restart_when_convenient(int fd, int argc, char *argv[])
599 return RESULT_SHOWUSAGE;
600 quit_handler(0, 2 /* really nicely */, 1 /* safely */, 1 /* restart */);
601 return RESULT_SUCCESS;
604 static int handle_abort_halt(int fd, int argc, char *argv[])
607 return RESULT_SHOWUSAGE;
608 ast_cancel_shutdown();
610 return RESULT_SUCCESS;
613 #define ASTERISK_PROMPT "*CLI> "
615 #define ASTERISK_PROMPT2 "%s*CLI> "
617 static struct ast_cli_entry aborthalt = { { "abort", "halt", NULL }, handle_abort_halt, "Cancel a running halt", abort_halt_help };
619 static struct ast_cli_entry quit = { { "quit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
620 static struct ast_cli_entry astexit = { { "exit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
622 static struct ast_cli_entry astshutdownnow = { { "stop", "now", NULL }, handle_shutdown_now, "Shut down Asterisk imediately", shutdown_now_help };
623 static struct ast_cli_entry astshutdowngracefully = { { "stop", "gracefully", NULL }, handle_shutdown_gracefully, "Gracefully shut down Asterisk", shutdown_gracefully_help };
624 static struct ast_cli_entry astrestartnow = { { "restart", "now", NULL }, handle_restart_now, "Restart Asterisk immediately", restart_now_help };
625 static struct ast_cli_entry astrestartgracefully = { { "restart", "gracefully", NULL }, handle_restart_gracefully, "Restart Asterisk gracefully", restart_gracefully_help };
626 static struct ast_cli_entry astrestartwhenconvenient= { { "restart", "when", "convenient", NULL }, handle_restart_when_convenient, "Restart Asterisk at empty call volume", restart_when_convenient_help };
628 static int ast_el_read_char(EditLine *el, char *cp)
639 FD_SET(ast_consock, &rfds);
640 FD_SET(STDIN_FILENO, &rfds);
642 if (STDIN_FILENO > max)
644 res = select(max+1, &rfds, NULL, NULL, NULL);
648 ast_log(LOG_ERROR, "select failed: %s\n", strerror(errno));
652 if (FD_ISSET(STDIN_FILENO, &rfds)) {
653 num_read = read(STDIN_FILENO, cp, 1);
659 if (FD_ISSET(ast_consock, &rfds)) {
660 res = read(ast_consock, buf, sizeof(buf) - 1);
661 /* if the remote side disappears exit */
663 fprintf(stderr, "\nDisconnected from Asterisk server\n");
664 quit_handler(0, 0, 0, 0);
670 write(STDOUT_FILENO, "\r", 1);
671 write(STDOUT_FILENO, buf, res);
672 if ((buf[res-1] == '\n') || (buf[res-2] == '\n')) {
684 static char *cli_prompt(EditLine *el)
689 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT2, remotehostname);
691 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT);
693 return strdup(prompt);
696 static char **ast_el_strtoarr(char *buf)
698 char **match_list = NULL, *retstr;
699 size_t match_list_len;
703 while ( (retstr = strsep(&buf, " ")) != NULL) {
705 if (matches + 1 >= match_list_len) {
706 match_list_len <<= 1;
707 match_list = realloc(match_list, match_list_len * sizeof(char *));
710 match_list[matches++] = retstr;
714 return (char **) NULL;
716 if (matches>= match_list_len)
717 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
719 match_list[matches] = (char *) NULL;
724 static int ast_el_sort_compare(const void *i1, const void *i2)
728 s1 = ((char **)i1)[0];
729 s2 = ((char **)i2)[0];
731 return strcasecmp(s1, s2);
734 static int ast_cli_display_match_list(char **matches, int len, int max)
736 int i, idx, limit, count;
738 int numoutput = 0, numoutputline = 0;
740 screenwidth = ast_get_termcols(STDOUT_FILENO);
742 /* find out how many entries can be put on one line, with two spaces between strings */
743 limit = screenwidth / (max + 2);
747 /* how many lines of output */
749 if (count * limit < len)
754 qsort(&matches[0], (size_t)(len + 1), sizeof(char *), ast_el_sort_compare);
756 for (; count > 0; count--) {
758 for (i=0; i < limit && matches[idx]; i++, idx++) {
760 /* Don't print dupes */
761 if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
766 numoutput++; numoutputline++;
767 fprintf(stdout, "%-*s ", max, matches[idx]);
769 if (numoutputline > 0)
770 fprintf(stdout, "\n");
777 static char *cli_complete(EditLine *el, int ch)
783 int retval = CC_ERROR;
787 LineInfo *lf = (LineInfo *)el_line(el);
790 ptr = (char *)lf->cursor;
792 while (ptr > lf->buffer) {
801 len = lf->cursor - ptr;
804 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr);
805 fdprint(ast_consock, buf);
806 res = read(ast_consock, buf, sizeof(buf));
808 nummatches = atoi(buf);
810 if (nummatches > 0) {
811 snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr);
812 fdprint(ast_consock, buf);
813 res = read(ast_consock, buf, sizeof(buf));
816 matches = ast_el_strtoarr(buf);
818 matches = (char **) NULL;
823 nummatches = ast_cli_generatornummatches((char *)lf->buffer,ptr);
824 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
829 int matches_num, maxlen, match_len;
831 if (matches[0][0] != '\0') {
832 el_deletestr(el, (int) len);
833 el_insertstr(el, matches[0]);
837 if (nummatches == 1) {
838 /* Found an exact match */
839 el_insertstr(el, strdup(" "));
842 /* Must be more than one match */
843 for (i=1, maxlen=0; matches[i]; i++) {
844 match_len = strlen(matches[i]);
845 if (match_len > maxlen)
849 if (matches_num >1) {
850 fprintf(stdout, "\n");
851 ast_cli_display_match_list(matches, nummatches, maxlen);
852 retval = CC_REDISPLAY;
854 el_insertstr(el,strdup(" "));
861 return (char *)retval;
864 static int ast_el_initialize(void)
871 history_end(el_hist);
873 el = el_init("asterisk", stdin, stdout, stderr);
874 el_set(el, EL_PROMPT, cli_prompt);
876 el_set(el, EL_EDITMODE, 1);
877 el_set(el, EL_EDITOR, "emacs");
878 el_hist = history_init();
882 /* setup history with 100 entries */
883 history(el_hist, &ev, H_SETSIZE, 100);
885 el_set(el, EL_HIST, history, el_hist);
887 el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
888 /* Bind <tab> to command completion */
889 el_set(el, EL_BIND, "^I", "ed-complete", NULL);
890 /* Bind ? to command completion */
891 el_set(el, EL_BIND, "?", "ed-complete", NULL);
896 static int ast_el_add_history(char *buf)
900 if (el_hist == NULL || el == NULL)
903 return (history(el_hist, &ev, H_ENTER, buf));
906 static int ast_el_write_history(char *filename)
910 if (el_hist == NULL || el == NULL)
913 return (history(el_hist, &ev, H_SAVE, filename));
916 static int ast_el_read_history(char *filename)
922 if (el_hist == NULL || el == NULL)
925 if ((f = fopen(filename, "r")) == NULL)
929 fgets(buf, sizeof(buf), f);
930 if (!strcmp(buf, "_HiStOrY_V2_\n"))
932 if ((ret = ast_el_add_history(buf)) == -1)
940 static void ast_remotecontrol(char * data)
944 char filename[80] = "";
955 read(ast_consock, buf, sizeof(buf));
957 write(ast_consock, data, strlen(data) + 1);
959 hostname = strsep(&stringp, "/");
960 cpid = strsep(&stringp, "/");
961 version = strsep(&stringp, "/");
963 version = "<Version Unknown>";
965 strsep(&stringp, ".");
970 snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
971 fdprint(ast_consock, tmp);
972 ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
973 remotehostname = hostname;
975 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
976 if (el_hist == NULL || el == NULL)
979 el_set(el, EL_GETCFN, ast_el_read_char);
981 if (strlen(filename))
982 ast_el_read_history(filename);
984 ast_cli_register(&quit);
985 ast_cli_register(&astexit);
987 ast_cli_register(&astshutdown);
990 ebuf = (char *)el_gets(el, &num);
992 if (data) /* hack to print output then exit if asterisk -rx is used */
993 ebuf = strdup("quit");
995 if (ebuf && strlen(ebuf)) {
996 if (ebuf[strlen(ebuf)-1] == '\n')
997 ebuf[strlen(ebuf)-1] = '\0';
998 if (!remoteconsolehandler(ebuf)) {
999 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
1001 ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
1007 printf("\nDisconnected from Asterisk server\n");
1010 static int show_cli_help(void) {
1011 printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 2000-2002, Digium.\n");
1012 printf("Usage: asterisk [OPTIONS]\n");
1013 printf("Valid Options:\n");
1014 printf(" -h This help screen\n");
1015 printf(" -r Connect to Asterisk on this machine\n");
1016 printf(" -f Do not fork\n");
1017 printf(" -n Disable console colorization\n");
1018 printf(" -p Run as pseudo-realtime thread\n");
1019 printf(" -v Increase verbosity (multiple v's = more verbose)\n");
1020 printf(" -q Quiet mode (supress output)\n");
1021 printf(" -g Dump core in case of a crash\n");
1022 printf(" -x <cmd> Execute command <cmd> (only valid with -r)\n");
1023 printf(" -i Initializie crypto keys at startup\n");
1024 printf(" -c Provide console CLI\n");
1025 printf(" -d Enable extra debugging\n");
1030 static void ast_readconfig() {
1031 struct ast_config *cfg;
1032 struct ast_variable *v;
1033 char *config = ASTCONFPATH;
1035 if (option_overrideconfig == 1) {
1036 cfg = ast_load((char *)ast_config_AST_CONFIG_FILE);
1038 cfg = ast_load(config);
1041 /* init with buildtime config */
1042 strncpy((char *)ast_config_AST_CONFIG_DIR,AST_CONFIG_DIR,sizeof(ast_config_AST_CONFIG_DIR)-1);
1043 strncpy((char *)ast_config_AST_SPOOL_DIR,AST_SPOOL_DIR,sizeof(ast_config_AST_SPOOL_DIR)-1);
1044 strncpy((char *)ast_config_AST_MODULE_DIR,AST_MODULE_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1045 strncpy((char *)ast_config_AST_VAR_DIR,AST_VAR_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1046 strncpy((char *)ast_config_AST_LOG_DIR,AST_LOG_DIR,sizeof(ast_config_AST_LOG_DIR)-1);
1047 strncpy((char *)ast_config_AST_AGI_DIR,AST_AGI_DIR,sizeof(ast_config_AST_AGI_DIR)-1);
1048 strncpy((char *)ast_config_AST_DB,AST_DB,sizeof(ast_config_AST_DB)-1);
1049 strncpy((char *)ast_config_AST_KEY_DIR,AST_KEY_DIR,sizeof(ast_config_AST_KEY_DIR)-1);
1050 strncpy((char *)ast_config_AST_PID,AST_PID,sizeof(ast_config_AST_PID)-1);
1051 strncpy((char *)ast_config_AST_SOCKET,AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1);
1052 strncpy((char *)ast_config_AST_RUN_DIR,AST_RUN_DIR,sizeof(ast_config_AST_RUN_DIR)-1);
1054 /* no asterisk.conf? no problem, use buildtime config! */
1058 v = ast_variable_browse(cfg, "directories");
1060 if (!strcasecmp(v->name, "astetcdir")) {
1061 strncpy((char *)ast_config_AST_CONFIG_DIR,v->value,sizeof(ast_config_AST_CONFIG_DIR)-1);
1062 } else if (!strcasecmp(v->name, "astspooldir")) {
1063 strncpy((char *)ast_config_AST_SPOOL_DIR,v->value,sizeof(ast_config_AST_SPOOL_DIR)-1);
1064 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1065 strncpy((char *)ast_config_AST_VAR_DIR,v->value,sizeof(ast_config_AST_VAR_DIR)-1);
1066 snprintf((char *)ast_config_AST_DB,sizeof(ast_config_AST_DB)-1,"%s/%s",v->value,"astdb");
1067 } else if (!strcasecmp(v->name, "astlogdir")) {
1068 strncpy((char *)ast_config_AST_LOG_DIR,v->value,sizeof(ast_config_AST_LOG_DIR)-1);
1069 } else if (!strcasecmp(v->name, "astagidir")) {
1070 strncpy((char *)ast_config_AST_AGI_DIR,v->value,sizeof(ast_config_AST_AGI_DIR)-1);
1071 } else if (!strcasecmp(v->name, "astrundir")) {
1072 snprintf((char *)ast_config_AST_PID,sizeof(ast_config_AST_PID)-1,"%s/%s",v->value,"asterisk.pid");
1073 snprintf((char *)ast_config_AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1,"%s/%s",v->value,"asterisk.ctl");
1074 strncpy((char *)ast_config_AST_RUN_DIR,v->value,sizeof(ast_config_AST_RUN_DIR)-1);
1075 } else if (!strcasecmp(v->name, "astmoddir")) {
1076 strncpy((char *)ast_config_AST_MODULE_DIR,v->value,sizeof(ast_config_AST_MODULE_DIR)-1);
1083 int main(int argc, char *argv[])
1086 char filename[80] = "";
1096 /* Remember original args for restart */
1097 if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1098 fprintf(stderr, "Truncating argument size to %d\n", sizeof(_argv) / sizeof(_argv[0]) - 1);
1099 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1101 for (x=0;x<argc;x++)
1105 if (gethostname(hostname, sizeof(hostname)))
1106 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
1113 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1114 /* Check if we're root */
1117 ast_log(LOG_ERROR, "Must be run as root\n");
1121 /* Check for options */
1122 while((c=getopt(argc, argv, "hfdvqprgcinx:C:")) != EOF) {
1143 option_highpriority++;
1157 strncpy((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE));
1158 option_overrideconfig++;
1161 option_initcrypto++;
1174 if (option_dumpcore) {
1176 memset(&l, 0, sizeof(l));
1177 l.rlim_cur = RLIM_INFINITY;
1178 l.rlim_max = RLIM_INFINITY;
1179 if (setrlimit(RLIMIT_CORE, &l)) {
1180 ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
1187 if (option_console && !option_verbose)
1188 ast_verbose("[ Reading Master Configuration ]");
1191 if (el_hist == NULL || el == NULL)
1192 ast_el_initialize();
1194 if (strlen(filename))
1195 ast_el_read_history(filename);
1197 if (ast_tryconnect()) {
1198 /* One is already running */
1199 if (option_remote) {
1201 ast_remotecontrol(xarg);
1202 quit_handler(0, 0, 0, 0);
1205 printf(term_quit());
1206 ast_register_verbose(console_verboser);
1207 ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2001 Linux Support Services, Inc.\n");
1208 ast_verbose( "Written by Mark Spencer <markster@linux-support.net>\n");
1209 ast_verbose( "=========================================================================\n");
1210 ast_remotecontrol(NULL);
1211 quit_handler(0, 0, 0, 0);
1214 ast_log(LOG_ERROR, "Asterisk already running on %s. Use 'asterisk -r' to connect.\n", (char *)ast_config_AST_SOCKET);
1215 printf(term_quit());
1218 } else if (option_remote || option_exec) {
1219 ast_log(LOG_ERROR, "Unable to connect to remote asterisk\n");
1220 printf(term_quit());
1223 /* Blindly write pid file since we couldn't connect */
1224 unlink((char *)ast_config_AST_PID);
1225 f = fopen((char *)ast_config_AST_PID, "w");
1227 fprintf(f, "%d\n", getpid());
1230 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1232 if (!option_verbose && !option_debug && !option_nofork && !option_console) {
1238 ast_log(LOG_ERROR, "Unable to fork(): %s\n", strerror(errno));
1239 printf(term_quit());
1249 sigaddset(&sigs, SIGHUP);
1250 sigaddset(&sigs, SIGTERM);
1251 sigaddset(&sigs, SIGINT);
1252 sigaddset(&sigs, SIGPIPE);
1253 sigaddset(&sigs, SIGWINCH);
1254 pthread_sigmask(SIG_BLOCK, &sigs, NULL);
1255 if (option_console || option_verbose || option_remote)
1256 ast_register_verbose(console_verboser);
1257 /* Print a welcome message if desired */
1258 if (option_verbose || option_console) {
1259 ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2001 Linux Support Services, Inc.\n");
1260 ast_verbose( "Written by Mark Spencer <markster@linux-support.net>\n");
1261 ast_verbose( "=========================================================================\n");
1263 if (option_console && !option_verbose)
1264 ast_verbose("[ Booting...");
1265 signal(SIGURG, urg_handler);
1266 signal(SIGINT, __quit_handler);
1267 signal(SIGTERM, __quit_handler);
1268 signal(SIGHUP, hup_handler);
1269 signal(SIGPIPE, pipe_handler);
1270 if (set_priority(option_highpriority)) {
1271 printf(term_quit());
1274 if (init_logger()) {
1275 printf(term_quit());
1278 if (init_manager()) {
1279 printf(term_quit());
1282 if (ast_image_init()) {
1283 printf(term_quit());
1287 printf(term_quit());
1290 if (load_modules()) {
1291 printf(term_quit());
1294 if (init_framer()) {
1295 printf(term_quit());
1299 printf(term_quit());
1302 /* We might have the option of showing a console, but for now just
1304 if (option_console && !option_verbose)
1305 ast_verbose(" ]\n");
1306 if (option_verbose || option_console)
1307 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
1309 pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
1310 ast_cli_register(&astshutdownnow);
1311 ast_cli_register(&astshutdowngracefully);
1312 ast_cli_register(&astrestartnow);
1313 ast_cli_register(&astrestartgracefully);
1314 ast_cli_register(&astrestartwhenconvenient);
1315 ast_cli_register(&aborthalt);
1316 if (option_console) {
1317 /* Console stuff now... */
1318 /* Register our quit function */
1320 set_icon("Asterisk");
1321 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, mainpid);
1323 ast_cli_register(&quit);
1324 ast_cli_register(&astexit);
1325 consolethread = pthread_self();
1327 while ( (buf = (char *)el_gets(el, &num) ) != NULL && num != 0) {
1329 if (buf[strlen(buf)-1] == '\n')
1330 buf[strlen(buf)-1] = '\0';
1332 consolehandler((char *)buf);
1337 select(0,NULL,NULL,NULL,NULL);