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, const char *s)
99 return write(fd, s, strlen(s) + 1);
102 static void network_verboser(const 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 = ast_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. */
318 sched.sched_priority = 10;
319 if (sched_setscheduler(0, SCHED_RR, &sched)) {
320 ast_log(LOG_WARNING, "Unable to set high priority\n");
324 ast_verbose("Set to realtime thread\n");
326 sched.sched_priority = 0;
327 if (sched_setscheduler(0, SCHED_OTHER, &sched)) {
328 ast_log(LOG_WARNING, "Unable to set normal priority\n");
334 if (setpriority(PRIO_PROCESS, 0, -10) == -1) {
335 ast_log(LOG_WARNING, "Unable to set high priority\n");
339 ast_verbose("Set to high priority\n");
341 if (setpriority(PRIO_PROCESS, 0, 0) == -1) {
342 ast_log(LOG_WARNING, "Unable to set normal priority\n");
350 static char *_argv[256];
352 static int shuttingdown = 0;
354 static void quit_handler(int num, int nice, int safeshutdown, int restart)
356 char filename[80] = "";
362 /* Begin shutdown routine, hanging up active channels */
363 ast_begin_shutdown(1);
364 if (option_verbose && option_console)
365 ast_verbose("Beginning asterisk %s....\n", restart ? "restart" : "shutdown");
369 /* Wait up to 15 seconds for all channels to go away */
372 if (!ast_active_channels())
376 /* Sleep 1/10 of a second */
381 ast_begin_shutdown(0);
382 if (option_verbose && option_console)
383 ast_verbose("Waiting for inactivity to perform %s...\n", restart ? "restart" : "halt");
385 if (!ast_active_channels())
394 if (option_verbose && option_console)
395 ast_verbose("Asterisk %s cancelled.\n", restart ? "restart" : "shutdown");
399 if (option_console || option_remote) {
401 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
402 if (strlen(filename))
403 ast_el_write_history(filename);
407 history_end(el_hist);
410 if (option_verbose && option_console)
411 ast_verbose("Asterisk %s ending (%d).\n", ast_active_channels() ? "uncleanly" : "cleanly", num);
412 else if (option_debug)
413 ast_log(LOG_DEBUG, "Asterisk ending (%d).\n", num);
414 manager_event(EVENT_FLAG_SYSTEM, "Shutdown", "Shutdown: %s\r\nRestart: %s\r\n", ast_active_channels() ? "Uncleanly" : "Cleanly", restart ? "True" : "False");
415 if (ast_socket > -1) {
419 if (ast_consock > -1)
422 unlink((char *)ast_config_AST_SOCKET);
423 unlink((char *)ast_config_AST_PID);
426 if (option_verbose || option_console)
427 ast_verbose("Preparing for Asterisk restart...\n");
428 /* Mark all FD's for closing on exec */
429 for (x=3;x<32768;x++) {
430 fcntl(x, F_SETFD, FD_CLOEXEC);
432 if (option_verbose || option_console)
433 ast_verbose("Restarting Asterisk NOW...\n");
434 execvp(_argv[0], _argv);
439 static void __quit_handler(int num)
441 quit_handler(num, 0, 1, 0);
444 static pthread_t consolethread = -1;
446 static int fix_header(char *outbuf, int maxout, char **s, char *cmp)
448 if (!strncmp(*s, cmp, strlen(cmp))) {
450 term_color(outbuf, cmp, COLOR_GRAY, 0, maxout);
456 static void console_verboser(const char *s, int pos, int replace, int complete)
459 /* Return to the beginning of the line */
461 fprintf(stdout, "\r");
462 if (fix_header(tmp, sizeof(tmp), &s, VERBOSE_PREFIX_4) ||
463 fix_header(tmp, sizeof(tmp), &s, VERBOSE_PREFIX_3) ||
464 fix_header(tmp, sizeof(tmp), &s, VERBOSE_PREFIX_2) ||
465 fix_header(tmp, sizeof(tmp), &s, VERBOSE_PREFIX_1))
468 fputs(s + pos,stdout);
471 /* Wake up a select()ing console */
472 if (consolethread > -1)
473 pthread_kill(consolethread, SIGURG);
476 static void consolehandler(char *s)
480 /* Called when readline data is available */
482 ast_el_add_history(s);
483 /* Give the console access to the shell */
489 system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
491 ast_cli_command(STDOUT_FILENO, s);
492 if (!strcasecmp(s, "help"))
493 fprintf(stdout, " !<command> Executes a given shell command\n");
495 fprintf(stdout, "\nUse \"quit\" to exit\n");
498 static int remoteconsolehandler(char *s)
501 /* Called when readline data is available */
503 ast_el_add_history(s);
504 /* Give the console access to the shell */
510 system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
513 if (!strcasecmp(s, "help")) {
514 fprintf(stdout, " !<command> Executes a given shell command\n");
517 if (!strcasecmp(s, "quit")) {
518 quit_handler(0, 0, 0, 0);
521 if (!strcasecmp(s, "exit")) {
522 quit_handler(0, 0, 0, 0);
526 fprintf(stdout, "\nUse \"quit\" to exit\n");
531 static char quit_help[] =
533 " Exits Asterisk.\n";
535 static char abort_halt_help[] =
536 "Usage: abort shutdown\n"
537 " Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
538 " call operations.\n";
540 static char shutdown_now_help[] =
542 " Shuts down a running Asterisk immediately, hanging up all active calls .\n";
544 static char shutdown_gracefully_help[] =
545 "Usage: stop gracefully\n"
546 " Causes Asterisk to not accept new calls, and exit when all\n"
547 " active calls have terminated normally.\n";
549 static char shutdown_when_convenient_help[] =
550 "Usage: stop when convenient\n"
551 " Causes Asterisk to perform a shutdown when all active calls have ended.\n";
553 static char restart_now_help[] =
554 "Usage: restart now\n"
555 " Causes Asterisk to hangup all calls and exec() itself performing a cold.\n"
558 static char restart_gracefully_help[] =
559 "Usage: restart gracefully\n"
560 " Causes Asterisk to stop accepting new calls and exec() itself performing a cold.\n"
561 " restart when all active calls have ended.\n";
563 static char restart_when_convenient_help[] =
564 "Usage: restart when convenient\n"
565 " Causes Asterisk to perform a cold restart when all active calls have ended.\n";
568 static int handle_quit(int fd, int argc, char *argv[])
571 return RESULT_SHOWUSAGE;
572 quit_handler(0, 0, 1, 0);
573 return RESULT_SUCCESS;
577 static int no_more_quit(int fd, int argc, char *argv[])
580 return RESULT_SHOWUSAGE;
581 ast_cli(fd, "The QUIT and EXIT commands may no longer be used to shutdown the PBX.\n"
582 "Please use STOP NOW instead, if you wish to shutdown the PBX.\n");
583 return RESULT_SUCCESS;
586 static int handle_shutdown_now(int fd, int argc, char *argv[])
589 return RESULT_SHOWUSAGE;
590 quit_handler(0, 0 /* Not nice */, 1 /* safely */, 0 /* not restart */);
591 return RESULT_SUCCESS;
594 static int handle_shutdown_gracefully(int fd, int argc, char *argv[])
597 return RESULT_SHOWUSAGE;
598 quit_handler(0, 1 /* nicely */, 1 /* safely */, 0 /* no restart */);
599 return RESULT_SUCCESS;
602 static int handle_shutdown_when_convenient(int fd, int argc, char *argv[])
605 return RESULT_SHOWUSAGE;
606 quit_handler(0, 2 /* really nicely */, 1 /* safely */, 0 /* don't restart */);
607 return RESULT_SUCCESS;
610 static int handle_restart_now(int fd, int argc, char *argv[])
613 return RESULT_SHOWUSAGE;
614 quit_handler(0, 0 /* not nicely */, 1 /* safely */, 1 /* restart */);
615 return RESULT_SUCCESS;
618 static int handle_restart_gracefully(int fd, int argc, char *argv[])
621 return RESULT_SHOWUSAGE;
622 quit_handler(0, 1 /* nicely */, 1 /* safely */, 1 /* restart */);
623 return RESULT_SUCCESS;
626 static int handle_restart_when_convenient(int fd, int argc, char *argv[])
629 return RESULT_SHOWUSAGE;
630 quit_handler(0, 2 /* really nicely */, 1 /* safely */, 1 /* restart */);
631 return RESULT_SUCCESS;
634 static int handle_abort_halt(int fd, int argc, char *argv[])
637 return RESULT_SHOWUSAGE;
638 ast_cancel_shutdown();
640 return RESULT_SUCCESS;
643 #define ASTERISK_PROMPT "*CLI> "
645 #define ASTERISK_PROMPT2 "%s*CLI> "
647 static struct ast_cli_entry aborthalt = { { "abort", "halt", NULL }, handle_abort_halt, "Cancel a running halt", abort_halt_help };
649 static struct ast_cli_entry quit = { { "quit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
650 static struct ast_cli_entry astexit = { { "exit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
652 static struct ast_cli_entry astshutdownnow = { { "stop", "now", NULL }, handle_shutdown_now, "Shut down Asterisk imediately", shutdown_now_help };
653 static struct ast_cli_entry astshutdowngracefully = { { "stop", "gracefully", NULL }, handle_shutdown_gracefully, "Gracefully shut down Asterisk", shutdown_gracefully_help };
654 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 };
655 static struct ast_cli_entry astrestartnow = { { "restart", "now", NULL }, handle_restart_now, "Restart Asterisk immediately", restart_now_help };
656 static struct ast_cli_entry astrestartgracefully = { { "restart", "gracefully", NULL }, handle_restart_gracefully, "Restart Asterisk gracefully", restart_gracefully_help };
657 static struct ast_cli_entry astrestartwhenconvenient= { { "restart", "when", "convenient", NULL }, handle_restart_when_convenient, "Restart Asterisk at empty call volume", restart_when_convenient_help };
659 static int ast_el_read_char(EditLine *el, char *cp)
670 FD_SET(ast_consock, &rfds);
671 FD_SET(STDIN_FILENO, &rfds);
673 if (STDIN_FILENO > max)
675 res = ast_select(max+1, &rfds, NULL, NULL, NULL);
679 ast_log(LOG_ERROR, "select failed: %s\n", strerror(errno));
683 if (FD_ISSET(STDIN_FILENO, &rfds)) {
684 num_read = read(STDIN_FILENO, cp, 1);
690 if (FD_ISSET(ast_consock, &rfds)) {
691 res = read(ast_consock, buf, sizeof(buf) - 1);
692 /* if the remote side disappears exit */
694 fprintf(stderr, "\nDisconnected from Asterisk server\n");
695 quit_handler(0, 0, 0, 0);
701 write(STDOUT_FILENO, "\r", 1);
702 write(STDOUT_FILENO, buf, res);
703 if ((buf[res-1] == '\n') || (buf[res-2] == '\n')) {
716 static char *cli_prompt(EditLine *el)
718 static char prompt[80];
721 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT2, remotehostname);
723 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT);
728 static char **ast_el_strtoarr(char *buf)
730 char **match_list = NULL, *retstr;
731 size_t match_list_len;
735 while ( (retstr = strsep(&buf, " ")) != NULL) {
737 if (matches + 1 >= match_list_len) {
738 match_list_len <<= 1;
739 match_list = realloc(match_list, match_list_len * sizeof(char *));
742 match_list[matches++] = retstr;
746 return (char **) NULL;
748 if (matches>= match_list_len)
749 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
751 match_list[matches] = (char *) NULL;
756 static int ast_el_sort_compare(const void *i1, const void *i2)
760 s1 = ((char **)i1)[0];
761 s2 = ((char **)i2)[0];
763 return strcasecmp(s1, s2);
766 static int ast_cli_display_match_list(char **matches, int len, int max)
768 int i, idx, limit, count;
770 int numoutput = 0, numoutputline = 0;
772 screenwidth = ast_get_termcols(STDOUT_FILENO);
774 /* find out how many entries can be put on one line, with two spaces between strings */
775 limit = screenwidth / (max + 2);
779 /* how many lines of output */
781 if (count * limit < len)
786 qsort(&matches[0], (size_t)(len + 1), sizeof(char *), ast_el_sort_compare);
788 for (; count > 0; count--) {
790 for (i=0; i < limit && matches[idx]; i++, idx++) {
792 /* Don't print dupes */
793 if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
798 numoutput++; numoutputline++;
799 fprintf(stdout, "%-*s ", max, matches[idx]);
801 if (numoutputline > 0)
802 fprintf(stdout, "\n");
809 static char *cli_complete(EditLine *el, int ch)
815 int retval = CC_ERROR;
819 LineInfo *lf = (LineInfo *)el_line(el);
822 ptr = (char *)lf->cursor;
824 while (ptr > lf->buffer) {
833 len = lf->cursor - ptr;
836 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr);
837 fdprint(ast_consock, buf);
838 res = read(ast_consock, buf, sizeof(buf));
840 nummatches = atoi(buf);
842 if (nummatches > 0) {
843 snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr);
844 fdprint(ast_consock, buf);
845 res = read(ast_consock, buf, sizeof(buf));
848 matches = ast_el_strtoarr(buf);
850 matches = (char **) NULL;
855 nummatches = ast_cli_generatornummatches((char *)lf->buffer,ptr);
856 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
861 int matches_num, maxlen, match_len;
863 if (matches[0][0] != '\0') {
864 el_deletestr(el, (int) len);
865 el_insertstr(el, matches[0]);
869 if (nummatches == 1) {
870 /* Found an exact match */
871 el_insertstr(el, " ");
874 /* Must be more than one match */
875 for (i=1, maxlen=0; matches[i]; i++) {
876 match_len = strlen(matches[i]);
877 if (match_len > maxlen)
881 if (matches_num >1) {
882 fprintf(stdout, "\n");
883 ast_cli_display_match_list(matches, nummatches, maxlen);
884 retval = CC_REDISPLAY;
886 el_insertstr(el," ");
893 return (char *)retval;
896 static int ast_el_initialize(void)
903 history_end(el_hist);
905 el = el_init("asterisk", stdin, stdout, stderr);
906 el_set(el, EL_PROMPT, cli_prompt);
908 el_set(el, EL_EDITMODE, 1);
909 el_set(el, EL_EDITOR, "emacs");
910 el_hist = history_init();
914 /* setup history with 100 entries */
915 history(el_hist, &ev, H_SETSIZE, 100);
917 el_set(el, EL_HIST, history, el_hist);
919 el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
920 /* Bind <tab> to command completion */
921 el_set(el, EL_BIND, "^I", "ed-complete", NULL);
922 /* Bind ? to command completion */
923 el_set(el, EL_BIND, "?", "ed-complete", NULL);
928 static int ast_el_add_history(char *buf)
932 if (el_hist == NULL || el == NULL)
935 return (history(el_hist, &ev, H_ENTER, buf));
938 static int ast_el_write_history(char *filename)
942 if (el_hist == NULL || el == NULL)
945 return (history(el_hist, &ev, H_SAVE, filename));
948 static int ast_el_read_history(char *filename)
954 if (el_hist == NULL || el == NULL)
957 if ((f = fopen(filename, "r")) == NULL)
961 fgets(buf, sizeof(buf), f);
962 if (!strcmp(buf, "_HiStOrY_V2_\n"))
964 if ((ret = ast_el_add_history(buf)) == -1)
972 static void ast_remotecontrol(char * data)
976 char filename[80] = "";
987 read(ast_consock, buf, sizeof(buf));
989 write(ast_consock, data, strlen(data) + 1);
991 hostname = strsep(&stringp, "/");
992 cpid = strsep(&stringp, "/");
993 version = strsep(&stringp, "/");
995 version = "<Version Unknown>";
997 strsep(&stringp, ".");
1002 snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
1003 fdprint(ast_consock, tmp);
1004 ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
1005 remotehostname = hostname;
1007 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1008 if (el_hist == NULL || el == NULL)
1009 ast_el_initialize();
1011 el_set(el, EL_GETCFN, ast_el_read_char);
1013 if (strlen(filename))
1014 ast_el_read_history(filename);
1016 ast_cli_register(&quit);
1017 ast_cli_register(&astexit);
1019 ast_cli_register(&astshutdown);
1022 ebuf = (char *)el_gets(el, &num);
1024 if (data) /* hack to print output then exit if asterisk -rx is used */
1025 ebuf = strdup("quit");
1027 if (ebuf && strlen(ebuf)) {
1028 if (ebuf[strlen(ebuf)-1] == '\n')
1029 ebuf[strlen(ebuf)-1] = '\0';
1030 if (!remoteconsolehandler(ebuf)) {
1031 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
1033 ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
1039 printf("\nDisconnected from Asterisk server\n");
1042 static int show_cli_help(void) {
1043 printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 2000-2002, Digium.\n");
1044 printf("Usage: asterisk [OPTIONS]\n");
1045 printf("Valid Options:\n");
1046 printf(" -h This help screen\n");
1047 printf(" -r Connect to Asterisk on this machine\n");
1048 printf(" -f Do not fork\n");
1049 printf(" -n Disable console colorization\n");
1050 printf(" -p Run as pseudo-realtime thread\n");
1051 printf(" -v Increase verbosity (multiple v's = more verbose)\n");
1052 printf(" -q Quiet mode (supress output)\n");
1053 printf(" -g Dump core in case of a crash\n");
1054 printf(" -x <cmd> Execute command <cmd> (only valid with -r)\n");
1055 printf(" -i Initializie crypto keys at startup\n");
1056 printf(" -c Provide console CLI\n");
1057 printf(" -d Enable extra debugging\n");
1062 static void ast_readconfig(void) {
1063 struct ast_config *cfg;
1064 struct ast_variable *v;
1065 char *config = ASTCONFPATH;
1067 if (option_overrideconfig == 1) {
1068 cfg = ast_load((char *)ast_config_AST_CONFIG_FILE);
1070 cfg = ast_load(config);
1073 /* init with buildtime config */
1074 strncpy((char *)ast_config_AST_CONFIG_DIR,AST_CONFIG_DIR,sizeof(ast_config_AST_CONFIG_DIR)-1);
1075 strncpy((char *)ast_config_AST_SPOOL_DIR,AST_SPOOL_DIR,sizeof(ast_config_AST_SPOOL_DIR)-1);
1076 strncpy((char *)ast_config_AST_MODULE_DIR,AST_MODULE_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1077 strncpy((char *)ast_config_AST_VAR_DIR,AST_VAR_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1078 strncpy((char *)ast_config_AST_LOG_DIR,AST_LOG_DIR,sizeof(ast_config_AST_LOG_DIR)-1);
1079 strncpy((char *)ast_config_AST_AGI_DIR,AST_AGI_DIR,sizeof(ast_config_AST_AGI_DIR)-1);
1080 strncpy((char *)ast_config_AST_DB,AST_DB,sizeof(ast_config_AST_DB)-1);
1081 strncpy((char *)ast_config_AST_KEY_DIR,AST_KEY_DIR,sizeof(ast_config_AST_KEY_DIR)-1);
1082 strncpy((char *)ast_config_AST_PID,AST_PID,sizeof(ast_config_AST_PID)-1);
1083 strncpy((char *)ast_config_AST_SOCKET,AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1);
1084 strncpy((char *)ast_config_AST_RUN_DIR,AST_RUN_DIR,sizeof(ast_config_AST_RUN_DIR)-1);
1086 /* no asterisk.conf? no problem, use buildtime config! */
1090 v = ast_variable_browse(cfg, "directories");
1092 if (!strcasecmp(v->name, "astetcdir")) {
1093 strncpy((char *)ast_config_AST_CONFIG_DIR,v->value,sizeof(ast_config_AST_CONFIG_DIR)-1);
1094 } else if (!strcasecmp(v->name, "astspooldir")) {
1095 strncpy((char *)ast_config_AST_SPOOL_DIR,v->value,sizeof(ast_config_AST_SPOOL_DIR)-1);
1096 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1097 strncpy((char *)ast_config_AST_VAR_DIR,v->value,sizeof(ast_config_AST_VAR_DIR)-1);
1098 snprintf((char *)ast_config_AST_DB,sizeof(ast_config_AST_DB)-1,"%s/%s",v->value,"astdb");
1099 } else if (!strcasecmp(v->name, "astlogdir")) {
1100 strncpy((char *)ast_config_AST_LOG_DIR,v->value,sizeof(ast_config_AST_LOG_DIR)-1);
1101 } else if (!strcasecmp(v->name, "astagidir")) {
1102 strncpy((char *)ast_config_AST_AGI_DIR,v->value,sizeof(ast_config_AST_AGI_DIR)-1);
1103 } else if (!strcasecmp(v->name, "astrundir")) {
1104 snprintf((char *)ast_config_AST_PID,sizeof(ast_config_AST_PID)-1,"%s/%s",v->value,"asterisk.pid");
1105 snprintf((char *)ast_config_AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1,"%s/%s",v->value,"asterisk.ctl");
1106 strncpy((char *)ast_config_AST_RUN_DIR,v->value,sizeof(ast_config_AST_RUN_DIR)-1);
1107 } else if (!strcasecmp(v->name, "astmoddir")) {
1108 strncpy((char *)ast_config_AST_MODULE_DIR,v->value,sizeof(ast_config_AST_MODULE_DIR)-1);
1115 int main(int argc, char *argv[])
1118 char filename[80] = "";
1128 /* Remember original args for restart */
1129 if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1130 fprintf(stderr, "Truncating argument size to %d\n", sizeof(_argv) / sizeof(_argv[0]) - 1);
1131 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1133 for (x=0;x<argc;x++)
1137 if (gethostname(hostname, sizeof(hostname)))
1138 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
1145 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1146 /* Check if we're root */
1149 ast_log(LOG_ERROR, "Must be run as root\n");
1153 /* Check for options */
1154 while((c=getopt(argc, argv, "hfdvqprgcinx:C:")) != EOF) {
1175 option_highpriority++;
1189 strncpy((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE));
1190 option_overrideconfig++;
1193 option_initcrypto++;
1206 if (option_dumpcore) {
1208 memset(&l, 0, sizeof(l));
1209 l.rlim_cur = RLIM_INFINITY;
1210 l.rlim_max = RLIM_INFINITY;
1211 if (setrlimit(RLIMIT_CORE, &l)) {
1212 ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
1219 if (option_console && !option_verbose)
1220 ast_verbose("[ Reading Master Configuration ]");
1223 if (option_console) {
1224 if (el_hist == NULL || el == NULL)
1225 ast_el_initialize();
1227 if (strlen(filename))
1228 ast_el_read_history(filename);
1231 if (ast_tryconnect()) {
1232 /* One is already running */
1233 if (option_remote) {
1235 ast_remotecontrol(xarg);
1236 quit_handler(0, 0, 0, 0);
1239 printf(term_quit());
1240 ast_register_verbose(console_verboser);
1241 ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2001 Linux Support Services, Inc.\n");
1242 ast_verbose( "Written by Mark Spencer <markster@linux-support.net>\n");
1243 ast_verbose( "=========================================================================\n");
1244 ast_remotecontrol(NULL);
1245 quit_handler(0, 0, 0, 0);
1248 ast_log(LOG_ERROR, "Asterisk already running on %s. Use 'asterisk -r' to connect.\n", (char *)ast_config_AST_SOCKET);
1249 printf(term_quit());
1252 } else if (option_remote || option_exec) {
1253 ast_log(LOG_ERROR, "Unable to connect to remote asterisk\n");
1254 printf(term_quit());
1257 /* Blindly write pid file since we couldn't connect */
1258 unlink((char *)ast_config_AST_PID);
1259 f = fopen((char *)ast_config_AST_PID, "w");
1261 fprintf(f, "%d\n", getpid());
1264 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1266 if (!option_verbose && !option_debug && !option_nofork && !option_console) {
1272 ast_log(LOG_ERROR, "Unable to fork(): %s\n", strerror(errno));
1273 printf(term_quit());
1283 sigaddset(&sigs, SIGHUP);
1284 sigaddset(&sigs, SIGTERM);
1285 sigaddset(&sigs, SIGINT);
1286 sigaddset(&sigs, SIGPIPE);
1287 sigaddset(&sigs, SIGWINCH);
1288 pthread_sigmask(SIG_BLOCK, &sigs, NULL);
1289 if (option_console || option_verbose || option_remote)
1290 ast_register_verbose(console_verboser);
1291 /* Print a welcome message if desired */
1292 if (option_verbose || option_console) {
1293 ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2001 Linux Support Services, Inc.\n");
1294 ast_verbose( "Written by Mark Spencer <markster@linux-support.net>\n");
1295 ast_verbose( "=========================================================================\n");
1297 if (option_console && !option_verbose)
1298 ast_verbose("[ Booting...");
1299 signal(SIGURG, urg_handler);
1300 signal(SIGINT, __quit_handler);
1301 signal(SIGTERM, __quit_handler);
1302 signal(SIGHUP, hup_handler);
1303 signal(SIGPIPE, pipe_handler);
1304 if (set_priority(option_highpriority)) {
1305 printf(term_quit());
1308 if (init_logger()) {
1309 printf(term_quit());
1312 if (init_manager()) {
1313 printf(term_quit());
1316 if (ast_image_init()) {
1317 printf(term_quit());
1321 printf(term_quit());
1324 if (load_modules()) {
1325 printf(term_quit());
1328 if (init_framer()) {
1329 printf(term_quit());
1333 printf(term_quit());
1336 /* We might have the option of showing a console, but for now just
1338 if (option_console && !option_verbose)
1339 ast_verbose(" ]\n");
1340 if (option_verbose || option_console)
1341 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
1343 pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
1344 #ifdef __AST_DEBUG_MALLOC
1347 ast_cli_register(&astshutdownnow);
1348 ast_cli_register(&astshutdowngracefully);
1349 ast_cli_register(&astrestartnow);
1350 ast_cli_register(&astrestartgracefully);
1351 ast_cli_register(&astrestartwhenconvenient);
1352 ast_cli_register(&astshutdownwhenconvenient);
1353 ast_cli_register(&aborthalt);
1354 if (option_console) {
1355 /* Console stuff now... */
1356 /* Register our quit function */
1358 set_icon("Asterisk");
1359 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, mainpid);
1361 ast_cli_register(&quit);
1362 ast_cli_register(&astexit);
1363 consolethread = pthread_self();
1365 while ( (buf = (char *)el_gets(el, &num) ) != NULL && num != 0) {
1367 if (buf[strlen(buf)-1] == '\n')
1368 buf[strlen(buf)-1] = '\0';
1370 consolehandler((char *)buf);
1375 ast_select(0,NULL,NULL,NULL,NULL);