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);
267 ast_log(LOG_WARNING, "Accept retured %d: %s\n", s, strerror(errno));
269 for (x=0;x<AST_MAX_CONNECTS;x++) {
270 if (consoles[x].fd < 0) {
271 if (socketpair(AF_LOCAL, SOCK_STREAM, 0, consoles[x].p)) {
272 ast_log(LOG_ERROR, "Unable to create pipe: %s\n", strerror(errno));
274 fdprint(s, "Server failed to create pipe\n");
278 flags = fcntl(consoles[x].p[1], F_GETFL);
279 fcntl(consoles[x].p[1], F_SETFL, flags | O_NONBLOCK);
281 if (pthread_create(&consoles[x].t, &attr, netconsole, &consoles[x])) {
282 ast_log(LOG_ERROR, "Unable to spawn thread to handle connection\n");
284 fdprint(s, "Server failed to spawn thread\n");
290 if (x >= AST_MAX_CONNECTS) {
291 fdprint(s, "No more connections allowed\n");
292 ast_log(LOG_WARNING, "No more connections allowed\n");
294 } else if (consoles[x].fd > -1) {
295 if (option_verbose > 2)
296 ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection\n");
303 static int ast_makesocket(void)
305 struct sockaddr_un sun;
308 for (x=0;x<AST_MAX_CONNECTS;x++)
310 unlink((char *)ast_config_AST_SOCKET);
311 ast_socket = socket(PF_LOCAL, SOCK_STREAM, 0);
312 if (ast_socket < 0) {
313 ast_log(LOG_WARNING, "Unable to create control socket: %s\n", strerror(errno));
316 memset(&sun, 0, sizeof(sun));
317 sun.sun_family = AF_LOCAL;
318 strncpy(sun.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sun.sun_path)-1);
319 res = bind(ast_socket, (struct sockaddr *)&sun, sizeof(sun));
321 ast_log(LOG_WARNING, "Unable to bind socket to %s: %s\n", (char *)ast_config_AST_SOCKET, strerror(errno));
326 res = listen(ast_socket, 2);
328 ast_log(LOG_WARNING, "Unable to listen on socket %s: %s\n", (char *)ast_config_AST_SOCKET, strerror(errno));
333 ast_register_verbose(network_verboser);
334 pthread_create(<hread, NULL, listener, NULL);
338 static int ast_tryconnect(void)
340 struct sockaddr_un sun;
342 ast_consock = socket(PF_LOCAL, SOCK_STREAM, 0);
343 if (ast_consock < 0) {
344 ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
347 memset(&sun, 0, sizeof(sun));
348 sun.sun_family = AF_LOCAL;
349 strncpy(sun.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sun.sun_path)-1);
350 res = connect(ast_consock, (struct sockaddr *)&sun, sizeof(sun));
359 static void urg_handler(int num)
361 /* Called by soft_hangup to interrupt the select, read, or other
362 system call. We don't actually need to do anything though. */
363 /* Cannot EVER ast_log from within a signal handler */
365 printf("Urgent handler\n");
366 signal(num, urg_handler);
370 static void hup_handler(int num)
372 if (option_verbose > 1)
373 printf("Received HUP signal -- Reloading configs\n");
375 execvp(_argv[0], _argv);
376 /* XXX This could deadlock XXX */
380 static void child_handler(int sig)
382 /* Must not ever ast_log or ast_verbose within signal handler */
386 * Reap all dead children -- not just one
388 for (n = 0; wait4(-1, &status, WNOHANG, NULL) > 0; n++)
390 if (n == 0 && option_debug)
391 printf("Huh? Child handler, but nobody there?\n");
394 static void set_title(char *text)
396 /* Set an X-term or screen title */
397 if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
398 fprintf(stdout, "\033]2;%s\007", text);
401 static void set_icon(char *text)
403 if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
404 fprintf(stdout, "\033]1;%s\007", text);
407 static int set_priority(int pri)
409 struct sched_param sched;
410 memset(&sched, 0, sizeof(sched));
411 /* We set ourselves to a high priority, that we might pre-empt everything
412 else. If your PBX has heavy activity on it, this is a good thing. */
415 sched.sched_priority = 10;
416 if (sched_setscheduler(0, SCHED_RR, &sched)) {
417 ast_log(LOG_WARNING, "Unable to set high priority\n");
421 ast_verbose("Set to realtime thread\n");
423 sched.sched_priority = 0;
424 if (sched_setscheduler(0, SCHED_OTHER, &sched)) {
425 ast_log(LOG_WARNING, "Unable to set normal priority\n");
431 if (setpriority(PRIO_PROCESS, 0, -10) == -1) {
432 ast_log(LOG_WARNING, "Unable to set high priority\n");
436 ast_verbose("Set to high priority\n");
438 if (setpriority(PRIO_PROCESS, 0, 0) == -1) {
439 ast_log(LOG_WARNING, "Unable to set normal priority\n");
447 static void ast_run_atexits(void)
449 struct ast_atexit *ae;
450 ast_mutex_lock(&atexitslock);
457 ast_mutex_unlock(&atexitslock);
460 static void quit_handler(int num, int nice, int safeshutdown, int restart)
462 char filename[80] = "";
468 /* Begin shutdown routine, hanging up active channels */
469 ast_begin_shutdown(1);
470 if (option_verbose && option_console)
471 ast_verbose("Beginning asterisk %s....\n", restart ? "restart" : "shutdown");
475 /* Wait up to 15 seconds for all channels to go away */
478 if (!ast_active_channels())
482 /* Sleep 1/10 of a second */
487 ast_begin_shutdown(0);
488 if (option_verbose && option_console)
489 ast_verbose("Waiting for inactivity to perform %s...\n", restart ? "restart" : "halt");
491 if (!ast_active_channels())
500 if (option_verbose && option_console)
501 ast_verbose("Asterisk %s cancelled.\n", restart ? "restart" : "shutdown");
505 if (option_console || option_remote) {
507 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
508 if (strlen(filename))
509 ast_el_write_history(filename);
513 history_end(el_hist);
516 ast_verbose("Executing last minute cleanups\n");
519 if (option_verbose && option_console)
520 ast_verbose("Asterisk %s ending (%d).\n", ast_active_channels() ? "uncleanly" : "cleanly", num);
521 else if (option_debug)
522 ast_log(LOG_DEBUG, "Asterisk ending (%d).\n", num);
523 manager_event(EVENT_FLAG_SYSTEM, "Shutdown", "Shutdown: %s\r\nRestart: %s\r\n", ast_active_channels() ? "Uncleanly" : "Cleanly", restart ? "True" : "False");
524 if (ast_socket > -1) {
528 if (ast_consock > -1)
531 unlink((char *)ast_config_AST_SOCKET);
532 if (!option_remote) unlink((char *)ast_config_AST_PID);
535 if (option_verbose || option_console)
536 ast_verbose("Preparing for Asterisk restart...\n");
537 /* Mark all FD's for closing on exec */
538 for (x=3;x<32768;x++) {
539 fcntl(x, F_SETFD, FD_CLOEXEC);
541 if (option_verbose || option_console)
542 ast_verbose("Restarting Asterisk NOW...\n");
544 /* If there is a consolethread running send it a SIGHUP
545 so it can execvp, otherwise we can do it ourselves */
546 if (consolethread != (pthread_t) -1)
547 pthread_kill(consolethread, SIGHUP);
549 execvp(_argv[0], _argv);
555 static void __quit_handler(int num)
557 quit_handler(num, 0, 1, 0);
560 static const char *fix_header(char *outbuf, int maxout, const char *s, char *cmp)
563 if (!strncmp(s, cmp, strlen(cmp))) {
565 term_color(outbuf, cmp, COLOR_GRAY, 0, maxout);
571 static void console_verboser(const char *s, int pos, int replace, int complete)
575 /* Return to the beginning of the line */
577 fprintf(stdout, "\r");
578 if ((c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_4)) ||
579 (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_3)) ||
580 (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_2)) ||
581 (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_1)))
585 fputs(c + pos,stdout);
587 fputs(s + pos,stdout);
590 /* Wake up a select()ing console */
591 if (consolethread != (pthread_t) -1)
592 pthread_kill(consolethread, SIGURG);
595 static void consolehandler(char *s)
599 /* Called when readline data is available */
601 ast_el_add_history(s);
602 /* Give the console access to the shell */
604 /* The real handler for bang */
609 system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
611 ast_cli_command(STDOUT_FILENO, s);
613 fprintf(stdout, "\nUse \"quit\" to exit\n");
616 static int remoteconsolehandler(char *s)
619 /* Called when readline data is available */
621 ast_el_add_history(s);
622 /* Give the console access to the shell */
624 /* The real handler for bang */
629 system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
632 if ((strncasecmp(s, "quit", 4) == 0 || strncasecmp(s, "exit", 4) == 0) &&
633 (s[4] == '\0' || isspace(s[4]))) {
634 quit_handler(0, 0, 0, 0);
638 fprintf(stdout, "\nUse \"quit\" to exit\n");
643 static char quit_help[] =
645 " Exits Asterisk.\n";
647 static char abort_halt_help[] =
648 "Usage: abort shutdown\n"
649 " Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
650 " call operations.\n";
652 static char shutdown_now_help[] =
654 " Shuts down a running Asterisk immediately, hanging up all active calls .\n";
656 static char shutdown_gracefully_help[] =
657 "Usage: stop gracefully\n"
658 " Causes Asterisk to not accept new calls, and exit when all\n"
659 " active calls have terminated normally.\n";
661 static char shutdown_when_convenient_help[] =
662 "Usage: stop when convenient\n"
663 " Causes Asterisk to perform a shutdown when all active calls have ended.\n";
665 static char restart_now_help[] =
666 "Usage: restart now\n"
667 " Causes Asterisk to hangup all calls and exec() itself performing a cold.\n"
670 static char restart_gracefully_help[] =
671 "Usage: restart gracefully\n"
672 " Causes Asterisk to stop accepting new calls and exec() itself performing a cold.\n"
673 " restart when all active calls have ended.\n";
675 static char restart_when_convenient_help[] =
676 "Usage: restart when convenient\n"
677 " Causes Asterisk to perform a cold restart when all active calls have ended.\n";
679 static char bang_help[] =
680 "Usage: !<command>\n"
681 " Executes a given shell command\n";
684 static int handle_quit(int fd, int argc, char *argv[])
687 return RESULT_SHOWUSAGE;
688 quit_handler(0, 0, 1, 0);
689 return RESULT_SUCCESS;
693 static int no_more_quit(int fd, int argc, char *argv[])
696 return RESULT_SHOWUSAGE;
697 ast_cli(fd, "The QUIT and EXIT commands may no longer be used to shutdown the PBX.\n"
698 "Please use STOP NOW instead, if you wish to shutdown the PBX.\n");
699 return RESULT_SUCCESS;
702 static int handle_shutdown_now(int fd, int argc, char *argv[])
705 return RESULT_SHOWUSAGE;
706 quit_handler(0, 0 /* Not nice */, 1 /* safely */, 0 /* not restart */);
707 return RESULT_SUCCESS;
710 static int handle_shutdown_gracefully(int fd, int argc, char *argv[])
713 return RESULT_SHOWUSAGE;
714 quit_handler(0, 1 /* nicely */, 1 /* safely */, 0 /* no restart */);
715 return RESULT_SUCCESS;
718 static int handle_shutdown_when_convenient(int fd, int argc, char *argv[])
721 return RESULT_SHOWUSAGE;
722 quit_handler(0, 2 /* really nicely */, 1 /* safely */, 0 /* don't restart */);
723 return RESULT_SUCCESS;
726 static int handle_restart_now(int fd, int argc, char *argv[])
729 return RESULT_SHOWUSAGE;
730 quit_handler(0, 0 /* not nicely */, 1 /* safely */, 1 /* restart */);
731 return RESULT_SUCCESS;
734 static int handle_restart_gracefully(int fd, int argc, char *argv[])
737 return RESULT_SHOWUSAGE;
738 quit_handler(0, 1 /* nicely */, 1 /* safely */, 1 /* restart */);
739 return RESULT_SUCCESS;
742 static int handle_restart_when_convenient(int fd, int argc, char *argv[])
745 return RESULT_SHOWUSAGE;
746 quit_handler(0, 2 /* really nicely */, 1 /* safely */, 1 /* restart */);
747 return RESULT_SUCCESS;
750 static int handle_abort_halt(int fd, int argc, char *argv[])
753 return RESULT_SHOWUSAGE;
754 ast_cancel_shutdown();
756 return RESULT_SUCCESS;
759 static int handle_bang(int fd, int argc, char *argv[])
761 return RESULT_SUCCESS;
764 #define ASTERISK_PROMPT "*CLI> "
766 #define ASTERISK_PROMPT2 "%s*CLI> "
768 static struct ast_cli_entry aborthalt = { { "abort", "halt", NULL }, handle_abort_halt, "Cancel a running halt", abort_halt_help };
770 static struct ast_cli_entry quit = { { "quit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
771 static struct ast_cli_entry astexit = { { "exit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
773 static struct ast_cli_entry astshutdownnow = { { "stop", "now", NULL }, handle_shutdown_now, "Shut down Asterisk immediately", shutdown_now_help };
774 static struct ast_cli_entry astshutdowngracefully = { { "stop", "gracefully", NULL }, handle_shutdown_gracefully, "Gracefully shut down Asterisk", shutdown_gracefully_help };
775 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 };
776 static struct ast_cli_entry astrestartnow = { { "restart", "now", NULL }, handle_restart_now, "Restart Asterisk immediately", restart_now_help };
777 static struct ast_cli_entry astrestartgracefully = { { "restart", "gracefully", NULL }, handle_restart_gracefully, "Restart Asterisk gracefully", restart_gracefully_help };
778 static struct ast_cli_entry astrestartwhenconvenient= { { "restart", "when", "convenient", NULL }, handle_restart_when_convenient, "Restart Asterisk at empty call volume", restart_when_convenient_help };
779 static struct ast_cli_entry astbang = { { "!", NULL }, handle_bang, "Execute a shell command", bang_help };
781 static int ast_el_read_char(EditLine *el, char *cp)
792 FD_SET(ast_consock, &rfds);
795 FD_SET(STDIN_FILENO, &rfds);
796 if (STDIN_FILENO > max)
799 res = ast_select(max+1, &rfds, NULL, NULL, NULL);
803 ast_log(LOG_ERROR, "select failed: %s\n", strerror(errno));
807 if (FD_ISSET(STDIN_FILENO, &rfds)) {
808 num_read = read(STDIN_FILENO, cp, 1);
814 if (FD_ISSET(ast_consock, &rfds)) {
815 res = read(ast_consock, buf, sizeof(buf) - 1);
816 /* if the remote side disappears exit */
818 fprintf(stderr, "\nDisconnected from Asterisk server\n");
819 quit_handler(0, 0, 0, 0);
824 if (!option_exec && !lastpos)
825 write(STDOUT_FILENO, "\r", 1);
826 write(STDOUT_FILENO, buf, res);
827 if ((buf[res-1] == '\n') || (buf[res-2] == '\n')) {
840 static char *cli_prompt(EditLine *el)
842 static char prompt[80];
845 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT2, remotehostname);
847 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT);
852 static char **ast_el_strtoarr(char *buf)
854 char **match_list = NULL, *retstr;
855 size_t match_list_len;
859 while ( (retstr = strsep(&buf, " ")) != NULL) {
861 if (matches + 1 >= match_list_len) {
862 match_list_len <<= 1;
863 match_list = realloc(match_list, match_list_len * sizeof(char *));
866 match_list[matches++] = retstr;
870 return (char **) NULL;
872 if (matches>= match_list_len)
873 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
875 match_list[matches] = (char *) NULL;
880 static int ast_el_sort_compare(const void *i1, const void *i2)
884 s1 = ((char **)i1)[0];
885 s2 = ((char **)i2)[0];
887 return strcasecmp(s1, s2);
890 static int ast_cli_display_match_list(char **matches, int len, int max)
892 int i, idx, limit, count;
894 int numoutput = 0, numoutputline = 0;
896 screenwidth = ast_get_termcols(STDOUT_FILENO);
898 /* find out how many entries can be put on one line, with two spaces between strings */
899 limit = screenwidth / (max + 2);
903 /* how many lines of output */
905 if (count * limit < len)
910 qsort(&matches[0], (size_t)(len + 1), sizeof(char *), ast_el_sort_compare);
912 for (; count > 0; count--) {
914 for (i=0; i < limit && matches[idx]; i++, idx++) {
916 /* Don't print dupes */
917 if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
922 numoutput++; numoutputline++;
923 fprintf(stdout, "%-*s ", max, matches[idx]);
925 if (numoutputline > 0)
926 fprintf(stdout, "\n");
933 static char *cli_complete(EditLine *el, int ch)
939 int retval = CC_ERROR;
943 LineInfo *lf = (LineInfo *)el_line(el);
945 *(char *)lf->cursor = '\0';
946 ptr = (char *)lf->cursor;
948 while (ptr > lf->buffer) {
957 len = lf->cursor - ptr;
960 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr);
961 fdprint(ast_consock, buf);
962 res = read(ast_consock, buf, sizeof(buf));
964 nummatches = atoi(buf);
966 if (nummatches > 0) {
967 snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr);
968 fdprint(ast_consock, buf);
969 res = read(ast_consock, buf, sizeof(buf));
972 matches = ast_el_strtoarr(buf);
974 matches = (char **) NULL;
979 nummatches = ast_cli_generatornummatches((char *)lf->buffer,ptr);
980 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
985 int matches_num, maxlen, match_len;
987 if (matches[0][0] != '\0') {
988 el_deletestr(el, (int) len);
989 el_insertstr(el, matches[0]);
993 if (nummatches == 1) {
994 /* Found an exact match */
995 el_insertstr(el, " ");
998 /* Must be more than one match */
999 for (i=1, maxlen=0; matches[i]; i++) {
1000 match_len = strlen(matches[i]);
1001 if (match_len > maxlen)
1004 matches_num = i - 1;
1005 if (matches_num >1) {
1006 fprintf(stdout, "\n");
1007 ast_cli_display_match_list(matches, nummatches, maxlen);
1008 retval = CC_REDISPLAY;
1010 el_insertstr(el," ");
1011 retval = CC_REFRESH;
1017 return (char *)retval;
1020 static int ast_el_initialize(void)
1026 if (el_hist != NULL)
1027 history_end(el_hist);
1029 el = el_init("asterisk", stdin, stdout, stderr);
1030 el_set(el, EL_PROMPT, cli_prompt);
1032 el_set(el, EL_EDITMODE, 1);
1033 el_set(el, EL_EDITOR, "emacs");
1034 el_hist = history_init();
1035 if (!el || !el_hist)
1038 /* setup history with 100 entries */
1039 history(el_hist, &ev, H_SETSIZE, 100);
1041 el_set(el, EL_HIST, history, el_hist);
1043 el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
1044 /* Bind <tab> to command completion */
1045 el_set(el, EL_BIND, "^I", "ed-complete", NULL);
1046 /* Bind ? to command completion */
1047 el_set(el, EL_BIND, "?", "ed-complete", NULL);
1052 static int ast_el_add_history(char *buf)
1056 if (el_hist == NULL || el == NULL)
1057 ast_el_initialize();
1058 if (strlen(buf) > 256)
1060 return (history(el_hist, &ev, H_ENTER, buf));
1063 static int ast_el_write_history(char *filename)
1067 if (el_hist == NULL || el == NULL)
1068 ast_el_initialize();
1070 return (history(el_hist, &ev, H_SAVE, filename));
1073 static int ast_el_read_history(char *filename)
1079 if (el_hist == NULL || el == NULL)
1080 ast_el_initialize();
1082 if ((f = fopen(filename, "r")) == NULL)
1086 fgets(buf, sizeof(buf), f);
1087 if (!strcmp(buf, "_HiStOrY_V2_\n"))
1089 if ((ret = ast_el_add_history(buf)) == -1)
1097 static void ast_remotecontrol(char * data)
1101 char filename[80] = "";
1112 read(ast_consock, buf, sizeof(buf));
1114 write(ast_consock, data, strlen(data) + 1);
1116 hostname = strsep(&stringp, "/");
1117 cpid = strsep(&stringp, "/");
1118 version = strsep(&stringp, "\n");
1120 version = "<Version Unknown>";
1122 strsep(&stringp, ".");
1127 snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
1128 fdprint(ast_consock, tmp);
1129 ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
1130 remotehostname = hostname;
1132 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1133 if (el_hist == NULL || el == NULL)
1134 ast_el_initialize();
1136 el_set(el, EL_GETCFN, ast_el_read_char);
1138 if (strlen(filename))
1139 ast_el_read_history(filename);
1141 ast_cli_register(&quit);
1142 ast_cli_register(&astexit);
1144 ast_cli_register(&astshutdown);
1146 if (option_exec && data) { /* hack to print output then exit if asterisk -rx is used */
1148 ast_el_read_char(el, &tempchar);
1152 ebuf = (char *)el_gets(el, &num);
1154 if (ebuf && strlen(ebuf)) {
1155 if (ebuf[strlen(ebuf)-1] == '\n')
1156 ebuf[strlen(ebuf)-1] = '\0';
1157 if (!remoteconsolehandler(ebuf)) {
1158 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
1160 ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
1166 printf("\nDisconnected from Asterisk server\n");
1169 static int show_cli_help(void) {
1170 printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 2000-2002, Digium.\n");
1171 printf("Usage: asterisk [OPTIONS]\n");
1172 printf("Valid Options:\n");
1173 printf(" -h This help screen\n");
1174 printf(" -r Connect to Asterisk on this machine\n");
1175 printf(" -f Do not fork\n");
1176 printf(" -n Disable console colorization\n");
1177 printf(" -p Run as pseudo-realtime thread\n");
1178 printf(" -v Increase verbosity (multiple v's = more verbose)\n");
1179 printf(" -q Quiet mode (supress output)\n");
1180 printf(" -g Dump core in case of a crash\n");
1181 printf(" -x <cmd> Execute command <cmd> (only valid with -r)\n");
1182 printf(" -i Initializie crypto keys at startup\n");
1183 printf(" -c Provide console CLI\n");
1184 printf(" -d Enable extra debugging\n");
1189 static void ast_readconfig(void) {
1190 struct ast_config *cfg;
1191 struct ast_variable *v;
1192 char *config = ASTCONFPATH;
1194 if (option_overrideconfig == 1) {
1195 cfg = ast_load((char *)ast_config_AST_CONFIG_FILE);
1197 cfg = ast_load(config);
1200 /* init with buildtime config */
1201 strncpy((char *)ast_config_AST_CONFIG_DIR,AST_CONFIG_DIR,sizeof(ast_config_AST_CONFIG_DIR)-1);
1202 strncpy((char *)ast_config_AST_SPOOL_DIR,AST_SPOOL_DIR,sizeof(ast_config_AST_SPOOL_DIR)-1);
1203 strncpy((char *)ast_config_AST_MODULE_DIR,AST_MODULE_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1204 strncpy((char *)ast_config_AST_VAR_DIR,AST_VAR_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1205 strncpy((char *)ast_config_AST_LOG_DIR,AST_LOG_DIR,sizeof(ast_config_AST_LOG_DIR)-1);
1206 strncpy((char *)ast_config_AST_AGI_DIR,AST_AGI_DIR,sizeof(ast_config_AST_AGI_DIR)-1);
1207 strncpy((char *)ast_config_AST_DB,AST_DB,sizeof(ast_config_AST_DB)-1);
1208 strncpy((char *)ast_config_AST_KEY_DIR,AST_KEY_DIR,sizeof(ast_config_AST_KEY_DIR)-1);
1209 strncpy((char *)ast_config_AST_PID,AST_PID,sizeof(ast_config_AST_PID)-1);
1210 strncpy((char *)ast_config_AST_SOCKET,AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1);
1211 strncpy((char *)ast_config_AST_RUN_DIR,AST_RUN_DIR,sizeof(ast_config_AST_RUN_DIR)-1);
1213 /* no asterisk.conf? no problem, use buildtime config! */
1217 v = ast_variable_browse(cfg, "directories");
1219 if (!strcasecmp(v->name, "astetcdir")) {
1220 strncpy((char *)ast_config_AST_CONFIG_DIR,v->value,sizeof(ast_config_AST_CONFIG_DIR)-1);
1221 } else if (!strcasecmp(v->name, "astspooldir")) {
1222 strncpy((char *)ast_config_AST_SPOOL_DIR,v->value,sizeof(ast_config_AST_SPOOL_DIR)-1);
1223 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1224 strncpy((char *)ast_config_AST_VAR_DIR,v->value,sizeof(ast_config_AST_VAR_DIR)-1);
1225 snprintf((char *)ast_config_AST_DB,sizeof(ast_config_AST_DB)-1,"%s/%s",v->value,"astdb");
1226 } else if (!strcasecmp(v->name, "astlogdir")) {
1227 strncpy((char *)ast_config_AST_LOG_DIR,v->value,sizeof(ast_config_AST_LOG_DIR)-1);
1228 } else if (!strcasecmp(v->name, "astagidir")) {
1229 strncpy((char *)ast_config_AST_AGI_DIR,v->value,sizeof(ast_config_AST_AGI_DIR)-1);
1230 } else if (!strcasecmp(v->name, "astrundir")) {
1231 snprintf((char *)ast_config_AST_PID,sizeof(ast_config_AST_PID)-1,"%s/%s",v->value,"asterisk.pid");
1232 snprintf((char *)ast_config_AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1,"%s/%s",v->value,"asterisk.ctl");
1233 strncpy((char *)ast_config_AST_RUN_DIR,v->value,sizeof(ast_config_AST_RUN_DIR)-1);
1234 } else if (!strcasecmp(v->name, "astmoddir")) {
1235 strncpy((char *)ast_config_AST_MODULE_DIR,v->value,sizeof(ast_config_AST_MODULE_DIR)-1);
1242 int main(int argc, char *argv[])
1245 char filename[80] = "";
1255 /* Remember original args for restart */
1256 if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1257 fprintf(stderr, "Truncating argument size to %d\n", sizeof(_argv) / sizeof(_argv[0]) - 1);
1258 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1260 for (x=0;x<argc;x++)
1264 if (gethostname(hostname, sizeof(hostname)))
1265 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
1272 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1273 /* Check if we're root */
1276 ast_log(LOG_ERROR, "Must be run as root\n");
1280 /* Check for options */
1281 while((c=getopt(argc, argv, "hfdvqprgcinx:C:")) != -1) {
1302 option_highpriority++;
1316 strncpy((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE));
1317 option_overrideconfig++;
1320 option_initcrypto++;
1333 if (option_dumpcore) {
1335 memset(&l, 0, sizeof(l));
1336 l.rlim_cur = RLIM_INFINITY;
1337 l.rlim_max = RLIM_INFINITY;
1338 if (setrlimit(RLIMIT_CORE, &l)) {
1339 ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
1346 if (option_console && !option_verbose)
1347 ast_verbose("[ Reading Master Configuration ]");
1350 if (option_console) {
1351 if (el_hist == NULL || el == NULL)
1352 ast_el_initialize();
1354 if (strlen(filename))
1355 ast_el_read_history(filename);
1358 if (ast_tryconnect()) {
1359 /* One is already running */
1360 if (option_remote) {
1362 ast_remotecontrol(xarg);
1363 quit_handler(0, 0, 0, 0);
1366 printf(term_quit());
1367 ast_register_verbose(console_verboser);
1368 ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2004 Digium.\n");
1369 ast_verbose( "Written by Mark Spencer <markster@digium.com>\n");
1370 ast_verbose( "=========================================================================\n");
1371 ast_remotecontrol(NULL);
1372 quit_handler(0, 0, 0, 0);
1375 ast_log(LOG_ERROR, "Asterisk already running on %s. Use 'asterisk -r' to connect.\n", (char *)ast_config_AST_SOCKET);
1376 printf(term_quit());
1379 } else if (option_remote || option_exec) {
1380 ast_log(LOG_ERROR, "Unable to connect to remote asterisk\n");
1381 printf(term_quit());
1384 /* Blindly write pid file since we couldn't connect */
1385 unlink((char *)ast_config_AST_PID);
1386 f = fopen((char *)ast_config_AST_PID, "w");
1388 fprintf(f, "%d\n", getpid());
1391 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1393 if (!option_verbose && !option_debug && !option_nofork && !option_console) {
1395 /* Blindly re-write pid file since we are forking */
1396 unlink((char *)ast_config_AST_PID);
1397 f = fopen((char *)ast_config_AST_PID, "w");
1399 fprintf(f, "%d\n", getpid());
1402 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1407 sigaddset(&sigs, SIGHUP);
1408 sigaddset(&sigs, SIGTERM);
1409 sigaddset(&sigs, SIGINT);
1410 sigaddset(&sigs, SIGPIPE);
1411 sigaddset(&sigs, SIGWINCH);
1412 pthread_sigmask(SIG_BLOCK, &sigs, NULL);
1413 if (option_console || option_verbose || option_remote)
1414 ast_register_verbose(console_verboser);
1415 /* Print a welcome message if desired */
1416 if (option_verbose || option_console) {
1417 ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2001 Linux Support Services, Inc.\n");
1418 ast_verbose( "Written by Mark Spencer <markster@linux-support.net>\n");
1419 ast_verbose( "=========================================================================\n");
1421 if (option_console && !option_verbose)
1422 ast_verbose("[ Booting...");
1424 signal(SIGURG, urg_handler);
1425 signal(SIGINT, __quit_handler);
1426 signal(SIGTERM, __quit_handler);
1427 signal(SIGHUP, hup_handler);
1428 signal(SIGCHLD, child_handler);
1429 signal(SIGPIPE, SIG_IGN);
1431 if (set_priority(option_highpriority)) {
1432 printf(term_quit());
1435 if (init_logger()) {
1436 printf(term_quit());
1439 if (init_manager()) {
1440 printf(term_quit());
1444 if (ast_image_init()) {
1445 printf(term_quit());
1449 printf(term_quit());
1452 if (load_modules()) {
1453 printf(term_quit());
1456 if (init_framer()) {
1457 printf(term_quit());
1461 printf(term_quit());
1464 if (ast_enum_init()) {
1465 printf(term_quit());
1468 /* We might have the option of showing a console, but for now just
1470 if (option_console && !option_verbose)
1471 ast_verbose(" ]\n");
1472 if (option_verbose || option_console)
1473 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
1475 pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
1476 #ifdef __AST_DEBUG_MALLOC
1479 time(&ast_startuptime);
1480 ast_cli_register(&astshutdownnow);
1481 ast_cli_register(&astshutdowngracefully);
1482 ast_cli_register(&astrestartnow);
1483 ast_cli_register(&astrestartgracefully);
1484 ast_cli_register(&astrestartwhenconvenient);
1485 ast_cli_register(&astshutdownwhenconvenient);
1486 ast_cli_register(&aborthalt);
1487 ast_cli_register(&astbang);
1489 consolethread = pthread_self();
1490 if (option_console) {
1491 /* Console stuff now... */
1492 /* Register our quit function */
1494 set_icon("Asterisk");
1495 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, mainpid);
1497 ast_cli_register(&quit);
1498 ast_cli_register(&astexit);
1501 buf = (char *)el_gets(el, &num);
1503 if (buf[strlen(buf)-1] == '\n')
1504 buf[strlen(buf)-1] = '\0';
1506 consolehandler((char *)buf);
1509 ast_cli(STDOUT_FILENO, "\nUse EXIT or QUIT to exit the asterisk console\n");
1511 ast_cli(STDOUT_FILENO, "\nUse STOP NOW to shutdown Asterisk\n");
1517 ast_select(0,NULL,NULL,NULL,NULL);