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 <asterisk/enum.h>
30 #include <sys/resource.h>
35 #include <asterisk/io.h>
37 #include <sys/socket.h>
39 #include <sys/select.h>
43 #include "editline/histedit.h"
45 #include <asterisk/config.h>
47 #define AST_MAX_CONNECTS 128
55 int option_highpriority=0;
58 int option_initcrypto=0;
60 int option_dumpcore = 0;
61 int option_overrideconfig = 0;
64 static int ast_socket = -1; /* UNIX Socket for allowing remote control */
65 static int ast_consock = -1; /* UNIX Socket for controlling another asterisk */
68 int fd; /* File descriptor */
70 pthread_t t; /* Thread of handler */
73 static History *el_hist = NULL;
74 static EditLine *el = NULL;
75 static char *remotehostname;
77 struct console consoles[AST_MAX_CONNECTS];
79 char defaultlanguage[MAX_LANGUAGE] = DEFAULT_LANGUAGE;
81 static int ast_el_add_history(char *);
82 static int ast_el_read_history(char *);
83 static int ast_el_write_history(char *);
85 char ast_config_AST_CONFIG_DIR[AST_CONFIG_MAX_PATH];
86 char ast_config_AST_CONFIG_FILE[AST_CONFIG_MAX_PATH];
87 char ast_config_AST_MODULE_DIR[AST_CONFIG_MAX_PATH];
88 char ast_config_AST_SPOOL_DIR[AST_CONFIG_MAX_PATH];
89 char ast_config_AST_VAR_DIR[AST_CONFIG_MAX_PATH];
90 char ast_config_AST_LOG_DIR[AST_CONFIG_MAX_PATH];
91 char ast_config_AST_AGI_DIR[AST_CONFIG_MAX_PATH];
92 char ast_config_AST_DB[AST_CONFIG_MAX_PATH];
93 char ast_config_AST_KEY_DIR[AST_CONFIG_MAX_PATH];
94 char ast_config_AST_PID[AST_CONFIG_MAX_PATH];
95 char ast_config_AST_SOCKET[AST_CONFIG_MAX_PATH];
96 char ast_config_AST_RUN_DIR[AST_CONFIG_MAX_PATH];
98 static int fdprint(int fd, const char *s)
100 return write(fd, s, strlen(s) + 1);
103 static void network_verboser(const char *s, int pos, int replace, int complete)
106 for (x=0;x<AST_MAX_CONNECTS; x++) {
107 if (consoles[x].fd > -1)
108 fdprint(consoles[x].p[1], s);
112 static pthread_t lthread;
114 static void *netconsole(void *vconsole)
116 struct console *con = vconsole;
123 if (gethostname(hostname, sizeof(hostname)))
124 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
125 snprintf(tmp, sizeof(tmp), "%s/%d/%s\n", hostname, mainpid, ASTERISK_VERSION);
126 fdprint(con->fd, tmp);
129 FD_SET(con->fd, &rfds);
130 FD_SET(con->p[0], &rfds);
134 res = ast_select(max + 1, &rfds, NULL, NULL, NULL);
136 ast_log(LOG_WARNING, "select returned < 0: %s\n", strerror(errno));
139 if (FD_ISSET(con->fd, &rfds)) {
140 res = read(con->fd, tmp, sizeof(tmp));
145 ast_cli_command(con->fd, tmp);
147 if (FD_ISSET(con->p[0], &rfds)) {
148 res = read(con->p[0], tmp, sizeof(tmp));
150 ast_log(LOG_ERROR, "read returned %d\n", res);
153 res = write(con->fd, tmp, res);
158 if (option_verbose > 2)
159 ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection disconnected\n");
168 static void *listener(void *unused)
170 struct sockaddr_un sun;
176 pthread_attr_init(&attr);
177 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
182 s = accept(ast_socket, (struct sockaddr *)&sun, &len);
184 ast_log(LOG_WARNING, "Accept retured %d: %s\n", s, strerror(errno));
186 for (x=0;x<AST_MAX_CONNECTS;x++) {
187 if (consoles[x].fd < 0) {
188 if (socketpair(AF_LOCAL, SOCK_STREAM, 0, consoles[x].p)) {
189 ast_log(LOG_ERROR, "Unable to create pipe: %s\n", strerror(errno));
191 fdprint(s, "Server failed to create pipe\n");
195 flags = fcntl(consoles[x].p[1], F_GETFL);
196 fcntl(consoles[x].p[1], F_SETFL, flags | O_NONBLOCK);
198 if (pthread_create(&consoles[x].t, &attr, netconsole, &consoles[x])) {
199 ast_log(LOG_ERROR, "Unable to spawn thread to handle connection\n");
201 fdprint(s, "Server failed to spawn thread\n");
207 if (x >= AST_MAX_CONNECTS) {
208 fdprint(s, "No more connections allowed\n");
209 ast_log(LOG_WARNING, "No more connections allowed\n");
211 } else if (consoles[x].fd > -1) {
212 if (option_verbose > 2)
213 ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection\n");
220 static int ast_makesocket(void)
222 struct sockaddr_un sun;
225 for (x=0;x<AST_MAX_CONNECTS;x++)
227 unlink((char *)ast_config_AST_SOCKET);
228 ast_socket = socket(PF_LOCAL, SOCK_STREAM, 0);
229 if (ast_socket < 0) {
230 ast_log(LOG_WARNING, "Unable to create control socket: %s\n", strerror(errno));
233 memset(&sun, 0, sizeof(sun));
234 sun.sun_family = AF_LOCAL;
235 strncpy(sun.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sun.sun_path)-1);
236 res = bind(ast_socket, (struct sockaddr *)&sun, sizeof(sun));
238 ast_log(LOG_WARNING, "Unable to bind socket to %s: %s\n", (char *)ast_config_AST_SOCKET, strerror(errno));
243 res = listen(ast_socket, 2);
245 ast_log(LOG_WARNING, "Unable to listen on socket %s: %s\n", (char *)ast_config_AST_SOCKET, strerror(errno));
250 ast_register_verbose(network_verboser);
251 pthread_create(<hread, NULL, listener, NULL);
255 static int ast_tryconnect(void)
257 struct sockaddr_un sun;
259 ast_consock = socket(PF_LOCAL, SOCK_STREAM, 0);
260 if (ast_consock < 0) {
261 ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
264 memset(&sun, 0, sizeof(sun));
265 sun.sun_family = AF_LOCAL;
266 strncpy(sun.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sun.sun_path)-1);
267 res = connect(ast_consock, (struct sockaddr *)&sun, sizeof(sun));
276 static void urg_handler(int num)
278 /* Called by soft_hangup to interrupt the select, read, or other
279 system call. We don't actually need to do anything though. */
281 ast_log(LOG_DEBUG, "Urgent handler\n");
282 signal(num, urg_handler);
286 static void hup_handler(int num)
288 if (option_verbose > 1)
289 ast_verbose(VERBOSE_PREFIX_2 "Received HUP signal -- Reloading configs\n");
294 static void pipe_handler(int num)
298 static void set_title(char *text)
300 /* Set an X-term or screen title */
301 if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
302 fprintf(stdout, "\033]2;%s\007", text);
305 static void set_icon(char *text)
307 if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
308 fprintf(stdout, "\033]1;%s\007", text);
311 static int set_priority(int pri)
313 struct sched_param sched;
314 memset(&sched, 0, sizeof(sched));
315 /* We set ourselves to a high priority, that we might pre-empt everything
316 else. If your PBX has heavy activity on it, this is a good thing. */
319 sched.sched_priority = 10;
320 if (sched_setscheduler(0, SCHED_RR, &sched)) {
321 ast_log(LOG_WARNING, "Unable to set high priority\n");
325 ast_verbose("Set to realtime thread\n");
327 sched.sched_priority = 0;
328 if (sched_setscheduler(0, SCHED_OTHER, &sched)) {
329 ast_log(LOG_WARNING, "Unable to set normal priority\n");
335 if (setpriority(PRIO_PROCESS, 0, -10) == -1) {
336 ast_log(LOG_WARNING, "Unable to set high priority\n");
340 ast_verbose("Set to high priority\n");
342 if (setpriority(PRIO_PROCESS, 0, 0) == -1) {
343 ast_log(LOG_WARNING, "Unable to set normal priority\n");
351 static char *_argv[256];
353 static int shuttingdown = 0;
355 static void quit_handler(int num, int nice, int safeshutdown, int restart)
357 char filename[80] = "";
363 /* Begin shutdown routine, hanging up active channels */
364 ast_begin_shutdown(1);
365 if (option_verbose && option_console)
366 ast_verbose("Beginning asterisk %s....\n", restart ? "restart" : "shutdown");
370 /* Wait up to 15 seconds for all channels to go away */
373 if (!ast_active_channels())
377 /* Sleep 1/10 of a second */
382 ast_begin_shutdown(0);
383 if (option_verbose && option_console)
384 ast_verbose("Waiting for inactivity to perform %s...\n", restart ? "restart" : "halt");
386 if (!ast_active_channels())
395 if (option_verbose && option_console)
396 ast_verbose("Asterisk %s cancelled.\n", restart ? "restart" : "shutdown");
400 if (option_console || option_remote) {
402 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
403 if (strlen(filename))
404 ast_el_write_history(filename);
408 history_end(el_hist);
411 if (option_verbose && option_console)
412 ast_verbose("Asterisk %s ending (%d).\n", ast_active_channels() ? "uncleanly" : "cleanly", num);
413 else if (option_debug)
414 ast_log(LOG_DEBUG, "Asterisk ending (%d).\n", num);
415 manager_event(EVENT_FLAG_SYSTEM, "Shutdown", "Shutdown: %s\r\nRestart: %s\r\n", ast_active_channels() ? "Uncleanly" : "Cleanly", restart ? "True" : "False");
416 if (ast_socket > -1) {
420 if (ast_consock > -1)
423 unlink((char *)ast_config_AST_SOCKET);
424 unlink((char *)ast_config_AST_PID);
427 if (option_verbose || option_console)
428 ast_verbose("Preparing for Asterisk restart...\n");
429 /* Mark all FD's for closing on exec */
430 for (x=3;x<32768;x++) {
431 fcntl(x, F_SETFD, FD_CLOEXEC);
433 if (option_verbose || option_console)
434 ast_verbose("Restarting Asterisk NOW...\n");
435 execvp(_argv[0], _argv);
440 static void __quit_handler(int num)
442 quit_handler(num, 0, 1, 0);
445 static pthread_t consolethread = -1;
447 static int fix_header(char *outbuf, int maxout, char **s, char *cmp)
449 if (!strncmp(*s, cmp, strlen(cmp))) {
451 term_color(outbuf, cmp, COLOR_GRAY, 0, maxout);
457 static void console_verboser(const char *s, int pos, int replace, int complete)
460 /* Return to the beginning of the line */
462 fprintf(stdout, "\r");
463 if (fix_header(tmp, sizeof(tmp), &s, VERBOSE_PREFIX_4) ||
464 fix_header(tmp, sizeof(tmp), &s, VERBOSE_PREFIX_3) ||
465 fix_header(tmp, sizeof(tmp), &s, VERBOSE_PREFIX_2) ||
466 fix_header(tmp, sizeof(tmp), &s, VERBOSE_PREFIX_1))
469 fputs(s + pos,stdout);
472 /* Wake up a select()ing console */
473 if (consolethread > -1)
474 pthread_kill(consolethread, SIGURG);
477 static void consolehandler(char *s)
481 /* Called when readline data is available */
483 ast_el_add_history(s);
484 /* Give the console access to the shell */
490 system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
492 ast_cli_command(STDOUT_FILENO, s);
493 if (!strcasecmp(s, "help"))
494 fprintf(stdout, " !<command> Executes a given shell command\n");
496 fprintf(stdout, "\nUse \"quit\" to exit\n");
499 static int remoteconsolehandler(char *s)
502 /* Called when readline data is available */
504 ast_el_add_history(s);
505 /* Give the console access to the shell */
511 system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
514 if (!strcasecmp(s, "help")) {
515 fprintf(stdout, " !<command> Executes a given shell command\n");
518 if (!strcasecmp(s, "quit")) {
519 quit_handler(0, 0, 0, 0);
522 if (!strcasecmp(s, "exit")) {
523 quit_handler(0, 0, 0, 0);
527 fprintf(stdout, "\nUse \"quit\" to exit\n");
532 static char quit_help[] =
534 " Exits Asterisk.\n";
536 static char abort_halt_help[] =
537 "Usage: abort shutdown\n"
538 " Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
539 " call operations.\n";
541 static char shutdown_now_help[] =
543 " Shuts down a running Asterisk immediately, hanging up all active calls .\n";
545 static char shutdown_gracefully_help[] =
546 "Usage: stop gracefully\n"
547 " Causes Asterisk to not accept new calls, and exit when all\n"
548 " active calls have terminated normally.\n";
550 static char shutdown_when_convenient_help[] =
551 "Usage: stop when convenient\n"
552 " Causes Asterisk to perform a shutdown when all active calls have ended.\n";
554 static char restart_now_help[] =
555 "Usage: restart now\n"
556 " Causes Asterisk to hangup all calls and exec() itself performing a cold.\n"
559 static char restart_gracefully_help[] =
560 "Usage: restart gracefully\n"
561 " Causes Asterisk to stop accepting new calls and exec() itself performing a cold.\n"
562 " restart when all active calls have ended.\n";
564 static char restart_when_convenient_help[] =
565 "Usage: restart when convenient\n"
566 " Causes Asterisk to perform a cold restart when all active calls have ended.\n";
569 static int handle_quit(int fd, int argc, char *argv[])
572 return RESULT_SHOWUSAGE;
573 quit_handler(0, 0, 1, 0);
574 return RESULT_SUCCESS;
578 static int no_more_quit(int fd, int argc, char *argv[])
581 return RESULT_SHOWUSAGE;
582 ast_cli(fd, "The QUIT and EXIT commands may no longer be used to shutdown the PBX.\n"
583 "Please use STOP NOW instead, if you wish to shutdown the PBX.\n");
584 return RESULT_SUCCESS;
587 static int handle_shutdown_now(int fd, int argc, char *argv[])
590 return RESULT_SHOWUSAGE;
591 quit_handler(0, 0 /* Not nice */, 1 /* safely */, 0 /* not restart */);
592 return RESULT_SUCCESS;
595 static int handle_shutdown_gracefully(int fd, int argc, char *argv[])
598 return RESULT_SHOWUSAGE;
599 quit_handler(0, 1 /* nicely */, 1 /* safely */, 0 /* no restart */);
600 return RESULT_SUCCESS;
603 static int handle_shutdown_when_convenient(int fd, int argc, char *argv[])
606 return RESULT_SHOWUSAGE;
607 quit_handler(0, 2 /* really nicely */, 1 /* safely */, 0 /* don't restart */);
608 return RESULT_SUCCESS;
611 static int handle_restart_now(int fd, int argc, char *argv[])
614 return RESULT_SHOWUSAGE;
615 quit_handler(0, 0 /* not nicely */, 1 /* safely */, 1 /* restart */);
616 return RESULT_SUCCESS;
619 static int handle_restart_gracefully(int fd, int argc, char *argv[])
622 return RESULT_SHOWUSAGE;
623 quit_handler(0, 1 /* nicely */, 1 /* safely */, 1 /* restart */);
624 return RESULT_SUCCESS;
627 static int handle_restart_when_convenient(int fd, int argc, char *argv[])
630 return RESULT_SHOWUSAGE;
631 quit_handler(0, 2 /* really nicely */, 1 /* safely */, 1 /* restart */);
632 return RESULT_SUCCESS;
635 static int handle_abort_halt(int fd, int argc, char *argv[])
638 return RESULT_SHOWUSAGE;
639 ast_cancel_shutdown();
641 return RESULT_SUCCESS;
644 #define ASTERISK_PROMPT "*CLI> "
646 #define ASTERISK_PROMPT2 "%s*CLI> "
648 static struct ast_cli_entry aborthalt = { { "abort", "halt", NULL }, handle_abort_halt, "Cancel a running halt", abort_halt_help };
650 static struct ast_cli_entry quit = { { "quit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
651 static struct ast_cli_entry astexit = { { "exit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
653 static struct ast_cli_entry astshutdownnow = { { "stop", "now", NULL }, handle_shutdown_now, "Shut down Asterisk imediately", shutdown_now_help };
654 static struct ast_cli_entry astshutdowngracefully = { { "stop", "gracefully", NULL }, handle_shutdown_gracefully, "Gracefully shut down Asterisk", shutdown_gracefully_help };
655 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 };
656 static struct ast_cli_entry astrestartnow = { { "restart", "now", NULL }, handle_restart_now, "Restart Asterisk immediately", restart_now_help };
657 static struct ast_cli_entry astrestartgracefully = { { "restart", "gracefully", NULL }, handle_restart_gracefully, "Restart Asterisk gracefully", restart_gracefully_help };
658 static struct ast_cli_entry astrestartwhenconvenient= { { "restart", "when", "convenient", NULL }, handle_restart_when_convenient, "Restart Asterisk at empty call volume", restart_when_convenient_help };
660 static int ast_el_read_char(EditLine *el, char *cp)
671 FD_SET(ast_consock, &rfds);
672 FD_SET(STDIN_FILENO, &rfds);
674 if (STDIN_FILENO > max)
676 res = ast_select(max+1, &rfds, NULL, NULL, NULL);
680 ast_log(LOG_ERROR, "select failed: %s\n", strerror(errno));
684 if (FD_ISSET(STDIN_FILENO, &rfds)) {
685 num_read = read(STDIN_FILENO, cp, 1);
691 if (FD_ISSET(ast_consock, &rfds)) {
692 res = read(ast_consock, buf, sizeof(buf) - 1);
693 /* if the remote side disappears exit */
695 fprintf(stderr, "\nDisconnected from Asterisk server\n");
696 quit_handler(0, 0, 0, 0);
702 write(STDOUT_FILENO, "\r", 1);
703 write(STDOUT_FILENO, buf, res);
704 if ((buf[res-1] == '\n') || (buf[res-2] == '\n')) {
717 static char *cli_prompt(EditLine *el)
719 static char prompt[80];
722 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT2, remotehostname);
724 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT);
729 static char **ast_el_strtoarr(char *buf)
731 char **match_list = NULL, *retstr;
732 size_t match_list_len;
736 while ( (retstr = strsep(&buf, " ")) != NULL) {
738 if (matches + 1 >= match_list_len) {
739 match_list_len <<= 1;
740 match_list = realloc(match_list, match_list_len * sizeof(char *));
743 match_list[matches++] = retstr;
747 return (char **) NULL;
749 if (matches>= match_list_len)
750 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
752 match_list[matches] = (char *) NULL;
757 static int ast_el_sort_compare(const void *i1, const void *i2)
761 s1 = ((char **)i1)[0];
762 s2 = ((char **)i2)[0];
764 return strcasecmp(s1, s2);
767 static int ast_cli_display_match_list(char **matches, int len, int max)
769 int i, idx, limit, count;
771 int numoutput = 0, numoutputline = 0;
773 screenwidth = ast_get_termcols(STDOUT_FILENO);
775 /* find out how many entries can be put on one line, with two spaces between strings */
776 limit = screenwidth / (max + 2);
780 /* how many lines of output */
782 if (count * limit < len)
787 qsort(&matches[0], (size_t)(len + 1), sizeof(char *), ast_el_sort_compare);
789 for (; count > 0; count--) {
791 for (i=0; i < limit && matches[idx]; i++, idx++) {
793 /* Don't print dupes */
794 if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
799 numoutput++; numoutputline++;
800 fprintf(stdout, "%-*s ", max, matches[idx]);
802 if (numoutputline > 0)
803 fprintf(stdout, "\n");
810 static char *cli_complete(EditLine *el, int ch)
816 int retval = CC_ERROR;
820 LineInfo *lf = (LineInfo *)el_line(el);
823 ptr = (char *)lf->cursor;
825 while (ptr > lf->buffer) {
834 len = lf->cursor - ptr;
837 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr);
838 fdprint(ast_consock, buf);
839 res = read(ast_consock, buf, sizeof(buf));
841 nummatches = atoi(buf);
843 if (nummatches > 0) {
844 snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr);
845 fdprint(ast_consock, buf);
846 res = read(ast_consock, buf, sizeof(buf));
849 matches = ast_el_strtoarr(buf);
851 matches = (char **) NULL;
856 nummatches = ast_cli_generatornummatches((char *)lf->buffer,ptr);
857 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
862 int matches_num, maxlen, match_len;
864 if (matches[0][0] != '\0') {
865 el_deletestr(el, (int) len);
866 el_insertstr(el, matches[0]);
870 if (nummatches == 1) {
871 /* Found an exact match */
872 el_insertstr(el, " ");
875 /* Must be more than one match */
876 for (i=1, maxlen=0; matches[i]; i++) {
877 match_len = strlen(matches[i]);
878 if (match_len > maxlen)
882 if (matches_num >1) {
883 fprintf(stdout, "\n");
884 ast_cli_display_match_list(matches, nummatches, maxlen);
885 retval = CC_REDISPLAY;
887 el_insertstr(el," ");
894 return (char *)retval;
897 static int ast_el_initialize(void)
904 history_end(el_hist);
906 el = el_init("asterisk", stdin, stdout, stderr);
907 el_set(el, EL_PROMPT, cli_prompt);
909 el_set(el, EL_EDITMODE, 1);
910 el_set(el, EL_EDITOR, "emacs");
911 el_hist = history_init();
915 /* setup history with 100 entries */
916 history(el_hist, &ev, H_SETSIZE, 100);
918 el_set(el, EL_HIST, history, el_hist);
920 el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
921 /* Bind <tab> to command completion */
922 el_set(el, EL_BIND, "^I", "ed-complete", NULL);
923 /* Bind ? to command completion */
924 el_set(el, EL_BIND, "?", "ed-complete", NULL);
929 static int ast_el_add_history(char *buf)
933 if (el_hist == NULL || el == NULL)
936 return (history(el_hist, &ev, H_ENTER, buf));
939 static int ast_el_write_history(char *filename)
943 if (el_hist == NULL || el == NULL)
946 return (history(el_hist, &ev, H_SAVE, filename));
949 static int ast_el_read_history(char *filename)
955 if (el_hist == NULL || el == NULL)
958 if ((f = fopen(filename, "r")) == NULL)
962 fgets(buf, sizeof(buf), f);
963 if (!strcmp(buf, "_HiStOrY_V2_\n"))
965 if ((ret = ast_el_add_history(buf)) == -1)
973 static void ast_remotecontrol(char * data)
977 char filename[80] = "";
988 read(ast_consock, buf, sizeof(buf));
990 write(ast_consock, data, strlen(data) + 1);
992 hostname = strsep(&stringp, "/");
993 cpid = strsep(&stringp, "/");
994 version = strsep(&stringp, "/");
996 version = "<Version Unknown>";
998 strsep(&stringp, ".");
1003 snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
1004 fdprint(ast_consock, tmp);
1005 ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
1006 remotehostname = hostname;
1008 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1009 if (el_hist == NULL || el == NULL)
1010 ast_el_initialize();
1012 el_set(el, EL_GETCFN, ast_el_read_char);
1014 if (strlen(filename))
1015 ast_el_read_history(filename);
1017 ast_cli_register(&quit);
1018 ast_cli_register(&astexit);
1020 ast_cli_register(&astshutdown);
1023 ebuf = (char *)el_gets(el, &num);
1025 if (data) /* hack to print output then exit if asterisk -rx is used */
1026 ebuf = strdup("quit");
1028 if (ebuf && strlen(ebuf)) {
1029 if (ebuf[strlen(ebuf)-1] == '\n')
1030 ebuf[strlen(ebuf)-1] = '\0';
1031 if (!remoteconsolehandler(ebuf)) {
1032 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
1034 ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
1040 printf("\nDisconnected from Asterisk server\n");
1043 static int show_cli_help(void) {
1044 printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 2000-2002, Digium.\n");
1045 printf("Usage: asterisk [OPTIONS]\n");
1046 printf("Valid Options:\n");
1047 printf(" -h This help screen\n");
1048 printf(" -r Connect to Asterisk on this machine\n");
1049 printf(" -f Do not fork\n");
1050 printf(" -n Disable console colorization\n");
1051 printf(" -p Run as pseudo-realtime thread\n");
1052 printf(" -v Increase verbosity (multiple v's = more verbose)\n");
1053 printf(" -q Quiet mode (supress output)\n");
1054 printf(" -g Dump core in case of a crash\n");
1055 printf(" -x <cmd> Execute command <cmd> (only valid with -r)\n");
1056 printf(" -i Initializie crypto keys at startup\n");
1057 printf(" -c Provide console CLI\n");
1058 printf(" -d Enable extra debugging\n");
1063 static void ast_readconfig(void) {
1064 struct ast_config *cfg;
1065 struct ast_variable *v;
1066 char *config = ASTCONFPATH;
1068 if (option_overrideconfig == 1) {
1069 cfg = ast_load((char *)ast_config_AST_CONFIG_FILE);
1071 cfg = ast_load(config);
1074 /* init with buildtime config */
1075 strncpy((char *)ast_config_AST_CONFIG_DIR,AST_CONFIG_DIR,sizeof(ast_config_AST_CONFIG_DIR)-1);
1076 strncpy((char *)ast_config_AST_SPOOL_DIR,AST_SPOOL_DIR,sizeof(ast_config_AST_SPOOL_DIR)-1);
1077 strncpy((char *)ast_config_AST_MODULE_DIR,AST_MODULE_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1078 strncpy((char *)ast_config_AST_VAR_DIR,AST_VAR_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1079 strncpy((char *)ast_config_AST_LOG_DIR,AST_LOG_DIR,sizeof(ast_config_AST_LOG_DIR)-1);
1080 strncpy((char *)ast_config_AST_AGI_DIR,AST_AGI_DIR,sizeof(ast_config_AST_AGI_DIR)-1);
1081 strncpy((char *)ast_config_AST_DB,AST_DB,sizeof(ast_config_AST_DB)-1);
1082 strncpy((char *)ast_config_AST_KEY_DIR,AST_KEY_DIR,sizeof(ast_config_AST_KEY_DIR)-1);
1083 strncpy((char *)ast_config_AST_PID,AST_PID,sizeof(ast_config_AST_PID)-1);
1084 strncpy((char *)ast_config_AST_SOCKET,AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1);
1085 strncpy((char *)ast_config_AST_RUN_DIR,AST_RUN_DIR,sizeof(ast_config_AST_RUN_DIR)-1);
1087 /* no asterisk.conf? no problem, use buildtime config! */
1091 v = ast_variable_browse(cfg, "directories");
1093 if (!strcasecmp(v->name, "astetcdir")) {
1094 strncpy((char *)ast_config_AST_CONFIG_DIR,v->value,sizeof(ast_config_AST_CONFIG_DIR)-1);
1095 } else if (!strcasecmp(v->name, "astspooldir")) {
1096 strncpy((char *)ast_config_AST_SPOOL_DIR,v->value,sizeof(ast_config_AST_SPOOL_DIR)-1);
1097 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1098 strncpy((char *)ast_config_AST_VAR_DIR,v->value,sizeof(ast_config_AST_VAR_DIR)-1);
1099 snprintf((char *)ast_config_AST_DB,sizeof(ast_config_AST_DB)-1,"%s/%s",v->value,"astdb");
1100 } else if (!strcasecmp(v->name, "astlogdir")) {
1101 strncpy((char *)ast_config_AST_LOG_DIR,v->value,sizeof(ast_config_AST_LOG_DIR)-1);
1102 } else if (!strcasecmp(v->name, "astagidir")) {
1103 strncpy((char *)ast_config_AST_AGI_DIR,v->value,sizeof(ast_config_AST_AGI_DIR)-1);
1104 } else if (!strcasecmp(v->name, "astrundir")) {
1105 snprintf((char *)ast_config_AST_PID,sizeof(ast_config_AST_PID)-1,"%s/%s",v->value,"asterisk.pid");
1106 snprintf((char *)ast_config_AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1,"%s/%s",v->value,"asterisk.ctl");
1107 strncpy((char *)ast_config_AST_RUN_DIR,v->value,sizeof(ast_config_AST_RUN_DIR)-1);
1108 } else if (!strcasecmp(v->name, "astmoddir")) {
1109 strncpy((char *)ast_config_AST_MODULE_DIR,v->value,sizeof(ast_config_AST_MODULE_DIR)-1);
1116 int main(int argc, char *argv[])
1119 char filename[80] = "";
1129 /* Remember original args for restart */
1130 if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1131 fprintf(stderr, "Truncating argument size to %d\n", sizeof(_argv) / sizeof(_argv[0]) - 1);
1132 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1134 for (x=0;x<argc;x++)
1138 if (gethostname(hostname, sizeof(hostname)))
1139 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
1146 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1147 /* Check if we're root */
1150 ast_log(LOG_ERROR, "Must be run as root\n");
1154 /* Check for options */
1155 while((c=getopt(argc, argv, "hfdvqprgcinx:C:")) != EOF) {
1176 option_highpriority++;
1190 strncpy((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE));
1191 option_overrideconfig++;
1194 option_initcrypto++;
1207 if (option_dumpcore) {
1209 memset(&l, 0, sizeof(l));
1210 l.rlim_cur = RLIM_INFINITY;
1211 l.rlim_max = RLIM_INFINITY;
1212 if (setrlimit(RLIMIT_CORE, &l)) {
1213 ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
1220 if (option_console && !option_verbose)
1221 ast_verbose("[ Reading Master Configuration ]");
1224 if (option_console) {
1225 if (el_hist == NULL || el == NULL)
1226 ast_el_initialize();
1228 if (strlen(filename))
1229 ast_el_read_history(filename);
1232 if (ast_tryconnect()) {
1233 /* One is already running */
1234 if (option_remote) {
1236 ast_remotecontrol(xarg);
1237 quit_handler(0, 0, 0, 0);
1240 printf(term_quit());
1241 ast_register_verbose(console_verboser);
1242 ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2001 Linux Support Services, Inc.\n");
1243 ast_verbose( "Written by Mark Spencer <markster@linux-support.net>\n");
1244 ast_verbose( "=========================================================================\n");
1245 ast_remotecontrol(NULL);
1246 quit_handler(0, 0, 0, 0);
1249 ast_log(LOG_ERROR, "Asterisk already running on %s. Use 'asterisk -r' to connect.\n", (char *)ast_config_AST_SOCKET);
1250 printf(term_quit());
1253 } else if (option_remote || option_exec) {
1254 ast_log(LOG_ERROR, "Unable to connect to remote asterisk\n");
1255 printf(term_quit());
1258 /* Blindly write pid file since we couldn't connect */
1259 unlink((char *)ast_config_AST_PID);
1260 f = fopen((char *)ast_config_AST_PID, "w");
1262 fprintf(f, "%d\n", getpid());
1265 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1267 if (!option_verbose && !option_debug && !option_nofork && !option_console) {
1273 ast_log(LOG_ERROR, "Unable to fork(): %s\n", strerror(errno));
1274 printf(term_quit());
1284 sigaddset(&sigs, SIGHUP);
1285 sigaddset(&sigs, SIGTERM);
1286 sigaddset(&sigs, SIGINT);
1287 sigaddset(&sigs, SIGPIPE);
1288 sigaddset(&sigs, SIGWINCH);
1289 pthread_sigmask(SIG_BLOCK, &sigs, NULL);
1290 if (option_console || option_verbose || option_remote)
1291 ast_register_verbose(console_verboser);
1292 /* Print a welcome message if desired */
1293 if (option_verbose || option_console) {
1294 ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2001 Linux Support Services, Inc.\n");
1295 ast_verbose( "Written by Mark Spencer <markster@linux-support.net>\n");
1296 ast_verbose( "=========================================================================\n");
1298 if (option_console && !option_verbose)
1299 ast_verbose("[ Booting...");
1300 signal(SIGURG, urg_handler);
1301 signal(SIGINT, __quit_handler);
1302 signal(SIGTERM, __quit_handler);
1303 signal(SIGHUP, hup_handler);
1304 signal(SIGPIPE, pipe_handler);
1305 if (set_priority(option_highpriority)) {
1306 printf(term_quit());
1309 if (init_logger()) {
1310 printf(term_quit());
1313 if (init_manager()) {
1314 printf(term_quit());
1317 if (ast_image_init()) {
1318 printf(term_quit());
1322 printf(term_quit());
1325 if (load_modules()) {
1326 printf(term_quit());
1329 if (init_framer()) {
1330 printf(term_quit());
1334 printf(term_quit());
1337 if (ast_enum_init()) {
1338 printf(term_quit());
1341 /* We might have the option of showing a console, but for now just
1343 if (option_console && !option_verbose)
1344 ast_verbose(" ]\n");
1345 if (option_verbose || option_console)
1346 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
1348 pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
1349 #ifdef __AST_DEBUG_MALLOC
1352 ast_cli_register(&astshutdownnow);
1353 ast_cli_register(&astshutdowngracefully);
1354 ast_cli_register(&astrestartnow);
1355 ast_cli_register(&astrestartgracefully);
1356 ast_cli_register(&astrestartwhenconvenient);
1357 ast_cli_register(&astshutdownwhenconvenient);
1358 ast_cli_register(&aborthalt);
1359 if (option_console) {
1360 /* Console stuff now... */
1361 /* Register our quit function */
1363 set_icon("Asterisk");
1364 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, mainpid);
1366 ast_cli_register(&quit);
1367 ast_cli_register(&astexit);
1368 consolethread = pthread_self();
1370 while ( (buf = (char *)el_gets(el, &num) ) != NULL && num != 0) {
1372 if (buf[strlen(buf)-1] == '\n')
1373 buf[strlen(buf)-1] = '\0';
1375 consolehandler((char *)buf);
1380 ast_select(0,NULL,NULL,NULL,NULL);