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 <asterisk/rtp.h>
31 #include <sys/resource.h>
36 #include <asterisk/io.h>
38 #include <sys/socket.h>
40 #include <sys/select.h>
45 #include "editline/histedit.h"
47 #include <asterisk/config.h>
49 #define AST_MAX_CONNECTS 128
57 int option_highpriority=0;
60 int option_initcrypto=0;
62 int option_dumpcore = 0;
63 int option_overrideconfig = 0;
66 static int ast_socket = -1; /* UNIX Socket for allowing remote control */
67 static int ast_consock = -1; /* UNIX Socket for controlling another asterisk */
70 int fd; /* File descriptor */
72 pthread_t t; /* Thread of handler */
75 static struct ast_atexit {
77 struct ast_atexit *next;
79 static ast_mutex_t atexitslock = AST_MUTEX_INITIALIZER;
81 time_t ast_startuptime;
82 time_t ast_lastreloadtime;
84 static History *el_hist = NULL;
85 static EditLine *el = NULL;
86 static char *remotehostname;
88 struct console consoles[AST_MAX_CONNECTS];
90 char defaultlanguage[MAX_LANGUAGE] = DEFAULT_LANGUAGE;
92 static int ast_el_add_history(char *);
93 static int ast_el_read_history(char *);
94 static int ast_el_write_history(char *);
96 char ast_config_AST_CONFIG_DIR[AST_CONFIG_MAX_PATH];
97 char ast_config_AST_CONFIG_FILE[AST_CONFIG_MAX_PATH];
98 char ast_config_AST_MODULE_DIR[AST_CONFIG_MAX_PATH];
99 char ast_config_AST_SPOOL_DIR[AST_CONFIG_MAX_PATH];
100 char ast_config_AST_VAR_DIR[AST_CONFIG_MAX_PATH];
101 char ast_config_AST_LOG_DIR[AST_CONFIG_MAX_PATH];
102 char ast_config_AST_AGI_DIR[AST_CONFIG_MAX_PATH];
103 char ast_config_AST_DB[AST_CONFIG_MAX_PATH];
104 char ast_config_AST_KEY_DIR[AST_CONFIG_MAX_PATH];
105 char ast_config_AST_PID[AST_CONFIG_MAX_PATH];
106 char ast_config_AST_SOCKET[AST_CONFIG_MAX_PATH];
107 char ast_config_AST_RUN_DIR[AST_CONFIG_MAX_PATH];
109 static char *_argv[256];
110 static int shuttingdown = 0;
111 static int restartnow = 0;
112 static pthread_t consolethread = (pthread_t) -1;
114 int ast_register_atexit(void (*func)(void))
117 struct ast_atexit *ae;
118 ast_unregister_atexit(func);
119 ae = malloc(sizeof(struct ast_atexit));
120 ast_mutex_lock(&atexitslock);
122 memset(ae, 0, sizeof(struct ast_atexit));
128 ast_mutex_unlock(&atexitslock);
132 void ast_unregister_atexit(void (*func)(void))
134 struct ast_atexit *ae, *prev = NULL;
135 ast_mutex_lock(&atexitslock);
138 if (ae->func == func) {
140 prev->next = ae->next;
148 ast_mutex_unlock(&atexitslock);
151 static int fdprint(int fd, const char *s)
153 return write(fd, s, strlen(s) + 1);
157 * write the string to all attached console clients
159 static void ast_network_puts(const char *string)
162 for (x=0;x<AST_MAX_CONNECTS; x++) {
163 if (consoles[x].fd > -1)
164 fdprint(consoles[x].p[1], string);
170 * write the string to the console, and all attached
173 void ast_console_puts(const char *string)
175 fputs(string, stdout);
177 ast_network_puts(string);
180 static void network_verboser(const char *s, int pos, int replace, int complete)
186 static pthread_t lthread;
188 static void *netconsole(void *vconsole)
190 struct console *con = vconsole;
197 if (gethostname(hostname, sizeof(hostname)))
198 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
199 snprintf(tmp, sizeof(tmp), "%s/%d/%s\n", hostname, mainpid, ASTERISK_VERSION);
200 fdprint(con->fd, tmp);
203 FD_SET(con->fd, &rfds);
204 FD_SET(con->p[0], &rfds);
208 res = ast_select(max + 1, &rfds, NULL, NULL, NULL);
210 ast_log(LOG_WARNING, "select returned < 0: %s\n", strerror(errno));
213 if (FD_ISSET(con->fd, &rfds)) {
214 res = read(con->fd, tmp, sizeof(tmp));
219 ast_cli_command(con->fd, tmp);
221 if (FD_ISSET(con->p[0], &rfds)) {
222 res = read(con->p[0], tmp, sizeof(tmp));
224 ast_log(LOG_ERROR, "read returned %d\n", res);
227 res = write(con->fd, tmp, res);
232 if (option_verbose > 2)
233 ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection disconnected\n");
242 static void *listener(void *unused)
244 struct sockaddr_un sun;
251 pthread_attr_init(&attr);
252 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
257 FD_SET(ast_socket, &fds);
258 s = ast_select(ast_socket + 1, &fds, NULL, NULL, NULL);
260 ast_log(LOG_WARNING, "Select retured error: %s\n", strerror(errno));
264 s = accept(ast_socket, (struct sockaddr *)&sun, &len);
266 ast_log(LOG_WARNING, "Accept retured %d: %s\n", s, strerror(errno));
268 for (x=0;x<AST_MAX_CONNECTS;x++) {
269 if (consoles[x].fd < 0) {
270 if (socketpair(AF_LOCAL, SOCK_STREAM, 0, consoles[x].p)) {
271 ast_log(LOG_ERROR, "Unable to create pipe: %s\n", strerror(errno));
273 fdprint(s, "Server failed to create pipe\n");
277 flags = fcntl(consoles[x].p[1], F_GETFL);
278 fcntl(consoles[x].p[1], F_SETFL, flags | O_NONBLOCK);
280 if (pthread_create(&consoles[x].t, &attr, netconsole, &consoles[x])) {
281 ast_log(LOG_ERROR, "Unable to spawn thread to handle connection\n");
283 fdprint(s, "Server failed to spawn thread\n");
289 if (x >= AST_MAX_CONNECTS) {
290 fdprint(s, "No more connections allowed\n");
291 ast_log(LOG_WARNING, "No more connections allowed\n");
293 } else if (consoles[x].fd > -1) {
294 if (option_verbose > 2)
295 ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection\n");
302 static int ast_makesocket(void)
304 struct sockaddr_un sun;
307 for (x=0;x<AST_MAX_CONNECTS;x++)
309 unlink((char *)ast_config_AST_SOCKET);
310 ast_socket = socket(PF_LOCAL, SOCK_STREAM, 0);
311 if (ast_socket < 0) {
312 ast_log(LOG_WARNING, "Unable to create control socket: %s\n", strerror(errno));
315 memset(&sun, 0, sizeof(sun));
316 sun.sun_family = AF_LOCAL;
317 strncpy(sun.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sun.sun_path)-1);
318 res = bind(ast_socket, (struct sockaddr *)&sun, sizeof(sun));
320 ast_log(LOG_WARNING, "Unable to bind socket to %s: %s\n", (char *)ast_config_AST_SOCKET, strerror(errno));
325 res = listen(ast_socket, 2);
327 ast_log(LOG_WARNING, "Unable to listen on socket %s: %s\n", (char *)ast_config_AST_SOCKET, strerror(errno));
332 ast_register_verbose(network_verboser);
333 pthread_create(<hread, NULL, listener, NULL);
337 static int ast_tryconnect(void)
339 struct sockaddr_un sun;
341 ast_consock = socket(PF_LOCAL, SOCK_STREAM, 0);
342 if (ast_consock < 0) {
343 ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
346 memset(&sun, 0, sizeof(sun));
347 sun.sun_family = AF_LOCAL;
348 strncpy(sun.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sun.sun_path)-1);
349 res = connect(ast_consock, (struct sockaddr *)&sun, sizeof(sun));
358 static void urg_handler(int num)
360 /* Called by soft_hangup to interrupt the select, read, or other
361 system call. We don't actually need to do anything though. */
362 /* Cannot EVER ast_log from within a signal handler */
364 printf("Urgent handler\n");
365 signal(num, urg_handler);
369 static void hup_handler(int num)
371 if (option_verbose > 1)
372 printf("Received HUP signal -- Reloading configs\n");
374 execvp(_argv[0], _argv);
375 /* XXX This could deadlock XXX */
379 static void child_handler(int sig)
381 /* Must not ever ast_log or ast_verbose within signal handler */
385 * Reap all dead children -- not just one
387 for (n = 0; wait4(-1, &status, WNOHANG, NULL) > 0; n++)
389 if (n == 0 && option_debug)
390 printf("Huh? Child handler, but nobody there?\n");
393 static void set_title(char *text)
395 /* Set an X-term or screen title */
396 if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
397 fprintf(stdout, "\033]2;%s\007", text);
400 static void set_icon(char *text)
402 if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
403 fprintf(stdout, "\033]1;%s\007", text);
406 static int set_priority(int pri)
408 struct sched_param sched;
409 memset(&sched, 0, sizeof(sched));
410 /* We set ourselves to a high priority, that we might pre-empt everything
411 else. If your PBX has heavy activity on it, this is a good thing. */
414 sched.sched_priority = 10;
415 if (sched_setscheduler(0, SCHED_RR, &sched)) {
416 ast_log(LOG_WARNING, "Unable to set high priority\n");
420 ast_verbose("Set to realtime thread\n");
422 sched.sched_priority = 0;
423 if (sched_setscheduler(0, SCHED_OTHER, &sched)) {
424 ast_log(LOG_WARNING, "Unable to set normal priority\n");
430 if (setpriority(PRIO_PROCESS, 0, -10) == -1) {
431 ast_log(LOG_WARNING, "Unable to set high priority\n");
435 ast_verbose("Set to high priority\n");
437 if (setpriority(PRIO_PROCESS, 0, 0) == -1) {
438 ast_log(LOG_WARNING, "Unable to set normal priority\n");
446 static void ast_run_atexits(void)
448 struct ast_atexit *ae;
449 ast_mutex_lock(&atexitslock);
456 ast_mutex_unlock(&atexitslock);
459 static void quit_handler(int num, int nice, int safeshutdown, int restart)
461 char filename[80] = "";
467 /* Begin shutdown routine, hanging up active channels */
468 ast_begin_shutdown(1);
469 if (option_verbose && option_console)
470 ast_verbose("Beginning asterisk %s....\n", restart ? "restart" : "shutdown");
474 /* Wait up to 15 seconds for all channels to go away */
477 if (!ast_active_channels())
481 /* Sleep 1/10 of a second */
486 ast_begin_shutdown(0);
487 if (option_verbose && option_console)
488 ast_verbose("Waiting for inactivity to perform %s...\n", restart ? "restart" : "halt");
490 if (!ast_active_channels())
499 if (option_verbose && option_console)
500 ast_verbose("Asterisk %s cancelled.\n", restart ? "restart" : "shutdown");
504 if (option_console || option_remote) {
506 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
507 if (strlen(filename))
508 ast_el_write_history(filename);
512 history_end(el_hist);
515 ast_verbose("Executing last minute cleanups\n");
518 if (option_verbose && option_console)
519 ast_verbose("Asterisk %s ending (%d).\n", ast_active_channels() ? "uncleanly" : "cleanly", num);
520 else if (option_debug)
521 ast_log(LOG_DEBUG, "Asterisk ending (%d).\n", num);
522 manager_event(EVENT_FLAG_SYSTEM, "Shutdown", "Shutdown: %s\r\nRestart: %s\r\n", ast_active_channels() ? "Uncleanly" : "Cleanly", restart ? "True" : "False");
523 if (ast_socket > -1) {
527 if (ast_consock > -1)
530 unlink((char *)ast_config_AST_SOCKET);
531 if (!option_remote) unlink((char *)ast_config_AST_PID);
534 if (option_verbose || option_console)
535 ast_verbose("Preparing for Asterisk restart...\n");
536 /* Mark all FD's for closing on exec */
537 for (x=3;x<32768;x++) {
538 fcntl(x, F_SETFD, FD_CLOEXEC);
540 if (option_verbose || option_console)
541 ast_verbose("Restarting Asterisk NOW...\n");
543 /* If there is a consolethread running send it a SIGHUP
544 so it can execvp, otherwise we can do it ourselves */
545 if (consolethread != (pthread_t) -1)
546 pthread_kill(consolethread, SIGHUP);
548 execvp(_argv[0], _argv);
554 static void __quit_handler(int num)
556 quit_handler(num, 0, 1, 0);
559 static const char *fix_header(char *outbuf, int maxout, const char *s, char *cmp)
562 if (!strncmp(s, cmp, strlen(cmp))) {
564 term_color(outbuf, cmp, COLOR_GRAY, 0, maxout);
570 static void console_verboser(const char *s, int pos, int replace, int complete)
574 /* Return to the beginning of the line */
576 fprintf(stdout, "\r");
577 if ((c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_4)) ||
578 (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_3)) ||
579 (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_2)) ||
580 (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_1)))
584 fputs(c + pos,stdout);
586 fputs(s + pos,stdout);
589 /* Wake up a select()ing console */
590 if (consolethread != (pthread_t) -1)
591 pthread_kill(consolethread, SIGURG);
594 static void consolehandler(char *s)
598 /* Called when readline data is available */
600 ast_el_add_history(s);
601 /* Give the console access to the shell */
603 /* The real handler for bang */
608 system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
610 ast_cli_command(STDOUT_FILENO, s);
612 fprintf(stdout, "\nUse \"quit\" to exit\n");
615 static int remoteconsolehandler(char *s)
618 /* Called when readline data is available */
620 ast_el_add_history(s);
621 /* Give the console access to the shell */
623 /* The real handler for bang */
628 system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
631 if ((strncasecmp(s, "quit", 4) == 0 || strncasecmp(s, "exit", 4) == 0) &&
632 (s[4] == '\0' || isspace(s[4]))) {
633 quit_handler(0, 0, 0, 0);
637 fprintf(stdout, "\nUse \"quit\" to exit\n");
642 static char quit_help[] =
644 " Exits Asterisk.\n";
646 static char abort_halt_help[] =
647 "Usage: abort shutdown\n"
648 " Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
649 " call operations.\n";
651 static char shutdown_now_help[] =
653 " Shuts down a running Asterisk immediately, hanging up all active calls .\n";
655 static char shutdown_gracefully_help[] =
656 "Usage: stop gracefully\n"
657 " Causes Asterisk to not accept new calls, and exit when all\n"
658 " active calls have terminated normally.\n";
660 static char shutdown_when_convenient_help[] =
661 "Usage: stop when convenient\n"
662 " Causes Asterisk to perform a shutdown when all active calls have ended.\n";
664 static char restart_now_help[] =
665 "Usage: restart now\n"
666 " Causes Asterisk to hangup all calls and exec() itself performing a cold.\n"
669 static char restart_gracefully_help[] =
670 "Usage: restart gracefully\n"
671 " Causes Asterisk to stop accepting new calls and exec() itself performing a cold.\n"
672 " restart when all active calls have ended.\n";
674 static char restart_when_convenient_help[] =
675 "Usage: restart when convenient\n"
676 " Causes Asterisk to perform a cold restart when all active calls have ended.\n";
678 static char bang_help[] =
679 "Usage: !<command>\n"
680 " Executes a given shell command\n";
683 static int handle_quit(int fd, int argc, char *argv[])
686 return RESULT_SHOWUSAGE;
687 quit_handler(0, 0, 1, 0);
688 return RESULT_SUCCESS;
692 static int no_more_quit(int fd, int argc, char *argv[])
695 return RESULT_SHOWUSAGE;
696 ast_cli(fd, "The QUIT and EXIT commands may no longer be used to shutdown the PBX.\n"
697 "Please use STOP NOW instead, if you wish to shutdown the PBX.\n");
698 return RESULT_SUCCESS;
701 static int handle_shutdown_now(int fd, int argc, char *argv[])
704 return RESULT_SHOWUSAGE;
705 quit_handler(0, 0 /* Not nice */, 1 /* safely */, 0 /* not restart */);
706 return RESULT_SUCCESS;
709 static int handle_shutdown_gracefully(int fd, int argc, char *argv[])
712 return RESULT_SHOWUSAGE;
713 quit_handler(0, 1 /* nicely */, 1 /* safely */, 0 /* no restart */);
714 return RESULT_SUCCESS;
717 static int handle_shutdown_when_convenient(int fd, int argc, char *argv[])
720 return RESULT_SHOWUSAGE;
721 quit_handler(0, 2 /* really nicely */, 1 /* safely */, 0 /* don't restart */);
722 return RESULT_SUCCESS;
725 static int handle_restart_now(int fd, int argc, char *argv[])
728 return RESULT_SHOWUSAGE;
729 quit_handler(0, 0 /* not nicely */, 1 /* safely */, 1 /* restart */);
730 return RESULT_SUCCESS;
733 static int handle_restart_gracefully(int fd, int argc, char *argv[])
736 return RESULT_SHOWUSAGE;
737 quit_handler(0, 1 /* nicely */, 1 /* safely */, 1 /* restart */);
738 return RESULT_SUCCESS;
741 static int handle_restart_when_convenient(int fd, int argc, char *argv[])
744 return RESULT_SHOWUSAGE;
745 quit_handler(0, 2 /* really nicely */, 1 /* safely */, 1 /* restart */);
746 return RESULT_SUCCESS;
749 static int handle_abort_halt(int fd, int argc, char *argv[])
752 return RESULT_SHOWUSAGE;
753 ast_cancel_shutdown();
755 return RESULT_SUCCESS;
758 static int handle_bang(int fd, int argc, char *argv[])
760 return RESULT_SUCCESS;
763 #define ASTERISK_PROMPT "*CLI> "
765 #define ASTERISK_PROMPT2 "%s*CLI> "
767 static struct ast_cli_entry aborthalt = { { "abort", "halt", NULL }, handle_abort_halt, "Cancel a running halt", abort_halt_help };
769 static struct ast_cli_entry quit = { { "quit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
770 static struct ast_cli_entry astexit = { { "exit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
772 static struct ast_cli_entry astshutdownnow = { { "stop", "now", NULL }, handle_shutdown_now, "Shut down Asterisk immediately", shutdown_now_help };
773 static struct ast_cli_entry astshutdowngracefully = { { "stop", "gracefully", NULL }, handle_shutdown_gracefully, "Gracefully shut down Asterisk", shutdown_gracefully_help };
774 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 };
775 static struct ast_cli_entry astrestartnow = { { "restart", "now", NULL }, handle_restart_now, "Restart Asterisk immediately", restart_now_help };
776 static struct ast_cli_entry astrestartgracefully = { { "restart", "gracefully", NULL }, handle_restart_gracefully, "Restart Asterisk gracefully", restart_gracefully_help };
777 static struct ast_cli_entry astrestartwhenconvenient= { { "restart", "when", "convenient", NULL }, handle_restart_when_convenient, "Restart Asterisk at empty call volume", restart_when_convenient_help };
778 static struct ast_cli_entry astbang = { { "!", NULL }, handle_bang, "Execute a shell command", bang_help };
780 static int ast_el_read_char(EditLine *el, char *cp)
791 FD_SET(ast_consock, &rfds);
794 FD_SET(STDIN_FILENO, &rfds);
795 if (STDIN_FILENO > max)
798 res = ast_select(max+1, &rfds, NULL, NULL, NULL);
802 ast_log(LOG_ERROR, "select failed: %s\n", strerror(errno));
806 if (FD_ISSET(STDIN_FILENO, &rfds)) {
807 num_read = read(STDIN_FILENO, cp, 1);
813 if (FD_ISSET(ast_consock, &rfds)) {
814 res = read(ast_consock, buf, sizeof(buf) - 1);
815 /* if the remote side disappears exit */
817 fprintf(stderr, "\nDisconnected from Asterisk server\n");
818 quit_handler(0, 0, 0, 0);
823 if (!option_exec && !lastpos)
824 write(STDOUT_FILENO, "\r", 1);
825 write(STDOUT_FILENO, buf, res);
826 if ((buf[res-1] == '\n') || (buf[res-2] == '\n')) {
839 static char *cli_prompt(EditLine *el)
841 static char prompt[80];
844 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT2, remotehostname);
846 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT);
851 static char **ast_el_strtoarr(char *buf)
853 char **match_list = NULL, *retstr;
854 size_t match_list_len;
858 while ( (retstr = strsep(&buf, " ")) != NULL) {
860 if (matches + 1 >= match_list_len) {
861 match_list_len <<= 1;
862 match_list = realloc(match_list, match_list_len * sizeof(char *));
865 match_list[matches++] = retstr;
869 return (char **) NULL;
871 if (matches>= match_list_len)
872 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
874 match_list[matches] = (char *) NULL;
879 static int ast_el_sort_compare(const void *i1, const void *i2)
883 s1 = ((char **)i1)[0];
884 s2 = ((char **)i2)[0];
886 return strcasecmp(s1, s2);
889 static int ast_cli_display_match_list(char **matches, int len, int max)
891 int i, idx, limit, count;
893 int numoutput = 0, numoutputline = 0;
895 screenwidth = ast_get_termcols(STDOUT_FILENO);
897 /* find out how many entries can be put on one line, with two spaces between strings */
898 limit = screenwidth / (max + 2);
902 /* how many lines of output */
904 if (count * limit < len)
909 qsort(&matches[0], (size_t)(len + 1), sizeof(char *), ast_el_sort_compare);
911 for (; count > 0; count--) {
913 for (i=0; i < limit && matches[idx]; i++, idx++) {
915 /* Don't print dupes */
916 if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
921 numoutput++; numoutputline++;
922 fprintf(stdout, "%-*s ", max, matches[idx]);
924 if (numoutputline > 0)
925 fprintf(stdout, "\n");
932 static char *cli_complete(EditLine *el, int ch)
938 int retval = CC_ERROR;
942 LineInfo *lf = (LineInfo *)el_line(el);
944 *(char *)lf->cursor = '\0';
945 ptr = (char *)lf->cursor;
947 while (ptr > lf->buffer) {
956 len = lf->cursor - ptr;
959 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr);
960 fdprint(ast_consock, buf);
961 res = read(ast_consock, buf, sizeof(buf));
963 nummatches = atoi(buf);
965 if (nummatches > 0) {
966 snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr);
967 fdprint(ast_consock, buf);
968 res = read(ast_consock, buf, sizeof(buf));
971 matches = ast_el_strtoarr(buf);
973 matches = (char **) NULL;
978 nummatches = ast_cli_generatornummatches((char *)lf->buffer,ptr);
979 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
984 int matches_num, maxlen, match_len;
986 if (matches[0][0] != '\0') {
987 el_deletestr(el, (int) len);
988 el_insertstr(el, matches[0]);
992 if (nummatches == 1) {
993 /* Found an exact match */
994 el_insertstr(el, " ");
997 /* Must be more than one match */
998 for (i=1, maxlen=0; matches[i]; i++) {
999 match_len = strlen(matches[i]);
1000 if (match_len > maxlen)
1003 matches_num = i - 1;
1004 if (matches_num >1) {
1005 fprintf(stdout, "\n");
1006 ast_cli_display_match_list(matches, nummatches, maxlen);
1007 retval = CC_REDISPLAY;
1009 el_insertstr(el," ");
1010 retval = CC_REFRESH;
1016 return (char *)retval;
1019 static int ast_el_initialize(void)
1025 if (el_hist != NULL)
1026 history_end(el_hist);
1028 el = el_init("asterisk", stdin, stdout, stderr);
1029 el_set(el, EL_PROMPT, cli_prompt);
1031 el_set(el, EL_EDITMODE, 1);
1032 el_set(el, EL_EDITOR, "emacs");
1033 el_hist = history_init();
1034 if (!el || !el_hist)
1037 /* setup history with 100 entries */
1038 history(el_hist, &ev, H_SETSIZE, 100);
1040 el_set(el, EL_HIST, history, el_hist);
1042 el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
1043 /* Bind <tab> to command completion */
1044 el_set(el, EL_BIND, "^I", "ed-complete", NULL);
1045 /* Bind ? to command completion */
1046 el_set(el, EL_BIND, "?", "ed-complete", NULL);
1051 static int ast_el_add_history(char *buf)
1055 if (el_hist == NULL || el == NULL)
1056 ast_el_initialize();
1057 if (strlen(buf) > 256)
1059 return (history(el_hist, &ev, H_ENTER, buf));
1062 static int ast_el_write_history(char *filename)
1066 if (el_hist == NULL || el == NULL)
1067 ast_el_initialize();
1069 return (history(el_hist, &ev, H_SAVE, filename));
1072 static int ast_el_read_history(char *filename)
1078 if (el_hist == NULL || el == NULL)
1079 ast_el_initialize();
1081 if ((f = fopen(filename, "r")) == NULL)
1085 fgets(buf, sizeof(buf), f);
1086 if (!strcmp(buf, "_HiStOrY_V2_\n"))
1088 if ((ret = ast_el_add_history(buf)) == -1)
1096 static void ast_remotecontrol(char * data)
1100 char filename[80] = "";
1111 read(ast_consock, buf, sizeof(buf));
1113 write(ast_consock, data, strlen(data) + 1);
1115 hostname = strsep(&stringp, "/");
1116 cpid = strsep(&stringp, "/");
1117 version = strsep(&stringp, "\n");
1119 version = "<Version Unknown>";
1121 strsep(&stringp, ".");
1126 snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
1127 fdprint(ast_consock, tmp);
1128 ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
1129 remotehostname = hostname;
1131 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1132 if (el_hist == NULL || el == NULL)
1133 ast_el_initialize();
1135 el_set(el, EL_GETCFN, ast_el_read_char);
1137 if (strlen(filename))
1138 ast_el_read_history(filename);
1140 ast_cli_register(&quit);
1141 ast_cli_register(&astexit);
1143 ast_cli_register(&astshutdown);
1145 if (option_exec && data) { /* hack to print output then exit if asterisk -rx is used */
1147 ast_el_read_char(el, &tempchar);
1151 ebuf = (char *)el_gets(el, &num);
1153 if (ebuf && strlen(ebuf)) {
1154 if (ebuf[strlen(ebuf)-1] == '\n')
1155 ebuf[strlen(ebuf)-1] = '\0';
1156 if (!remoteconsolehandler(ebuf)) {
1157 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
1159 ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
1165 printf("\nDisconnected from Asterisk server\n");
1168 static int show_cli_help(void) {
1169 printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 2000-2002, Digium.\n");
1170 printf("Usage: asterisk [OPTIONS]\n");
1171 printf("Valid Options:\n");
1172 printf(" -h This help screen\n");
1173 printf(" -r Connect to Asterisk on this machine\n");
1174 printf(" -f Do not fork\n");
1175 printf(" -n Disable console colorization\n");
1176 printf(" -p Run as pseudo-realtime thread\n");
1177 printf(" -v Increase verbosity (multiple v's = more verbose)\n");
1178 printf(" -q Quiet mode (supress output)\n");
1179 printf(" -g Dump core in case of a crash\n");
1180 printf(" -x <cmd> Execute command <cmd> (only valid with -r)\n");
1181 printf(" -i Initializie crypto keys at startup\n");
1182 printf(" -c Provide console CLI\n");
1183 printf(" -d Enable extra debugging\n");
1188 static void ast_readconfig(void) {
1189 struct ast_config *cfg;
1190 struct ast_variable *v;
1191 char *config = ASTCONFPATH;
1193 if (option_overrideconfig == 1) {
1194 cfg = ast_load((char *)ast_config_AST_CONFIG_FILE);
1196 cfg = ast_load(config);
1199 /* init with buildtime config */
1200 strncpy((char *)ast_config_AST_CONFIG_DIR,AST_CONFIG_DIR,sizeof(ast_config_AST_CONFIG_DIR)-1);
1201 strncpy((char *)ast_config_AST_SPOOL_DIR,AST_SPOOL_DIR,sizeof(ast_config_AST_SPOOL_DIR)-1);
1202 strncpy((char *)ast_config_AST_MODULE_DIR,AST_MODULE_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1203 strncpy((char *)ast_config_AST_VAR_DIR,AST_VAR_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1204 strncpy((char *)ast_config_AST_LOG_DIR,AST_LOG_DIR,sizeof(ast_config_AST_LOG_DIR)-1);
1205 strncpy((char *)ast_config_AST_AGI_DIR,AST_AGI_DIR,sizeof(ast_config_AST_AGI_DIR)-1);
1206 strncpy((char *)ast_config_AST_DB,AST_DB,sizeof(ast_config_AST_DB)-1);
1207 strncpy((char *)ast_config_AST_KEY_DIR,AST_KEY_DIR,sizeof(ast_config_AST_KEY_DIR)-1);
1208 strncpy((char *)ast_config_AST_PID,AST_PID,sizeof(ast_config_AST_PID)-1);
1209 strncpy((char *)ast_config_AST_SOCKET,AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1);
1210 strncpy((char *)ast_config_AST_RUN_DIR,AST_RUN_DIR,sizeof(ast_config_AST_RUN_DIR)-1);
1212 /* no asterisk.conf? no problem, use buildtime config! */
1216 v = ast_variable_browse(cfg, "directories");
1218 if (!strcasecmp(v->name, "astetcdir")) {
1219 strncpy((char *)ast_config_AST_CONFIG_DIR,v->value,sizeof(ast_config_AST_CONFIG_DIR)-1);
1220 } else if (!strcasecmp(v->name, "astspooldir")) {
1221 strncpy((char *)ast_config_AST_SPOOL_DIR,v->value,sizeof(ast_config_AST_SPOOL_DIR)-1);
1222 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1223 strncpy((char *)ast_config_AST_VAR_DIR,v->value,sizeof(ast_config_AST_VAR_DIR)-1);
1224 snprintf((char *)ast_config_AST_DB,sizeof(ast_config_AST_DB)-1,"%s/%s",v->value,"astdb");
1225 } else if (!strcasecmp(v->name, "astlogdir")) {
1226 strncpy((char *)ast_config_AST_LOG_DIR,v->value,sizeof(ast_config_AST_LOG_DIR)-1);
1227 } else if (!strcasecmp(v->name, "astagidir")) {
1228 strncpy((char *)ast_config_AST_AGI_DIR,v->value,sizeof(ast_config_AST_AGI_DIR)-1);
1229 } else if (!strcasecmp(v->name, "astrundir")) {
1230 snprintf((char *)ast_config_AST_PID,sizeof(ast_config_AST_PID)-1,"%s/%s",v->value,"asterisk.pid");
1231 snprintf((char *)ast_config_AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1,"%s/%s",v->value,"asterisk.ctl");
1232 strncpy((char *)ast_config_AST_RUN_DIR,v->value,sizeof(ast_config_AST_RUN_DIR)-1);
1233 } else if (!strcasecmp(v->name, "astmoddir")) {
1234 strncpy((char *)ast_config_AST_MODULE_DIR,v->value,sizeof(ast_config_AST_MODULE_DIR)-1);
1241 int main(int argc, char *argv[])
1244 char filename[80] = "";
1254 /* Remember original args for restart */
1255 if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1256 fprintf(stderr, "Truncating argument size to %d\n", sizeof(_argv) / sizeof(_argv[0]) - 1);
1257 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1259 for (x=0;x<argc;x++)
1263 if (gethostname(hostname, sizeof(hostname)))
1264 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
1271 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1272 /* Check if we're root */
1275 ast_log(LOG_ERROR, "Must be run as root\n");
1279 /* Check for options */
1280 while((c=getopt(argc, argv, "hfdvqprgcinx:C:")) != -1) {
1301 option_highpriority++;
1315 strncpy((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE));
1316 option_overrideconfig++;
1319 option_initcrypto++;
1332 if (option_dumpcore) {
1334 memset(&l, 0, sizeof(l));
1335 l.rlim_cur = RLIM_INFINITY;
1336 l.rlim_max = RLIM_INFINITY;
1337 if (setrlimit(RLIMIT_CORE, &l)) {
1338 ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
1345 if (option_console && !option_verbose)
1346 ast_verbose("[ Reading Master Configuration ]");
1349 if (option_console) {
1350 if (el_hist == NULL || el == NULL)
1351 ast_el_initialize();
1353 if (strlen(filename))
1354 ast_el_read_history(filename);
1357 if (ast_tryconnect()) {
1358 /* One is already running */
1359 if (option_remote) {
1361 ast_remotecontrol(xarg);
1362 quit_handler(0, 0, 0, 0);
1365 printf(term_quit());
1366 ast_register_verbose(console_verboser);
1367 ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2004 Digium.\n");
1368 ast_verbose( "Written by Mark Spencer <markster@digium.com>\n");
1369 ast_verbose( "=========================================================================\n");
1370 ast_remotecontrol(NULL);
1371 quit_handler(0, 0, 0, 0);
1374 ast_log(LOG_ERROR, "Asterisk already running on %s. Use 'asterisk -r' to connect.\n", (char *)ast_config_AST_SOCKET);
1375 printf(term_quit());
1378 } else if (option_remote || option_exec) {
1379 ast_log(LOG_ERROR, "Unable to connect to remote asterisk\n");
1380 printf(term_quit());
1383 /* Blindly write pid file since we couldn't connect */
1384 unlink((char *)ast_config_AST_PID);
1385 f = fopen((char *)ast_config_AST_PID, "w");
1387 fprintf(f, "%d\n", getpid());
1390 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1392 if (!option_verbose && !option_debug && !option_nofork && !option_console) {
1394 /* Blindly re-write pid file since we are forking */
1395 unlink((char *)ast_config_AST_PID);
1396 f = fopen((char *)ast_config_AST_PID, "w");
1398 fprintf(f, "%d\n", getpid());
1401 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1406 sigaddset(&sigs, SIGHUP);
1407 sigaddset(&sigs, SIGTERM);
1408 sigaddset(&sigs, SIGINT);
1409 sigaddset(&sigs, SIGPIPE);
1410 sigaddset(&sigs, SIGWINCH);
1411 pthread_sigmask(SIG_BLOCK, &sigs, NULL);
1412 if (option_console || option_verbose || option_remote)
1413 ast_register_verbose(console_verboser);
1414 /* Print a welcome message if desired */
1415 if (option_verbose || option_console) {
1416 ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2001 Linux Support Services, Inc.\n");
1417 ast_verbose( "Written by Mark Spencer <markster@linux-support.net>\n");
1418 ast_verbose( "=========================================================================\n");
1420 if (option_console && !option_verbose)
1421 ast_verbose("[ Booting...");
1423 signal(SIGURG, urg_handler);
1424 signal(SIGINT, __quit_handler);
1425 signal(SIGTERM, __quit_handler);
1426 signal(SIGHUP, hup_handler);
1427 signal(SIGCHLD, child_handler);
1428 signal(SIGPIPE, SIG_IGN);
1430 if (set_priority(option_highpriority)) {
1431 printf(term_quit());
1434 if (init_logger()) {
1435 printf(term_quit());
1438 if (init_manager()) {
1439 printf(term_quit());
1443 if (ast_image_init()) {
1444 printf(term_quit());
1448 printf(term_quit());
1451 if (load_modules()) {
1452 printf(term_quit());
1455 if (init_framer()) {
1456 printf(term_quit());
1460 printf(term_quit());
1463 if (ast_enum_init()) {
1464 printf(term_quit());
1467 /* We might have the option of showing a console, but for now just
1469 if (option_console && !option_verbose)
1470 ast_verbose(" ]\n");
1471 if (option_verbose || option_console)
1472 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
1474 pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
1475 #ifdef __AST_DEBUG_MALLOC
1478 time(&ast_startuptime);
1479 ast_cli_register(&astshutdownnow);
1480 ast_cli_register(&astshutdowngracefully);
1481 ast_cli_register(&astrestartnow);
1482 ast_cli_register(&astrestartgracefully);
1483 ast_cli_register(&astrestartwhenconvenient);
1484 ast_cli_register(&astshutdownwhenconvenient);
1485 ast_cli_register(&aborthalt);
1486 ast_cli_register(&astbang);
1488 consolethread = pthread_self();
1489 if (option_console) {
1490 /* Console stuff now... */
1491 /* Register our quit function */
1493 set_icon("Asterisk");
1494 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, mainpid);
1496 ast_cli_register(&quit);
1497 ast_cli_register(&astexit);
1500 buf = (char *)el_gets(el, &num);
1502 if (buf[strlen(buf)-1] == '\n')
1503 buf[strlen(buf)-1] = '\0';
1505 consolehandler((char *)buf);
1508 ast_cli(STDOUT_FILENO, "\nUse EXIT or QUIT to exit the asterisk console\n");
1510 ast_cli(STDOUT_FILENO, "\nUse STOP NOW to shutdown Asterisk\n");
1516 ast_select(0,NULL,NULL,NULL,NULL);