2 * Asterisk -- A telephony toolkit for Linux.
4 * Top level source file for asterisk
6 * Copyright (C) 1999 - 2005, 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
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 <asterisk/app.h>
32 #include <asterisk/lock.h>
33 #include <asterisk/utils.h>
34 #include <asterisk/file.h>
35 #include <sys/resource.h>
40 #include <asterisk/io.h>
41 #include <asterisk/lock.h>
42 #include <sys/socket.h>
48 #include "editline/histedit.h"
50 #include <asterisk/config.h>
51 #include <sys/resource.h>
55 #if defined(__FreeBSD__) || defined( __NetBSD__ ) || defined(SOLARIS)
60 #define AF_LOCAL AF_UNIX
61 #define PF_LOCAL PF_UNIX
64 #define AST_MAX_CONNECTS 128
67 #define WELCOME_MESSAGE ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999 - 2005 Digium.\n"); \
68 ast_verbose( "Written by Mark Spencer <markster@digium.com>\n"); \
69 ast_verbose( "=========================================================================\n")
73 int option_exec_includes=0;
77 int option_highpriority=0;
80 int option_initcrypto=0;
82 int option_dumpcore = 0;
83 int option_cache_record_files = 0;
84 int option_timestamp = 0;
85 int option_overrideconfig = 0;
86 int option_reconnect = 0;
88 char record_cache_dir[AST_CACHE_DIR_LEN] = AST_TMP_DIR;
89 char debug_filename[AST_FILENAME_MAX] = "";
91 static int ast_socket = -1; /* UNIX Socket for allowing remote control */
92 static int ast_consock = -1; /* UNIX Socket for controlling another asterisk */
95 int fd; /* File descriptor */
97 pthread_t t; /* Thread of handler */
100 static struct ast_atexit {
102 struct ast_atexit *next;
104 AST_MUTEX_DEFINE_STATIC(atexitslock);
106 time_t ast_startuptime;
107 time_t ast_lastreloadtime;
109 static History *el_hist = NULL;
110 static EditLine *el = NULL;
111 static char *remotehostname;
113 struct console consoles[AST_MAX_CONNECTS];
115 char defaultlanguage[MAX_LANGUAGE] = DEFAULT_LANGUAGE;
117 static int ast_el_add_history(char *);
118 static int ast_el_read_history(char *);
119 static int ast_el_write_history(char *);
121 char ast_config_AST_CONFIG_DIR[AST_CONFIG_MAX_PATH];
122 char ast_config_AST_CONFIG_FILE[AST_CONFIG_MAX_PATH];
123 char ast_config_AST_MODULE_DIR[AST_CONFIG_MAX_PATH];
124 char ast_config_AST_SPOOL_DIR[AST_CONFIG_MAX_PATH];
125 char ast_config_AST_VAR_DIR[AST_CONFIG_MAX_PATH];
126 char ast_config_AST_LOG_DIR[AST_CONFIG_MAX_PATH];
127 char ast_config_AST_AGI_DIR[AST_CONFIG_MAX_PATH];
128 char ast_config_AST_DB[AST_CONFIG_MAX_PATH];
129 char ast_config_AST_KEY_DIR[AST_CONFIG_MAX_PATH];
130 char ast_config_AST_PID[AST_CONFIG_MAX_PATH];
131 char ast_config_AST_SOCKET[AST_CONFIG_MAX_PATH];
132 char ast_config_AST_RUN_DIR[AST_CONFIG_MAX_PATH];
134 static char *_argv[256];
135 static int shuttingdown = 0;
136 static int restartnow = 0;
137 static pthread_t consolethread = AST_PTHREADT_NULL;
139 int ast_register_atexit(void (*func)(void))
142 struct ast_atexit *ae;
143 ast_unregister_atexit(func);
144 ae = malloc(sizeof(struct ast_atexit));
145 ast_mutex_lock(&atexitslock);
147 memset(ae, 0, sizeof(struct ast_atexit));
153 ast_mutex_unlock(&atexitslock);
157 void ast_unregister_atexit(void (*func)(void))
159 struct ast_atexit *ae, *prev = NULL;
160 ast_mutex_lock(&atexitslock);
163 if (ae->func == func) {
165 prev->next = ae->next;
173 ast_mutex_unlock(&atexitslock);
176 static int fdprint(int fd, const char *s)
178 return write(fd, s, strlen(s) + 1);
181 /* NULL handler so we can collect the child exit status */
182 static void null_sig_handler(int signal)
187 int ast_safe_system(const char *s)
189 /* XXX This function needs some optimization work XXX */
193 struct rusage rusage;
195 void (*prev_handler) = signal(SIGCHLD, null_sig_handler);
198 /* Close file descriptors and launch system command */
199 for (x=STDERR_FILENO + 1; x<4096;x++) {
202 res = execl("/bin/sh", "/bin/sh", "-c", s, NULL);
204 } else if (pid > 0) {
206 res = wait4(pid, &status, 0, &rusage);
208 if (WIFEXITED(status))
209 res = WEXITSTATUS(status);
219 ast_log(LOG_WARNING, "Fork failed: %s\n", strerror(errno));
222 signal(SIGCHLD, prev_handler);
227 * write the string to all attached console clients
229 static void ast_network_puts(const char *string)
232 for (x=0;x<AST_MAX_CONNECTS; x++) {
233 if (consoles[x].fd > -1)
234 fdprint(consoles[x].p[1], string);
239 * write the string to the console, and all attached
242 void ast_console_puts(const char *string)
244 fputs(string, stdout);
246 ast_network_puts(string);
249 static void network_verboser(const char *s, int pos, int replace, int complete)
253 char *t = alloca(strlen(s) + 2);
255 sprintf(t, "\r%s", s);
259 ast_log(LOG_ERROR, "Out of memory\n");
268 static pthread_t lthread;
270 static void *netconsole(void *vconsole)
272 struct console *con = vconsole;
276 struct pollfd fds[2];
278 if (gethostname(hostname, sizeof(hostname)))
279 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
280 snprintf(tmp, sizeof(tmp), "%s/%d/%s\n", hostname, ast_mainpid, ASTERISK_VERSION);
281 fdprint(con->fd, tmp);
284 fds[0].events = POLLIN;
285 fds[1].fd = con->p[0];
286 fds[1].events = POLLIN;
288 res = poll(fds, 2, -1);
291 ast_log(LOG_WARNING, "poll returned < 0: %s\n", strerror(errno));
294 if (fds[0].revents) {
295 res = read(con->fd, tmp, sizeof(tmp));
300 ast_cli_command(con->fd, tmp);
302 if (fds[1].revents) {
303 res = read(con->p[0], tmp, sizeof(tmp));
305 ast_log(LOG_ERROR, "read returned %d\n", res);
308 res = write(con->fd, tmp, res);
313 if (option_verbose > 2)
314 ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection disconnected\n");
323 static void *listener(void *unused)
325 struct sockaddr_un sunaddr;
330 struct pollfd fds[1];
332 pthread_attr_init(&attr);
333 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
337 fds[0].fd = ast_socket;
338 fds[0].events= POLLIN;
339 s = poll(fds, 1, -1);
342 ast_log(LOG_WARNING, "poll returned error: %s\n", strerror(errno));
345 len = sizeof(sunaddr);
346 s = accept(ast_socket, (struct sockaddr *)&sunaddr, &len);
349 ast_log(LOG_WARNING, "Accept returned %d: %s\n", s, strerror(errno));
351 for (x=0;x<AST_MAX_CONNECTS;x++) {
352 if (consoles[x].fd < 0) {
353 if (socketpair(AF_LOCAL, SOCK_STREAM, 0, consoles[x].p)) {
354 ast_log(LOG_ERROR, "Unable to create pipe: %s\n", strerror(errno));
356 fdprint(s, "Server failed to create pipe\n");
360 flags = fcntl(consoles[x].p[1], F_GETFL);
361 fcntl(consoles[x].p[1], F_SETFL, flags | O_NONBLOCK);
363 if (ast_pthread_create(&consoles[x].t, &attr, netconsole, &consoles[x])) {
364 ast_log(LOG_ERROR, "Unable to spawn thread to handle connection: %s\n", strerror(errno));
366 fdprint(s, "Server failed to spawn thread\n");
372 if (x >= AST_MAX_CONNECTS) {
373 fdprint(s, "No more connections allowed\n");
374 ast_log(LOG_WARNING, "No more connections allowed\n");
376 } else if (consoles[x].fd > -1) {
377 if (option_verbose > 2)
378 ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection\n");
385 static int ast_makesocket(void)
387 struct sockaddr_un sunaddr;
391 struct ast_config *cfg;
392 char *config = ASTCONFPATH;
400 for (x=0;x<AST_MAX_CONNECTS;x++)
402 unlink((char *)ast_config_AST_SOCKET);
403 ast_socket = socket(PF_LOCAL, SOCK_STREAM, 0);
404 if (ast_socket < 0) {
405 ast_log(LOG_WARNING, "Unable to create control socket: %s\n", strerror(errno));
408 memset(&sunaddr, 0, sizeof(sunaddr));
409 sunaddr.sun_family = AF_LOCAL;
410 strncpy(sunaddr.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sunaddr.sun_path)-1);
411 res = bind(ast_socket, (struct sockaddr *)&sunaddr, sizeof(sunaddr));
413 ast_log(LOG_WARNING, "Unable to bind socket to %s: %s\n", (char *)ast_config_AST_SOCKET, strerror(errno));
418 res = listen(ast_socket, 2);
420 ast_log(LOG_WARNING, "Unable to listen on socket %s: %s\n", (char *)ast_config_AST_SOCKET, strerror(errno));
425 ast_register_verbose(network_verboser);
426 ast_pthread_create(<hread, NULL, listener, NULL);
428 /* Load the options for owner, group and permissions from
429 asterisk.conf. if the file doesn't exist (????) just skip
432 if (option_overrideconfig == 1) {
433 cfg = ast_config_load((char *)ast_config_AST_CONFIG_FILE);
435 cfg = ast_config_load(config);
441 group = ast_variable_retrieve(cfg, "files", "astctlgroup");
442 owner = ast_variable_retrieve(cfg, "files", "astctlowner");
443 perms = ast_variable_retrieve(cfg, "files", "astctlpermissions");
447 if ((pw=getpwnam(owner))==NULL)
448 ast_log(LOG_WARNING, "Unable to find uid of user %s\n", owner);
454 if ((grp=getgrnam(group))==NULL)
455 ast_log(LOG_WARNING, "Unable to find gid of group %s\n", group);
459 if (chown(ast_config_AST_SOCKET,uid,gid)<0)
460 ast_log(LOG_WARNING, "Unable to change ownership of %s: %s\n", ast_config_AST_SOCKET,strerror(errno));
464 sscanf(perms,"%o",&p);
465 if ((chmod(ast_config_AST_SOCKET,p))<0)
466 ast_log(LOG_WARNING, "Unable to change file permissions of %s: %s\n", ast_config_AST_SOCKET,strerror(errno));
472 static int ast_tryconnect(void)
474 struct sockaddr_un sunaddr;
476 ast_consock = socket(PF_LOCAL, SOCK_STREAM, 0);
477 if (ast_consock < 0) {
478 ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
481 memset(&sunaddr, 0, sizeof(sunaddr));
482 sunaddr.sun_family = AF_LOCAL;
483 strncpy(sunaddr.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sunaddr.sun_path)-1);
484 res = connect(ast_consock, (struct sockaddr *)&sunaddr, sizeof(sunaddr));
493 static void urg_handler(int num)
495 /* Called by soft_hangup to interrupt the poll, read, or other
496 system call. We don't actually need to do anything though. */
497 /* Cannot EVER ast_log from within a signal handler */
499 printf("Urgent handler\n");
500 signal(num, urg_handler);
504 static void hup_handler(int num)
506 if (option_verbose > 1)
507 printf("Received HUP signal -- Reloading configs\n");
509 execvp(_argv[0], _argv);
510 /* XXX This could deadlock XXX */
511 ast_module_reload(NULL);
514 static void child_handler(int sig)
516 /* Must not ever ast_log or ast_verbose within signal handler */
520 * Reap all dead children -- not just one
522 for (n = 0; wait4(-1, &status, WNOHANG, NULL) > 0; n++)
524 if (n == 0 && option_debug)
525 printf("Huh? Child handler, but nobody there?\n");
528 static void set_title(char *text)
530 /* Set an X-term or screen title */
531 if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
532 fprintf(stdout, "\033]2;%s\007", text);
535 static void set_icon(char *text)
537 if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
538 fprintf(stdout, "\033]1;%s\007", text);
541 static int set_priority(int pri)
543 struct sched_param sched;
544 memset(&sched, 0, sizeof(sched));
545 /* We set ourselves to a high priority, that we might pre-empt everything
546 else. If your PBX has heavy activity on it, this is a good thing. */
549 sched.sched_priority = 10;
550 if (sched_setscheduler(0, SCHED_RR, &sched)) {
551 ast_log(LOG_WARNING, "Unable to set high priority\n");
555 ast_verbose("Set to realtime thread\n");
557 sched.sched_priority = 0;
558 if (sched_setscheduler(0, SCHED_OTHER, &sched)) {
559 ast_log(LOG_WARNING, "Unable to set normal priority\n");
565 if (setpriority(PRIO_PROCESS, 0, -10) == -1) {
566 ast_log(LOG_WARNING, "Unable to set high priority\n");
570 ast_verbose("Set to high priority\n");
572 if (setpriority(PRIO_PROCESS, 0, 0) == -1) {
573 ast_log(LOG_WARNING, "Unable to set normal priority\n");
581 static void ast_run_atexits(void)
583 struct ast_atexit *ae;
584 ast_mutex_lock(&atexitslock);
591 ast_mutex_unlock(&atexitslock);
594 static void quit_handler(int num, int nice, int safeshutdown, int restart)
596 char filename[80] = "";
602 /* Begin shutdown routine, hanging up active channels */
603 ast_begin_shutdown(1);
604 if (option_verbose && option_console)
605 ast_verbose("Beginning asterisk %s....\n", restart ? "restart" : "shutdown");
609 /* Wait up to 15 seconds for all channels to go away */
612 if (!ast_active_channels())
616 /* Sleep 1/10 of a second */
621 ast_begin_shutdown(0);
622 if (option_verbose && option_console)
623 ast_verbose("Waiting for inactivity to perform %s...\n", restart ? "restart" : "halt");
625 if (!ast_active_channels())
634 if (option_verbose && option_console)
635 ast_verbose("Asterisk %s cancelled.\n", restart ? "restart" : "shutdown");
639 if (option_console || option_remote) {
641 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
642 if (!ast_strlen_zero(filename))
643 ast_el_write_history(filename);
647 history_end(el_hist);
650 ast_verbose("Executing last minute cleanups\n");
653 if (option_verbose && option_console)
654 ast_verbose("Asterisk %s ending (%d).\n", ast_active_channels() ? "uncleanly" : "cleanly", num);
655 else if (option_debug)
656 ast_log(LOG_DEBUG, "Asterisk ending (%d).\n", num);
657 manager_event(EVENT_FLAG_SYSTEM, "Shutdown", "Shutdown: %s\r\nRestart: %s\r\n", ast_active_channels() ? "Uncleanly" : "Cleanly", restart ? "True" : "False");
658 if (ast_socket > -1) {
662 if (ast_consock > -1)
665 unlink((char *)ast_config_AST_SOCKET);
666 if (!option_remote) unlink((char *)ast_config_AST_PID);
669 if (option_verbose || option_console)
670 ast_verbose("Preparing for Asterisk restart...\n");
671 /* Mark all FD's for closing on exec */
672 for (x=3;x<32768;x++) {
673 fcntl(x, F_SETFD, FD_CLOEXEC);
675 if (option_verbose || option_console)
676 ast_verbose("Restarting Asterisk NOW...\n");
682 /* If there is a consolethread running send it a SIGHUP
683 so it can execvp, otherwise we can do it ourselves */
684 if (consolethread != AST_PTHREADT_NULL) {
685 pthread_kill(consolethread, SIGHUP);
686 /* Give the signal handler some time to complete */
689 execvp(_argv[0], _argv);
698 static void __quit_handler(int num)
700 quit_handler(num, 0, 1, 0);
703 static const char *fix_header(char *outbuf, int maxout, const char *s, char *cmp)
706 if (!strncmp(s, cmp, strlen(cmp))) {
708 term_color(outbuf, cmp, COLOR_GRAY, 0, maxout);
714 static void console_verboser(const char *s, int pos, int replace, int complete)
718 /* Return to the beginning of the line */
720 fprintf(stdout, "\r");
721 if ((c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_4)) ||
722 (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_3)) ||
723 (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_2)) ||
724 (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_1)))
728 fputs(c + pos,stdout);
730 fputs(s + pos,stdout);
733 /* Wake up a poll()ing console */
734 if (option_console && consolethread != AST_PTHREADT_NULL)
735 pthread_kill(consolethread, SIGURG);
739 static int ast_all_zeros(char *s)
749 static void consolehandler(char *s)
753 /* Called when readline data is available */
754 if (s && !ast_all_zeros(s))
755 ast_el_add_history(s);
756 /* Give the console access to the shell */
758 /* The real handler for bang */
761 ast_safe_system(s+1);
763 ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
765 ast_cli_command(STDOUT_FILENO, s);
767 fprintf(stdout, "\nUse \"quit\" to exit\n");
770 static int remoteconsolehandler(char *s)
773 /* Called when readline data is available */
774 if (s && !ast_all_zeros(s))
775 ast_el_add_history(s);
776 /* Give the console access to the shell */
778 /* The real handler for bang */
781 ast_safe_system(s+1);
783 ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
786 if ((strncasecmp(s, "quit", 4) == 0 || strncasecmp(s, "exit", 4) == 0) &&
787 (s[4] == '\0' || isspace(s[4]))) {
788 quit_handler(0, 0, 0, 0);
792 fprintf(stdout, "\nUse \"quit\" to exit\n");
797 static char quit_help[] =
799 " Exits Asterisk.\n";
801 static char abort_halt_help[] =
802 "Usage: abort shutdown\n"
803 " Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
804 " call operations.\n";
806 static char shutdown_now_help[] =
808 " Shuts down a running Asterisk immediately, hanging up all active calls .\n";
810 static char shutdown_gracefully_help[] =
811 "Usage: stop gracefully\n"
812 " Causes Asterisk to not accept new calls, and exit when all\n"
813 " active calls have terminated normally.\n";
815 static char shutdown_when_convenient_help[] =
816 "Usage: stop when convenient\n"
817 " Causes Asterisk to perform a shutdown when all active calls have ended.\n";
819 static char restart_now_help[] =
820 "Usage: restart now\n"
821 " Causes Asterisk to hangup all calls and exec() itself performing a cold\n"
824 static char restart_gracefully_help[] =
825 "Usage: restart gracefully\n"
826 " Causes Asterisk to stop accepting new calls and exec() itself performing a cold\n"
827 " restart when all active calls have ended.\n";
829 static char restart_when_convenient_help[] =
830 "Usage: restart when convenient\n"
831 " Causes Asterisk to perform a cold restart when all active calls have ended.\n";
833 static char bang_help[] =
834 "Usage: !<command>\n"
835 " Executes a given shell command\n";
838 static int handle_quit(int fd, int argc, char *argv[])
841 return RESULT_SHOWUSAGE;
842 quit_handler(0, 0, 1, 0);
843 return RESULT_SUCCESS;
847 static int no_more_quit(int fd, int argc, char *argv[])
850 return RESULT_SHOWUSAGE;
851 ast_cli(fd, "The QUIT and EXIT commands may no longer be used to shutdown the PBX.\n"
852 "Please use STOP NOW instead, if you wish to shutdown the PBX.\n");
853 return RESULT_SUCCESS;
856 static int handle_shutdown_now(int fd, int argc, char *argv[])
859 return RESULT_SHOWUSAGE;
860 quit_handler(0, 0 /* Not nice */, 1 /* safely */, 0 /* not restart */);
861 return RESULT_SUCCESS;
864 static int handle_shutdown_gracefully(int fd, int argc, char *argv[])
867 return RESULT_SHOWUSAGE;
868 quit_handler(0, 1 /* nicely */, 1 /* safely */, 0 /* no restart */);
869 return RESULT_SUCCESS;
872 static int handle_shutdown_when_convenient(int fd, int argc, char *argv[])
875 return RESULT_SHOWUSAGE;
876 quit_handler(0, 2 /* really nicely */, 1 /* safely */, 0 /* don't restart */);
877 return RESULT_SUCCESS;
880 static int handle_restart_now(int fd, int argc, char *argv[])
883 return RESULT_SHOWUSAGE;
884 quit_handler(0, 0 /* not nicely */, 1 /* safely */, 1 /* restart */);
885 return RESULT_SUCCESS;
888 static int handle_restart_gracefully(int fd, int argc, char *argv[])
891 return RESULT_SHOWUSAGE;
892 quit_handler(0, 1 /* nicely */, 1 /* safely */, 1 /* restart */);
893 return RESULT_SUCCESS;
896 static int handle_restart_when_convenient(int fd, int argc, char *argv[])
899 return RESULT_SHOWUSAGE;
900 quit_handler(0, 2 /* really nicely */, 1 /* safely */, 1 /* restart */);
901 return RESULT_SUCCESS;
904 static int handle_abort_halt(int fd, int argc, char *argv[])
907 return RESULT_SHOWUSAGE;
908 ast_cancel_shutdown();
910 return RESULT_SUCCESS;
913 static int handle_bang(int fd, int argc, char *argv[])
915 return RESULT_SUCCESS;
918 #define ASTERISK_PROMPT "*CLI> "
920 #define ASTERISK_PROMPT2 "%s*CLI> "
922 static struct ast_cli_entry aborthalt = { { "abort", "halt", NULL }, handle_abort_halt, "Cancel a running halt", abort_halt_help };
924 static struct ast_cli_entry quit = { { "quit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
925 static struct ast_cli_entry astexit = { { "exit", NULL }, no_more_quit, "Exit Asterisk", quit_help };
927 static struct ast_cli_entry astshutdownnow = { { "stop", "now", NULL }, handle_shutdown_now, "Shut down Asterisk immediately", shutdown_now_help };
928 static struct ast_cli_entry astshutdowngracefully = { { "stop", "gracefully", NULL }, handle_shutdown_gracefully, "Gracefully shut down Asterisk", shutdown_gracefully_help };
929 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 };
930 static struct ast_cli_entry astrestartnow = { { "restart", "now", NULL }, handle_restart_now, "Restart Asterisk immediately", restart_now_help };
931 static struct ast_cli_entry astrestartgracefully = { { "restart", "gracefully", NULL }, handle_restart_gracefully, "Restart Asterisk gracefully", restart_gracefully_help };
932 static struct ast_cli_entry astrestartwhenconvenient= { { "restart", "when", "convenient", NULL }, handle_restart_when_convenient, "Restart Asterisk at empty call volume", restart_when_convenient_help };
933 static struct ast_cli_entry astbang = { { "!", NULL }, handle_bang, "Execute a shell command", bang_help };
935 static int ast_el_read_char(EditLine *el, char *cp)
939 struct pollfd fds[2];
946 fds[0].fd = ast_consock;
947 fds[0].events = POLLIN;
949 fds[1].fd = STDIN_FILENO;
950 fds[1].events = POLLIN;
953 res = poll(fds, max, -1);
957 ast_log(LOG_ERROR, "poll failed: %s\n", strerror(errno));
961 if (!option_exec && fds[1].revents) {
962 num_read = read(STDIN_FILENO, cp, 1);
968 if (fds[0].revents) {
969 res = read(ast_consock, buf, sizeof(buf) - 1);
970 /* if the remote side disappears exit */
972 fprintf(stderr, "\nDisconnected from Asterisk server\n");
973 if (!option_reconnect) {
974 quit_handler(0, 0, 0, 0);
977 int reconnects_per_second = 20;
978 fprintf(stderr, "Attempting to reconnect for 30 seconds\n");
979 for (tries=0;tries<30 * reconnects_per_second;tries++) {
980 if (ast_tryconnect()) {
981 fprintf(stderr, "Reconnect succeeded after %.3f seconds\n", 1.0 / reconnects_per_second * tries);
986 usleep(1000000 / reconnects_per_second);
989 if (tries >= 30 * reconnects_per_second) {
990 fprintf(stderr, "Failed to reconnect for 30 seconds. Quitting.\n");
991 quit_handler(0, 0, 0, 0);
998 if (!option_exec && !lastpos)
999 write(STDOUT_FILENO, "\r", 1);
1000 write(STDOUT_FILENO, buf, res);
1001 if ((buf[res-1] == '\n') || (buf[res-2] == '\n')) {
1014 static char *cli_prompt(EditLine *el)
1016 static char prompt[200];
1021 if ((pfmt = getenv("ASTERISK_PROMPT"))) {
1022 char *t = pfmt, *p = prompt;
1023 memset(prompt, 0, sizeof(prompt));
1024 while (*t != '\0' && *p < sizeof(prompt)) {
1033 int fgcolor = COLOR_WHITE, bgcolor = COLOR_BLACK;
1037 case 'C': /* color */
1039 if (sscanf(t, "%d;%d%n", &fgcolor, &bgcolor, &i) == 2) {
1040 strncat(p, term_color_code(term_code, fgcolor, bgcolor, sizeof(term_code)),sizeof(prompt) - strlen(prompt) - 1);
1042 } else if (sscanf(t, "%d%n", &fgcolor, &i) == 1) {
1043 strncat(p, term_color_code(term_code, fgcolor, 0, sizeof(term_code)),sizeof(prompt) - strlen(prompt) - 1);
1047 /* If the color has been reset correctly, then there's no need to reset it later */
1048 if ((fgcolor == COLOR_WHITE) && (bgcolor == COLOR_BLACK)) {
1054 case 'd': /* date */
1055 memset(&tm, 0, sizeof(struct tm));
1056 gettimeofday(&tv, NULL);
1057 if (localtime_r(&(tv.tv_sec), &tm)) {
1058 strftime(p, sizeof(prompt) - strlen(prompt), "%Y-%m-%d", &tm);
1061 case 'h': /* hostname */
1062 if (!gethostname(hostname, sizeof(hostname) - 1)) {
1063 strncat(p, hostname, sizeof(prompt) - strlen(prompt) - 1);
1065 strncat(p, "localhost", sizeof(prompt) - strlen(prompt) - 1);
1068 case 'H': /* short hostname */
1069 if (!gethostname(hostname, sizeof(hostname) - 1)) {
1070 for (i=0;i<sizeof(hostname);i++) {
1071 if (hostname[i] == '.') {
1076 strncat(p, hostname, sizeof(prompt) - strlen(prompt) - 1);
1078 strncat(p, "localhost", sizeof(prompt) - strlen(prompt) - 1);
1082 case 'l': /* load avg */
1084 if ((LOADAVG = fopen("/proc/loadavg", "r"))) {
1085 float avg1, avg2, avg3;
1086 int actproc, totproc, npid, which;
1087 fscanf(LOADAVG, "%f %f %f %d/%d %d",
1088 &avg1, &avg2, &avg3, &actproc, &totproc, &npid);
1089 if (sscanf(t, "%d", &which) == 1) {
1092 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg1);
1095 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg2);
1098 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg3);
1101 snprintf(p, sizeof(prompt) - strlen(prompt), "%d/%d", actproc, totproc);
1104 snprintf(p, sizeof(prompt) - strlen(prompt), "%d", npid);
1111 case 't': /* time */
1112 memset(&tm, 0, sizeof(struct tm));
1113 gettimeofday(&tv, NULL);
1114 if (localtime_r(&(tv.tv_sec), &tm)) {
1115 strftime(p, sizeof(prompt) - strlen(prompt), "%H:%M:%S", &tm);
1118 case '#': /* process console or remote? */
1119 if (! option_remote) {
1120 strncat(p, "#", sizeof(prompt) - strlen(prompt) - 1);
1122 strncat(p, ">", sizeof(prompt) - strlen(prompt) - 1);
1125 case '%': /* literal % */
1126 strncat(p, "%", sizeof(prompt) - strlen(prompt) - 1);
1128 case '\0': /* % is last character - prevent bug */
1132 while (*p != '\0') {
1143 /* Force colors back to normal at end */
1144 term_color_code(term_code, COLOR_WHITE, COLOR_BLACK, sizeof(term_code));
1145 if (strlen(term_code) > sizeof(prompt) - strlen(prompt)) {
1146 strncat(prompt + sizeof(prompt) - strlen(term_code) - 1, term_code, strlen(term_code));
1148 strncat(p, term_code, sizeof(term_code));
1151 } else if (remotehostname)
1152 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT2, remotehostname);
1154 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT);
1159 static char **ast_el_strtoarr(char *buf)
1161 char **match_list = NULL, *retstr;
1162 size_t match_list_len;
1166 while ( (retstr = strsep(&buf, " ")) != NULL) {
1168 if (!strcmp(retstr, AST_CLI_COMPLETE_EOF))
1170 if (matches + 1 >= match_list_len) {
1171 match_list_len <<= 1;
1172 match_list = realloc(match_list, match_list_len * sizeof(char *));
1175 match_list[matches++] = strdup(retstr);
1179 return (char **) NULL;
1181 if (matches>= match_list_len)
1182 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
1184 match_list[matches] = (char *) NULL;
1189 static int ast_el_sort_compare(const void *i1, const void *i2)
1193 s1 = ((char **)i1)[0];
1194 s2 = ((char **)i2)[0];
1196 return strcasecmp(s1, s2);
1199 static int ast_cli_display_match_list(char **matches, int len, int max)
1201 int i, idx, limit, count;
1202 int screenwidth = 0;
1203 int numoutput = 0, numoutputline = 0;
1205 screenwidth = ast_get_termcols(STDOUT_FILENO);
1207 /* find out how many entries can be put on one line, with two spaces between strings */
1208 limit = screenwidth / (max + 2);
1212 /* how many lines of output */
1213 count = len / limit;
1214 if (count * limit < len)
1219 qsort(&matches[0], (size_t)(len + 1), sizeof(char *), ast_el_sort_compare);
1221 for (; count > 0; count--) {
1223 for (i=0; i < limit && matches[idx]; i++, idx++) {
1225 /* Don't print dupes */
1226 if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
1229 matches[idx] = NULL;
1235 fprintf(stdout, "%-*s ", max, matches[idx]);
1237 matches[idx] = NULL;
1239 if (numoutputline > 0)
1240 fprintf(stdout, "\n");
1247 static char *cli_complete(EditLine *el, int ch)
1253 int retval = CC_ERROR;
1257 LineInfo *lf = (LineInfo *)el_line(el);
1259 *(char *)lf->cursor = '\0';
1260 ptr = (char *)lf->cursor;
1262 while (ptr > lf->buffer) {
1263 if (isspace(*ptr)) {
1271 len = lf->cursor - ptr;
1273 if (option_remote) {
1274 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr);
1275 fdprint(ast_consock, buf);
1276 res = read(ast_consock, buf, sizeof(buf));
1278 nummatches = atoi(buf);
1280 if (nummatches > 0) {
1282 int mlen = 0, maxmbuf = 2048;
1283 /* Start with a 2048 byte buffer */
1284 mbuf = malloc(maxmbuf);
1286 return (char *)(CC_ERROR);
1287 snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr);
1288 fdprint(ast_consock, buf);
1291 while (!strstr(mbuf, AST_CLI_COMPLETE_EOF) && res != -1) {
1292 if (mlen + 1024 > maxmbuf) {
1293 /* Every step increment buffer 1024 bytes */
1295 mbuf = realloc(mbuf, maxmbuf);
1297 return (char *)(CC_ERROR);
1299 /* Only read 1024 bytes at a time */
1300 res = read(ast_consock, mbuf + mlen, 1024);
1306 matches = ast_el_strtoarr(mbuf);
1309 matches = (char **) NULL;
1314 nummatches = ast_cli_generatornummatches((char *)lf->buffer,ptr);
1315 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
1320 int matches_num, maxlen, match_len;
1322 if (matches[0][0] != '\0') {
1323 el_deletestr(el, (int) len);
1324 el_insertstr(el, matches[0]);
1325 retval = CC_REFRESH;
1328 if (nummatches == 1) {
1329 /* Found an exact match */
1330 el_insertstr(el, " ");
1331 retval = CC_REFRESH;
1333 /* Must be more than one match */
1334 for (i=1, maxlen=0; matches[i]; i++) {
1335 match_len = strlen(matches[i]);
1336 if (match_len > maxlen)
1339 matches_num = i - 1;
1340 if (matches_num >1) {
1341 fprintf(stdout, "\n");
1342 ast_cli_display_match_list(matches, nummatches, maxlen);
1343 retval = CC_REDISPLAY;
1345 el_insertstr(el," ");
1346 retval = CC_REFRESH;
1352 return (char *)(long)retval;
1355 static int ast_el_initialize(void)
1358 char *editor = getenv("AST_EDITOR");
1362 if (el_hist != NULL)
1363 history_end(el_hist);
1365 el = el_init("asterisk", stdin, stdout, stderr);
1366 el_set(el, EL_PROMPT, cli_prompt);
1368 el_set(el, EL_EDITMODE, 1);
1369 el_set(el, EL_EDITOR, editor ? editor : "emacs");
1370 el_hist = history_init();
1371 if (!el || !el_hist)
1374 /* setup history with 100 entries */
1375 history(el_hist, &ev, H_SETSIZE, 100);
1377 el_set(el, EL_HIST, history, el_hist);
1379 el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
1380 /* Bind <tab> to command completion */
1381 el_set(el, EL_BIND, "^I", "ed-complete", NULL);
1382 /* Bind ? to command completion */
1383 el_set(el, EL_BIND, "?", "ed-complete", NULL);
1384 /* Bind ^D to redisplay */
1385 el_set(el, EL_BIND, "^D", "ed-redisplay", NULL);
1390 static int ast_el_add_history(char *buf)
1394 if (el_hist == NULL || el == NULL)
1395 ast_el_initialize();
1396 if (strlen(buf) > 256)
1398 return (history(el_hist, &ev, H_ENTER, buf));
1401 static int ast_el_write_history(char *filename)
1405 if (el_hist == NULL || el == NULL)
1406 ast_el_initialize();
1408 return (history(el_hist, &ev, H_SAVE, filename));
1411 static int ast_el_read_history(char *filename)
1417 if (el_hist == NULL || el == NULL)
1418 ast_el_initialize();
1420 if ((f = fopen(filename, "r")) == NULL)
1424 fgets(buf, sizeof(buf), f);
1425 if (!strcmp(buf, "_HiStOrY_V2_\n"))
1427 if (ast_all_zeros(buf))
1429 if ((ret = ast_el_add_history(buf)) == -1)
1437 static void ast_remotecontrol(char * data)
1441 char filename[80] = "";
1452 read(ast_consock, buf, sizeof(buf));
1454 write(ast_consock, data, strlen(data) + 1);
1456 hostname = strsep(&stringp, "/");
1457 cpid = strsep(&stringp, "/");
1458 version = strsep(&stringp, "\n");
1460 version = "<Version Unknown>";
1462 strsep(&stringp, ".");
1467 snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
1468 fdprint(ast_consock, tmp);
1469 snprintf(tmp, sizeof(tmp), "set debug atleast %d", option_debug);
1470 fdprint(ast_consock, tmp);
1471 ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
1472 remotehostname = hostname;
1474 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1475 if (el_hist == NULL || el == NULL)
1476 ast_el_initialize();
1478 el_set(el, EL_GETCFN, ast_el_read_char);
1480 if (!ast_strlen_zero(filename))
1481 ast_el_read_history(filename);
1483 ast_cli_register(&quit);
1484 ast_cli_register(&astexit);
1486 ast_cli_register(&astshutdown);
1488 if (option_exec && data) { /* hack to print output then exit if asterisk -rx is used */
1490 struct pollfd fds[0];
1491 fds[0].fd = ast_consock;
1492 fds[0].events = POLLIN;
1494 while(poll(fds, 1, 100) > 0) {
1495 ast_el_read_char(el, &tempchar);
1500 ebuf = (char *)el_gets(el, &num);
1502 if (ebuf && !ast_strlen_zero(ebuf)) {
1503 if (ebuf[strlen(ebuf)-1] == '\n')
1504 ebuf[strlen(ebuf)-1] = '\0';
1505 if (!remoteconsolehandler(ebuf)) {
1506 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
1508 ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
1514 printf("\nDisconnected from Asterisk server\n");
1517 static int show_version(void)
1519 printf("Asterisk " ASTERISK_VERSION "\n");
1523 static int show_cli_help(void) {
1524 printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 2000 - 2005, Digium.\n");
1525 printf("Usage: asterisk [OPTIONS]\n");
1526 printf("Valid Options:\n");
1527 printf(" -V Display version number and exit\n");
1528 printf(" -C <configfile> Use an alternate configuration file\n");
1529 printf(" -G <group> Run as a group other than the caller\n");
1530 printf(" -U <user> Run as a user other than the caller\n");
1531 printf(" -c Provide console CLI\n");
1532 printf(" -d Enable extra debugging\n");
1533 printf(" -f Do not fork\n");
1534 printf(" -g Dump core in case of a crash\n");
1535 printf(" -h This help screen\n");
1536 printf(" -i Initialize crypto keys at startup\n");
1537 printf(" -n Disable console colorization\n");
1538 printf(" -p Run as pseudo-realtime thread\n");
1539 printf(" -q Quiet mode (suppress output)\n");
1540 printf(" -r Connect to Asterisk on this machine\n");
1541 printf(" -R Connect to Asterisk, and attempt to reconnect if disconnected\n");
1542 printf(" -t Record soundfiles in /var/tmp and move them where they belong after they are done.\n");
1543 printf(" -T Display the time in [Mmm dd hh:mm:ss] format for each line of output to the CLI.\n");
1544 printf(" -v Increase verbosity (multiple v's = more verbose)\n");
1545 printf(" -x <cmd> Execute command <cmd> (only valid with -r)\n");
1550 static void ast_readconfig(void) {
1551 struct ast_config *cfg;
1552 struct ast_variable *v;
1553 struct ast_variable *v_ctlfile;
1554 char *config = ASTCONFPATH;
1556 if (option_overrideconfig == 1) {
1557 cfg = ast_config_load((char *)ast_config_AST_CONFIG_FILE);
1559 ast_log(LOG_WARNING, "Unable to open specified master config file '%s', using builtin defaults\n", ast_config_AST_CONFIG_FILE);
1561 cfg = ast_config_load(config);
1564 /* init with buildtime config */
1565 strncpy((char *)ast_config_AST_CONFIG_DIR,AST_CONFIG_DIR,sizeof(ast_config_AST_CONFIG_DIR)-1);
1566 strncpy((char *)ast_config_AST_SPOOL_DIR,AST_SPOOL_DIR,sizeof(ast_config_AST_SPOOL_DIR)-1);
1567 strncpy((char *)ast_config_AST_MODULE_DIR,AST_MODULE_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1568 strncpy((char *)ast_config_AST_VAR_DIR,AST_VAR_DIR,sizeof(ast_config_AST_VAR_DIR)-1);
1569 strncpy((char *)ast_config_AST_LOG_DIR,AST_LOG_DIR,sizeof(ast_config_AST_LOG_DIR)-1);
1570 strncpy((char *)ast_config_AST_AGI_DIR,AST_AGI_DIR,sizeof(ast_config_AST_AGI_DIR)-1);
1571 strncpy((char *)ast_config_AST_DB,AST_DB,sizeof(ast_config_AST_DB)-1);
1572 strncpy((char *)ast_config_AST_KEY_DIR,AST_KEY_DIR,sizeof(ast_config_AST_KEY_DIR)-1);
1573 strncpy((char *)ast_config_AST_PID,AST_PID,sizeof(ast_config_AST_PID)-1);
1574 strncpy((char *)ast_config_AST_SOCKET,AST_SOCKET,sizeof(ast_config_AST_SOCKET)-1);
1575 strncpy((char *)ast_config_AST_RUN_DIR,AST_RUN_DIR,sizeof(ast_config_AST_RUN_DIR)-1);
1577 /* no asterisk.conf? no problem, use buildtime config! */
1582 v_ctlfile = ast_variable_browse(cfg, "files");
1583 while (v_ctlfile!=NULL) {
1584 if (strcmp(v_ctlfile->name,"astctl")==0)
1586 v_ctlfile=v_ctlfile->next;
1589 v = ast_variable_browse(cfg, "directories");
1591 if (!strcasecmp(v->name, "astetcdir")) {
1592 strncpy((char *)ast_config_AST_CONFIG_DIR,v->value,sizeof(ast_config_AST_CONFIG_DIR)-1);
1593 } else if (!strcasecmp(v->name, "astspooldir")) {
1594 strncpy((char *)ast_config_AST_SPOOL_DIR,v->value,sizeof(ast_config_AST_SPOOL_DIR)-1);
1595 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1596 strncpy((char *)ast_config_AST_VAR_DIR,v->value,sizeof(ast_config_AST_VAR_DIR)-1);
1597 snprintf((char *)ast_config_AST_DB,sizeof(ast_config_AST_DB),"%s/%s",v->value,"astdb");
1598 } else if (!strcasecmp(v->name, "astlogdir")) {
1599 strncpy((char *)ast_config_AST_LOG_DIR,v->value,sizeof(ast_config_AST_LOG_DIR)-1);
1600 } else if (!strcasecmp(v->name, "astagidir")) {
1601 strncpy((char *)ast_config_AST_AGI_DIR,v->value,sizeof(ast_config_AST_AGI_DIR)-1);
1602 } else if (!strcasecmp(v->name, "astrundir")) {
1603 snprintf((char *)ast_config_AST_PID,sizeof(ast_config_AST_PID),"%s/%s",v->value,"asterisk.pid");
1604 snprintf((char *)ast_config_AST_SOCKET,sizeof(ast_config_AST_SOCKET),"%s/%s",v->value,v_ctlfile==NULL?"asterisk.ctl":v_ctlfile->value);
1605 strncpy((char *)ast_config_AST_RUN_DIR,v->value,sizeof(ast_config_AST_RUN_DIR)-1);
1606 } else if (!strcasecmp(v->name, "astmoddir")) {
1607 strncpy((char *)ast_config_AST_MODULE_DIR,v->value,sizeof(ast_config_AST_MODULE_DIR)-1);
1611 v = ast_variable_browse(cfg, "options");
1613 /* verbose level (-v at startup) */
1614 if (!strcasecmp(v->name, "verbose")) {
1615 option_verbose= atoi(v->value);
1616 /* whether or not to force timestamping. (-T at startup) */
1617 } else if (!strcasecmp(v->name, "timestamp")) {
1618 option_timestamp = ast_true(v->value);
1619 /* whether or not to support #exec in config files */
1620 } else if (!strcasecmp(v->name, "execincludes")) {
1621 option_exec_includes = ast_true(v->value);
1622 /* debug level (-d at startup) */
1623 } else if (!strcasecmp(v->name, "debug")) {
1625 if (sscanf(v->value, "%d", &option_debug) != 1) {
1626 option_debug = ast_true(v->value);
1628 /* Disable forking (-f at startup) */
1629 } else if (!strcasecmp(v->name, "nofork")) {
1630 option_nofork = ast_true(v->value);
1631 /* Run quietly (-q at startup ) */
1632 } else if (!strcasecmp(v->name, "quiet")) {
1633 option_quiet = ast_true(v->value);
1634 /* Run as console (-c at startup, implies nofork) */
1635 } else if (!strcasecmp(v->name, "console")) {
1636 option_console = ast_true(v->value);
1637 /* Run with highg priority if the O/S permits (-p at startup) */
1638 } else if (!strcasecmp(v->name, "highpriority")) {
1639 option_highpriority = ast_true(v->value);
1640 /* Initialize RSA auth keys (IAX2) (-i at startup) */
1641 } else if (!strcasecmp(v->name, "initcrypto")) {
1642 option_initcrypto = ast_true(v->value);
1643 /* Disable ANSI colors for console (-c at startup) */
1644 } else if (!strcasecmp(v->name, "nocolor")) {
1645 option_nocolor = ast_true(v->value);
1646 /* Dump core in case of crash (-g) */
1647 } else if (!strcasecmp(v->name, "dumpcore")) {
1648 option_dumpcore = ast_true(v->value);
1649 /* Cache recorded sound files to another directory during recording */
1650 } else if (!strcasecmp(v->name, "cache_record_files")) {
1651 option_cache_record_files = ast_true(v->value);
1652 /* Specify cache directory */
1653 } else if (!strcasecmp(v->name, "record_cache_dir")) {
1654 strncpy(record_cache_dir,v->value,AST_CACHE_DIR_LEN);
1658 ast_config_destroy(cfg);
1661 int main(int argc, char *argv[])
1664 char filename[80] = "";
1673 char *runuser=NULL, *rungroup=NULL;
1674 struct pollfd silly_macos[1];
1676 /* Remember original args for restart */
1677 if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1678 fprintf(stderr, "Truncating argument size to %d\n", (int)(sizeof(_argv) / sizeof(_argv[0])) - 1);
1679 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1681 for (x=0;x<argc;x++)
1685 /* if the progname is rasterisk consider it a remote console */
1686 if (argv[0] && (strstr(argv[0], "rasterisk")) != NULL) {
1690 if (gethostname(hostname, sizeof(hostname)))
1691 strncpy(hostname, "<Unknown>", sizeof(hostname)-1);
1692 ast_mainpid = getpid();
1699 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1700 /* Check if we're root */
1703 ast_log(LOG_ERROR, "Must be run as root\n");
1707 /* Check for options */
1708 while((c=getopt(argc, argv, "tThfdvVqprRgcinx:U:G:C:")) != -1) {
1734 option_highpriority++;
1744 option_cache_record_files++;
1754 strncpy((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE) - 1);
1755 option_overrideconfig++;
1758 option_initcrypto++;
1780 if (option_dumpcore) {
1782 memset(&l, 0, sizeof(l));
1783 l.rlim_cur = RLIM_INFINITY;
1784 l.rlim_max = RLIM_INFINITY;
1785 if (setrlimit(RLIMIT_CORE, &l)) {
1786 ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
1792 gr = getgrnam(rungroup);
1794 ast_log(LOG_WARNING, "No such group '%s'!\n", rungroup);
1797 if (setgid(gr->gr_gid)) {
1798 ast_log(LOG_WARNING, "Unable to setgid to %d (%s)\n", gr->gr_gid, rungroup);
1802 ast_verbose("Running as group '%s'\n", rungroup);
1805 if (set_priority(option_highpriority)) {
1810 pw = getpwnam(runuser);
1812 ast_log(LOG_WARNING, "No such user '%s'!\n", runuser);
1815 if (setuid(pw->pw_uid)) {
1816 ast_log(LOG_WARNING, "Unable to setuid to %d (%s)\n", pw->pw_uid, runuser);
1820 ast_verbose("Running as user '%s'\n", runuser);
1827 if (option_console && !option_verbose)
1828 ast_verbose("[ Reading Master Configuration ]");
1831 if (option_console && !option_verbose)
1832 ast_verbose("[ Initializing Custom Configuration Options ]");
1833 /* custom config setup */
1834 register_config_cli();
1838 if (option_console) {
1839 if (el_hist == NULL || el == NULL)
1840 ast_el_initialize();
1842 if (!ast_strlen_zero(filename))
1843 ast_el_read_history(filename);
1846 if (ast_tryconnect()) {
1847 /* One is already running */
1848 if (option_remote) {
1850 ast_remotecontrol(xarg);
1851 quit_handler(0, 0, 0, 0);
1854 printf(term_quit());
1855 ast_register_verbose(console_verboser);
1857 ast_remotecontrol(NULL);
1858 quit_handler(0, 0, 0, 0);
1861 ast_log(LOG_ERROR, "Asterisk already running on %s. Use 'asterisk -r' to connect.\n", (char *)ast_config_AST_SOCKET);
1862 printf(term_quit());
1865 } else if (option_remote || option_exec) {
1866 ast_log(LOG_ERROR, "Unable to connect to remote asterisk (does %s exist?)\n",ast_config_AST_SOCKET);
1867 printf(term_quit());
1870 /* Blindly write pid file since we couldn't connect */
1871 unlink((char *)ast_config_AST_PID);
1872 f = fopen((char *)ast_config_AST_PID, "w");
1874 fprintf(f, "%d\n", getpid());
1877 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1879 if (!option_verbose && !option_debug && !option_nofork && !option_console) {
1881 /* Blindly re-write pid file since we are forking */
1882 unlink((char *)ast_config_AST_PID);
1883 f = fopen((char *)ast_config_AST_PID, "w");
1885 fprintf(f, "%d\n", getpid());
1888 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
1891 /* Test recursive mutex locking. */
1892 if (test_for_thread_safety())
1893 ast_verbose("Warning! Asterisk is not thread safe.\n");
1897 sigaddset(&sigs, SIGHUP);
1898 sigaddset(&sigs, SIGTERM);
1899 sigaddset(&sigs, SIGINT);
1900 sigaddset(&sigs, SIGPIPE);
1901 sigaddset(&sigs, SIGWINCH);
1902 pthread_sigmask(SIG_BLOCK, &sigs, NULL);
1903 if (option_console || option_verbose || option_remote)
1904 ast_register_verbose(console_verboser);
1905 /* Print a welcome message if desired */
1906 if (option_verbose || option_console) {
1909 if (option_console && !option_verbose)
1910 ast_verbose("[ Booting...");
1912 signal(SIGURG, urg_handler);
1913 signal(SIGINT, __quit_handler);
1914 signal(SIGTERM, __quit_handler);
1915 signal(SIGHUP, hup_handler);
1916 signal(SIGCHLD, child_handler);
1917 signal(SIGPIPE, SIG_IGN);
1919 if (init_logger()) {
1920 printf(term_quit());
1923 ast_channels_init();
1924 if (init_manager()) {
1925 printf(term_quit());
1929 if (ast_image_init()) {
1930 printf(term_quit());
1933 if (ast_file_init()) {
1934 printf(term_quit());
1938 printf(term_quit());
1941 if (load_modules()) {
1942 printf(term_quit());
1945 if (init_framer()) {
1946 printf(term_quit());
1950 printf(term_quit());
1953 if (ast_enum_init()) {
1954 printf(term_quit());
1958 /* This should no longer be necessary */
1959 /* sync cust config and reload some internals in case a custom config handler binded to them */
1960 read_ast_cust_config();
1968 /* We might have the option of showing a console, but for now just
1970 if (option_console && !option_verbose)
1971 ast_verbose(" ]\n");
1972 if (option_verbose || option_console)
1973 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
1975 consolethread = pthread_self();
1977 pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
1978 #ifdef __AST_DEBUG_MALLOC
1981 time(&ast_startuptime);
1982 ast_cli_register(&astshutdownnow);
1983 ast_cli_register(&astshutdowngracefully);
1984 ast_cli_register(&astrestartnow);
1985 ast_cli_register(&astrestartgracefully);
1986 ast_cli_register(&astrestartwhenconvenient);
1987 ast_cli_register(&astshutdownwhenconvenient);
1988 ast_cli_register(&aborthalt);
1989 ast_cli_register(&astbang);
1990 if (option_console) {
1991 /* Console stuff now... */
1992 /* Register our quit function */
1994 set_icon("Asterisk");
1995 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, ast_mainpid);
1997 ast_cli_register(&quit);
1998 ast_cli_register(&astexit);
2001 buf = (char *)el_gets(el, &num);
2003 if (buf[strlen(buf)-1] == '\n')
2004 buf[strlen(buf)-1] = '\0';
2006 consolehandler((char *)buf);
2008 if (write(STDOUT_FILENO, "\nUse EXIT or QUIT to exit the asterisk console\n",
2009 strlen("\nUse EXIT or QUIT to exit the asterisk console\n")) < 0) {
2010 /* Whoa, stdout disappeared from under us... Make /dev/null's */
2012 fd = open("/dev/null", O_RDWR);
2014 dup2(fd, STDOUT_FILENO);
2015 dup2(fd, STDIN_FILENO);
2017 ast_log(LOG_WARNING, "Failed to open /dev/null to recover from dead console. Bad things will happen!\n");
2026 poll(silly_macos,0, -1);