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
17 #include <asterisk/logger.h>
18 #include <asterisk/options.h>
19 #include <asterisk/cli.h>
20 #include <asterisk/channel.h>
21 #include <asterisk/ulaw.h>
22 #include <asterisk/alaw.h>
23 #include <asterisk/callerid.h>
24 #include <asterisk/module.h>
25 #include <asterisk/image.h>
26 #include <asterisk/tdd.h>
27 #include <asterisk/term.h>
28 #include <asterisk/manager.h>
29 #include <asterisk/pbx.h>
30 #include <asterisk/enum.h>
31 #include <asterisk/rtp.h>
32 #include <asterisk/app.h>
33 #include <asterisk/lock.h>
34 #include <asterisk/utils.h>
35 #include <asterisk/file.h>
36 #include <sys/resource.h>
41 #include <asterisk/io.h>
42 #include <asterisk/lock.h>
43 #include <sys/socket.h>
49 #include "editline/histedit.h"
51 #include <asterisk/config.h>
52 #include <asterisk/config_pvt.h>
53 #include <sys/resource.h>
55 #if defined(__FreeBSD__)
59 #define AST_MAX_CONNECTS 128
62 #define WELCOME_MESSAGE ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2004 Digium.\n"); \
63 ast_verbose( "Written by Mark Spencer <markster@digium.com>\n"); \
64 ast_verbose( "=========================================================================\n")
71 int option_highpriority=0;
74 int option_initcrypto=0;
76 int option_dumpcore = 0;
77 int option_overrideconfig = 0;
78 int option_reconnect = 0;
81 static int ast_socket = -1; /* UNIX Socket for allowing remote control */
82 static int ast_consock = -1; /* UNIX Socket for controlling another asterisk */
85 int fd; /* File descriptor */
87 pthread_t t; /* Thread of handler */
90 static struct ast_atexit {
92 struct ast_atexit *next;
94 AST_MUTEX_DEFINE_STATIC(atexitslock);
96 time_t ast_startuptime;
97 time_t ast_lastreloadtime;
99 static History *el_hist = NULL;
100 static EditLine *el = NULL;
101 static char *remotehostname;
103 struct console consoles[AST_MAX_CONNECTS];
105 char defaultlanguage[MAX_LANGUAGE] = DEFAULT_LANGUAGE;
107 static int ast_el_add_history(char *);
108 static int ast_el_read_history(char *);
109 static int ast_el_write_history(char *);
111 char ast_config_AST_CONFIG_DIR[AST_CONFIG_MAX_PATH];
112 char ast_config_AST_CONFIG_FILE[AST_CONFIG_MAX_PATH];
113 char ast_config_AST_MODULE_DIR[AST_CONFIG_MAX_PATH];
114 char ast_config_AST_SPOOL_DIR[AST_CONFIG_MAX_PATH];
115 char ast_config_AST_VAR_DIR[AST_CONFIG_MAX_PATH];
116 char ast_config_AST_LOG_DIR[AST_CONFIG_MAX_PATH];
117 char ast_config_AST_AGI_DIR[AST_CONFIG_MAX_PATH];
118 char ast_config_AST_DB[AST_CONFIG_MAX_PATH];
119 char ast_config_AST_KEY_DIR[AST_CONFIG_MAX_PATH];
120 char ast_config_AST_PID[AST_CONFIG_MAX_PATH];
121 char ast_config_AST_SOCKET[AST_CONFIG_MAX_PATH];
122 char ast_config_AST_RUN_DIR[AST_CONFIG_MAX_PATH];
124 static char *_argv[256];
125 static int shuttingdown = 0;
126 static int restartnow = 0;
127 static pthread_t consolethread = AST_PTHREADT_NULL;
129 int ast_register_atexit(void (*func)(void))
132 struct ast_atexit *ae;
133 ast_unregister_atexit(func);
134 ae = malloc(sizeof(struct ast_atexit));
135 ast_mutex_lock(&atexitslock);
137 memset(ae, 0, sizeof(struct ast_atexit));
143 ast_mutex_unlock(&atexitslock);
147 void ast_unregister_atexit(void (*func)(void))
149 struct ast_atexit *ae, *prev = NULL;
150 ast_mutex_lock(&atexitslock);
153 if (ae->func == func) {
155 prev->next = ae->next;
163 ast_mutex_unlock(&atexitslock);
166 static int fdprint(int fd, const char *s)
168 return write(fd, s, strlen(s) + 1);
171 int ast_safe_system(const char *s)
173 /* XXX This function needs some optimization work XXX */
177 struct rusage rusage;
181 /* Close file descriptors and launch system command */
182 for (x=STDERR_FILENO + 1; x<4096;x++) {
185 res = execl("/bin/sh", "/bin/sh", "-c", s, NULL);
187 } else if (pid > 0) {
189 res = wait4(pid, &status, 0, &rusage);
191 if (WIFEXITED(status))
192 res = WEXITSTATUS(status);
202 ast_log(LOG_WARNING, "Fork failed: %s\n", strerror(errno));
209 * write the string to all attached console clients
211 static void ast_network_puts(const char *string)
214 for (x=0;x<AST_MAX_CONNECTS; x++) {
215 if (consoles[x].fd > -1)
216 fdprint(consoles[x].p[1], string);
221 * write the string to the console, and all attached
224 void ast_console_puts(const char *string)
226 fputs(string, stdout);
228 ast_network_puts(string);
231 static void network_verboser(const char *s, int pos, int replace, int complete)
237 static pthread_t lthread;
239 static void *netconsole(void *vconsole)
241 struct console *con = vconsole;
245 struct pollfd fds[2];
247 if (gethostname(hostname, sizeof(hostname)))
248 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
249 snprintf(tmp, sizeof(tmp), "%s/%d/%s\n", hostname, ast_mainpid, ASTERISK_VERSION);
250 fdprint(con->fd, tmp);
253 fds[0].events = POLLIN;
254 fds[1].fd = con->p[0];
255 fds[1].events = POLLIN;
257 res = poll(fds, 2, -1);
260 ast_log(LOG_WARNING, "poll returned < 0: %s\n", strerror(errno));
263 if (fds[0].revents) {
264 res = read(con->fd, tmp, sizeof(tmp));
269 ast_cli_command(con->fd, tmp);
271 if (fds[1].revents) {
272 res = read(con->p[0], tmp, sizeof(tmp));
274 ast_log(LOG_ERROR, "read returned %d\n", res);
277 res = write(con->fd, tmp, res);
282 if (option_verbose > 2)
283 ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection disconnected\n");
292 static void *listener(void *unused)
294 struct sockaddr_un sun;
299 struct pollfd fds[1];
301 pthread_attr_init(&attr);
302 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
306 fds[0].fd = ast_socket;
307 fds[0].events= POLLIN;
308 s = poll(fds, 1, -1);
311 ast_log(LOG_WARNING, "poll returned error: %s\n", strerror(errno));
315 s = accept(ast_socket, (struct sockaddr *)&sun, &len);
318 ast_log(LOG_WARNING, "Accept returned %d: %s\n", s, strerror(errno));
320 for (x=0;x<AST_MAX_CONNECTS;x++) {
321 if (consoles[x].fd < 0) {
322 if (socketpair(AF_LOCAL, SOCK_STREAM, 0, consoles[x].p)) {
323 ast_log(LOG_ERROR, "Unable to create pipe: %s\n", strerror(errno));
325 fdprint(s, "Server failed to create pipe\n");
329 flags = fcntl(consoles[x].p[1], F_GETFL);
330 fcntl(consoles[x].p[1], F_SETFL, flags | O_NONBLOCK);
332 if (pthread_create(&consoles[x].t, &attr, netconsole, &consoles[x])) {
333 ast_log(LOG_ERROR, "Unable to spawn thread to handle connection: %s\n", strerror(errno));
335 fdprint(s, "Server failed to spawn thread\n");
341 if (x >= AST_MAX_CONNECTS) {
342 fdprint(s, "No more connections allowed\n");
343 ast_log(LOG_WARNING, "No more connections allowed\n");
345 } else if (consoles[x].fd > -1) {
346 if (option_verbose > 2)
347 ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection\n");
354 static int ast_makesocket(void)
356 struct sockaddr_un sun;
359 for (x=0;x<AST_MAX_CONNECTS;x++)
361 unlink((char *)ast_config_AST_SOCKET);
362 ast_socket = socket(PF_LOCAL, SOCK_STREAM, 0);
363 if (ast_socket < 0) {
364 ast_log(LOG_WARNING, "Unable to create control socket: %s\n", strerror(errno));
367 memset(&sun, 0, sizeof(sun));
368 sun.sun_family = AF_LOCAL;
369 strncpy(sun.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sun.sun_path)-1);
370 res = bind(ast_socket, (struct sockaddr *)&sun, sizeof(sun));
372 ast_log(LOG_WARNING, "Unable to bind socket to %s: %s\n", (char *)ast_config_AST_SOCKET, strerror(errno));
377 res = listen(ast_socket, 2);
379 ast_log(LOG_WARNING, "Unable to listen on socket %s: %s\n", (char *)ast_config_AST_SOCKET, strerror(errno));
384 ast_register_verbose(network_verboser);
385 pthread_create(<hread, NULL, listener, NULL);
389 static int ast_tryconnect(void)
391 struct sockaddr_un sun;
393 ast_consock = socket(PF_LOCAL, SOCK_STREAM, 0);
394 if (ast_consock < 0) {
395 ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
398 memset(&sun, 0, sizeof(sun));
399 sun.sun_family = AF_LOCAL;
400 strncpy(sun.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sun.sun_path)-1);
401 res = connect(ast_consock, (struct sockaddr *)&sun, sizeof(sun));
410 static void urg_handler(int num)
412 /* Called by soft_hangup to interrupt the poll, read, or other
413 system call. We don't actually need to do anything though. */
414 /* Cannot EVER ast_log from within a signal handler */
416 printf("Urgent handler\n");
417 signal(num, urg_handler);
421 static void hup_handler(int num)
423 if (option_verbose > 1)
424 printf("Received HUP signal -- Reloading configs\n");
426 execvp(_argv[0], _argv);
427 /* XXX This could deadlock XXX */
431 static void child_handler(int sig)
433 /* Must not ever ast_log or ast_verbose within signal handler */
437 * Reap all dead children -- not just one
439 for (n = 0; wait4(-1, &status, WNOHANG, NULL) > 0; n++)
441 if (n == 0 && option_debug)
442 printf("Huh? Child handler, but nobody there?\n");
445 static void set_title(char *text)
447 /* Set an X-term or screen title */
448 if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
449 fprintf(stdout, "\033]2;%s\007", text);
452 static void set_icon(char *text)
454 if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
455 fprintf(stdout, "\033]1;%s\007", text);
458 static int set_priority(int pri)
460 struct sched_param sched;
461 memset(&sched, 0, sizeof(sched));
462 /* We set ourselves to a high priority, that we might pre-empt everything
463 else. If your PBX has heavy activity on it, this is a good thing. */
466 sched.sched_priority = 10;
467 if (sched_setscheduler(0, SCHED_RR, &sched)) {
468 ast_log(LOG_WARNING, "Unable to set high priority\n");
472 ast_verbose("Set to realtime thread\n");
474 sched.sched_priority = 0;
475 if (sched_setscheduler(0, SCHED_OTHER, &sched)) {
476 ast_log(LOG_WARNING, "Unable to set normal priority\n");
482 if (setpriority(PRIO_PROCESS, 0, -10) == -1) {
483 ast_log(LOG_WARNING, "Unable to set high priority\n");
487 ast_verbose("Set to high priority\n");
489 if (setpriority(PRIO_PROCESS, 0, 0) == -1) {
490 ast_log(LOG_WARNING, "Unable to set normal priority\n");
498 static void ast_run_atexits(void)
500 struct ast_atexit *ae;
501 ast_mutex_lock(&atexitslock);
508 ast_mutex_unlock(&atexitslock);
511 static void quit_handler(int num, int nice, int safeshutdown, int restart)
513 char filename[80] = "";
519 /* Begin shutdown routine, hanging up active channels */
520 ast_begin_shutdown(1);
521 if (option_verbose && option_console)
522 ast_verbose("Beginning asterisk %s....\n", restart ? "restart" : "shutdown");
526 /* Wait up to 15 seconds for all channels to go away */
529 if (!ast_active_channels())
533 /* Sleep 1/10 of a second */
538 ast_begin_shutdown(0);
539 if (option_verbose && option_console)
540 ast_verbose("Waiting for inactivity to perform %s...\n", restart ? "restart" : "halt");
542 if (!ast_active_channels())
551 if (option_verbose && option_console)
552 ast_verbose("Asterisk %s cancelled.\n", restart ? "restart" : "shutdown");
556 if (option_console || option_remote) {
558 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
559 if (!ast_strlen_zero(filename))
560 ast_el_write_history(filename);
564 history_end(el_hist);
567 ast_verbose("Executing last minute cleanups\n");
570 if (option_verbose && option_console)
571 ast_verbose("Asterisk %s ending (%d).\n", ast_active_channels() ? "uncleanly" : "cleanly", num);
572 else if (option_debug)
573 ast_log(LOG_DEBUG, "Asterisk ending (%d).\n", num);
574 manager_event(EVENT_FLAG_SYSTEM, "Shutdown", "Shutdown: %s\r\nRestart: %s\r\n", ast_active_channels() ? "Uncleanly" : "Cleanly", restart ? "True" : "False");
575 if (ast_socket > -1) {
579 if (ast_consock > -1)
582 unlink((char *)ast_config_AST_SOCKET);
583 if (!option_remote) unlink((char *)ast_config_AST_PID);
586 if (option_verbose || option_console)
587 ast_verbose("Preparing for Asterisk restart...\n");
588 /* Mark all FD's for closing on exec */
589 for (x=3;x<32768;x++) {
590 fcntl(x, F_SETFD, FD_CLOEXEC);
592 if (option_verbose || option_console)
593 ast_verbose("Restarting Asterisk NOW...\n");
599 /* If there is a consolethread running send it a SIGHUP
600 so it can execvp, otherwise we can do it ourselves */
601 if (consolethread != AST_PTHREADT_NULL) {
602 pthread_kill(consolethread, SIGHUP);
603 /* Give the signal handler some time to complete */
606 execvp(_argv[0], _argv);
615 static void __quit_handler(int num)
617 quit_handler(num, 0, 1, 0);
620 static const char *fix_header(char *outbuf, int maxout, const char *s, char *cmp)
623 if (!strncmp(s, cmp, strlen(cmp))) {
625 term_color(outbuf, cmp, COLOR_GRAY, 0, maxout);
631 static void console_verboser(const char *s, int pos, int replace, int complete)
635 /* Return to the beginning of the line */
637 fprintf(stdout, "\r");
638 if ((c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_4)) ||
639 (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_3)) ||
640 (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_2)) ||
641 (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_1)))
645 fputs(c + pos,stdout);
647 fputs(s + pos,stdout);
650 /* Wake up a poll()ing console */
651 if (option_console && consolethread != AST_PTHREADT_NULL)
652 pthread_kill(consolethread, SIGURG);
655 static void consolehandler(char *s)
659 /* Called when readline data is available */
660 if (s && !ast_strlen_zero(s))
661 ast_el_add_history(s);
662 /* Give the console access to the shell */
664 /* The real handler for bang */
667 ast_safe_system(s+1);
669 ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
671 ast_cli_command(STDOUT_FILENO, s);
673 fprintf(stdout, "\nUse \"quit\" to exit\n");
676 static int remoteconsolehandler(char *s)
679 /* Called when readline data is available */
680 if (s && !ast_strlen_zero(s))
681 ast_el_add_history(s);
682 /* Give the console access to the shell */
684 /* The real handler for bang */
687 ast_safe_system(s+1);
689 ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
692 if ((strncasecmp(s, "quit", 4) == 0 || strncasecmp(s, "exit", 4) == 0) &&
693 (s[4] == '\0' || isspace(s[4]))) {
694 quit_handler(0, 0, 0, 0);
698 fprintf(stdout, "\nUse \"quit\" to exit\n");
703 static char quit_help[] =
705 " Exits Asterisk.\n";
707 static char abort_halt_help[] =
708 "Usage: abort shutdown\n"
709 " Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
710 " call operations.\n";
712 static char shutdown_now_help[] =
714 " Shuts down a running Asterisk immediately, hanging up all active calls .\n";
716 static char shutdown_gracefully_help[] =
717 "Usage: stop gracefully\n"
718 " Causes Asterisk to not accept new calls, and exit when all\n"
719 " active calls have terminated normally.\n";
721 static char shutdown_when_convenient_help[] =
722 "Usage: stop when convenient\n"
723 " Causes Asterisk to perform a shutdown when all active calls have ended.\n";
725 static char restart_now_help[] =
726 "Usage: restart now\n"
727 " Causes Asterisk to hangup all calls and exec() itself performing a cold.\n"
730 static char restart_gracefully_help[] =
731 "Usage: restart gracefully\n"
732 " Causes Asterisk to stop accepting new calls and exec() itself performing a cold.\n"
733 " restart when all active calls have ended.\n";
735 static char restart_when_convenient_help[] =
736 "Usage: restart when convenient\n"
737 " Causes Asterisk to perform a cold restart when all active calls have ended.\n";
739 static char bang_help[] =
740 "Usage: !<command>\n"
741 " Executes a given shell command\n";
744 static int handle_quit(int fd, int argc, char *argv[])
747 return RESULT_SHOWUSAGE;
748 quit_handler(0, 0, 1, 0);
749 return RESULT_SUCCESS;
753 static int no_more_quit(int fd, int argc, char *argv[])
756 return RESULT_SHOWUSAGE;
757 ast_cli(fd, "The QUIT and EXIT commands may no longer be used to shutdown the PBX.\n"
758 "Please use STOP NOW instead, if you wish to shutdown the PBX.\n");
759 return RESULT_SUCCESS;
762 static int handle_shutdown_now(int fd, int argc, char *argv[])
765 return RESULT_SHOWUSAGE;
766 quit_handler(0, 0 /* Not nice */, 1 /* safely */, 0 /* not restart */);
767 return RESULT_SUCCESS;
770 static int handle_shutdown_gracefully(int fd, int argc, char *argv[])
773 return RESULT_SHOWUSAGE;
774 quit_handler(0, 1 /* nicely */, 1 /* safely */, 0 /* no restart */);
775 return RESULT_SUCCESS;
778 static int handle_shutdown_when_convenient(int fd, int argc, char *argv[])
781 return RESULT_SHOWUSAGE;
782 quit_handler(0, 2 /* really nicely */, 1 /* safely */, 0 /* don't restart */);
783 return RESULT_SUCCESS;
786 static int handle_restart_now(int fd, int argc, char *argv[])
789 return RESULT_SHOWUSAGE;
790 quit_handler(0, 0 /* not nicely */, 1 /* safely */, 1 /* restart */);
791 return RESULT_SUCCESS;
794 static int handle_restart_gracefully(int fd, int argc, char *argv[])
797 return RESULT_SHOWUSAGE;
798 quit_handler(0, 1 /* nicely */, 1 /* safely */, 1 /* restart */);
799 return RESULT_SUCCESS;
802 static int handle_restart_when_convenient(int fd, int argc, char *argv[])
805 return RESULT_SHOWUSAGE;
806 quit_handler(0, 2 /* really nicely */, 1 /* safely */, 1 /* restart */);
807 return RESULT_SUCCESS;
810 static int handle_abort_halt(int fd, int argc, char *argv[])
813 return RESULT_SHOWUSAGE;
814 ast_cancel_shutdown();
816 return RESULT_SUCCESS;
819 static int handle_bang(int fd, int argc, char *argv[])
821 return RESULT_SUCCESS;
824 #define ASTERISK_PROMPT "*CLI> "
826 #define ASTERISK_PROMPT2 "%s*CLI> "
828 static struct ast_cli_entry aborthalt = { { "abort", "halt", NULL }, handle_abort_halt, "Cancel a running halt", abort_halt_help };
830 static struct ast_cli_entry quit = { { "quit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
831 static struct ast_cli_entry astexit = { { "exit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
833 static struct ast_cli_entry astshutdownnow = { { "stop", "now", NULL }, handle_shutdown_now, "Shut down Asterisk immediately", shutdown_now_help };
834 static struct ast_cli_entry astshutdowngracefully = { { "stop", "gracefully", NULL }, handle_shutdown_gracefully, "Gracefully shut down Asterisk", shutdown_gracefully_help };
835 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 };
836 static struct ast_cli_entry astrestartnow = { { "restart", "now", NULL }, handle_restart_now, "Restart Asterisk immediately", restart_now_help };
837 static struct ast_cli_entry astrestartgracefully = { { "restart", "gracefully", NULL }, handle_restart_gracefully, "Restart Asterisk gracefully", restart_gracefully_help };
838 static struct ast_cli_entry astrestartwhenconvenient= { { "restart", "when", "convenient", NULL }, handle_restart_when_convenient, "Restart Asterisk at empty call volume", restart_when_convenient_help };
839 static struct ast_cli_entry astbang = { { "!", NULL }, handle_bang, "Execute a shell command", bang_help };
841 static int ast_el_read_char(EditLine *el, char *cp)
845 struct pollfd fds[2];
852 fds[0].fd = ast_consock;
853 fds[0].events = POLLIN;
855 fds[1].fd = STDIN_FILENO;
856 fds[1].events = POLLIN;
859 res = poll(fds, max, -1);
863 ast_log(LOG_ERROR, "poll failed: %s\n", strerror(errno));
867 if (!option_exec && fds[1].revents) {
868 num_read = read(STDIN_FILENO, cp, 1);
874 if (fds[0].revents) {
875 res = read(ast_consock, buf, sizeof(buf) - 1);
876 /* if the remote side disappears exit */
878 fprintf(stderr, "\nDisconnected from Asterisk server\n");
879 if (!option_reconnect) {
880 quit_handler(0, 0, 0, 0);
883 int reconnects_per_second = 20;
884 fprintf(stderr, "Attempting to reconnect for 30 seconds\n");
885 for (tries=0;tries<30 * reconnects_per_second;tries++) {
886 if (ast_tryconnect()) {
887 fprintf(stderr, "Reconnect succeeded after %.3f seconds\n", 1.0 / reconnects_per_second * tries);
892 usleep(1000000 / reconnects_per_second);
896 fprintf(stderr, "Failed to reconnect for 30 seconds. Quitting.\n");
897 quit_handler(0, 0, 0, 0);
904 if (!option_exec && !lastpos)
905 write(STDOUT_FILENO, "\r", 1);
906 write(STDOUT_FILENO, buf, res);
907 if ((buf[res-1] == '\n') || (buf[res-2] == '\n')) {
920 static char *cli_prompt(EditLine *el)
922 static char prompt[200];
927 if ((pfmt = getenv("ASTERISK_PROMPT"))) {
928 char *t = pfmt, *p = prompt;
929 memset(prompt, 0, sizeof(prompt));
930 while (*t != '\0' && *p < sizeof(prompt)) {
939 int fgcolor = COLOR_WHITE, bgcolor = COLOR_BLACK;
943 case 'C': /* color */
945 if (sscanf(t, "%d;%d%n", &fgcolor, &bgcolor, &i) == 2) {
946 strncat(p, term_color_code(term_code, fgcolor, bgcolor, sizeof(term_code)),sizeof(prompt) - strlen(prompt) - 1);
948 } else if (sscanf(t, "%d%n", &fgcolor, &i) == 1) {
949 strncat(p, term_color_code(term_code, fgcolor, 0, sizeof(term_code)),sizeof(prompt) - strlen(prompt) - 1);
953 /* If the color has been reset correctly, then there's no need to reset it later */
954 if ((fgcolor == COLOR_WHITE) && (bgcolor == COLOR_BLACK)) {
961 memset(&tm, 0, sizeof(struct tm));
962 gettimeofday(&tv, NULL);
963 if (localtime_r(&(tv.tv_sec), &tm)) {
964 strftime(p, sizeof(prompt) - strlen(prompt), "%Y-%m-%d", &tm);
967 case 'h': /* hostname */
968 if (!gethostname(hostname, sizeof(hostname) - 1)) {
969 strncat(p, hostname, sizeof(prompt) - strlen(prompt) - 1);
971 strncat(p, "localhost", sizeof(prompt) - strlen(prompt) - 1);
974 case 'H': /* short hostname */
975 if (!gethostname(hostname, sizeof(hostname) - 1)) {
976 for (i=0;i<sizeof(hostname);i++) {
977 if (hostname[i] == '.') {
982 strncat(p, hostname, sizeof(prompt) - strlen(prompt) - 1);
984 strncat(p, "localhost", sizeof(prompt) - strlen(prompt) - 1);
988 case 'l': /* load avg */
990 if ((LOADAVG = fopen("/proc/loadavg", "r"))) {
991 float avg1, avg2, avg3;
992 int actproc, totproc, npid, which;
993 fscanf(LOADAVG, "%f %f %f %d/%d %d",
994 &avg1, &avg2, &avg3, &actproc, &totproc, &npid);
995 if (sscanf(t, "%d", &which) == 1) {
998 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg1);
1001 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg2);
1004 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg3);
1007 snprintf(p, sizeof(prompt) - strlen(prompt), "%d/%d", actproc, totproc);
1010 snprintf(p, sizeof(prompt) - strlen(prompt), "%d", npid);
1017 case 't': /* time */
1018 memset(&tm, 0, sizeof(struct tm));
1019 gettimeofday(&tv, NULL);
1020 if (localtime_r(&(tv.tv_sec), &tm)) {
1021 strftime(p, sizeof(prompt) - strlen(prompt), "%H:%M:%S", &tm);
1024 case '#': /* process console or remote? */
1025 if (! option_remote) {
1026 strncat(p, "#", sizeof(prompt) - strlen(prompt) - 1);
1028 strncat(p, ">", sizeof(prompt) - strlen(prompt) - 1);
1031 case '%': /* literal % */
1032 strncat(p, "%", sizeof(prompt) - strlen(prompt) - 1);
1034 case '\0': /* % is last character - prevent bug */
1038 while (*p != '\0') {
1049 /* Force colors back to normal at end */
1050 term_color_code(term_code, COLOR_WHITE, COLOR_BLACK, sizeof(term_code));
1051 if (strlen(term_code) > sizeof(prompt) - strlen(prompt)) {
1052 strncat(prompt + sizeof(prompt) - strlen(term_code) - 1, term_code, strlen(term_code));
1054 strncat(p, term_code, sizeof(term_code));
1057 } else if (remotehostname)
1058 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT2, remotehostname);
1060 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT);
1065 static char **ast_el_strtoarr(char *buf)
1067 char **match_list = NULL, *retstr;
1068 size_t match_list_len;
1072 while ( (retstr = strsep(&buf, " ")) != NULL) {
1074 if (!strcmp(retstr, AST_CLI_COMPLETE_EOF))
1076 if (matches + 1 >= match_list_len) {
1077 match_list_len <<= 1;
1078 match_list = realloc(match_list, match_list_len * sizeof(char *));
1081 match_list[matches++] = strdup(retstr);
1085 return (char **) NULL;
1087 if (matches>= match_list_len)
1088 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
1090 match_list[matches] = (char *) NULL;
1095 static int ast_el_sort_compare(const void *i1, const void *i2)
1099 s1 = ((char **)i1)[0];
1100 s2 = ((char **)i2)[0];
1102 return strcasecmp(s1, s2);
1105 static int ast_cli_display_match_list(char **matches, int len, int max)
1107 int i, idx, limit, count;
1108 int screenwidth = 0;
1109 int numoutput = 0, numoutputline = 0;
1111 screenwidth = ast_get_termcols(STDOUT_FILENO);
1113 /* find out how many entries can be put on one line, with two spaces between strings */
1114 limit = screenwidth / (max + 2);
1118 /* how many lines of output */
1119 count = len / limit;
1120 if (count * limit < len)
1125 qsort(&matches[0], (size_t)(len + 1), sizeof(char *), ast_el_sort_compare);
1127 for (; count > 0; count--) {
1129 for (i=0; i < limit && matches[idx]; i++, idx++) {
1131 /* Don't print dupes */
1132 if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
1135 matches[idx] = NULL;
1139 numoutput++; numoutputline++;
1140 fprintf(stdout, "%-*s ", max, matches[idx]);
1142 matches[idx] = NULL;
1144 if (numoutputline > 0)
1145 fprintf(stdout, "\n");
1152 static char *cli_complete(EditLine *el, int ch)
1158 int retval = CC_ERROR;
1162 LineInfo *lf = (LineInfo *)el_line(el);
1164 *(char *)lf->cursor = '\0';
1165 ptr = (char *)lf->cursor;
1167 while (ptr > lf->buffer) {
1168 if (isspace(*ptr)) {
1176 len = lf->cursor - ptr;
1178 if (option_remote) {
1179 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr);
1180 fdprint(ast_consock, buf);
1181 res = read(ast_consock, buf, sizeof(buf));
1183 nummatches = atoi(buf);
1185 if (nummatches > 0) {
1187 int mlen = 0, maxmbuf = 2048;
1188 /* Start with a 2048 byte buffer */
1189 mbuf = malloc(maxmbuf);
1191 return (char *)(CC_ERROR);
1192 snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr);
1193 fdprint(ast_consock, buf);
1196 while (!strstr(mbuf, AST_CLI_COMPLETE_EOF) && res != -1) {
1197 if (mlen + 1024 > maxmbuf) {
1198 /* Every step increment buffer 1024 bytes */
1200 mbuf = realloc(mbuf, maxmbuf);
1202 return (char *)(CC_ERROR);
1204 /* Only read 1024 bytes at a time */
1205 res = read(ast_consock, mbuf + mlen, 1024);
1211 matches = ast_el_strtoarr(mbuf);
1214 matches = (char **) NULL;
1219 nummatches = ast_cli_generatornummatches((char *)lf->buffer,ptr);
1220 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
1225 int matches_num, maxlen, match_len;
1227 if (matches[0][0] != '\0') {
1228 el_deletestr(el, (int) len);
1229 el_insertstr(el, matches[0]);
1230 retval = CC_REFRESH;
1233 if (nummatches == 1) {
1234 /* Found an exact match */
1235 el_insertstr(el, " ");
1236 retval = CC_REFRESH;
1238 /* Must be more than one match */
1239 for (i=1, maxlen=0; matches[i]; i++) {
1240 match_len = strlen(matches[i]);
1241 if (match_len > maxlen)
1244 matches_num = i - 1;
1245 if (matches_num >1) {
1246 fprintf(stdout, "\n");
1247 ast_cli_display_match_list(matches, nummatches, maxlen);
1248 retval = CC_REDISPLAY;
1250 el_insertstr(el," ");
1251 retval = CC_REFRESH;
1257 return (char *)(long)retval;
1260 static int ast_el_initialize(void)
1266 if (el_hist != NULL)
1267 history_end(el_hist);
1269 el = el_init("asterisk", stdin, stdout, stderr);
1270 el_set(el, EL_PROMPT, cli_prompt);
1272 el_set(el, EL_EDITMODE, 1);
1273 el_set(el, EL_EDITOR, "emacs");
1274 el_hist = history_init();
1275 if (!el || !el_hist)
1278 /* setup history with 100 entries */
1279 history(el_hist, &ev, H_SETSIZE, 100);
1281 el_set(el, EL_HIST, history, el_hist);
1283 el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
1284 /* Bind <tab> to command completion */
1285 el_set(el, EL_BIND, "^I", "ed-complete", NULL);
1286 /* Bind ? to command completion */
1287 el_set(el, EL_BIND, "?", "ed-complete", NULL);
1288 /* Bind ^D to redisplay */
1289 el_set(el, EL_BIND, "^D", "ed-redisplay", NULL);
1294 static int ast_el_add_history(char *buf)
1298 if (el_hist == NULL || el == NULL)
1299 ast_el_initialize();
1300 if (strlen(buf) > 256)
1302 return (history(el_hist, &ev, H_ENTER, buf));
1305 static int ast_el_write_history(char *filename)
1309 if (el_hist == NULL || el == NULL)
1310 ast_el_initialize();
1312 return (history(el_hist, &ev, H_SAVE, filename));
1315 static int ast_el_read_history(char *filename)
1321 if (el_hist == NULL || el == NULL)
1322 ast_el_initialize();
1324 if ((f = fopen(filename, "r")) == NULL)
1328 fgets(buf, sizeof(buf), f);
1329 if (!strcmp(buf, "_HiStOrY_V2_\n"))
1331 if ((ret = ast_el_add_history(buf)) == -1)
1339 static void ast_remotecontrol(char * data)
1343 char filename[80] = "";
1354 read(ast_consock, buf, sizeof(buf));
1356 write(ast_consock, data, strlen(data) + 1);
1358 hostname = strsep(&stringp, "/");
1359 cpid = strsep(&stringp, "/");
1360 version = strsep(&stringp, "\n");
1362 version = "<Version Unknown>";
1364 strsep(&stringp, ".");
1369 snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
1370 fdprint(ast_consock, tmp);
1371 ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
1372 remotehostname = hostname;
1374 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1375 if (el_hist == NULL || el == NULL)
1376 ast_el_initialize();
1378 el_set(el, EL_GETCFN, ast_el_read_char);
1380 if (!ast_strlen_zero(filename))
1381 ast_el_read_history(filename);
1383 ast_cli_register(&quit);
1384 ast_cli_register(&astexit);
1386 ast_cli_register(&astshutdown);
1388 if (option_exec && data) { /* hack to print output then exit if asterisk -rx is used */
1390 ast_el_read_char(el, &tempchar);
1394 ebuf = (char *)el_gets(el, &num);
1396 if (ebuf && !ast_strlen_zero(ebuf)) {
1397 if (ebuf[strlen(ebuf)-1] == '\n')
1398 ebuf[strlen(ebuf)-1] = '\0';
1399 if (!remoteconsolehandler(ebuf)) {
1400 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
1402 ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
1408 printf("\nDisconnected from Asterisk server\n");
1411 static int show_cli_help(void) {
1412 printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 2000-2004, Digium.\n");
1413 printf("Usage: asterisk [OPTIONS]\n");
1414 printf("Valid Options:\n");
1415 printf(" -C <configfile> Use an alternate configuration file\n");
1416 printf(" -c Provide console CLI\n");
1417 printf(" -d Enable extra debugging\n");
1418 printf(" -f Do not fork\n");
1419 printf(" -g Dump core in case of a crash\n");
1420 printf(" -h This help screen\n");
1421 printf(" -i Initializie crypto keys at startup\n");
1422 printf(" -n Disable console colorization\n");
1423 printf(" -p Run as pseudo-realtime thread\n");
1424 printf(" -q Quiet mode (supress output)\n");
1425 printf(" -r Connect to Asterisk on this machine\n");
1426 printf(" -R Connect to Asterisk, and attempt to reconnect if disconnected\n");
1427 printf(" -v Increase verbosity (multiple v's = more verbose)\n");
1428 printf(" -x <cmd> Execute command <cmd> (only valid with -r)\n");
1433 static void ast_readconfig(void) {
1434 struct ast_config *cfg;
1435 struct ast_variable *v;
1436 char *config = ASTCONFPATH;
1438 if (option_overrideconfig == 1) {
1439 cfg = ast_load((char *)ast_config_AST_CONFIG_FILE);
1441 cfg = ast_load(config);
1444 /* init with buildtime config */
1445 strncpy((char *)ast_config_AST_CONFIG_DIR,AST_CONFIG_DIR,sizeof(ast_config_AST_CONFIG_DIR)-1);
1446 strncpy((char *)ast_config_AST_SPOOL_DIR,AST_SPOOL_DIR,sizeof(ast_config_AST_SPOOL_DIR)-1);
1447 strncpy((char *)ast_config_AST_MODULE_DIR,AST_MODULE_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1448 strncpy((char *)ast_config_AST_VAR_DIR,AST_VAR_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1449 strncpy((char *)ast_config_AST_LOG_DIR,AST_LOG_DIR,sizeof(ast_config_AST_LOG_DIR)-1);
1450 strncpy((char *)ast_config_AST_AGI_DIR,AST_AGI_DIR,sizeof(ast_config_AST_AGI_DIR)-1);
1451 strncpy((char *)ast_config_AST_DB,AST_DB,sizeof(ast_config_AST_DB)-1);
1452 strncpy((char *)ast_config_AST_KEY_DIR,AST_KEY_DIR,sizeof(ast_config_AST_KEY_DIR)-1);
1453 strncpy((char *)ast_config_AST_PID,AST_PID,sizeof(ast_config_AST_PID)-1);
1454 strncpy((char *)ast_config_AST_SOCKET,AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1);
1455 strncpy((char *)ast_config_AST_RUN_DIR,AST_RUN_DIR,sizeof(ast_config_AST_RUN_DIR)-1);
1457 /* no asterisk.conf? no problem, use buildtime config! */
1461 v = ast_variable_browse(cfg, "directories");
1463 if (!strcasecmp(v->name, "astetcdir")) {
1464 strncpy((char *)ast_config_AST_CONFIG_DIR,v->value,sizeof(ast_config_AST_CONFIG_DIR)-1);
1465 } else if (!strcasecmp(v->name, "astspooldir")) {
1466 strncpy((char *)ast_config_AST_SPOOL_DIR,v->value,sizeof(ast_config_AST_SPOOL_DIR)-1);
1467 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1468 strncpy((char *)ast_config_AST_VAR_DIR,v->value,sizeof(ast_config_AST_VAR_DIR)-1);
1469 snprintf((char *)ast_config_AST_DB,sizeof(ast_config_AST_DB),"%s/%s",v->value,"astdb");
1470 } else if (!strcasecmp(v->name, "astlogdir")) {
1471 strncpy((char *)ast_config_AST_LOG_DIR,v->value,sizeof(ast_config_AST_LOG_DIR)-1);
1472 } else if (!strcasecmp(v->name, "astagidir")) {
1473 strncpy((char *)ast_config_AST_AGI_DIR,v->value,sizeof(ast_config_AST_AGI_DIR)-1);
1474 } else if (!strcasecmp(v->name, "astrundir")) {
1475 snprintf((char *)ast_config_AST_PID,sizeof(ast_config_AST_PID),"%s/%s",v->value,"asterisk.pid");
1476 snprintf((char *)ast_config_AST_SOCKET,sizeof(ast_config_AST_SOCKET),"%s/%s",v->value,"asterisk.ctl");
1477 strncpy((char *)ast_config_AST_RUN_DIR,v->value,sizeof(ast_config_AST_RUN_DIR)-1);
1478 } else if (!strcasecmp(v->name, "astmoddir")) {
1479 strncpy((char *)ast_config_AST_MODULE_DIR,v->value,sizeof(ast_config_AST_MODULE_DIR)-1);
1486 int main(int argc, char *argv[])
1489 char filename[80] = "";
1499 /* Remember original args for restart */
1500 if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1501 fprintf(stderr, "Truncating argument size to %d\n", (int)(sizeof(_argv) / sizeof(_argv[0])) - 1);
1502 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1504 for (x=0;x<argc;x++)
1508 /* if the progname is rasterisk consider it a remote console */
1509 if ( argv[0] && (strstr(argv[0], "rasterisk")) != NULL) {
1513 if (gethostname(hostname, sizeof(hostname)))
1514 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
1515 ast_mainpid = getpid();
1522 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1523 /* Check if we're root */
1526 ast_log(LOG_ERROR, "Must be run as root\n");
1530 /* Check for options */
1531 while((c=getopt(argc, argv, "hfdvqprRgcinx:C:")) != -1) {
1557 option_highpriority++;
1571 strncpy((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE) - 1);
1572 option_overrideconfig++;
1575 option_initcrypto++;
1588 if (option_dumpcore) {
1590 memset(&l, 0, sizeof(l));
1591 l.rlim_cur = RLIM_INFINITY;
1592 l.rlim_max = RLIM_INFINITY;
1593 if (setrlimit(RLIMIT_CORE, &l)) {
1594 ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
1602 /* Test recursive mutex locking. */
1603 if (test_for_thread_safety())
1604 ast_verbose("Warning! Asterisk is not thread safe.\n");
1606 if (option_console && !option_verbose)
1607 ast_verbose("[ Reading Master Configuration ]");
1610 if (option_console && !option_verbose)
1611 ast_verbose("[ Initializing Custom Configuration Options]");
1612 /* custom config setup */
1613 register_config_cli();
1614 read_ast_cust_config();
1617 if (option_console) {
1618 if (el_hist == NULL || el == NULL)
1619 ast_el_initialize();
1621 if (!ast_strlen_zero(filename))
1622 ast_el_read_history(filename);
1625 if (ast_tryconnect()) {
1626 /* One is already running */
1627 if (option_remote) {
1629 ast_remotecontrol(xarg);
1630 quit_handler(0, 0, 0, 0);
1633 printf(term_quit());
1634 ast_register_verbose(console_verboser);
1636 ast_remotecontrol(NULL);
1637 quit_handler(0, 0, 0, 0);
1640 ast_log(LOG_ERROR, "Asterisk already running on %s. Use 'asterisk -r' to connect.\n", (char *)ast_config_AST_SOCKET);
1641 printf(term_quit());
1644 } else if (option_remote || option_exec) {
1645 ast_log(LOG_ERROR, "Unable to connect to remote asterisk\n");
1646 printf(term_quit());
1649 /* Blindly write pid file since we couldn't connect */
1650 unlink((char *)ast_config_AST_PID);
1651 f = fopen((char *)ast_config_AST_PID, "w");
1653 fprintf(f, "%d\n", getpid());
1656 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1658 if (!option_verbose && !option_debug && !option_nofork && !option_console) {
1660 /* Blindly re-write pid file since we are forking */
1661 unlink((char *)ast_config_AST_PID);
1662 f = fopen((char *)ast_config_AST_PID, "w");
1664 fprintf(f, "%d\n", getpid());
1667 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1672 sigaddset(&sigs, SIGHUP);
1673 sigaddset(&sigs, SIGTERM);
1674 sigaddset(&sigs, SIGINT);
1675 sigaddset(&sigs, SIGPIPE);
1676 sigaddset(&sigs, SIGWINCH);
1677 pthread_sigmask(SIG_BLOCK, &sigs, NULL);
1678 if (option_console || option_verbose || option_remote)
1679 ast_register_verbose(console_verboser);
1680 /* Print a welcome message if desired */
1681 if (option_verbose || option_console) {
1684 if (option_console && !option_verbose)
1685 ast_verbose("[ Booting...");
1687 signal(SIGURG, urg_handler);
1688 signal(SIGINT, __quit_handler);
1689 signal(SIGTERM, __quit_handler);
1690 signal(SIGHUP, hup_handler);
1691 signal(SIGCHLD, child_handler);
1692 signal(SIGPIPE, SIG_IGN);
1694 if (set_priority(option_highpriority)) {
1695 printf(term_quit());
1698 if (init_logger()) {
1699 printf(term_quit());
1702 if (init_manager()) {
1703 printf(term_quit());
1707 if (ast_image_init()) {
1708 printf(term_quit());
1711 if (ast_file_init()) {
1712 printf(term_quit());
1716 printf(term_quit());
1719 if (load_modules()) {
1720 printf(term_quit());
1723 if (init_framer()) {
1724 printf(term_quit());
1728 printf(term_quit());
1731 if (ast_enum_init()) {
1732 printf(term_quit());
1735 /* reload logger in case a custom config handler binded to logger.conf*/
1738 /* We might have the option of showing a console, but for now just
1740 if (option_console && !option_verbose)
1741 ast_verbose(" ]\n");
1742 if (option_verbose || option_console)
1743 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
1745 consolethread = pthread_self();
1747 pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
1748 #ifdef __AST_DEBUG_MALLOC
1751 time(&ast_startuptime);
1752 ast_cli_register(&astshutdownnow);
1753 ast_cli_register(&astshutdowngracefully);
1754 ast_cli_register(&astrestartnow);
1755 ast_cli_register(&astrestartgracefully);
1756 ast_cli_register(&astrestartwhenconvenient);
1757 ast_cli_register(&astshutdownwhenconvenient);
1758 ast_cli_register(&aborthalt);
1759 ast_cli_register(&astbang);
1760 if (option_console) {
1761 /* Console stuff now... */
1762 /* Register our quit function */
1764 set_icon("Asterisk");
1765 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, ast_mainpid);
1767 ast_cli_register(&quit);
1768 ast_cli_register(&astexit);
1771 buf = (char *)el_gets(el, &num);
1773 if (buf[strlen(buf)-1] == '\n')
1774 buf[strlen(buf)-1] = '\0';
1776 consolehandler((char *)buf);
1779 ast_cli(STDOUT_FILENO, "\nUse EXIT or QUIT to exit the asterisk console\n");