2 * Asterisk -- A telephony toolkit for Linux.
4 * Top level source file for asterisk
6 * Copyright (C) 1999-2004, Digium, Inc.
8 * Mark Spencer <markster@digium.com>
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>
57 #if defined(__FreeBSD__) || defined( __NetBSD__ )
61 #define AST_MAX_CONNECTS 128
64 #define WELCOME_MESSAGE ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999-2004 Digium.\n"); \
65 ast_verbose( "Written by Mark Spencer <markster@digium.com>\n"); \
66 ast_verbose( "=========================================================================\n")
73 int option_highpriority=0;
76 int option_initcrypto=0;
78 int option_dumpcore = 0;
79 int option_cache_record_files = 0;
80 int option_overrideconfig = 0;
81 int option_reconnect = 0;
83 char record_cache_dir[AST_CACHE_DIR_LEN] = "/var/spool/asterisk/tmp";
85 static int ast_socket = -1; /* UNIX Socket for allowing remote control */
86 static int ast_consock = -1; /* UNIX Socket for controlling another asterisk */
89 int fd; /* File descriptor */
91 pthread_t t; /* Thread of handler */
94 static struct ast_atexit {
96 struct ast_atexit *next;
98 AST_MUTEX_DEFINE_STATIC(atexitslock);
100 time_t ast_startuptime;
101 time_t ast_lastreloadtime;
103 static History *el_hist = NULL;
104 static EditLine *el = NULL;
105 static char *remotehostname;
107 struct console consoles[AST_MAX_CONNECTS];
109 char defaultlanguage[MAX_LANGUAGE] = DEFAULT_LANGUAGE;
111 static int ast_el_add_history(char *);
112 static int ast_el_read_history(char *);
113 static int ast_el_write_history(char *);
115 char ast_config_AST_CONFIG_DIR[AST_CONFIG_MAX_PATH];
116 char ast_config_AST_CONFIG_FILE[AST_CONFIG_MAX_PATH];
117 char ast_config_AST_MODULE_DIR[AST_CONFIG_MAX_PATH];
118 char ast_config_AST_SPOOL_DIR[AST_CONFIG_MAX_PATH];
119 char ast_config_AST_VAR_DIR[AST_CONFIG_MAX_PATH];
120 char ast_config_AST_LOG_DIR[AST_CONFIG_MAX_PATH];
121 char ast_config_AST_AGI_DIR[AST_CONFIG_MAX_PATH];
122 char ast_config_AST_DB[AST_CONFIG_MAX_PATH];
123 char ast_config_AST_KEY_DIR[AST_CONFIG_MAX_PATH];
124 char ast_config_AST_PID[AST_CONFIG_MAX_PATH];
125 char ast_config_AST_SOCKET[AST_CONFIG_MAX_PATH];
126 char ast_config_AST_RUN_DIR[AST_CONFIG_MAX_PATH];
128 static char *_argv[256];
129 static int shuttingdown = 0;
130 static int restartnow = 0;
131 static pthread_t consolethread = AST_PTHREADT_NULL;
133 int ast_register_atexit(void (*func)(void))
136 struct ast_atexit *ae;
137 ast_unregister_atexit(func);
138 ae = malloc(sizeof(struct ast_atexit));
139 ast_mutex_lock(&atexitslock);
141 memset(ae, 0, sizeof(struct ast_atexit));
147 ast_mutex_unlock(&atexitslock);
151 void ast_unregister_atexit(void (*func)(void))
153 struct ast_atexit *ae, *prev = NULL;
154 ast_mutex_lock(&atexitslock);
157 if (ae->func == func) {
159 prev->next = ae->next;
167 ast_mutex_unlock(&atexitslock);
170 static int fdprint(int fd, const char *s)
172 return write(fd, s, strlen(s) + 1);
175 /* NULL handler so we can collect the child exit status */
176 static void null_sig_handler(int signal)
181 int ast_safe_system(const char *s)
183 /* XXX This function needs some optimization work XXX */
187 struct rusage rusage;
189 void (*prev_handler) = signal(SIGCHLD, null_sig_handler);
192 /* Close file descriptors and launch system command */
193 for (x=STDERR_FILENO + 1; x<4096;x++) {
196 res = execl("/bin/sh", "/bin/sh", "-c", s, NULL);
198 } else if (pid > 0) {
200 res = wait4(pid, &status, 0, &rusage);
202 if (WIFEXITED(status))
203 res = WEXITSTATUS(status);
213 ast_log(LOG_WARNING, "Fork failed: %s\n", strerror(errno));
216 signal(SIGCHLD, prev_handler);
221 * write the string to all attached console clients
223 static void ast_network_puts(const char *string)
226 for (x=0;x<AST_MAX_CONNECTS; x++) {
227 if (consoles[x].fd > -1)
228 fdprint(consoles[x].p[1], string);
233 * write the string to the console, and all attached
236 void ast_console_puts(const char *string)
238 fputs(string, stdout);
240 ast_network_puts(string);
243 static void network_verboser(const char *s, int pos, int replace, int complete)
247 char *t = alloca(strlen(s) + 2);
249 sprintf(t, "\r%s", s);
252 ast_log(LOG_ERROR, "Out of memory\n");
260 static pthread_t lthread;
262 static void *netconsole(void *vconsole)
264 struct console *con = vconsole;
268 struct pollfd fds[2];
270 if (gethostname(hostname, sizeof(hostname)))
271 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
272 snprintf(tmp, sizeof(tmp), "%s/%d/%s\n", hostname, ast_mainpid, ASTERISK_VERSION);
273 fdprint(con->fd, tmp);
276 fds[0].events = POLLIN;
277 fds[1].fd = con->p[0];
278 fds[1].events = POLLIN;
280 res = poll(fds, 2, -1);
283 ast_log(LOG_WARNING, "poll returned < 0: %s\n", strerror(errno));
286 if (fds[0].revents) {
287 res = read(con->fd, tmp, sizeof(tmp));
292 ast_cli_command(con->fd, tmp);
294 if (fds[1].revents) {
295 res = read(con->p[0], tmp, sizeof(tmp));
297 ast_log(LOG_ERROR, "read returned %d\n", res);
300 res = write(con->fd, tmp, res);
305 if (option_verbose > 2)
306 ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection disconnected\n");
315 static void *listener(void *unused)
317 struct sockaddr_un sun;
322 struct pollfd fds[1];
324 pthread_attr_init(&attr);
325 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
329 fds[0].fd = ast_socket;
330 fds[0].events= POLLIN;
331 s = poll(fds, 1, -1);
334 ast_log(LOG_WARNING, "poll returned error: %s\n", strerror(errno));
338 s = accept(ast_socket, (struct sockaddr *)&sun, &len);
341 ast_log(LOG_WARNING, "Accept returned %d: %s\n", s, strerror(errno));
343 for (x=0;x<AST_MAX_CONNECTS;x++) {
344 if (consoles[x].fd < 0) {
345 if (socketpair(AF_LOCAL, SOCK_STREAM, 0, consoles[x].p)) {
346 ast_log(LOG_ERROR, "Unable to create pipe: %s\n", strerror(errno));
348 fdprint(s, "Server failed to create pipe\n");
352 flags = fcntl(consoles[x].p[1], F_GETFL);
353 fcntl(consoles[x].p[1], F_SETFL, flags | O_NONBLOCK);
355 if (ast_pthread_create(&consoles[x].t, &attr, netconsole, &consoles[x])) {
356 ast_log(LOG_ERROR, "Unable to spawn thread to handle connection: %s\n", strerror(errno));
358 fdprint(s, "Server failed to spawn thread\n");
364 if (x >= AST_MAX_CONNECTS) {
365 fdprint(s, "No more connections allowed\n");
366 ast_log(LOG_WARNING, "No more connections allowed\n");
368 } else if (consoles[x].fd > -1) {
369 if (option_verbose > 2)
370 ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection\n");
377 static int ast_makesocket(void)
379 struct sockaddr_un sun;
382 for (x=0;x<AST_MAX_CONNECTS;x++)
384 unlink((char *)ast_config_AST_SOCKET);
385 ast_socket = socket(PF_LOCAL, SOCK_STREAM, 0);
386 if (ast_socket < 0) {
387 ast_log(LOG_WARNING, "Unable to create control socket: %s\n", strerror(errno));
390 memset(&sun, 0, sizeof(sun));
391 sun.sun_family = AF_LOCAL;
392 strncpy(sun.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sun.sun_path)-1);
393 res = bind(ast_socket, (struct sockaddr *)&sun, sizeof(sun));
395 ast_log(LOG_WARNING, "Unable to bind socket to %s: %s\n", (char *)ast_config_AST_SOCKET, strerror(errno));
400 res = listen(ast_socket, 2);
402 ast_log(LOG_WARNING, "Unable to listen on socket %s: %s\n", (char *)ast_config_AST_SOCKET, strerror(errno));
407 ast_register_verbose(network_verboser);
408 ast_pthread_create(<hread, NULL, listener, NULL);
412 static int ast_tryconnect(void)
414 struct sockaddr_un sun;
416 ast_consock = socket(PF_LOCAL, SOCK_STREAM, 0);
417 if (ast_consock < 0) {
418 ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
421 memset(&sun, 0, sizeof(sun));
422 sun.sun_family = AF_LOCAL;
423 strncpy(sun.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sun.sun_path)-1);
424 res = connect(ast_consock, (struct sockaddr *)&sun, sizeof(sun));
433 static void urg_handler(int num)
435 /* Called by soft_hangup to interrupt the poll, read, or other
436 system call. We don't actually need to do anything though. */
437 /* Cannot EVER ast_log from within a signal handler */
439 printf("Urgent handler\n");
440 signal(num, urg_handler);
444 static void hup_handler(int num)
446 if (option_verbose > 1)
447 printf("Received HUP signal -- Reloading configs\n");
449 execvp(_argv[0], _argv);
450 /* XXX This could deadlock XXX */
451 ast_module_reload(NULL);
454 static void child_handler(int sig)
456 /* Must not ever ast_log or ast_verbose within signal handler */
460 * Reap all dead children -- not just one
462 for (n = 0; wait4(-1, &status, WNOHANG, NULL) > 0; n++)
464 if (n == 0 && option_debug)
465 printf("Huh? Child handler, but nobody there?\n");
468 static void set_title(char *text)
470 /* Set an X-term or screen title */
471 if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
472 fprintf(stdout, "\033]2;%s\007", text);
475 static void set_icon(char *text)
477 if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
478 fprintf(stdout, "\033]1;%s\007", text);
481 static int set_priority(int pri)
483 struct sched_param sched;
484 memset(&sched, 0, sizeof(sched));
485 /* We set ourselves to a high priority, that we might pre-empt everything
486 else. If your PBX has heavy activity on it, this is a good thing. */
489 sched.sched_priority = 10;
490 if (sched_setscheduler(0, SCHED_RR, &sched)) {
491 ast_log(LOG_WARNING, "Unable to set high priority\n");
495 ast_verbose("Set to realtime thread\n");
497 sched.sched_priority = 0;
498 if (sched_setscheduler(0, SCHED_OTHER, &sched)) {
499 ast_log(LOG_WARNING, "Unable to set normal priority\n");
505 if (setpriority(PRIO_PROCESS, 0, -10) == -1) {
506 ast_log(LOG_WARNING, "Unable to set high priority\n");
510 ast_verbose("Set to high priority\n");
512 if (setpriority(PRIO_PROCESS, 0, 0) == -1) {
513 ast_log(LOG_WARNING, "Unable to set normal priority\n");
521 static void ast_run_atexits(void)
523 struct ast_atexit *ae;
524 ast_mutex_lock(&atexitslock);
531 ast_mutex_unlock(&atexitslock);
534 static void quit_handler(int num, int nice, int safeshutdown, int restart)
536 char filename[80] = "";
542 /* Begin shutdown routine, hanging up active channels */
543 ast_begin_shutdown(1);
544 if (option_verbose && option_console)
545 ast_verbose("Beginning asterisk %s....\n", restart ? "restart" : "shutdown");
549 /* Wait up to 15 seconds for all channels to go away */
552 if (!ast_active_channels())
556 /* Sleep 1/10 of a second */
561 ast_begin_shutdown(0);
562 if (option_verbose && option_console)
563 ast_verbose("Waiting for inactivity to perform %s...\n", restart ? "restart" : "halt");
565 if (!ast_active_channels())
574 if (option_verbose && option_console)
575 ast_verbose("Asterisk %s cancelled.\n", restart ? "restart" : "shutdown");
579 if (option_console || option_remote) {
581 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
582 if (!ast_strlen_zero(filename))
583 ast_el_write_history(filename);
587 history_end(el_hist);
590 ast_verbose("Executing last minute cleanups\n");
593 if (option_verbose && option_console)
594 ast_verbose("Asterisk %s ending (%d).\n", ast_active_channels() ? "uncleanly" : "cleanly", num);
595 else if (option_debug)
596 ast_log(LOG_DEBUG, "Asterisk ending (%d).\n", num);
597 manager_event(EVENT_FLAG_SYSTEM, "Shutdown", "Shutdown: %s\r\nRestart: %s\r\n", ast_active_channels() ? "Uncleanly" : "Cleanly", restart ? "True" : "False");
598 if (ast_socket > -1) {
602 if (ast_consock > -1)
605 unlink((char *)ast_config_AST_SOCKET);
606 if (!option_remote) unlink((char *)ast_config_AST_PID);
609 if (option_verbose || option_console)
610 ast_verbose("Preparing for Asterisk restart...\n");
611 /* Mark all FD's for closing on exec */
612 for (x=3;x<32768;x++) {
613 fcntl(x, F_SETFD, FD_CLOEXEC);
615 if (option_verbose || option_console)
616 ast_verbose("Restarting Asterisk NOW...\n");
622 /* If there is a consolethread running send it a SIGHUP
623 so it can execvp, otherwise we can do it ourselves */
624 if (consolethread != AST_PTHREADT_NULL) {
625 pthread_kill(consolethread, SIGHUP);
626 /* Give the signal handler some time to complete */
629 execvp(_argv[0], _argv);
638 static void __quit_handler(int num)
640 quit_handler(num, 0, 1, 0);
643 static const char *fix_header(char *outbuf, int maxout, const char *s, char *cmp)
646 if (!strncmp(s, cmp, strlen(cmp))) {
648 term_color(outbuf, cmp, COLOR_GRAY, 0, maxout);
654 static void console_verboser(const char *s, int pos, int replace, int complete)
658 /* Return to the beginning of the line */
660 fprintf(stdout, "\r");
661 if ((c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_4)) ||
662 (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_3)) ||
663 (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_2)) ||
664 (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_1)))
668 fputs(c + pos,stdout);
670 fputs(s + pos,stdout);
673 /* Wake up a poll()ing console */
674 if (option_console && consolethread != AST_PTHREADT_NULL)
675 pthread_kill(consolethread, SIGURG);
678 static int ast_all_zeros(char *s)
688 static void consolehandler(char *s)
692 /* Called when readline data is available */
693 if (s && !ast_all_zeros(s))
694 ast_el_add_history(s);
695 /* Give the console access to the shell */
697 /* The real handler for bang */
700 ast_safe_system(s+1);
702 ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
704 ast_cli_command(STDOUT_FILENO, s);
706 fprintf(stdout, "\nUse \"quit\" to exit\n");
709 static int remoteconsolehandler(char *s)
712 /* Called when readline data is available */
713 if (s && !ast_all_zeros(s))
714 ast_el_add_history(s);
715 /* Give the console access to the shell */
717 /* The real handler for bang */
720 ast_safe_system(s+1);
722 ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
725 if ((strncasecmp(s, "quit", 4) == 0 || strncasecmp(s, "exit", 4) == 0) &&
726 (s[4] == '\0' || isspace(s[4]))) {
727 quit_handler(0, 0, 0, 0);
731 fprintf(stdout, "\nUse \"quit\" to exit\n");
736 static char quit_help[] =
738 " Exits Asterisk.\n";
740 static char abort_halt_help[] =
741 "Usage: abort shutdown\n"
742 " Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
743 " call operations.\n";
745 static char shutdown_now_help[] =
747 " Shuts down a running Asterisk immediately, hanging up all active calls .\n";
749 static char shutdown_gracefully_help[] =
750 "Usage: stop gracefully\n"
751 " Causes Asterisk to not accept new calls, and exit when all\n"
752 " active calls have terminated normally.\n";
754 static char shutdown_when_convenient_help[] =
755 "Usage: stop when convenient\n"
756 " Causes Asterisk to perform a shutdown when all active calls have ended.\n";
758 static char restart_now_help[] =
759 "Usage: restart now\n"
760 " Causes Asterisk to hangup all calls and exec() itself performing a cold.\n"
763 static char restart_gracefully_help[] =
764 "Usage: restart gracefully\n"
765 " Causes Asterisk to stop accepting new calls and exec() itself performing a cold.\n"
766 " restart when all active calls have ended.\n";
768 static char restart_when_convenient_help[] =
769 "Usage: restart when convenient\n"
770 " Causes Asterisk to perform a cold restart when all active calls have ended.\n";
772 static char bang_help[] =
773 "Usage: !<command>\n"
774 " Executes a given shell command\n";
777 static int handle_quit(int fd, int argc, char *argv[])
780 return RESULT_SHOWUSAGE;
781 quit_handler(0, 0, 1, 0);
782 return RESULT_SUCCESS;
786 static int no_more_quit(int fd, int argc, char *argv[])
789 return RESULT_SHOWUSAGE;
790 ast_cli(fd, "The QUIT and EXIT commands may no longer be used to shutdown the PBX.\n"
791 "Please use STOP NOW instead, if you wish to shutdown the PBX.\n");
792 return RESULT_SUCCESS;
795 static int handle_shutdown_now(int fd, int argc, char *argv[])
798 return RESULT_SHOWUSAGE;
799 quit_handler(0, 0 /* Not nice */, 1 /* safely */, 0 /* not restart */);
800 return RESULT_SUCCESS;
803 static int handle_shutdown_gracefully(int fd, int argc, char *argv[])
806 return RESULT_SHOWUSAGE;
807 quit_handler(0, 1 /* nicely */, 1 /* safely */, 0 /* no restart */);
808 return RESULT_SUCCESS;
811 static int handle_shutdown_when_convenient(int fd, int argc, char *argv[])
814 return RESULT_SHOWUSAGE;
815 quit_handler(0, 2 /* really nicely */, 1 /* safely */, 0 /* don't restart */);
816 return RESULT_SUCCESS;
819 static int handle_restart_now(int fd, int argc, char *argv[])
822 return RESULT_SHOWUSAGE;
823 quit_handler(0, 0 /* not nicely */, 1 /* safely */, 1 /* restart */);
824 return RESULT_SUCCESS;
827 static int handle_restart_gracefully(int fd, int argc, char *argv[])
830 return RESULT_SHOWUSAGE;
831 quit_handler(0, 1 /* nicely */, 1 /* safely */, 1 /* restart */);
832 return RESULT_SUCCESS;
835 static int handle_restart_when_convenient(int fd, int argc, char *argv[])
838 return RESULT_SHOWUSAGE;
839 quit_handler(0, 2 /* really nicely */, 1 /* safely */, 1 /* restart */);
840 return RESULT_SUCCESS;
843 static int handle_abort_halt(int fd, int argc, char *argv[])
846 return RESULT_SHOWUSAGE;
847 ast_cancel_shutdown();
849 return RESULT_SUCCESS;
852 static int handle_bang(int fd, int argc, char *argv[])
854 return RESULT_SUCCESS;
857 #define ASTERISK_PROMPT "*CLI> "
859 #define ASTERISK_PROMPT2 "%s*CLI> "
861 static struct ast_cli_entry aborthalt = { { "abort", "halt", NULL }, handle_abort_halt, "Cancel a running halt", abort_halt_help };
863 static struct ast_cli_entry quit = { { "quit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
864 static struct ast_cli_entry astexit = { { "exit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
866 static struct ast_cli_entry astshutdownnow = { { "stop", "now", NULL }, handle_shutdown_now, "Shut down Asterisk immediately", shutdown_now_help };
867 static struct ast_cli_entry astshutdowngracefully = { { "stop", "gracefully", NULL }, handle_shutdown_gracefully, "Gracefully shut down Asterisk", shutdown_gracefully_help };
868 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 };
869 static struct ast_cli_entry astrestartnow = { { "restart", "now", NULL }, handle_restart_now, "Restart Asterisk immediately", restart_now_help };
870 static struct ast_cli_entry astrestartgracefully = { { "restart", "gracefully", NULL }, handle_restart_gracefully, "Restart Asterisk gracefully", restart_gracefully_help };
871 static struct ast_cli_entry astrestartwhenconvenient= { { "restart", "when", "convenient", NULL }, handle_restart_when_convenient, "Restart Asterisk at empty call volume", restart_when_convenient_help };
872 static struct ast_cli_entry astbang = { { "!", NULL }, handle_bang, "Execute a shell command", bang_help };
874 static int ast_el_read_char(EditLine *el, char *cp)
878 struct pollfd fds[2];
885 fds[0].fd = ast_consock;
886 fds[0].events = POLLIN;
888 fds[1].fd = STDIN_FILENO;
889 fds[1].events = POLLIN;
892 res = poll(fds, max, -1);
896 ast_log(LOG_ERROR, "poll failed: %s\n", strerror(errno));
900 if (!option_exec && fds[1].revents) {
901 num_read = read(STDIN_FILENO, cp, 1);
907 if (fds[0].revents) {
908 res = read(ast_consock, buf, sizeof(buf) - 1);
909 /* if the remote side disappears exit */
911 fprintf(stderr, "\nDisconnected from Asterisk server\n");
912 if (!option_reconnect) {
913 quit_handler(0, 0, 0, 0);
916 int reconnects_per_second = 20;
917 fprintf(stderr, "Attempting to reconnect for 30 seconds\n");
918 for (tries=0;tries<30 * reconnects_per_second;tries++) {
919 if (ast_tryconnect()) {
920 fprintf(stderr, "Reconnect succeeded after %.3f seconds\n", 1.0 / reconnects_per_second * tries);
925 usleep(1000000 / reconnects_per_second);
929 fprintf(stderr, "Failed to reconnect for 30 seconds. Quitting.\n");
930 quit_handler(0, 0, 0, 0);
937 if (!option_exec && !lastpos)
938 write(STDOUT_FILENO, "\r", 1);
939 write(STDOUT_FILENO, buf, res);
940 if ((buf[res-1] == '\n') || (buf[res-2] == '\n')) {
953 static char *cli_prompt(EditLine *el)
955 static char prompt[200];
960 if ((pfmt = getenv("ASTERISK_PROMPT"))) {
961 char *t = pfmt, *p = prompt;
962 memset(prompt, 0, sizeof(prompt));
963 while (*t != '\0' && *p < sizeof(prompt)) {
972 int fgcolor = COLOR_WHITE, bgcolor = COLOR_BLACK;
976 case 'C': /* color */
978 if (sscanf(t, "%d;%d%n", &fgcolor, &bgcolor, &i) == 2) {
979 strncat(p, term_color_code(term_code, fgcolor, bgcolor, sizeof(term_code)),sizeof(prompt) - strlen(prompt) - 1);
981 } else if (sscanf(t, "%d%n", &fgcolor, &i) == 1) {
982 strncat(p, term_color_code(term_code, fgcolor, 0, sizeof(term_code)),sizeof(prompt) - strlen(prompt) - 1);
986 /* If the color has been reset correctly, then there's no need to reset it later */
987 if ((fgcolor == COLOR_WHITE) && (bgcolor == COLOR_BLACK)) {
994 memset(&tm, 0, sizeof(struct tm));
995 gettimeofday(&tv, NULL);
996 if (localtime_r(&(tv.tv_sec), &tm)) {
997 strftime(p, sizeof(prompt) - strlen(prompt), "%Y-%m-%d", &tm);
1000 case 'h': /* hostname */
1001 if (!gethostname(hostname, sizeof(hostname) - 1)) {
1002 strncat(p, hostname, sizeof(prompt) - strlen(prompt) - 1);
1004 strncat(p, "localhost", sizeof(prompt) - strlen(prompt) - 1);
1007 case 'H': /* short hostname */
1008 if (!gethostname(hostname, sizeof(hostname) - 1)) {
1009 for (i=0;i<sizeof(hostname);i++) {
1010 if (hostname[i] == '.') {
1015 strncat(p, hostname, sizeof(prompt) - strlen(prompt) - 1);
1017 strncat(p, "localhost", sizeof(prompt) - strlen(prompt) - 1);
1021 case 'l': /* load avg */
1023 if ((LOADAVG = fopen("/proc/loadavg", "r"))) {
1024 float avg1, avg2, avg3;
1025 int actproc, totproc, npid, which;
1026 fscanf(LOADAVG, "%f %f %f %d/%d %d",
1027 &avg1, &avg2, &avg3, &actproc, &totproc, &npid);
1028 if (sscanf(t, "%d", &which) == 1) {
1031 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg1);
1034 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg2);
1037 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg3);
1040 snprintf(p, sizeof(prompt) - strlen(prompt), "%d/%d", actproc, totproc);
1043 snprintf(p, sizeof(prompt) - strlen(prompt), "%d", npid);
1050 case 't': /* time */
1051 memset(&tm, 0, sizeof(struct tm));
1052 gettimeofday(&tv, NULL);
1053 if (localtime_r(&(tv.tv_sec), &tm)) {
1054 strftime(p, sizeof(prompt) - strlen(prompt), "%H:%M:%S", &tm);
1057 case '#': /* process console or remote? */
1058 if (! option_remote) {
1059 strncat(p, "#", sizeof(prompt) - strlen(prompt) - 1);
1061 strncat(p, ">", sizeof(prompt) - strlen(prompt) - 1);
1064 case '%': /* literal % */
1065 strncat(p, "%", sizeof(prompt) - strlen(prompt) - 1);
1067 case '\0': /* % is last character - prevent bug */
1071 while (*p != '\0') {
1082 /* Force colors back to normal at end */
1083 term_color_code(term_code, COLOR_WHITE, COLOR_BLACK, sizeof(term_code));
1084 if (strlen(term_code) > sizeof(prompt) - strlen(prompt)) {
1085 strncat(prompt + sizeof(prompt) - strlen(term_code) - 1, term_code, strlen(term_code));
1087 strncat(p, term_code, sizeof(term_code));
1090 } else if (remotehostname)
1091 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT2, remotehostname);
1093 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT);
1098 static char **ast_el_strtoarr(char *buf)
1100 char **match_list = NULL, *retstr;
1101 size_t match_list_len;
1105 while ( (retstr = strsep(&buf, " ")) != NULL) {
1107 if (!strcmp(retstr, AST_CLI_COMPLETE_EOF))
1109 if (matches + 1 >= match_list_len) {
1110 match_list_len <<= 1;
1111 match_list = realloc(match_list, match_list_len * sizeof(char *));
1114 match_list[matches++] = strdup(retstr);
1118 return (char **) NULL;
1120 if (matches>= match_list_len)
1121 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
1123 match_list[matches] = (char *) NULL;
1128 static int ast_el_sort_compare(const void *i1, const void *i2)
1132 s1 = ((char **)i1)[0];
1133 s2 = ((char **)i2)[0];
1135 return strcasecmp(s1, s2);
1138 static int ast_cli_display_match_list(char **matches, int len, int max)
1140 int i, idx, limit, count;
1141 int screenwidth = 0;
1142 int numoutput = 0, numoutputline = 0;
1144 screenwidth = ast_get_termcols(STDOUT_FILENO);
1146 /* find out how many entries can be put on one line, with two spaces between strings */
1147 limit = screenwidth / (max + 2);
1151 /* how many lines of output */
1152 count = len / limit;
1153 if (count * limit < len)
1158 qsort(&matches[0], (size_t)(len + 1), sizeof(char *), ast_el_sort_compare);
1160 for (; count > 0; count--) {
1162 for (i=0; i < limit && matches[idx]; i++, idx++) {
1164 /* Don't print dupes */
1165 if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
1168 matches[idx] = NULL;
1172 numoutput++; numoutputline++;
1173 fprintf(stdout, "%-*s ", max, matches[idx]);
1175 matches[idx] = NULL;
1177 if (numoutputline > 0)
1178 fprintf(stdout, "\n");
1185 static char *cli_complete(EditLine *el, int ch)
1191 int retval = CC_ERROR;
1195 LineInfo *lf = (LineInfo *)el_line(el);
1197 *(char *)lf->cursor = '\0';
1198 ptr = (char *)lf->cursor;
1200 while (ptr > lf->buffer) {
1201 if (isspace(*ptr)) {
1209 len = lf->cursor - ptr;
1211 if (option_remote) {
1212 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr);
1213 fdprint(ast_consock, buf);
1214 res = read(ast_consock, buf, sizeof(buf));
1216 nummatches = atoi(buf);
1218 if (nummatches > 0) {
1220 int mlen = 0, maxmbuf = 2048;
1221 /* Start with a 2048 byte buffer */
1222 mbuf = malloc(maxmbuf);
1224 return (char *)(CC_ERROR);
1225 snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr);
1226 fdprint(ast_consock, buf);
1229 while (!strstr(mbuf, AST_CLI_COMPLETE_EOF) && res != -1) {
1230 if (mlen + 1024 > maxmbuf) {
1231 /* Every step increment buffer 1024 bytes */
1233 mbuf = realloc(mbuf, maxmbuf);
1235 return (char *)(CC_ERROR);
1237 /* Only read 1024 bytes at a time */
1238 res = read(ast_consock, mbuf + mlen, 1024);
1244 matches = ast_el_strtoarr(mbuf);
1247 matches = (char **) NULL;
1252 nummatches = ast_cli_generatornummatches((char *)lf->buffer,ptr);
1253 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
1258 int matches_num, maxlen, match_len;
1260 if (matches[0][0] != '\0') {
1261 el_deletestr(el, (int) len);
1262 el_insertstr(el, matches[0]);
1263 retval = CC_REFRESH;
1266 if (nummatches == 1) {
1267 /* Found an exact match */
1268 el_insertstr(el, " ");
1269 retval = CC_REFRESH;
1271 /* Must be more than one match */
1272 for (i=1, maxlen=0; matches[i]; i++) {
1273 match_len = strlen(matches[i]);
1274 if (match_len > maxlen)
1277 matches_num = i - 1;
1278 if (matches_num >1) {
1279 fprintf(stdout, "\n");
1280 ast_cli_display_match_list(matches, nummatches, maxlen);
1281 retval = CC_REDISPLAY;
1283 el_insertstr(el," ");
1284 retval = CC_REFRESH;
1290 return (char *)(long)retval;
1293 static int ast_el_initialize(void)
1296 char *editor = getenv("AST_EDITOR");
1300 if (el_hist != NULL)
1301 history_end(el_hist);
1303 el = el_init("asterisk", stdin, stdout, stderr);
1304 el_set(el, EL_PROMPT, cli_prompt);
1306 el_set(el, EL_EDITMODE, 1);
1307 el_set(el, EL_EDITOR, editor ? editor : "emacs");
1308 el_hist = history_init();
1309 if (!el || !el_hist)
1312 /* setup history with 100 entries */
1313 history(el_hist, &ev, H_SETSIZE, 100);
1315 el_set(el, EL_HIST, history, el_hist);
1317 el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
1318 /* Bind <tab> to command completion */
1319 el_set(el, EL_BIND, "^I", "ed-complete", NULL);
1320 /* Bind ? to command completion */
1321 el_set(el, EL_BIND, "?", "ed-complete", NULL);
1322 /* Bind ^D to redisplay */
1323 el_set(el, EL_BIND, "^D", "ed-redisplay", NULL);
1328 static int ast_el_add_history(char *buf)
1332 if (el_hist == NULL || el == NULL)
1333 ast_el_initialize();
1334 if (strlen(buf) > 256)
1336 return (history(el_hist, &ev, H_ENTER, buf));
1339 static int ast_el_write_history(char *filename)
1343 if (el_hist == NULL || el == NULL)
1344 ast_el_initialize();
1346 return (history(el_hist, &ev, H_SAVE, filename));
1349 static int ast_el_read_history(char *filename)
1355 if (el_hist == NULL || el == NULL)
1356 ast_el_initialize();
1358 if ((f = fopen(filename, "r")) == NULL)
1362 fgets(buf, sizeof(buf), f);
1363 if (!strcmp(buf, "_HiStOrY_V2_\n"))
1365 if (ast_all_zeros(buf))
1367 if ((ret = ast_el_add_history(buf)) == -1)
1375 static void ast_remotecontrol(char * data)
1379 char filename[80] = "";
1390 read(ast_consock, buf, sizeof(buf));
1392 write(ast_consock, data, strlen(data) + 1);
1394 hostname = strsep(&stringp, "/");
1395 cpid = strsep(&stringp, "/");
1396 version = strsep(&stringp, "\n");
1398 version = "<Version Unknown>";
1400 strsep(&stringp, ".");
1405 snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
1406 fdprint(ast_consock, tmp);
1407 ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
1408 remotehostname = hostname;
1410 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1411 if (el_hist == NULL || el == NULL)
1412 ast_el_initialize();
1414 el_set(el, EL_GETCFN, ast_el_read_char);
1416 if (!ast_strlen_zero(filename))
1417 ast_el_read_history(filename);
1419 ast_cli_register(&quit);
1420 ast_cli_register(&astexit);
1422 ast_cli_register(&astshutdown);
1424 if (option_exec && data) { /* hack to print output then exit if asterisk -rx is used */
1426 struct pollfd fds[0];
1427 fds[0].fd = ast_consock;
1428 fds[0].events = POLLIN;
1430 while(poll(fds, 1, 100) > 0) {
1431 ast_el_read_char(el, &tempchar);
1436 ebuf = (char *)el_gets(el, &num);
1438 if (ebuf && !ast_strlen_zero(ebuf)) {
1439 if (ebuf[strlen(ebuf)-1] == '\n')
1440 ebuf[strlen(ebuf)-1] = '\0';
1441 if (!remoteconsolehandler(ebuf)) {
1442 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
1444 ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
1450 printf("\nDisconnected from Asterisk server\n");
1453 static int show_version(void)
1455 printf("Asterisk " ASTERISK_VERSION "\n");
1459 static int show_cli_help(void) {
1460 printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 2000-2004, Digium.\n");
1461 printf("Usage: asterisk [OPTIONS]\n");
1462 printf("Valid Options:\n");
1463 printf(" -V Display version number and exit\n");
1464 printf(" -C <configfile> Use an alternate configuration file\n");
1465 printf(" -G <group> Run as a group other than the caller\n");
1466 printf(" -U <user> Run as a user other than the caller\n");
1467 printf(" -c Provide console CLI\n");
1468 printf(" -d Enable extra debugging\n");
1469 printf(" -f Do not fork\n");
1470 printf(" -g Dump core in case of a crash\n");
1471 printf(" -h This help screen\n");
1472 printf(" -i Initializie crypto keys at startup\n");
1473 printf(" -n Disable console colorization\n");
1474 printf(" -p Run as pseudo-realtime thread\n");
1475 printf(" -q Quiet mode (supress output)\n");
1476 printf(" -r Connect to Asterisk on this machine\n");
1477 printf(" -R Connect to Asterisk, and attempt to reconnect if disconnected\n");
1478 printf(" -t Record soundfiles in /tmp and move them where they belong after they are done.\n");
1479 printf(" -v Increase verbosity (multiple v's = more verbose)\n");
1480 printf(" -x <cmd> Execute command <cmd> (only valid with -r)\n");
1485 static void ast_readconfig(void) {
1486 struct ast_config *cfg;
1487 struct ast_variable *v;
1488 char *config = ASTCONFPATH;
1490 if (option_overrideconfig == 1) {
1491 cfg = ast_load((char *)ast_config_AST_CONFIG_FILE);
1493 ast_log(LOG_WARNING, "Unable to open specified master config file '%s', using builtin defaults\n", ast_config_AST_CONFIG_FILE);
1495 cfg = ast_load(config);
1498 /* init with buildtime config */
1499 strncpy((char *)ast_config_AST_CONFIG_DIR,AST_CONFIG_DIR,sizeof(ast_config_AST_CONFIG_DIR)-1);
1500 strncpy((char *)ast_config_AST_SPOOL_DIR,AST_SPOOL_DIR,sizeof(ast_config_AST_SPOOL_DIR)-1);
1501 strncpy((char *)ast_config_AST_MODULE_DIR,AST_MODULE_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1502 strncpy((char *)ast_config_AST_VAR_DIR,AST_VAR_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1503 strncpy((char *)ast_config_AST_LOG_DIR,AST_LOG_DIR,sizeof(ast_config_AST_LOG_DIR)-1);
1504 strncpy((char *)ast_config_AST_AGI_DIR,AST_AGI_DIR,sizeof(ast_config_AST_AGI_DIR)-1);
1505 strncpy((char *)ast_config_AST_DB,AST_DB,sizeof(ast_config_AST_DB)-1);
1506 strncpy((char *)ast_config_AST_KEY_DIR,AST_KEY_DIR,sizeof(ast_config_AST_KEY_DIR)-1);
1507 strncpy((char *)ast_config_AST_PID,AST_PID,sizeof(ast_config_AST_PID)-1);
1508 strncpy((char *)ast_config_AST_SOCKET,AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1);
1509 strncpy((char *)ast_config_AST_RUN_DIR,AST_RUN_DIR,sizeof(ast_config_AST_RUN_DIR)-1);
1511 /* no asterisk.conf? no problem, use buildtime config! */
1515 v = ast_variable_browse(cfg, "directories");
1517 if (!strcasecmp(v->name, "astetcdir")) {
1518 strncpy((char *)ast_config_AST_CONFIG_DIR,v->value,sizeof(ast_config_AST_CONFIG_DIR)-1);
1519 } else if (!strcasecmp(v->name, "astspooldir")) {
1520 strncpy((char *)ast_config_AST_SPOOL_DIR,v->value,sizeof(ast_config_AST_SPOOL_DIR)-1);
1521 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1522 strncpy((char *)ast_config_AST_VAR_DIR,v->value,sizeof(ast_config_AST_VAR_DIR)-1);
1523 snprintf((char *)ast_config_AST_DB,sizeof(ast_config_AST_DB),"%s/%s",v->value,"astdb");
1524 } else if (!strcasecmp(v->name, "astlogdir")) {
1525 strncpy((char *)ast_config_AST_LOG_DIR,v->value,sizeof(ast_config_AST_LOG_DIR)-1);
1526 } else if (!strcasecmp(v->name, "astagidir")) {
1527 strncpy((char *)ast_config_AST_AGI_DIR,v->value,sizeof(ast_config_AST_AGI_DIR)-1);
1528 } else if (!strcasecmp(v->name, "astrundir")) {
1529 snprintf((char *)ast_config_AST_PID,sizeof(ast_config_AST_PID),"%s/%s",v->value,"asterisk.pid");
1530 snprintf((char *)ast_config_AST_SOCKET,sizeof(ast_config_AST_SOCKET),"%s/%s",v->value,"asterisk.ctl");
1531 strncpy((char *)ast_config_AST_RUN_DIR,v->value,sizeof(ast_config_AST_RUN_DIR)-1);
1532 } else if (!strcasecmp(v->name, "astmoddir")) {
1533 strncpy((char *)ast_config_AST_MODULE_DIR,v->value,sizeof(ast_config_AST_MODULE_DIR)-1);
1537 v = ast_variable_browse(cfg, "options");
1539 if(!strcasecmp(v->name, "verbose")) {
1540 option_verbose= atoi(v->value);
1541 } else if (!strcasecmp(v->name, "debug")) {
1542 option_debug= ast_true(v->value);
1543 } else if (!strcasecmp(v->name, "nofork")) {
1544 option_nofork = ast_true(v->value);
1545 } else if (!strcasecmp(v->name, "quiet")) {
1546 option_quiet = ast_true(v->value);
1547 } else if (!strcasecmp(v->name, "console")) {
1548 option_console = ast_true(v->value);
1549 } else if (!strcasecmp(v->name, "highpriority")) {
1550 option_highpriority = ast_true(v->value);
1551 } else if (!strcasecmp(v->name, "initcrypto")) {
1552 option_initcrypto = ast_true(v->value);
1553 } else if (!strcasecmp(v->name, "nocolor")) {
1554 option_nocolor = ast_true(v->value);
1555 } else if (!strcasecmp(v->name, "dumpcore")) {
1556 option_dumpcore = ast_true(v->value);
1557 } else if (!strcasecmp(v->name, "cache_record_files")) {
1558 option_cache_record_files = ast_true(v->value);
1559 } else if (!strcasecmp(v->name, "record_cache_dir")) {
1560 strncpy(record_cache_dir,v->value,AST_CACHE_DIR_LEN);
1567 int main(int argc, char *argv[])
1570 char filename[80] = "";
1579 char *runuser=NULL, *rungroup=NULL;
1581 /* Remember original args for restart */
1582 if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1583 fprintf(stderr, "Truncating argument size to %d\n", (int)(sizeof(_argv) / sizeof(_argv[0])) - 1);
1584 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1586 for (x=0;x<argc;x++)
1590 /* if the progname is rasterisk consider it a remote console */
1591 if ( argv[0] && (strstr(argv[0], "rasterisk")) != NULL) {
1595 if (gethostname(hostname, sizeof(hostname)))
1596 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
1597 ast_mainpid = getpid();
1604 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1605 /* Check if we're root */
1608 ast_log(LOG_ERROR, "Must be run as root\n");
1612 /* Check for options */
1613 while((c=getopt(argc, argv, "thfdvVqprRgcinx:U:G:C:")) != -1) {
1639 option_highpriority++;
1649 option_cache_record_files++;
1656 strncpy((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE) - 1);
1657 option_overrideconfig++;
1660 option_initcrypto++;
1682 if (option_dumpcore) {
1684 memset(&l, 0, sizeof(l));
1685 l.rlim_cur = RLIM_INFINITY;
1686 l.rlim_max = RLIM_INFINITY;
1687 if (setrlimit(RLIMIT_CORE, &l)) {
1688 ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
1694 gr = getgrnam(rungroup);
1696 ast_log(LOG_WARNING, "No such group '%s'!\n", rungroup);
1699 if (setgid(gr->gr_gid)) {
1700 ast_log(LOG_WARNING, "Unable to setgid to %d (%s)\n", gr->gr_gid, rungroup);
1704 ast_verbose("Running as group '%s'\n", rungroup);
1707 if (set_priority(option_highpriority)) {
1712 pw = getpwnam(runuser);
1714 ast_log(LOG_WARNING, "No such user '%s'!\n", runuser);
1717 if (setuid(pw->pw_uid)) {
1718 ast_log(LOG_WARNING, "Unable to setuid to %d (%s)\n", pw->pw_uid, runuser);
1722 ast_verbose("Running as user '%s'\n", runuser);
1729 /* Test recursive mutex locking. */
1730 if (test_for_thread_safety())
1731 ast_verbose("Warning! Asterisk is not thread safe.\n");
1733 if (option_console && !option_verbose)
1734 ast_verbose("[ Reading Master Configuration ]");
1737 if (option_console && !option_verbose)
1738 ast_verbose("[ Initializing Custom Configuration Options]");
1739 /* custom config setup */
1740 register_config_cli();
1741 read_ast_cust_config();
1744 if (option_console) {
1745 if (el_hist == NULL || el == NULL)
1746 ast_el_initialize();
1748 if (!ast_strlen_zero(filename))
1749 ast_el_read_history(filename);
1752 if (ast_tryconnect()) {
1753 /* One is already running */
1754 if (option_remote) {
1756 ast_remotecontrol(xarg);
1757 quit_handler(0, 0, 0, 0);
1760 printf(term_quit());
1761 ast_register_verbose(console_verboser);
1763 ast_remotecontrol(NULL);
1764 quit_handler(0, 0, 0, 0);
1767 ast_log(LOG_ERROR, "Asterisk already running on %s. Use 'asterisk -r' to connect.\n", (char *)ast_config_AST_SOCKET);
1768 printf(term_quit());
1771 } else if (option_remote || option_exec) {
1772 ast_log(LOG_ERROR, "Unable to connect to remote asterisk\n");
1773 printf(term_quit());
1776 /* Blindly write pid file since we couldn't connect */
1777 unlink((char *)ast_config_AST_PID);
1778 f = fopen((char *)ast_config_AST_PID, "w");
1780 fprintf(f, "%d\n", getpid());
1783 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1785 if (!option_verbose && !option_debug && !option_nofork && !option_console) {
1787 /* Blindly re-write pid file since we are forking */
1788 unlink((char *)ast_config_AST_PID);
1789 f = fopen((char *)ast_config_AST_PID, "w");
1791 fprintf(f, "%d\n", getpid());
1794 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1799 sigaddset(&sigs, SIGHUP);
1800 sigaddset(&sigs, SIGTERM);
1801 sigaddset(&sigs, SIGINT);
1802 sigaddset(&sigs, SIGPIPE);
1803 sigaddset(&sigs, SIGWINCH);
1804 pthread_sigmask(SIG_BLOCK, &sigs, NULL);
1805 if (option_console || option_verbose || option_remote)
1806 ast_register_verbose(console_verboser);
1807 /* Print a welcome message if desired */
1808 if (option_verbose || option_console) {
1811 if (option_console && !option_verbose)
1812 ast_verbose("[ Booting...");
1814 signal(SIGURG, urg_handler);
1815 signal(SIGINT, __quit_handler);
1816 signal(SIGTERM, __quit_handler);
1817 signal(SIGHUP, hup_handler);
1818 signal(SIGCHLD, child_handler);
1819 signal(SIGPIPE, SIG_IGN);
1821 if (init_logger()) {
1822 printf(term_quit());
1825 if (init_manager()) {
1826 printf(term_quit());
1830 if (ast_image_init()) {
1831 printf(term_quit());
1834 if (ast_file_init()) {
1835 printf(term_quit());
1839 printf(term_quit());
1842 if (load_modules()) {
1843 printf(term_quit());
1846 if (init_framer()) {
1847 printf(term_quit());
1851 printf(term_quit());
1854 if (ast_enum_init()) {
1855 printf(term_quit());
1858 /* sync cust config and reload some internals in case a custom config handler binded to them */
1859 read_ast_cust_config();
1866 /* We might have the option of showing a console, but for now just
1868 if (option_console && !option_verbose)
1869 ast_verbose(" ]\n");
1870 if (option_verbose || option_console)
1871 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
1873 consolethread = pthread_self();
1875 pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
1876 #ifdef __AST_DEBUG_MALLOC
1879 time(&ast_startuptime);
1880 ast_cli_register(&astshutdownnow);
1881 ast_cli_register(&astshutdowngracefully);
1882 ast_cli_register(&astrestartnow);
1883 ast_cli_register(&astrestartgracefully);
1884 ast_cli_register(&astrestartwhenconvenient);
1885 ast_cli_register(&astshutdownwhenconvenient);
1886 ast_cli_register(&aborthalt);
1887 ast_cli_register(&astbang);
1888 if (option_console) {
1889 /* Console stuff now... */
1890 /* Register our quit function */
1892 set_icon("Asterisk");
1893 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, ast_mainpid);
1895 ast_cli_register(&quit);
1896 ast_cli_register(&astexit);
1899 buf = (char *)el_gets(el, &num);
1901 if (buf[strlen(buf)-1] == '\n')
1902 buf[strlen(buf)-1] = '\0';
1904 consolehandler((char *)buf);
1907 ast_cli(STDOUT_FILENO, "\nUse EXIT or QUIT to exit the asterisk console\n");