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>
37 #include <asterisk/lock.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 = AST_PTHREADT_NULL;
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);
261 ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
265 s = accept(ast_socket, (struct sockaddr *)&sun, &len);
268 ast_log(LOG_WARNING, "Accept returned %d: %s\n", s, strerror(errno));
270 for (x=0;x<AST_MAX_CONNECTS;x++) {
271 if (consoles[x].fd < 0) {
272 if (socketpair(AF_LOCAL, SOCK_STREAM, 0, consoles[x].p)) {
273 ast_log(LOG_ERROR, "Unable to create pipe: %s\n", strerror(errno));
275 fdprint(s, "Server failed to create pipe\n");
279 flags = fcntl(consoles[x].p[1], F_GETFL);
280 fcntl(consoles[x].p[1], F_SETFL, flags | O_NONBLOCK);
282 if (pthread_create(&consoles[x].t, &attr, netconsole, &consoles[x])) {
283 ast_log(LOG_ERROR, "Unable to spawn thread to handle connection\n");
285 fdprint(s, "Server failed to spawn thread\n");
291 if (x >= AST_MAX_CONNECTS) {
292 fdprint(s, "No more connections allowed\n");
293 ast_log(LOG_WARNING, "No more connections allowed\n");
295 } else if (consoles[x].fd > -1) {
296 if (option_verbose > 2)
297 ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection\n");
304 static int ast_makesocket(void)
306 struct sockaddr_un sun;
309 for (x=0;x<AST_MAX_CONNECTS;x++)
311 unlink((char *)ast_config_AST_SOCKET);
312 ast_socket = socket(PF_LOCAL, SOCK_STREAM, 0);
313 if (ast_socket < 0) {
314 ast_log(LOG_WARNING, "Unable to create control socket: %s\n", strerror(errno));
317 memset(&sun, 0, sizeof(sun));
318 sun.sun_family = AF_LOCAL;
319 strncpy(sun.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sun.sun_path)-1);
320 res = bind(ast_socket, (struct sockaddr *)&sun, sizeof(sun));
322 ast_log(LOG_WARNING, "Unable to bind socket to %s: %s\n", (char *)ast_config_AST_SOCKET, strerror(errno));
327 res = listen(ast_socket, 2);
329 ast_log(LOG_WARNING, "Unable to listen on socket %s: %s\n", (char *)ast_config_AST_SOCKET, strerror(errno));
334 ast_register_verbose(network_verboser);
335 pthread_create(<hread, NULL, listener, NULL);
339 static int ast_tryconnect(void)
341 struct sockaddr_un sun;
343 ast_consock = socket(PF_LOCAL, SOCK_STREAM, 0);
344 if (ast_consock < 0) {
345 ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
348 memset(&sun, 0, sizeof(sun));
349 sun.sun_family = AF_LOCAL;
350 strncpy(sun.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sun.sun_path)-1);
351 res = connect(ast_consock, (struct sockaddr *)&sun, sizeof(sun));
360 static void urg_handler(int num)
362 /* Called by soft_hangup to interrupt the select, read, or other
363 system call. We don't actually need to do anything though. */
364 /* Cannot EVER ast_log from within a signal handler */
366 printf("Urgent handler\n");
367 signal(num, urg_handler);
371 static void hup_handler(int num)
373 if (option_verbose > 1)
374 printf("Received HUP signal -- Reloading configs\n");
376 execvp(_argv[0], _argv);
377 /* XXX This could deadlock XXX */
381 static void child_handler(int sig)
383 /* Must not ever ast_log or ast_verbose within signal handler */
387 * Reap all dead children -- not just one
389 for (n = 0; wait4(-1, &status, WNOHANG, NULL) > 0; n++)
391 if (n == 0 && option_debug)
392 printf("Huh? Child handler, but nobody there?\n");
395 static void set_title(char *text)
397 /* Set an X-term or screen title */
398 if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
399 fprintf(stdout, "\033]2;%s\007", text);
402 static void set_icon(char *text)
404 if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
405 fprintf(stdout, "\033]1;%s\007", text);
408 static int set_priority(int pri)
410 struct sched_param sched;
411 memset(&sched, 0, sizeof(sched));
412 /* We set ourselves to a high priority, that we might pre-empt everything
413 else. If your PBX has heavy activity on it, this is a good thing. */
416 sched.sched_priority = 10;
417 if (sched_setscheduler(0, SCHED_RR, &sched)) {
418 ast_log(LOG_WARNING, "Unable to set high priority\n");
422 ast_verbose("Set to realtime thread\n");
424 sched.sched_priority = 0;
425 if (sched_setscheduler(0, SCHED_OTHER, &sched)) {
426 ast_log(LOG_WARNING, "Unable to set normal priority\n");
432 if (setpriority(PRIO_PROCESS, 0, -10) == -1) {
433 ast_log(LOG_WARNING, "Unable to set high priority\n");
437 ast_verbose("Set to high priority\n");
439 if (setpriority(PRIO_PROCESS, 0, 0) == -1) {
440 ast_log(LOG_WARNING, "Unable to set normal priority\n");
448 static void ast_run_atexits(void)
450 struct ast_atexit *ae;
451 ast_mutex_lock(&atexitslock);
458 ast_mutex_unlock(&atexitslock);
461 static void quit_handler(int num, int nice, int safeshutdown, int restart)
463 char filename[80] = "";
469 /* Begin shutdown routine, hanging up active channels */
470 ast_begin_shutdown(1);
471 if (option_verbose && option_console)
472 ast_verbose("Beginning asterisk %s....\n", restart ? "restart" : "shutdown");
476 /* Wait up to 15 seconds for all channels to go away */
479 if (!ast_active_channels())
483 /* Sleep 1/10 of a second */
488 ast_begin_shutdown(0);
489 if (option_verbose && option_console)
490 ast_verbose("Waiting for inactivity to perform %s...\n", restart ? "restart" : "halt");
492 if (!ast_active_channels())
501 if (option_verbose && option_console)
502 ast_verbose("Asterisk %s cancelled.\n", restart ? "restart" : "shutdown");
506 if (option_console || option_remote) {
508 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
509 if (strlen(filename))
510 ast_el_write_history(filename);
514 history_end(el_hist);
517 ast_verbose("Executing last minute cleanups\n");
520 if (option_verbose && option_console)
521 ast_verbose("Asterisk %s ending (%d).\n", ast_active_channels() ? "uncleanly" : "cleanly", num);
522 else if (option_debug)
523 ast_log(LOG_DEBUG, "Asterisk ending (%d).\n", num);
524 manager_event(EVENT_FLAG_SYSTEM, "Shutdown", "Shutdown: %s\r\nRestart: %s\r\n", ast_active_channels() ? "Uncleanly" : "Cleanly", restart ? "True" : "False");
525 if (ast_socket > -1) {
529 if (ast_consock > -1)
532 unlink((char *)ast_config_AST_SOCKET);
533 if (!option_remote) unlink((char *)ast_config_AST_PID);
536 if (option_verbose || option_console)
537 ast_verbose("Preparing for Asterisk restart...\n");
538 /* Mark all FD's for closing on exec */
539 for (x=3;x<32768;x++) {
540 fcntl(x, F_SETFD, FD_CLOEXEC);
542 if (option_verbose || option_console)
543 ast_verbose("Restarting Asterisk NOW...\n");
545 /* If there is a consolethread running send it a SIGHUP
546 so it can execvp, otherwise we can do it ourselves */
547 if (consolethread != AST_PTHREADT_NULL) {
548 pthread_kill(consolethread, SIGHUP);
549 /* Give the signal handler some time to complete */
552 execvp(_argv[0], _argv);
558 static void __quit_handler(int num)
560 quit_handler(num, 0, 1, 0);
563 static const char *fix_header(char *outbuf, int maxout, const char *s, char *cmp)
566 if (!strncmp(s, cmp, strlen(cmp))) {
568 term_color(outbuf, cmp, COLOR_GRAY, 0, maxout);
574 static void console_verboser(const char *s, int pos, int replace, int complete)
578 /* Return to the beginning of the line */
580 fprintf(stdout, "\r");
581 if ((c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_4)) ||
582 (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_3)) ||
583 (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_2)) ||
584 (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_1)))
588 fputs(c + pos,stdout);
590 fputs(s + pos,stdout);
593 /* Wake up a select()ing console */
594 if (option_console && consolethread != AST_PTHREADT_NULL)
595 pthread_kill(consolethread, SIGURG);
598 static void consolehandler(char *s)
602 /* Called when readline data is available */
604 ast_el_add_history(s);
605 /* Give the console access to the shell */
607 /* The real handler for bang */
612 system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
614 ast_cli_command(STDOUT_FILENO, s);
616 fprintf(stdout, "\nUse \"quit\" to exit\n");
619 static int remoteconsolehandler(char *s)
622 /* Called when readline data is available */
624 ast_el_add_history(s);
625 /* Give the console access to the shell */
627 /* The real handler for bang */
632 system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
635 if ((strncasecmp(s, "quit", 4) == 0 || strncasecmp(s, "exit", 4) == 0) &&
636 (s[4] == '\0' || isspace(s[4]))) {
637 quit_handler(0, 0, 0, 0);
641 fprintf(stdout, "\nUse \"quit\" to exit\n");
646 static char quit_help[] =
648 " Exits Asterisk.\n";
650 static char abort_halt_help[] =
651 "Usage: abort shutdown\n"
652 " Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
653 " call operations.\n";
655 static char shutdown_now_help[] =
657 " Shuts down a running Asterisk immediately, hanging up all active calls .\n";
659 static char shutdown_gracefully_help[] =
660 "Usage: stop gracefully\n"
661 " Causes Asterisk to not accept new calls, and exit when all\n"
662 " active calls have terminated normally.\n";
664 static char shutdown_when_convenient_help[] =
665 "Usage: stop when convenient\n"
666 " Causes Asterisk to perform a shutdown when all active calls have ended.\n";
668 static char restart_now_help[] =
669 "Usage: restart now\n"
670 " Causes Asterisk to hangup all calls and exec() itself performing a cold.\n"
673 static char restart_gracefully_help[] =
674 "Usage: restart gracefully\n"
675 " Causes Asterisk to stop accepting new calls and exec() itself performing a cold.\n"
676 " restart when all active calls have ended.\n";
678 static char restart_when_convenient_help[] =
679 "Usage: restart when convenient\n"
680 " Causes Asterisk to perform a cold restart when all active calls have ended.\n";
682 static char bang_help[] =
683 "Usage: !<command>\n"
684 " Executes a given shell command\n";
687 static int handle_quit(int fd, int argc, char *argv[])
690 return RESULT_SHOWUSAGE;
691 quit_handler(0, 0, 1, 0);
692 return RESULT_SUCCESS;
696 static int no_more_quit(int fd, int argc, char *argv[])
699 return RESULT_SHOWUSAGE;
700 ast_cli(fd, "The QUIT and EXIT commands may no longer be used to shutdown the PBX.\n"
701 "Please use STOP NOW instead, if you wish to shutdown the PBX.\n");
702 return RESULT_SUCCESS;
705 static int handle_shutdown_now(int fd, int argc, char *argv[])
708 return RESULT_SHOWUSAGE;
709 quit_handler(0, 0 /* Not nice */, 1 /* safely */, 0 /* not restart */);
710 return RESULT_SUCCESS;
713 static int handle_shutdown_gracefully(int fd, int argc, char *argv[])
716 return RESULT_SHOWUSAGE;
717 quit_handler(0, 1 /* nicely */, 1 /* safely */, 0 /* no restart */);
718 return RESULT_SUCCESS;
721 static int handle_shutdown_when_convenient(int fd, int argc, char *argv[])
724 return RESULT_SHOWUSAGE;
725 quit_handler(0, 2 /* really nicely */, 1 /* safely */, 0 /* don't restart */);
726 return RESULT_SUCCESS;
729 static int handle_restart_now(int fd, int argc, char *argv[])
732 return RESULT_SHOWUSAGE;
733 quit_handler(0, 0 /* not nicely */, 1 /* safely */, 1 /* restart */);
734 return RESULT_SUCCESS;
737 static int handle_restart_gracefully(int fd, int argc, char *argv[])
740 return RESULT_SHOWUSAGE;
741 quit_handler(0, 1 /* nicely */, 1 /* safely */, 1 /* restart */);
742 return RESULT_SUCCESS;
745 static int handle_restart_when_convenient(int fd, int argc, char *argv[])
748 return RESULT_SHOWUSAGE;
749 quit_handler(0, 2 /* really nicely */, 1 /* safely */, 1 /* restart */);
750 return RESULT_SUCCESS;
753 static int handle_abort_halt(int fd, int argc, char *argv[])
756 return RESULT_SHOWUSAGE;
757 ast_cancel_shutdown();
759 return RESULT_SUCCESS;
762 static int handle_bang(int fd, int argc, char *argv[])
764 return RESULT_SUCCESS;
767 #define ASTERISK_PROMPT "*CLI> "
769 #define ASTERISK_PROMPT2 "%s*CLI> "
771 static struct ast_cli_entry aborthalt = { { "abort", "halt", NULL }, handle_abort_halt, "Cancel a running halt", abort_halt_help };
773 static struct ast_cli_entry quit = { { "quit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
774 static struct ast_cli_entry astexit = { { "exit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
776 static struct ast_cli_entry astshutdownnow = { { "stop", "now", NULL }, handle_shutdown_now, "Shut down Asterisk immediately", shutdown_now_help };
777 static struct ast_cli_entry astshutdowngracefully = { { "stop", "gracefully", NULL }, handle_shutdown_gracefully, "Gracefully shut down Asterisk", shutdown_gracefully_help };
778 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 };
779 static struct ast_cli_entry astrestartnow = { { "restart", "now", NULL }, handle_restart_now, "Restart Asterisk immediately", restart_now_help };
780 static struct ast_cli_entry astrestartgracefully = { { "restart", "gracefully", NULL }, handle_restart_gracefully, "Restart Asterisk gracefully", restart_gracefully_help };
781 static struct ast_cli_entry astrestartwhenconvenient= { { "restart", "when", "convenient", NULL }, handle_restart_when_convenient, "Restart Asterisk at empty call volume", restart_when_convenient_help };
782 static struct ast_cli_entry astbang = { { "!", NULL }, handle_bang, "Execute a shell command", bang_help };
784 static int ast_el_read_char(EditLine *el, char *cp)
795 FD_SET(ast_consock, &rfds);
798 FD_SET(STDIN_FILENO, &rfds);
799 if (STDIN_FILENO > max)
802 res = ast_select(max+1, &rfds, NULL, NULL, NULL);
806 ast_log(LOG_ERROR, "select failed: %s\n", strerror(errno));
810 if (FD_ISSET(STDIN_FILENO, &rfds)) {
811 num_read = read(STDIN_FILENO, cp, 1);
817 if (FD_ISSET(ast_consock, &rfds)) {
818 res = read(ast_consock, buf, sizeof(buf) - 1);
819 /* if the remote side disappears exit */
821 fprintf(stderr, "\nDisconnected from Asterisk server\n");
822 quit_handler(0, 0, 0, 0);
827 if (!option_exec && !lastpos)
828 write(STDOUT_FILENO, "\r", 1);
829 write(STDOUT_FILENO, buf, res);
830 if ((buf[res-1] == '\n') || (buf[res-2] == '\n')) {
843 static char *cli_prompt(EditLine *el)
845 static char prompt[80];
848 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT2, remotehostname);
850 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT);
855 static char **ast_el_strtoarr(char *buf)
857 char **match_list = NULL, *retstr;
858 size_t match_list_len;
862 while ( (retstr = strsep(&buf, " ")) != NULL) {
864 if (matches + 1 >= match_list_len) {
865 match_list_len <<= 1;
866 match_list = realloc(match_list, match_list_len * sizeof(char *));
869 match_list[matches++] = retstr;
873 return (char **) NULL;
875 if (matches>= match_list_len)
876 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
878 match_list[matches] = (char *) NULL;
883 static int ast_el_sort_compare(const void *i1, const void *i2)
887 s1 = ((char **)i1)[0];
888 s2 = ((char **)i2)[0];
890 return strcasecmp(s1, s2);
893 static int ast_cli_display_match_list(char **matches, int len, int max)
895 int i, idx, limit, count;
897 int numoutput = 0, numoutputline = 0;
899 screenwidth = ast_get_termcols(STDOUT_FILENO);
901 /* find out how many entries can be put on one line, with two spaces between strings */
902 limit = screenwidth / (max + 2);
906 /* how many lines of output */
908 if (count * limit < len)
913 qsort(&matches[0], (size_t)(len + 1), sizeof(char *), ast_el_sort_compare);
915 for (; count > 0; count--) {
917 for (i=0; i < limit && matches[idx]; i++, idx++) {
919 /* Don't print dupes */
920 if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
925 numoutput++; numoutputline++;
926 fprintf(stdout, "%-*s ", max, matches[idx]);
928 if (numoutputline > 0)
929 fprintf(stdout, "\n");
936 static char *cli_complete(EditLine *el, int ch)
942 int retval = CC_ERROR;
946 LineInfo *lf = (LineInfo *)el_line(el);
948 *(char *)lf->cursor = '\0';
949 ptr = (char *)lf->cursor;
951 while (ptr > lf->buffer) {
960 len = lf->cursor - ptr;
963 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr);
964 fdprint(ast_consock, buf);
965 res = read(ast_consock, buf, sizeof(buf));
967 nummatches = atoi(buf);
969 if (nummatches > 0) {
970 snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr);
971 fdprint(ast_consock, buf);
972 res = read(ast_consock, buf, sizeof(buf));
975 matches = ast_el_strtoarr(buf);
977 matches = (char **) NULL;
982 nummatches = ast_cli_generatornummatches((char *)lf->buffer,ptr);
983 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
988 int matches_num, maxlen, match_len;
990 if (matches[0][0] != '\0') {
991 el_deletestr(el, (int) len);
992 el_insertstr(el, matches[0]);
996 if (nummatches == 1) {
997 /* Found an exact match */
998 el_insertstr(el, " ");
1001 /* Must be more than one match */
1002 for (i=1, maxlen=0; matches[i]; i++) {
1003 match_len = strlen(matches[i]);
1004 if (match_len > maxlen)
1007 matches_num = i - 1;
1008 if (matches_num >1) {
1009 fprintf(stdout, "\n");
1010 ast_cli_display_match_list(matches, nummatches, maxlen);
1011 retval = CC_REDISPLAY;
1013 el_insertstr(el," ");
1014 retval = CC_REFRESH;
1020 return (char *)retval;
1023 static int ast_el_initialize(void)
1029 if (el_hist != NULL)
1030 history_end(el_hist);
1032 el = el_init("asterisk", stdin, stdout, stderr);
1033 el_set(el, EL_PROMPT, cli_prompt);
1035 el_set(el, EL_EDITMODE, 1);
1036 el_set(el, EL_EDITOR, "emacs");
1037 el_hist = history_init();
1038 if (!el || !el_hist)
1041 /* setup history with 100 entries */
1042 history(el_hist, &ev, H_SETSIZE, 100);
1044 el_set(el, EL_HIST, history, el_hist);
1046 el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
1047 /* Bind <tab> to command completion */
1048 el_set(el, EL_BIND, "^I", "ed-complete", NULL);
1049 /* Bind ? to command completion */
1050 el_set(el, EL_BIND, "?", "ed-complete", NULL);
1055 static int ast_el_add_history(char *buf)
1059 if (el_hist == NULL || el == NULL)
1060 ast_el_initialize();
1061 if (strlen(buf) > 256)
1063 return (history(el_hist, &ev, H_ENTER, buf));
1066 static int ast_el_write_history(char *filename)
1070 if (el_hist == NULL || el == NULL)
1071 ast_el_initialize();
1073 return (history(el_hist, &ev, H_SAVE, filename));
1076 static int ast_el_read_history(char *filename)
1082 if (el_hist == NULL || el == NULL)
1083 ast_el_initialize();
1085 if ((f = fopen(filename, "r")) == NULL)
1089 fgets(buf, sizeof(buf), f);
1090 if (!strcmp(buf, "_HiStOrY_V2_\n"))
1092 if ((ret = ast_el_add_history(buf)) == -1)
1100 static void ast_remotecontrol(char * data)
1104 char filename[80] = "";
1115 read(ast_consock, buf, sizeof(buf));
1117 write(ast_consock, data, strlen(data) + 1);
1119 hostname = strsep(&stringp, "/");
1120 cpid = strsep(&stringp, "/");
1121 version = strsep(&stringp, "\n");
1123 version = "<Version Unknown>";
1125 strsep(&stringp, ".");
1130 snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
1131 fdprint(ast_consock, tmp);
1132 ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
1133 remotehostname = hostname;
1135 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1136 if (el_hist == NULL || el == NULL)
1137 ast_el_initialize();
1139 el_set(el, EL_GETCFN, ast_el_read_char);
1141 if (strlen(filename))
1142 ast_el_read_history(filename);
1144 ast_cli_register(&quit);
1145 ast_cli_register(&astexit);
1147 ast_cli_register(&astshutdown);
1149 if (option_exec && data) { /* hack to print output then exit if asterisk -rx is used */
1151 ast_el_read_char(el, &tempchar);
1155 ebuf = (char *)el_gets(el, &num);
1157 if (ebuf && strlen(ebuf)) {
1158 if (ebuf[strlen(ebuf)-1] == '\n')
1159 ebuf[strlen(ebuf)-1] = '\0';
1160 if (!remoteconsolehandler(ebuf)) {
1161 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
1163 ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
1169 printf("\nDisconnected from Asterisk server\n");
1172 static int show_cli_help(void) {
1173 printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 2000-2002, Digium.\n");
1174 printf("Usage: asterisk [OPTIONS]\n");
1175 printf("Valid Options:\n");
1176 printf(" -h This help screen\n");
1177 printf(" -r Connect to Asterisk on this machine\n");
1178 printf(" -f Do not fork\n");
1179 printf(" -n Disable console colorization\n");
1180 printf(" -p Run as pseudo-realtime thread\n");
1181 printf(" -v Increase verbosity (multiple v's = more verbose)\n");
1182 printf(" -q Quiet mode (supress output)\n");
1183 printf(" -g Dump core in case of a crash\n");
1184 printf(" -x <cmd> Execute command <cmd> (only valid with -r)\n");
1185 printf(" -i Initializie crypto keys at startup\n");
1186 printf(" -c Provide console CLI\n");
1187 printf(" -d Enable extra debugging\n");
1192 static void ast_readconfig(void) {
1193 struct ast_config *cfg;
1194 struct ast_variable *v;
1195 char *config = ASTCONFPATH;
1197 if (option_overrideconfig == 1) {
1198 cfg = ast_load((char *)ast_config_AST_CONFIG_FILE);
1200 cfg = ast_load(config);
1203 /* init with buildtime config */
1204 strncpy((char *)ast_config_AST_CONFIG_DIR,AST_CONFIG_DIR,sizeof(ast_config_AST_CONFIG_DIR)-1);
1205 strncpy((char *)ast_config_AST_SPOOL_DIR,AST_SPOOL_DIR,sizeof(ast_config_AST_SPOOL_DIR)-1);
1206 strncpy((char *)ast_config_AST_MODULE_DIR,AST_MODULE_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1207 strncpy((char *)ast_config_AST_VAR_DIR,AST_VAR_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1208 strncpy((char *)ast_config_AST_LOG_DIR,AST_LOG_DIR,sizeof(ast_config_AST_LOG_DIR)-1);
1209 strncpy((char *)ast_config_AST_AGI_DIR,AST_AGI_DIR,sizeof(ast_config_AST_AGI_DIR)-1);
1210 strncpy((char *)ast_config_AST_DB,AST_DB,sizeof(ast_config_AST_DB)-1);
1211 strncpy((char *)ast_config_AST_KEY_DIR,AST_KEY_DIR,sizeof(ast_config_AST_KEY_DIR)-1);
1212 strncpy((char *)ast_config_AST_PID,AST_PID,sizeof(ast_config_AST_PID)-1);
1213 strncpy((char *)ast_config_AST_SOCKET,AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1);
1214 strncpy((char *)ast_config_AST_RUN_DIR,AST_RUN_DIR,sizeof(ast_config_AST_RUN_DIR)-1);
1216 /* no asterisk.conf? no problem, use buildtime config! */
1220 v = ast_variable_browse(cfg, "directories");
1222 if (!strcasecmp(v->name, "astetcdir")) {
1223 strncpy((char *)ast_config_AST_CONFIG_DIR,v->value,sizeof(ast_config_AST_CONFIG_DIR)-1);
1224 } else if (!strcasecmp(v->name, "astspooldir")) {
1225 strncpy((char *)ast_config_AST_SPOOL_DIR,v->value,sizeof(ast_config_AST_SPOOL_DIR)-1);
1226 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1227 strncpy((char *)ast_config_AST_VAR_DIR,v->value,sizeof(ast_config_AST_VAR_DIR)-1);
1228 snprintf((char *)ast_config_AST_DB,sizeof(ast_config_AST_DB)-1,"%s/%s",v->value,"astdb");
1229 } else if (!strcasecmp(v->name, "astlogdir")) {
1230 strncpy((char *)ast_config_AST_LOG_DIR,v->value,sizeof(ast_config_AST_LOG_DIR)-1);
1231 } else if (!strcasecmp(v->name, "astagidir")) {
1232 strncpy((char *)ast_config_AST_AGI_DIR,v->value,sizeof(ast_config_AST_AGI_DIR)-1);
1233 } else if (!strcasecmp(v->name, "astrundir")) {
1234 snprintf((char *)ast_config_AST_PID,sizeof(ast_config_AST_PID)-1,"%s/%s",v->value,"asterisk.pid");
1235 snprintf((char *)ast_config_AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1,"%s/%s",v->value,"asterisk.ctl");
1236 strncpy((char *)ast_config_AST_RUN_DIR,v->value,sizeof(ast_config_AST_RUN_DIR)-1);
1237 } else if (!strcasecmp(v->name, "astmoddir")) {
1238 strncpy((char *)ast_config_AST_MODULE_DIR,v->value,sizeof(ast_config_AST_MODULE_DIR)-1);
1245 int main(int argc, char *argv[])
1248 char filename[80] = "";
1258 /* Remember original args for restart */
1259 if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1260 fprintf(stderr, "Truncating argument size to %d\n", sizeof(_argv) / sizeof(_argv[0]) - 1);
1261 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1263 for (x=0;x<argc;x++)
1267 /* if the progname is rasterisk consider it a remote console */
1268 if ( argv[0] && (strstr(argv[0], "rasterisk")) != NULL) {
1272 if (gethostname(hostname, sizeof(hostname)))
1273 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
1280 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1281 /* Check if we're root */
1284 ast_log(LOG_ERROR, "Must be run as root\n");
1288 /* Check for options */
1289 while((c=getopt(argc, argv, "hfdvqprgcinx:C:")) != -1) {
1310 option_highpriority++;
1324 strncpy((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE));
1325 option_overrideconfig++;
1328 option_initcrypto++;
1341 if (option_dumpcore) {
1343 memset(&l, 0, sizeof(l));
1344 l.rlim_cur = RLIM_INFINITY;
1345 l.rlim_max = RLIM_INFINITY;
1346 if (setrlimit(RLIMIT_CORE, &l)) {
1347 ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
1354 if (option_console && !option_verbose)
1355 ast_verbose("[ Reading Master Configuration ]");
1358 if (option_console) {
1359 if (el_hist == NULL || el == NULL)
1360 ast_el_initialize();
1362 if (strlen(filename))
1363 ast_el_read_history(filename);
1366 if (ast_tryconnect()) {
1367 /* One is already running */
1368 if (option_remote) {
1370 ast_remotecontrol(xarg);
1371 quit_handler(0, 0, 0, 0);
1374 printf(term_quit());
1375 ast_register_verbose(console_verboser);
1376 ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2004 Digium.\n");
1377 ast_verbose( "Written by Mark Spencer <markster@digium.com>\n");
1378 ast_verbose( "=========================================================================\n");
1379 ast_remotecontrol(NULL);
1380 quit_handler(0, 0, 0, 0);
1383 ast_log(LOG_ERROR, "Asterisk already running on %s. Use 'asterisk -r' to connect.\n", (char *)ast_config_AST_SOCKET);
1384 printf(term_quit());
1387 } else if (option_remote || option_exec) {
1388 ast_log(LOG_ERROR, "Unable to connect to remote asterisk\n");
1389 printf(term_quit());
1392 /* Blindly write pid file since we couldn't connect */
1393 unlink((char *)ast_config_AST_PID);
1394 f = fopen((char *)ast_config_AST_PID, "w");
1396 fprintf(f, "%d\n", getpid());
1399 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1401 if (!option_verbose && !option_debug && !option_nofork && !option_console) {
1403 /* Blindly re-write pid file since we are forking */
1404 unlink((char *)ast_config_AST_PID);
1405 f = fopen((char *)ast_config_AST_PID, "w");
1407 fprintf(f, "%d\n", getpid());
1410 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1415 sigaddset(&sigs, SIGHUP);
1416 sigaddset(&sigs, SIGTERM);
1417 sigaddset(&sigs, SIGINT);
1418 sigaddset(&sigs, SIGPIPE);
1419 sigaddset(&sigs, SIGWINCH);
1420 pthread_sigmask(SIG_BLOCK, &sigs, NULL);
1421 if (option_console || option_verbose || option_remote)
1422 ast_register_verbose(console_verboser);
1423 /* Print a welcome message if desired */
1424 if (option_verbose || option_console) {
1425 ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2001 Linux Support Services, Inc.\n");
1426 ast_verbose( "Written by Mark Spencer <markster@linux-support.net>\n");
1427 ast_verbose( "=========================================================================\n");
1429 if (option_console && !option_verbose)
1430 ast_verbose("[ Booting...");
1432 signal(SIGURG, urg_handler);
1433 signal(SIGINT, __quit_handler);
1434 signal(SIGTERM, __quit_handler);
1435 signal(SIGHUP, hup_handler);
1436 signal(SIGCHLD, child_handler);
1437 signal(SIGPIPE, SIG_IGN);
1439 if (set_priority(option_highpriority)) {
1440 printf(term_quit());
1443 if (init_logger()) {
1444 printf(term_quit());
1447 if (init_manager()) {
1448 printf(term_quit());
1452 if (ast_image_init()) {
1453 printf(term_quit());
1457 printf(term_quit());
1460 if (load_modules()) {
1461 printf(term_quit());
1464 if (init_framer()) {
1465 printf(term_quit());
1469 printf(term_quit());
1472 if (ast_enum_init()) {
1473 printf(term_quit());
1476 /* We might have the option of showing a console, but for now just
1478 if (option_console && !option_verbose)
1479 ast_verbose(" ]\n");
1480 if (option_verbose || option_console)
1481 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
1483 consolethread = pthread_self();
1485 pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
1486 #ifdef __AST_DEBUG_MALLOC
1489 time(&ast_startuptime);
1490 ast_cli_register(&astshutdownnow);
1491 ast_cli_register(&astshutdowngracefully);
1492 ast_cli_register(&astrestartnow);
1493 ast_cli_register(&astrestartgracefully);
1494 ast_cli_register(&astrestartwhenconvenient);
1495 ast_cli_register(&astshutdownwhenconvenient);
1496 ast_cli_register(&aborthalt);
1497 ast_cli_register(&astbang);
1498 if (option_console) {
1499 /* Console stuff now... */
1500 /* Register our quit function */
1502 set_icon("Asterisk");
1503 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, mainpid);
1505 ast_cli_register(&quit);
1506 ast_cli_register(&astexit);
1509 buf = (char *)el_gets(el, &num);
1511 if (buf[strlen(buf)-1] == '\n')
1512 buf[strlen(buf)-1] = '\0';
1514 consolehandler((char *)buf);
1517 ast_cli(STDOUT_FILENO, "\nUse EXIT or QUIT to exit the asterisk console\n");
1519 ast_cli(STDOUT_FILENO, "\nUse STOP NOW to shutdown Asterisk\n");
1525 ast_select(0,NULL,NULL,NULL,NULL);