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 time_t ast_startuptime;
74 time_t ast_lastreloadtime;
76 static History *el_hist = NULL;
77 static EditLine *el = NULL;
78 static char *remotehostname;
80 struct console consoles[AST_MAX_CONNECTS];
82 char defaultlanguage[MAX_LANGUAGE] = DEFAULT_LANGUAGE;
84 static int ast_el_add_history(char *);
85 static int ast_el_read_history(char *);
86 static int ast_el_write_history(char *);
88 char ast_config_AST_CONFIG_DIR[AST_CONFIG_MAX_PATH];
89 char ast_config_AST_CONFIG_FILE[AST_CONFIG_MAX_PATH];
90 char ast_config_AST_MODULE_DIR[AST_CONFIG_MAX_PATH];
91 char ast_config_AST_SPOOL_DIR[AST_CONFIG_MAX_PATH];
92 char ast_config_AST_VAR_DIR[AST_CONFIG_MAX_PATH];
93 char ast_config_AST_LOG_DIR[AST_CONFIG_MAX_PATH];
94 char ast_config_AST_AGI_DIR[AST_CONFIG_MAX_PATH];
95 char ast_config_AST_DB[AST_CONFIG_MAX_PATH];
96 char ast_config_AST_KEY_DIR[AST_CONFIG_MAX_PATH];
97 char ast_config_AST_PID[AST_CONFIG_MAX_PATH];
98 char ast_config_AST_SOCKET[AST_CONFIG_MAX_PATH];
99 char ast_config_AST_RUN_DIR[AST_CONFIG_MAX_PATH];
101 static int fdprint(int fd, const char *s)
103 return write(fd, s, strlen(s) + 1);
106 static void network_verboser(const char *s, int pos, int replace, int complete)
109 for (x=0;x<AST_MAX_CONNECTS; x++) {
110 if (consoles[x].fd > -1)
111 fdprint(consoles[x].p[1], s);
115 static pthread_t lthread;
117 static void *netconsole(void *vconsole)
119 struct console *con = vconsole;
126 if (gethostname(hostname, sizeof(hostname)))
127 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
128 snprintf(tmp, sizeof(tmp), "%s/%d/%s\n", hostname, mainpid, ASTERISK_VERSION);
129 fdprint(con->fd, tmp);
132 FD_SET(con->fd, &rfds);
133 FD_SET(con->p[0], &rfds);
137 res = ast_select(max + 1, &rfds, NULL, NULL, NULL);
139 ast_log(LOG_WARNING, "select returned < 0: %s\n", strerror(errno));
142 if (FD_ISSET(con->fd, &rfds)) {
143 res = read(con->fd, tmp, sizeof(tmp));
148 ast_cli_command(con->fd, tmp);
150 if (FD_ISSET(con->p[0], &rfds)) {
151 res = read(con->p[0], tmp, sizeof(tmp));
153 ast_log(LOG_ERROR, "read returned %d\n", res);
156 res = write(con->fd, tmp, res);
161 if (option_verbose > 2)
162 ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection disconnected\n");
171 static void *listener(void *unused)
173 struct sockaddr_un sun;
179 pthread_attr_init(&attr);
180 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
185 s = accept(ast_socket, (struct sockaddr *)&sun, &len);
187 ast_log(LOG_WARNING, "Accept retured %d: %s\n", s, strerror(errno));
189 for (x=0;x<AST_MAX_CONNECTS;x++) {
190 if (consoles[x].fd < 0) {
191 if (socketpair(AF_LOCAL, SOCK_STREAM, 0, consoles[x].p)) {
192 ast_log(LOG_ERROR, "Unable to create pipe: %s\n", strerror(errno));
194 fdprint(s, "Server failed to create pipe\n");
198 flags = fcntl(consoles[x].p[1], F_GETFL);
199 fcntl(consoles[x].p[1], F_SETFL, flags | O_NONBLOCK);
201 if (pthread_create(&consoles[x].t, &attr, netconsole, &consoles[x])) {
202 ast_log(LOG_ERROR, "Unable to spawn thread to handle connection\n");
204 fdprint(s, "Server failed to spawn thread\n");
210 if (x >= AST_MAX_CONNECTS) {
211 fdprint(s, "No more connections allowed\n");
212 ast_log(LOG_WARNING, "No more connections allowed\n");
214 } else if (consoles[x].fd > -1) {
215 if (option_verbose > 2)
216 ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection\n");
223 static int ast_makesocket(void)
225 struct sockaddr_un sun;
228 for (x=0;x<AST_MAX_CONNECTS;x++)
230 unlink((char *)ast_config_AST_SOCKET);
231 ast_socket = socket(PF_LOCAL, SOCK_STREAM, 0);
232 if (ast_socket < 0) {
233 ast_log(LOG_WARNING, "Unable to create control socket: %s\n", strerror(errno));
236 memset(&sun, 0, sizeof(sun));
237 sun.sun_family = AF_LOCAL;
238 strncpy(sun.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sun.sun_path)-1);
239 res = bind(ast_socket, (struct sockaddr *)&sun, sizeof(sun));
241 ast_log(LOG_WARNING, "Unable to bind socket to %s: %s\n", (char *)ast_config_AST_SOCKET, strerror(errno));
246 res = listen(ast_socket, 2);
248 ast_log(LOG_WARNING, "Unable to listen on socket %s: %s\n", (char *)ast_config_AST_SOCKET, strerror(errno));
253 ast_register_verbose(network_verboser);
254 pthread_create(<hread, NULL, listener, NULL);
258 static int ast_tryconnect(void)
260 struct sockaddr_un sun;
262 ast_consock = socket(PF_LOCAL, SOCK_STREAM, 0);
263 if (ast_consock < 0) {
264 ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
267 memset(&sun, 0, sizeof(sun));
268 sun.sun_family = AF_LOCAL;
269 strncpy(sun.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sun.sun_path)-1);
270 res = connect(ast_consock, (struct sockaddr *)&sun, sizeof(sun));
279 static void urg_handler(int num)
281 /* Called by soft_hangup to interrupt the select, read, or other
282 system call. We don't actually need to do anything though. */
284 ast_log(LOG_DEBUG, "Urgent handler\n");
285 signal(num, urg_handler);
289 static void hup_handler(int num)
291 if (option_verbose > 1)
292 ast_verbose(VERBOSE_PREFIX_2 "Received HUP signal -- Reloading configs\n");
297 static void pipe_handler(int num)
301 static void set_title(char *text)
303 /* Set an X-term or screen title */
304 if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
305 fprintf(stdout, "\033]2;%s\007", text);
308 static void set_icon(char *text)
310 if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
311 fprintf(stdout, "\033]1;%s\007", text);
314 static int set_priority(int pri)
316 struct sched_param sched;
317 memset(&sched, 0, sizeof(sched));
318 /* We set ourselves to a high priority, that we might pre-empt everything
319 else. If your PBX has heavy activity on it, this is a good thing. */
322 sched.sched_priority = 10;
323 if (sched_setscheduler(0, SCHED_RR, &sched)) {
324 ast_log(LOG_WARNING, "Unable to set high priority\n");
328 ast_verbose("Set to realtime thread\n");
330 sched.sched_priority = 0;
331 if (sched_setscheduler(0, SCHED_OTHER, &sched)) {
332 ast_log(LOG_WARNING, "Unable to set normal priority\n");
338 if (setpriority(PRIO_PROCESS, 0, -10) == -1) {
339 ast_log(LOG_WARNING, "Unable to set high priority\n");
343 ast_verbose("Set to high priority\n");
345 if (setpriority(PRIO_PROCESS, 0, 0) == -1) {
346 ast_log(LOG_WARNING, "Unable to set normal priority\n");
354 static char *_argv[256];
356 static int shuttingdown = 0;
358 static void quit_handler(int num, int nice, int safeshutdown, int restart)
360 char filename[80] = "";
366 /* Begin shutdown routine, hanging up active channels */
367 ast_begin_shutdown(1);
368 if (option_verbose && option_console)
369 ast_verbose("Beginning asterisk %s....\n", restart ? "restart" : "shutdown");
373 /* Wait up to 15 seconds for all channels to go away */
376 if (!ast_active_channels())
380 /* Sleep 1/10 of a second */
385 ast_begin_shutdown(0);
386 if (option_verbose && option_console)
387 ast_verbose("Waiting for inactivity to perform %s...\n", restart ? "restart" : "halt");
389 if (!ast_active_channels())
398 if (option_verbose && option_console)
399 ast_verbose("Asterisk %s cancelled.\n", restart ? "restart" : "shutdown");
403 if (option_console || option_remote) {
405 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
406 if (strlen(filename))
407 ast_el_write_history(filename);
411 history_end(el_hist);
414 if (option_verbose && option_console)
415 ast_verbose("Asterisk %s ending (%d).\n", ast_active_channels() ? "uncleanly" : "cleanly", num);
416 else if (option_debug)
417 ast_log(LOG_DEBUG, "Asterisk ending (%d).\n", num);
418 manager_event(EVENT_FLAG_SYSTEM, "Shutdown", "Shutdown: %s\r\nRestart: %s\r\n", ast_active_channels() ? "Uncleanly" : "Cleanly", restart ? "True" : "False");
419 if (ast_socket > -1) {
423 if (ast_consock > -1)
426 unlink((char *)ast_config_AST_SOCKET);
427 unlink((char *)ast_config_AST_PID);
430 if (option_verbose || option_console)
431 ast_verbose("Preparing for Asterisk restart...\n");
432 /* Mark all FD's for closing on exec */
433 for (x=3;x<32768;x++) {
434 fcntl(x, F_SETFD, FD_CLOEXEC);
436 if (option_verbose || option_console)
437 ast_verbose("Restarting Asterisk NOW...\n");
438 execvp(_argv[0], _argv);
443 static void __quit_handler(int num)
445 quit_handler(num, 0, 1, 0);
448 static pthread_t consolethread = -1;
450 static int fix_header(char *outbuf, int maxout, char **s, char *cmp)
452 if (!strncmp(*s, cmp, strlen(cmp))) {
454 term_color(outbuf, cmp, COLOR_GRAY, 0, maxout);
460 static void console_verboser(const char *s, int pos, int replace, int complete)
463 /* Return to the beginning of the line */
465 fprintf(stdout, "\r");
466 if (fix_header(tmp, sizeof(tmp), &s, VERBOSE_PREFIX_4) ||
467 fix_header(tmp, sizeof(tmp), &s, VERBOSE_PREFIX_3) ||
468 fix_header(tmp, sizeof(tmp), &s, VERBOSE_PREFIX_2) ||
469 fix_header(tmp, sizeof(tmp), &s, VERBOSE_PREFIX_1))
472 fputs(s + pos,stdout);
475 /* Wake up a select()ing console */
476 if (consolethread > -1)
477 pthread_kill(consolethread, SIGURG);
480 static void consolehandler(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");
495 ast_cli_command(STDOUT_FILENO, s);
496 if (!strcasecmp(s, "help"))
497 fprintf(stdout, " !<command> Executes a given shell command\n");
499 fprintf(stdout, "\nUse \"quit\" to exit\n");
502 static int remoteconsolehandler(char *s)
505 /* Called when readline data is available */
507 ast_el_add_history(s);
508 /* Give the console access to the shell */
514 system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
517 if (!strcasecmp(s, "help")) {
518 fprintf(stdout, " !<command> Executes a given shell command\n");
521 if (!strcasecmp(s, "quit")) {
522 quit_handler(0, 0, 0, 0);
525 if (!strcasecmp(s, "exit")) {
526 quit_handler(0, 0, 0, 0);
530 fprintf(stdout, "\nUse \"quit\" to exit\n");
535 static char quit_help[] =
537 " Exits Asterisk.\n";
539 static char abort_halt_help[] =
540 "Usage: abort shutdown\n"
541 " Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
542 " call operations.\n";
544 static char shutdown_now_help[] =
546 " Shuts down a running Asterisk immediately, hanging up all active calls .\n";
548 static char shutdown_gracefully_help[] =
549 "Usage: stop gracefully\n"
550 " Causes Asterisk to not accept new calls, and exit when all\n"
551 " active calls have terminated normally.\n";
553 static char shutdown_when_convenient_help[] =
554 "Usage: stop when convenient\n"
555 " Causes Asterisk to perform a shutdown when all active calls have ended.\n";
557 static char restart_now_help[] =
558 "Usage: restart now\n"
559 " Causes Asterisk to hangup all calls and exec() itself performing a cold.\n"
562 static char restart_gracefully_help[] =
563 "Usage: restart gracefully\n"
564 " Causes Asterisk to stop accepting new calls and exec() itself performing a cold.\n"
565 " restart when all active calls have ended.\n";
567 static char restart_when_convenient_help[] =
568 "Usage: restart when convenient\n"
569 " Causes Asterisk to perform a cold restart when all active calls have ended.\n";
572 static int handle_quit(int fd, int argc, char *argv[])
575 return RESULT_SHOWUSAGE;
576 quit_handler(0, 0, 1, 0);
577 return RESULT_SUCCESS;
581 static int no_more_quit(int fd, int argc, char *argv[])
584 return RESULT_SHOWUSAGE;
585 ast_cli(fd, "The QUIT and EXIT commands may no longer be used to shutdown the PBX.\n"
586 "Please use STOP NOW instead, if you wish to shutdown the PBX.\n");
587 return RESULT_SUCCESS;
590 static int handle_shutdown_now(int fd, int argc, char *argv[])
593 return RESULT_SHOWUSAGE;
594 quit_handler(0, 0 /* Not nice */, 1 /* safely */, 0 /* not restart */);
595 return RESULT_SUCCESS;
598 static int handle_shutdown_gracefully(int fd, int argc, char *argv[])
601 return RESULT_SHOWUSAGE;
602 quit_handler(0, 1 /* nicely */, 1 /* safely */, 0 /* no restart */);
603 return RESULT_SUCCESS;
606 static int handle_shutdown_when_convenient(int fd, int argc, char *argv[])
609 return RESULT_SHOWUSAGE;
610 quit_handler(0, 2 /* really nicely */, 1 /* safely */, 0 /* don't restart */);
611 return RESULT_SUCCESS;
614 static int handle_restart_now(int fd, int argc, char *argv[])
617 return RESULT_SHOWUSAGE;
618 quit_handler(0, 0 /* not nicely */, 1 /* safely */, 1 /* restart */);
619 return RESULT_SUCCESS;
622 static int handle_restart_gracefully(int fd, int argc, char *argv[])
625 return RESULT_SHOWUSAGE;
626 quit_handler(0, 1 /* nicely */, 1 /* safely */, 1 /* restart */);
627 return RESULT_SUCCESS;
630 static int handle_restart_when_convenient(int fd, int argc, char *argv[])
633 return RESULT_SHOWUSAGE;
634 quit_handler(0, 2 /* really nicely */, 1 /* safely */, 1 /* restart */);
635 return RESULT_SUCCESS;
638 static int handle_abort_halt(int fd, int argc, char *argv[])
641 return RESULT_SHOWUSAGE;
642 ast_cancel_shutdown();
644 return RESULT_SUCCESS;
647 #define ASTERISK_PROMPT "*CLI> "
649 #define ASTERISK_PROMPT2 "%s*CLI> "
651 static struct ast_cli_entry aborthalt = { { "abort", "halt", NULL }, handle_abort_halt, "Cancel a running halt", abort_halt_help };
653 static struct ast_cli_entry quit = { { "quit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
654 static struct ast_cli_entry astexit = { { "exit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
656 static struct ast_cli_entry astshutdownnow = { { "stop", "now", NULL }, handle_shutdown_now, "Shut down Asterisk imediately", shutdown_now_help };
657 static struct ast_cli_entry astshutdowngracefully = { { "stop", "gracefully", NULL }, handle_shutdown_gracefully, "Gracefully shut down Asterisk", shutdown_gracefully_help };
658 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 };
659 static struct ast_cli_entry astrestartnow = { { "restart", "now", NULL }, handle_restart_now, "Restart Asterisk immediately", restart_now_help };
660 static struct ast_cli_entry astrestartgracefully = { { "restart", "gracefully", NULL }, handle_restart_gracefully, "Restart Asterisk gracefully", restart_gracefully_help };
661 static struct ast_cli_entry astrestartwhenconvenient= { { "restart", "when", "convenient", NULL }, handle_restart_when_convenient, "Restart Asterisk at empty call volume", restart_when_convenient_help };
663 static int ast_el_read_char(EditLine *el, char *cp)
674 FD_SET(ast_consock, &rfds);
675 FD_SET(STDIN_FILENO, &rfds);
677 if (STDIN_FILENO > max)
679 res = ast_select(max+1, &rfds, NULL, NULL, NULL);
683 ast_log(LOG_ERROR, "select failed: %s\n", strerror(errno));
687 if (FD_ISSET(STDIN_FILENO, &rfds)) {
688 num_read = read(STDIN_FILENO, cp, 1);
694 if (FD_ISSET(ast_consock, &rfds)) {
695 res = read(ast_consock, buf, sizeof(buf) - 1);
696 /* if the remote side disappears exit */
698 fprintf(stderr, "\nDisconnected from Asterisk server\n");
699 quit_handler(0, 0, 0, 0);
705 write(STDOUT_FILENO, "\r", 1);
706 write(STDOUT_FILENO, buf, res);
707 if ((buf[res-1] == '\n') || (buf[res-2] == '\n')) {
720 static char *cli_prompt(EditLine *el)
722 static char prompt[80];
725 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT2, remotehostname);
727 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT);
732 static char **ast_el_strtoarr(char *buf)
734 char **match_list = NULL, *retstr;
735 size_t match_list_len;
739 while ( (retstr = strsep(&buf, " ")) != NULL) {
741 if (matches + 1 >= match_list_len) {
742 match_list_len <<= 1;
743 match_list = realloc(match_list, match_list_len * sizeof(char *));
746 match_list[matches++] = retstr;
750 return (char **) NULL;
752 if (matches>= match_list_len)
753 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
755 match_list[matches] = (char *) NULL;
760 static int ast_el_sort_compare(const void *i1, const void *i2)
764 s1 = ((char **)i1)[0];
765 s2 = ((char **)i2)[0];
767 return strcasecmp(s1, s2);
770 static int ast_cli_display_match_list(char **matches, int len, int max)
772 int i, idx, limit, count;
774 int numoutput = 0, numoutputline = 0;
776 screenwidth = ast_get_termcols(STDOUT_FILENO);
778 /* find out how many entries can be put on one line, with two spaces between strings */
779 limit = screenwidth / (max + 2);
783 /* how many lines of output */
785 if (count * limit < len)
790 qsort(&matches[0], (size_t)(len + 1), sizeof(char *), ast_el_sort_compare);
792 for (; count > 0; count--) {
794 for (i=0; i < limit && matches[idx]; i++, idx++) {
796 /* Don't print dupes */
797 if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
802 numoutput++; numoutputline++;
803 fprintf(stdout, "%-*s ", max, matches[idx]);
805 if (numoutputline > 0)
806 fprintf(stdout, "\n");
813 static char *cli_complete(EditLine *el, int ch)
819 int retval = CC_ERROR;
823 LineInfo *lf = (LineInfo *)el_line(el);
826 ptr = (char *)lf->cursor;
828 while (ptr > lf->buffer) {
837 len = lf->cursor - ptr;
840 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr);
841 fdprint(ast_consock, buf);
842 res = read(ast_consock, buf, sizeof(buf));
844 nummatches = atoi(buf);
846 if (nummatches > 0) {
847 snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr);
848 fdprint(ast_consock, buf);
849 res = read(ast_consock, buf, sizeof(buf));
852 matches = ast_el_strtoarr(buf);
854 matches = (char **) NULL;
859 nummatches = ast_cli_generatornummatches((char *)lf->buffer,ptr);
860 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
865 int matches_num, maxlen, match_len;
867 if (matches[0][0] != '\0') {
868 el_deletestr(el, (int) len);
869 el_insertstr(el, matches[0]);
873 if (nummatches == 1) {
874 /* Found an exact match */
875 el_insertstr(el, " ");
878 /* Must be more than one match */
879 for (i=1, maxlen=0; matches[i]; i++) {
880 match_len = strlen(matches[i]);
881 if (match_len > maxlen)
885 if (matches_num >1) {
886 fprintf(stdout, "\n");
887 ast_cli_display_match_list(matches, nummatches, maxlen);
888 retval = CC_REDISPLAY;
890 el_insertstr(el," ");
897 return (char *)retval;
900 static int ast_el_initialize(void)
907 history_end(el_hist);
909 el = el_init("asterisk", stdin, stdout, stderr);
910 el_set(el, EL_PROMPT, cli_prompt);
912 el_set(el, EL_EDITMODE, 1);
913 el_set(el, EL_EDITOR, "emacs");
914 el_hist = history_init();
918 /* setup history with 100 entries */
919 history(el_hist, &ev, H_SETSIZE, 100);
921 el_set(el, EL_HIST, history, el_hist);
923 el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
924 /* Bind <tab> to command completion */
925 el_set(el, EL_BIND, "^I", "ed-complete", NULL);
926 /* Bind ? to command completion */
927 el_set(el, EL_BIND, "?", "ed-complete", NULL);
932 static int ast_el_add_history(char *buf)
936 if (el_hist == NULL || el == NULL)
939 return (history(el_hist, &ev, H_ENTER, buf));
942 static int ast_el_write_history(char *filename)
946 if (el_hist == NULL || el == NULL)
949 return (history(el_hist, &ev, H_SAVE, filename));
952 static int ast_el_read_history(char *filename)
958 if (el_hist == NULL || el == NULL)
961 if ((f = fopen(filename, "r")) == NULL)
965 fgets(buf, sizeof(buf), f);
966 if (!strcmp(buf, "_HiStOrY_V2_\n"))
968 if ((ret = ast_el_add_history(buf)) == -1)
976 static void ast_remotecontrol(char * data)
980 char filename[80] = "";
991 read(ast_consock, buf, sizeof(buf));
993 write(ast_consock, data, strlen(data) + 1);
995 hostname = strsep(&stringp, "/");
996 cpid = strsep(&stringp, "/");
997 version = strsep(&stringp, "/");
999 version = "<Version Unknown>";
1001 strsep(&stringp, ".");
1006 snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
1007 fdprint(ast_consock, tmp);
1008 ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
1009 remotehostname = hostname;
1011 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1012 if (el_hist == NULL || el == NULL)
1013 ast_el_initialize();
1015 el_set(el, EL_GETCFN, ast_el_read_char);
1017 if (strlen(filename))
1018 ast_el_read_history(filename);
1020 ast_cli_register(&quit);
1021 ast_cli_register(&astexit);
1023 ast_cli_register(&astshutdown);
1026 ebuf = (char *)el_gets(el, &num);
1028 if (data) /* hack to print output then exit if asterisk -rx is used */
1029 ebuf = strdup("quit");
1031 if (ebuf && strlen(ebuf)) {
1032 if (ebuf[strlen(ebuf)-1] == '\n')
1033 ebuf[strlen(ebuf)-1] = '\0';
1034 if (!remoteconsolehandler(ebuf)) {
1035 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
1037 ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
1043 printf("\nDisconnected from Asterisk server\n");
1046 static int show_cli_help(void) {
1047 printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 2000-2002, Digium.\n");
1048 printf("Usage: asterisk [OPTIONS]\n");
1049 printf("Valid Options:\n");
1050 printf(" -h This help screen\n");
1051 printf(" -r Connect to Asterisk on this machine\n");
1052 printf(" -f Do not fork\n");
1053 printf(" -n Disable console colorization\n");
1054 printf(" -p Run as pseudo-realtime thread\n");
1055 printf(" -v Increase verbosity (multiple v's = more verbose)\n");
1056 printf(" -q Quiet mode (supress output)\n");
1057 printf(" -g Dump core in case of a crash\n");
1058 printf(" -x <cmd> Execute command <cmd> (only valid with -r)\n");
1059 printf(" -i Initializie crypto keys at startup\n");
1060 printf(" -c Provide console CLI\n");
1061 printf(" -d Enable extra debugging\n");
1066 static void ast_readconfig(void) {
1067 struct ast_config *cfg;
1068 struct ast_variable *v;
1069 char *config = ASTCONFPATH;
1071 if (option_overrideconfig == 1) {
1072 cfg = ast_load((char *)ast_config_AST_CONFIG_FILE);
1074 cfg = ast_load(config);
1077 /* init with buildtime config */
1078 strncpy((char *)ast_config_AST_CONFIG_DIR,AST_CONFIG_DIR,sizeof(ast_config_AST_CONFIG_DIR)-1);
1079 strncpy((char *)ast_config_AST_SPOOL_DIR,AST_SPOOL_DIR,sizeof(ast_config_AST_SPOOL_DIR)-1);
1080 strncpy((char *)ast_config_AST_MODULE_DIR,AST_MODULE_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1081 strncpy((char *)ast_config_AST_VAR_DIR,AST_VAR_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1082 strncpy((char *)ast_config_AST_LOG_DIR,AST_LOG_DIR,sizeof(ast_config_AST_LOG_DIR)-1);
1083 strncpy((char *)ast_config_AST_AGI_DIR,AST_AGI_DIR,sizeof(ast_config_AST_AGI_DIR)-1);
1084 strncpy((char *)ast_config_AST_DB,AST_DB,sizeof(ast_config_AST_DB)-1);
1085 strncpy((char *)ast_config_AST_KEY_DIR,AST_KEY_DIR,sizeof(ast_config_AST_KEY_DIR)-1);
1086 strncpy((char *)ast_config_AST_PID,AST_PID,sizeof(ast_config_AST_PID)-1);
1087 strncpy((char *)ast_config_AST_SOCKET,AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1);
1088 strncpy((char *)ast_config_AST_RUN_DIR,AST_RUN_DIR,sizeof(ast_config_AST_RUN_DIR)-1);
1090 /* no asterisk.conf? no problem, use buildtime config! */
1094 v = ast_variable_browse(cfg, "directories");
1096 if (!strcasecmp(v->name, "astetcdir")) {
1097 strncpy((char *)ast_config_AST_CONFIG_DIR,v->value,sizeof(ast_config_AST_CONFIG_DIR)-1);
1098 } else if (!strcasecmp(v->name, "astspooldir")) {
1099 strncpy((char *)ast_config_AST_SPOOL_DIR,v->value,sizeof(ast_config_AST_SPOOL_DIR)-1);
1100 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1101 strncpy((char *)ast_config_AST_VAR_DIR,v->value,sizeof(ast_config_AST_VAR_DIR)-1);
1102 snprintf((char *)ast_config_AST_DB,sizeof(ast_config_AST_DB)-1,"%s/%s",v->value,"astdb");
1103 } else if (!strcasecmp(v->name, "astlogdir")) {
1104 strncpy((char *)ast_config_AST_LOG_DIR,v->value,sizeof(ast_config_AST_LOG_DIR)-1);
1105 } else if (!strcasecmp(v->name, "astagidir")) {
1106 strncpy((char *)ast_config_AST_AGI_DIR,v->value,sizeof(ast_config_AST_AGI_DIR)-1);
1107 } else if (!strcasecmp(v->name, "astrundir")) {
1108 snprintf((char *)ast_config_AST_PID,sizeof(ast_config_AST_PID)-1,"%s/%s",v->value,"asterisk.pid");
1109 snprintf((char *)ast_config_AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1,"%s/%s",v->value,"asterisk.ctl");
1110 strncpy((char *)ast_config_AST_RUN_DIR,v->value,sizeof(ast_config_AST_RUN_DIR)-1);
1111 } else if (!strcasecmp(v->name, "astmoddir")) {
1112 strncpy((char *)ast_config_AST_MODULE_DIR,v->value,sizeof(ast_config_AST_MODULE_DIR)-1);
1119 int main(int argc, char *argv[])
1122 char filename[80] = "";
1132 /* Remember original args for restart */
1133 if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1134 fprintf(stderr, "Truncating argument size to %d\n", sizeof(_argv) / sizeof(_argv[0]) - 1);
1135 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1137 for (x=0;x<argc;x++)
1141 if (gethostname(hostname, sizeof(hostname)))
1142 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
1149 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1150 /* Check if we're root */
1153 ast_log(LOG_ERROR, "Must be run as root\n");
1157 /* Check for options */
1158 while((c=getopt(argc, argv, "hfdvqprgcinx:C:")) != EOF) {
1179 option_highpriority++;
1193 strncpy((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE));
1194 option_overrideconfig++;
1197 option_initcrypto++;
1210 if (option_dumpcore) {
1212 memset(&l, 0, sizeof(l));
1213 l.rlim_cur = RLIM_INFINITY;
1214 l.rlim_max = RLIM_INFINITY;
1215 if (setrlimit(RLIMIT_CORE, &l)) {
1216 ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
1223 if (option_console && !option_verbose)
1224 ast_verbose("[ Reading Master Configuration ]");
1227 if (option_console) {
1228 if (el_hist == NULL || el == NULL)
1229 ast_el_initialize();
1231 if (strlen(filename))
1232 ast_el_read_history(filename);
1235 if (ast_tryconnect()) {
1236 /* One is already running */
1237 if (option_remote) {
1239 ast_remotecontrol(xarg);
1240 quit_handler(0, 0, 0, 0);
1243 printf(term_quit());
1244 ast_register_verbose(console_verboser);
1245 ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2001 Linux Support Services, Inc.\n");
1246 ast_verbose( "Written by Mark Spencer <markster@linux-support.net>\n");
1247 ast_verbose( "=========================================================================\n");
1248 ast_remotecontrol(NULL);
1249 quit_handler(0, 0, 0, 0);
1252 ast_log(LOG_ERROR, "Asterisk already running on %s. Use 'asterisk -r' to connect.\n", (char *)ast_config_AST_SOCKET);
1253 printf(term_quit());
1256 } else if (option_remote || option_exec) {
1257 ast_log(LOG_ERROR, "Unable to connect to remote asterisk\n");
1258 printf(term_quit());
1261 /* Blindly write pid file since we couldn't connect */
1262 unlink((char *)ast_config_AST_PID);
1263 f = fopen((char *)ast_config_AST_PID, "w");
1265 fprintf(f, "%d\n", getpid());
1268 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1270 if (!option_verbose && !option_debug && !option_nofork && !option_console) {
1276 ast_log(LOG_ERROR, "Unable to fork(): %s\n", strerror(errno));
1277 printf(term_quit());
1287 sigaddset(&sigs, SIGHUP);
1288 sigaddset(&sigs, SIGTERM);
1289 sigaddset(&sigs, SIGINT);
1290 sigaddset(&sigs, SIGPIPE);
1291 sigaddset(&sigs, SIGWINCH);
1292 pthread_sigmask(SIG_BLOCK, &sigs, NULL);
1293 if (option_console || option_verbose || option_remote)
1294 ast_register_verbose(console_verboser);
1295 /* Print a welcome message if desired */
1296 if (option_verbose || option_console) {
1297 ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2001 Linux Support Services, Inc.\n");
1298 ast_verbose( "Written by Mark Spencer <markster@linux-support.net>\n");
1299 ast_verbose( "=========================================================================\n");
1301 if (option_console && !option_verbose)
1302 ast_verbose("[ Booting...");
1303 signal(SIGURG, urg_handler);
1304 signal(SIGINT, __quit_handler);
1305 signal(SIGTERM, __quit_handler);
1306 signal(SIGHUP, hup_handler);
1307 signal(SIGPIPE, pipe_handler);
1308 if (set_priority(option_highpriority)) {
1309 printf(term_quit());
1312 if (init_logger()) {
1313 printf(term_quit());
1316 if (init_manager()) {
1317 printf(term_quit());
1320 if (ast_image_init()) {
1321 printf(term_quit());
1325 printf(term_quit());
1328 if (load_modules()) {
1329 printf(term_quit());
1332 if (init_framer()) {
1333 printf(term_quit());
1337 printf(term_quit());
1340 if (ast_enum_init()) {
1341 printf(term_quit());
1344 /* We might have the option of showing a console, but for now just
1346 if (option_console && !option_verbose)
1347 ast_verbose(" ]\n");
1348 if (option_verbose || option_console)
1349 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
1351 pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
1352 #ifdef __AST_DEBUG_MALLOC
1355 time(&ast_startuptime);
1356 ast_cli_register(&astshutdownnow);
1357 ast_cli_register(&astshutdowngracefully);
1358 ast_cli_register(&astrestartnow);
1359 ast_cli_register(&astrestartgracefully);
1360 ast_cli_register(&astrestartwhenconvenient);
1361 ast_cli_register(&astshutdownwhenconvenient);
1362 ast_cli_register(&aborthalt);
1363 if (option_console) {
1364 /* Console stuff now... */
1365 /* Register our quit function */
1367 set_icon("Asterisk");
1368 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, mainpid);
1370 ast_cli_register(&quit);
1371 ast_cli_register(&astexit);
1372 consolethread = pthread_self();
1374 while ( (buf = (char *)el_gets(el, &num) ) != NULL && num != 0) {
1376 if (buf[strlen(buf)-1] == '\n')
1377 buf[strlen(buf)-1] = '\0';
1379 consolehandler((char *)buf);
1384 ast_select(0,NULL,NULL,NULL,NULL);