allow users of RTP to know when the peer endpoint is (apparently) behind a NAT
[asterisk/asterisk.git] / asterisk.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Top level source file for asterisk
5  * 
6  * Copyright (C) 1999 - 2005, Digium, Inc.
7  *
8  * Mark Spencer <markster@digium.com>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <unistd.h>
15 #include <stdlib.h>
16 #include <sys/time.h>
17 #include <fcntl.h>
18 #include <stdio.h>
19 #include <signal.h>
20 #include <sched.h>
21 #include <sys/socket.h>
22 #include <sys/un.h>
23 #include <sys/wait.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <ctype.h>
27 #include <sys/resource.h>
28 #include <grp.h>
29 #include <pwd.h>
30 #include <sys/stat.h>
31 #include <regex.h>
32
33 #if  defined(__FreeBSD__) || defined( __NetBSD__ ) || defined(SOLARIS)
34 #include <netdb.h>
35 #endif
36
37 #include "asterisk.h"
38
39 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
40
41 #include "asterisk/logger.h"
42 #include "asterisk/options.h"
43 #include "asterisk/cli.h"
44 #include "asterisk/channel.h"
45 #include "asterisk/ulaw.h"
46 #include "asterisk/alaw.h"
47 #include "asterisk/callerid.h"
48 #include "asterisk/module.h"
49 #include "asterisk/image.h"
50 #include "asterisk/tdd.h"
51 #include "asterisk/term.h"
52 #include "asterisk/manager.h"
53 #include "asterisk/cdr.h"
54 #include "asterisk/pbx.h"
55 #include "asterisk/enum.h"
56 #include "asterisk/rtp.h"
57 #include "asterisk/app.h"
58 #include "asterisk/lock.h"
59 #include "asterisk/utils.h"
60 #include "asterisk/file.h"
61 #include "asterisk/io.h"
62 #include "asterisk/lock.h"
63 #include "editline/histedit.h"
64 #include "asterisk/config.h"
65 #include "asterisk/version.h"
66 #include "asterisk/build.h"
67 #include "asterisk/linkedlists.h"
68 #include "asterisk/devicestate.h"
69
70 #include "defaults.h"
71
72 #ifndef AF_LOCAL
73 #define AF_LOCAL AF_UNIX
74 #define PF_LOCAL PF_UNIX
75 #endif
76
77 #define AST_MAX_CONNECTS 128
78 #define NUM_MSGS 64
79
80 #define WELCOME_MESSAGE ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999 - 2005 Digium.\n"); \
81                 ast_verbose( "Written by Mark Spencer <markster@digium.com>\n"); \
82                 ast_verbose( "=========================================================================\n")
83
84 int option_verbose=0;
85 int option_debug=0;
86 int option_exec_includes=0;
87 int option_nofork=0;
88 int option_quiet=0;
89 int option_console=0;
90 int option_highpriority=0;
91 int option_remote=0;
92 int option_exec=0;
93 int option_initcrypto=0;
94 int option_nocolor;
95 int option_dumpcore = 0;
96 int option_cache_record_files = 0;
97 int option_timestamp = 0;
98 int option_overrideconfig = 0;
99 int option_reconnect = 0;
100 int option_transcode_slin = 1;
101 int option_maxcalls = 0;
102 int option_dontwarn = 0;
103 int option_priority_jumping = 1;
104 int fully_booted = 0;
105 char record_cache_dir[AST_CACHE_DIR_LEN] = AST_TMP_DIR;
106 char debug_filename[AST_FILENAME_MAX] = "";
107
108 static int ast_socket = -1;             /* UNIX Socket for allowing remote control */
109 static int ast_consock = -1;            /* UNIX Socket for controlling another asterisk */
110 int ast_mainpid;
111 struct console {
112         int fd;                                 /* File descriptor */
113         int p[2];                               /* Pipe */
114         pthread_t t;                    /* Thread of handler */
115 };
116
117 static struct ast_atexit {
118         void (*func)(void);
119         struct ast_atexit *next;
120 } *atexits = NULL;
121 AST_MUTEX_DEFINE_STATIC(atexitslock);
122
123 time_t ast_startuptime;
124 time_t ast_lastreloadtime;
125
126 static History *el_hist = NULL;
127 static EditLine *el = NULL;
128 static char *remotehostname;
129
130 struct console consoles[AST_MAX_CONNECTS];
131
132 char defaultlanguage[MAX_LANGUAGE] = DEFAULT_LANGUAGE;
133
134 static int ast_el_add_history(char *);
135 static int ast_el_read_history(char *);
136 static int ast_el_write_history(char *);
137
138 char ast_config_AST_CONFIG_DIR[AST_CONFIG_MAX_PATH];
139 char ast_config_AST_CONFIG_FILE[AST_CONFIG_MAX_PATH];
140 char ast_config_AST_MODULE_DIR[AST_CONFIG_MAX_PATH];
141 char ast_config_AST_SPOOL_DIR[AST_CONFIG_MAX_PATH];
142 char ast_config_AST_MONITOR_DIR[AST_CONFIG_MAX_PATH];
143 char ast_config_AST_VAR_DIR[AST_CONFIG_MAX_PATH];
144 char ast_config_AST_LOG_DIR[AST_CONFIG_MAX_PATH];
145 char ast_config_AST_AGI_DIR[AST_CONFIG_MAX_PATH];
146 char ast_config_AST_DB[AST_CONFIG_MAX_PATH];
147 char ast_config_AST_KEY_DIR[AST_CONFIG_MAX_PATH];
148 char ast_config_AST_PID[AST_CONFIG_MAX_PATH];
149 char ast_config_AST_SOCKET[AST_CONFIG_MAX_PATH];
150 char ast_config_AST_RUN_DIR[AST_CONFIG_MAX_PATH];
151 char ast_config_AST_CTL_PERMISSIONS[AST_CONFIG_MAX_PATH];
152 char ast_config_AST_CTL_OWNER[AST_CONFIG_MAX_PATH] = "\0";
153 char ast_config_AST_CTL_GROUP[AST_CONFIG_MAX_PATH] = "\0";
154 char ast_config_AST_CTL[AST_CONFIG_MAX_PATH] = "asterisk.ctl";
155
156 static char *_argv[256];
157 static int shuttingdown = 0;
158 static int restartnow = 0;
159 static pthread_t consolethread = AST_PTHREADT_NULL;
160
161 #if !defined(LOW_MEMORY)
162 struct file_version {
163         AST_LIST_ENTRY(file_version) list;
164         const char *file;
165         char *version;
166 };
167
168 static AST_LIST_HEAD_STATIC(file_versions, file_version);
169
170 void ast_register_file_version(const char *file, const char *version)
171 {
172         struct file_version *new;
173         char *work;
174         size_t version_length;
175
176         work = ast_strdupa(version);
177         work = ast_strip(ast_strip_quoted(work, "$", "$"));
178         version_length = strlen(work) + 1;
179
180         new = calloc(1, sizeof(*new) + version_length);
181         if (!new)
182                 return;
183
184         new->file = file;
185         new->version = (char *) new + sizeof(*new);
186         memcpy(new->version, work, version_length);
187         AST_LIST_LOCK(&file_versions);
188         AST_LIST_INSERT_HEAD(&file_versions, new, list);
189         AST_LIST_UNLOCK(&file_versions);
190 }
191
192 void ast_unregister_file_version(const char *file)
193 {
194         struct file_version *find;
195
196         AST_LIST_LOCK(&file_versions);
197         AST_LIST_TRAVERSE_SAFE_BEGIN(&file_versions, find, list) {
198                 if (!strcasecmp(find->file, file)) {
199                         AST_LIST_REMOVE_CURRENT(&file_versions, list);
200                         break;
201                 }
202         }
203         AST_LIST_TRAVERSE_SAFE_END;
204         AST_LIST_UNLOCK(&file_versions);
205         if (find)
206                 free(find);
207 }
208
209 static char show_version_files_help[] = 
210 "Usage: show version files [like <pattern>]\n"
211 "       Shows the revision numbers of the files used to build this copy of Asterisk.\n"
212 "       Optional regular expression pattern is used to filter the file list.\n";
213
214 static int handle_show_version_files(int fd, int argc, char *argv[])
215 {
216 #define FORMAT "%-25.25s %-40.40s\n"
217         struct file_version *iterator;
218         regex_t regexbuf;
219         int havepattern = 0;
220         int havename = 0;
221         int count_files = 0;
222
223         switch (argc) {
224         case 5:
225                 if (!strcasecmp(argv[3], "like")) {
226                         if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
227                                 return RESULT_SHOWUSAGE;
228                         havepattern = 1;
229                 } else
230                         return RESULT_SHOWUSAGE;
231                 break;
232         case 4:
233                 havename = 1;
234                 break;
235         case 3:
236                 break;
237         default:
238                 return RESULT_SHOWUSAGE;
239         }
240
241         ast_cli(fd, FORMAT, "File", "Revision");
242         ast_cli(fd, FORMAT, "----", "--------");
243         AST_LIST_LOCK(&file_versions);
244         AST_LIST_TRAVERSE(&file_versions, iterator, list) {
245                 if (havename && strcasecmp(iterator->file, argv[3]))
246                         continue;
247
248                 if (havepattern && regexec(&regexbuf, iterator->file, 0, NULL, 0))
249                         continue;
250
251                 ast_cli(fd, FORMAT, iterator->file, iterator->version);
252                 count_files++;
253                 if (havename)
254                         break;
255         }
256         AST_LIST_UNLOCK(&file_versions);
257         if (!havename) {
258                 ast_cli(fd, "%d files listed.\n", count_files);
259         }
260
261         if (havepattern)
262                 regfree(&regexbuf);
263
264         return RESULT_SUCCESS;
265 #undef FORMAT
266 }
267
268 static char *complete_show_version_files(char *line, char *word, int pos, int state)
269 {
270         struct file_version *find;
271         int which = 0;
272         char *ret = NULL;
273         int matchlen = strlen(word);
274
275         if (pos != 3)
276                 return NULL;
277
278         AST_LIST_LOCK(&file_versions);
279         AST_LIST_TRAVERSE(&file_versions, find, list) {
280                 if (!strncasecmp(word, find->file, matchlen)) {
281                         if (++which > state) {
282                                 ret = strdup(find->file);
283                                 break;
284                         }
285                 }
286         }
287         AST_LIST_UNLOCK(&file_versions);
288
289         return ret;
290 }
291 #endif /* ! LOW_MEMORY */
292
293 int ast_register_atexit(void (*func)(void))
294 {
295         int res = -1;
296         struct ast_atexit *ae;
297         ast_unregister_atexit(func);
298         ae = malloc(sizeof(struct ast_atexit));
299         ast_mutex_lock(&atexitslock);
300         if (ae) {
301                 memset(ae, 0, sizeof(struct ast_atexit));
302                 ae->next = atexits;
303                 ae->func = func;
304                 atexits = ae;
305                 res = 0;
306         }
307         ast_mutex_unlock(&atexitslock);
308         return res;
309 }
310
311 void ast_unregister_atexit(void (*func)(void))
312 {
313         struct ast_atexit *ae, *prev = NULL;
314         ast_mutex_lock(&atexitslock);
315         ae = atexits;
316         while(ae) {
317                 if (ae->func == func) {
318                         if (prev)
319                                 prev->next = ae->next;
320                         else
321                                 atexits = ae->next;
322                         break;
323                 }
324                 prev = ae;
325                 ae = ae->next;
326         }
327         ast_mutex_unlock(&atexitslock);
328 }
329
330 static int fdprint(int fd, const char *s)
331 {
332         return write(fd, s, strlen(s) + 1);
333 }
334
335 /* NULL handler so we can collect the child exit status */
336 static void null_sig_handler(int signal)
337 {
338
339 }
340
341 int ast_safe_system(const char *s)
342 {
343         /* XXX This function needs some optimization work XXX */
344         pid_t pid;
345         int x;
346         int res;
347         struct rusage rusage;
348         int status;
349         void (*prev_handler) = signal(SIGCHLD, null_sig_handler);
350         pid = fork();
351         if (pid == 0) {
352                 /* Close file descriptors and launch system command */
353                 for (x=STDERR_FILENO + 1; x<4096;x++) {
354                         close(x);
355                 }
356                 res = execl("/bin/sh", "/bin/sh", "-c", s, NULL);
357                 exit(1);
358         } else if (pid > 0) {
359                 for(;;) {
360                         res = wait4(pid, &status, 0, &rusage);
361                         if (res > -1) {
362                                 if (WIFEXITED(status))
363                                         res = WEXITSTATUS(status);
364                                 else
365                                         res = -1;
366                                 break;
367                         } else {
368                                 if (errno != EINTR) 
369                                         break;
370                         }
371                 }
372         } else {
373                 ast_log(LOG_WARNING, "Fork failed: %s\n", strerror(errno));
374                 res = -1;
375         }
376         signal(SIGCHLD, prev_handler);
377         return res;
378 }
379
380 /*
381  * write the string to all attached console clients
382  */
383 static void ast_network_puts(const char *string)
384 {
385         int x;
386         for (x=0;x<AST_MAX_CONNECTS; x++) {
387                 if (consoles[x].fd > -1) 
388                         fdprint(consoles[x].p[1], string);
389         }
390 }
391
392 /*
393  * write the string to the console, and all attached
394  * console clients
395  */
396 void ast_console_puts(const char *string)
397 {
398         fputs(string, stdout);
399         fflush(stdout);
400         ast_network_puts(string);
401 }
402
403 static void network_verboser(const char *s, int pos, int replace, int complete)
404         /* ARGUSED */
405 {
406         if (replace) {
407                 char *t = alloca(strlen(s) + 2);
408                 if (t) {
409                         sprintf(t, "\r%s", s);
410                         if (complete)
411                                 ast_network_puts(t);
412                 } else {
413                         ast_log(LOG_ERROR, "Out of memory\n");
414                         ast_network_puts(s);
415                 }
416         } else {
417                 if (complete)
418                         ast_network_puts(s);
419         }
420 }
421
422 static pthread_t lthread;
423
424 static void *netconsole(void *vconsole)
425 {
426         struct console *con = vconsole;
427         char hostname[MAXHOSTNAMELEN]="";
428         char tmp[512];
429         int res;
430         struct pollfd fds[2];
431         
432         if (gethostname(hostname, sizeof(hostname)-1))
433                 ast_copy_string(hostname, "<Unknown>", sizeof(hostname));
434         snprintf(tmp, sizeof(tmp), "%s/%d/%s\n", hostname, ast_mainpid, ASTERISK_VERSION);
435         fdprint(con->fd, tmp);
436         for(;;) {
437                 fds[0].fd = con->fd;
438                 fds[0].events = POLLIN;
439                 fds[0].revents = 0;
440                 fds[1].fd = con->p[0];
441                 fds[1].events = POLLIN;
442                 fds[1].revents = 0;
443
444                 res = poll(fds, 2, -1);
445                 if (res < 0) {
446                         if (errno != EINTR)
447                                 ast_log(LOG_WARNING, "poll returned < 0: %s\n", strerror(errno));
448                         continue;
449                 }
450                 if (fds[0].revents) {
451                         res = read(con->fd, tmp, sizeof(tmp));
452                         if (res < 1) {
453                                 break;
454                         }
455                         tmp[res] = 0;
456                         ast_cli_command(con->fd, tmp);
457                 }
458                 if (fds[1].revents) {
459                         res = read(con->p[0], tmp, sizeof(tmp));
460                         if (res < 1) {
461                                 ast_log(LOG_ERROR, "read returned %d\n", res);
462                                 break;
463                         }
464                         res = write(con->fd, tmp, res);
465                         if (res < 1)
466                                 break;
467                 }
468         }
469         if (option_verbose > 2) 
470                 ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection disconnected\n");
471         close(con->fd);
472         close(con->p[0]);
473         close(con->p[1]);
474         con->fd = -1;
475         
476         return NULL;
477 }
478
479 static void *listener(void *unused)
480 {
481         struct sockaddr_un sunaddr;
482         int s;
483         socklen_t len;
484         int x;
485         int flags;
486         struct pollfd fds[1];
487         pthread_attr_t attr;
488         pthread_attr_init(&attr);
489         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
490         for(;;) {
491                 if (ast_socket < 0)
492                         return NULL;
493                 fds[0].fd = ast_socket;
494                 fds[0].events= POLLIN;
495                 s = poll(fds, 1, -1);
496                 if (s < 0) {
497                         if (errno != EINTR)
498                                 ast_log(LOG_WARNING, "poll returned error: %s\n", strerror(errno));
499                         continue;
500                 }
501                 len = sizeof(sunaddr);
502                 s = accept(ast_socket, (struct sockaddr *)&sunaddr, &len);
503                 if (s < 0) {
504                         if (errno != EINTR)
505                                 ast_log(LOG_WARNING, "Accept returned %d: %s\n", s, strerror(errno));
506                 } else {
507                         for (x=0;x<AST_MAX_CONNECTS;x++) {
508                                 if (consoles[x].fd < 0) {
509                                         if (socketpair(AF_LOCAL, SOCK_STREAM, 0, consoles[x].p)) {
510                                                 ast_log(LOG_ERROR, "Unable to create pipe: %s\n", strerror(errno));
511                                                 consoles[x].fd = -1;
512                                                 fdprint(s, "Server failed to create pipe\n");
513                                                 close(s);
514                                                 break;
515                                         }
516                                         flags = fcntl(consoles[x].p[1], F_GETFL);
517                                         fcntl(consoles[x].p[1], F_SETFL, flags | O_NONBLOCK);
518                                         consoles[x].fd = s;
519                                         if (ast_pthread_create(&consoles[x].t, &attr, netconsole, &consoles[x])) {
520                                                 ast_log(LOG_ERROR, "Unable to spawn thread to handle connection: %s\n", strerror(errno));
521                                                 consoles[x].fd = -1;
522                                                 fdprint(s, "Server failed to spawn thread\n");
523                                                 close(s);
524                                         }
525                                         break;
526                                 }
527                         }
528                         if (x >= AST_MAX_CONNECTS) {
529                                 fdprint(s, "No more connections allowed\n");
530                                 ast_log(LOG_WARNING, "No more connections allowed\n");
531                                 close(s);
532                         } else if (consoles[x].fd > -1) {
533                                 if (option_verbose > 2) 
534                                         ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection\n");
535                         }
536                 }
537         }
538         return NULL;
539 }
540
541 static int ast_makesocket(void)
542 {
543         struct sockaddr_un sunaddr;
544         int res;
545         int x;
546         uid_t uid = -1;
547         gid_t gid = -1;
548
549         for (x = 0; x < AST_MAX_CONNECTS; x++)  
550                 consoles[x].fd = -1;
551         unlink(ast_config_AST_SOCKET);
552         ast_socket = socket(PF_LOCAL, SOCK_STREAM, 0);
553         if (ast_socket < 0) {
554                 ast_log(LOG_WARNING, "Unable to create control socket: %s\n", strerror(errno));
555                 return -1;
556         }               
557         memset(&sunaddr, 0, sizeof(sunaddr));
558         sunaddr.sun_family = AF_LOCAL;
559         ast_copy_string(sunaddr.sun_path, ast_config_AST_SOCKET, sizeof(sunaddr.sun_path));
560         res = bind(ast_socket, (struct sockaddr *)&sunaddr, sizeof(sunaddr));
561         if (res) {
562                 ast_log(LOG_WARNING, "Unable to bind socket to %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
563                 close(ast_socket);
564                 ast_socket = -1;
565                 return -1;
566         }
567         res = listen(ast_socket, 2);
568         if (res < 0) {
569                 ast_log(LOG_WARNING, "Unable to listen on socket %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
570                 close(ast_socket);
571                 ast_socket = -1;
572                 return -1;
573         }
574         ast_register_verbose(network_verboser);
575         ast_pthread_create(&lthread, NULL, listener, NULL);
576
577         if (!ast_strlen_zero(ast_config_AST_CTL_OWNER)) {
578                 struct passwd *pw;
579                 if ((pw = getpwnam(ast_config_AST_CTL_OWNER)) == NULL) {
580                         ast_log(LOG_WARNING, "Unable to find uid of user %s\n", ast_config_AST_CTL_OWNER);
581                 } else {
582                         uid = pw->pw_uid;
583                 }
584         }
585                 
586         if (!ast_strlen_zero(ast_config_AST_CTL_GROUP)) {
587                 struct group *grp;
588                 if ((grp = getgrnam(ast_config_AST_CTL_GROUP)) == NULL) {
589                         ast_log(LOG_WARNING, "Unable to find gid of group %s\n", ast_config_AST_CTL_GROUP);
590                 } else {
591                         gid = grp->gr_gid;
592                 }
593         }
594
595         if (chown(ast_config_AST_SOCKET, uid, gid) < 0)
596                 ast_log(LOG_WARNING, "Unable to change ownership of %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
597
598         if (!ast_strlen_zero(ast_config_AST_CTL_PERMISSIONS)) {
599                 mode_t p;
600                 sscanf(ast_config_AST_CTL_PERMISSIONS, "%o", (int *) &p);
601                 if ((chmod(ast_config_AST_SOCKET, p)) < 0)
602                         ast_log(LOG_WARNING, "Unable to change file permissions of %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
603         }
604
605         return 0;
606 }
607
608 static int ast_tryconnect(void)
609 {
610         struct sockaddr_un sunaddr;
611         int res;
612         ast_consock = socket(PF_LOCAL, SOCK_STREAM, 0);
613         if (ast_consock < 0) {
614                 ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
615                 return 0;
616         }
617         memset(&sunaddr, 0, sizeof(sunaddr));
618         sunaddr.sun_family = AF_LOCAL;
619         ast_copy_string(sunaddr.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sunaddr.sun_path));
620         res = connect(ast_consock, (struct sockaddr *)&sunaddr, sizeof(sunaddr));
621         if (res) {
622                 close(ast_consock);
623                 ast_consock = -1;
624                 return 0;
625         } else
626                 return 1;
627 }
628
629 static void urg_handler(int num)
630 {
631         /* Called by soft_hangup to interrupt the poll, read, or other
632            system call.  We don't actually need to do anything though.  */
633         /* Cannot EVER ast_log from within a signal handler */
634         /* SLD: seems to be some pthread activity relating to the printf anyway:
635          * which is leading to a deadlock? */
636 #if 0
637         if (option_debug > 2) 
638                 printf("-- Asterisk Urgent handler\n");
639 #endif
640         signal(num, urg_handler);
641         return;
642 }
643
644 static void hup_handler(int num)
645 {
646         if (option_verbose > 1) 
647                 printf("Received HUP signal -- Reloading configs\n");
648         if (restartnow)
649                 execvp(_argv[0], _argv);
650         /* XXX This could deadlock XXX */
651         ast_module_reload(NULL);
652         signal(num, hup_handler);
653 }
654
655 static void child_handler(int sig)
656 {
657         /* Must not ever ast_log or ast_verbose within signal handler */
658         int n, status;
659
660         /*
661          * Reap all dead children -- not just one
662          */
663         for (n = 0; wait4(-1, &status, WNOHANG, NULL) > 0; n++)
664                 ;
665         if (n == 0 && option_debug)     
666                 printf("Huh?  Child handler, but nobody there?\n");
667         signal(sig, child_handler);
668 }
669
670 static void set_title(char *text)
671 {
672         /* Set an X-term or screen title */
673         if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
674                 fprintf(stdout, "\033]2;%s\007", text);
675 }
676
677 static void set_icon(char *text)
678 {
679         if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
680                 fprintf(stdout, "\033]1;%s\007", text);
681 }
682
683 int ast_set_priority(int pri)
684 {
685         struct sched_param sched;
686         memset(&sched, 0, sizeof(sched));
687         /* We set ourselves to a high priority, that we might pre-empt everything
688            else.  If your PBX has heavy activity on it, this is a good thing.  */
689 #ifdef __linux__
690         if (pri) {  
691                 sched.sched_priority = 10;
692                 if (sched_setscheduler(0, SCHED_RR, &sched)) {
693                         ast_log(LOG_WARNING, "Unable to set high priority\n");
694                         return -1;
695                 } else
696                         if (option_verbose)
697                                 ast_verbose("Set to realtime thread\n");
698         } else {
699                 sched.sched_priority = 0;
700                 if (sched_setscheduler(0, SCHED_OTHER, &sched)) {
701                         ast_log(LOG_WARNING, "Unable to set normal priority\n");
702                         return -1;
703                 }
704         }
705 #else
706         if (pri) {
707                 if (setpriority(PRIO_PROCESS, 0, -10) == -1) {
708                         ast_log(LOG_WARNING, "Unable to set high priority\n");
709                         return -1;
710                 } else
711                         if (option_verbose)
712                                 ast_verbose("Set to high priority\n");
713         } else {
714                 if (setpriority(PRIO_PROCESS, 0, 0) == -1) {
715                         ast_log(LOG_WARNING, "Unable to set normal priority\n");
716                         return -1;
717                 }
718         }
719 #endif
720         return 0;
721 }
722
723 static void ast_run_atexits(void)
724 {
725         struct ast_atexit *ae;
726         ast_mutex_lock(&atexitslock);
727         ae = atexits;
728         while(ae) {
729                 if (ae->func) 
730                         ae->func();
731                 ae = ae->next;
732         }
733         ast_mutex_unlock(&atexitslock);
734 }
735
736 static void quit_handler(int num, int nice, int safeshutdown, int restart)
737 {
738         char filename[80] = "";
739         time_t s,e;
740         int x;
741         /* Try to get as many CDRs as possible submitted to the backend engines (if in batch mode) */
742         ast_cdr_engine_term();
743         if (safeshutdown) {
744                 shuttingdown = 1;
745                 if (!nice) {
746                         /* Begin shutdown routine, hanging up active channels */
747                         ast_begin_shutdown(1);
748                         if (option_verbose && option_console)
749                                 ast_verbose("Beginning asterisk %s....\n", restart ? "restart" : "shutdown");
750                         time(&s);
751                         for(;;) {
752                                 time(&e);
753                                 /* Wait up to 15 seconds for all channels to go away */
754                                 if ((e - s) > 15)
755                                         break;
756                                 if (!ast_active_channels())
757                                         break;
758                                 if (!shuttingdown)
759                                         break;
760                                 /* Sleep 1/10 of a second */
761                                 usleep(100000);
762                         }
763                 } else {
764                         if (nice < 2)
765                                 ast_begin_shutdown(0);
766                         if (option_verbose && option_console)
767                                 ast_verbose("Waiting for inactivity to perform %s...\n", restart ? "restart" : "halt");
768                         for(;;) {
769                                 if (!ast_active_channels())
770                                         break;
771                                 if (!shuttingdown)
772                                         break;
773                                 sleep(1);
774                         }
775                 }
776
777                 if (!shuttingdown) {
778                         if (option_verbose && option_console)
779                                 ast_verbose("Asterisk %s cancelled.\n", restart ? "restart" : "shutdown");
780                         return;
781                 }
782         }
783         if (option_console || option_remote) {
784                 if (getenv("HOME")) 
785                         snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
786                 if (!ast_strlen_zero(filename))
787                         ast_el_write_history(filename);
788                 if (el != NULL)
789                         el_end(el);
790                 if (el_hist != NULL)
791                         history_end(el_hist);
792         }
793         if (option_verbose)
794                 ast_verbose("Executing last minute cleanups\n");
795         ast_run_atexits();
796         /* Called on exit */
797         if (option_verbose && option_console)
798                 ast_verbose("Asterisk %s ending (%d).\n", ast_active_channels() ? "uncleanly" : "cleanly", num);
799         else if (option_debug)
800                 ast_log(LOG_DEBUG, "Asterisk ending (%d).\n", num);
801         manager_event(EVENT_FLAG_SYSTEM, "Shutdown", "Shutdown: %s\r\nRestart: %s\r\n", ast_active_channels() ? "Uncleanly" : "Cleanly", restart ? "True" : "False");
802         if (ast_socket > -1) {
803                 close(ast_socket);
804                 ast_socket = -1;
805         }
806         if (ast_consock > -1)
807                 close(ast_consock);
808         if (ast_socket > -1)
809                 unlink((char *)ast_config_AST_SOCKET);
810         if (!option_remote) unlink((char *)ast_config_AST_PID);
811         printf(term_quit());
812         if (restart) {
813                 if (option_verbose || option_console)
814                         ast_verbose("Preparing for Asterisk restart...\n");
815                 /* Mark all FD's for closing on exec */
816                 for (x=3;x<32768;x++) {
817                         fcntl(x, F_SETFD, FD_CLOEXEC);
818                 }
819                 if (option_verbose || option_console)
820                         ast_verbose("Restarting Asterisk NOW...\n");
821                 restartnow = 1;
822
823                 /* close logger */
824                 close_logger();
825
826                 /* If there is a consolethread running send it a SIGHUP 
827                    so it can execvp, otherwise we can do it ourselves */
828                 if (consolethread != AST_PTHREADT_NULL) {
829                         pthread_kill(consolethread, SIGHUP);
830                         /* Give the signal handler some time to complete */
831                         sleep(2);
832                 } else
833                         execvp(_argv[0], _argv);
834         
835         } else {
836                 /* close logger */
837                 close_logger();
838         }
839         exit(0);
840 }
841
842 static void __quit_handler(int num)
843 {
844         quit_handler(num, 0, 1, 0);
845 }
846
847 static const char *fix_header(char *outbuf, int maxout, const char *s, char *cmp)
848 {
849         const char *c;
850         if (!strncmp(s, cmp, strlen(cmp))) {
851                 c = s + strlen(cmp);
852                 term_color(outbuf, cmp, COLOR_GRAY, 0, maxout);
853                 return c;
854         }
855         return NULL;
856 }
857
858 static void console_verboser(const char *s, int pos, int replace, int complete)
859 {
860         char tmp[80];
861         const char *c=NULL;
862         /* Return to the beginning of the line */
863         if (!pos) {
864                 fprintf(stdout, "\r");
865                 if ((c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_4)) ||
866                         (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_3)) ||
867                         (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_2)) ||
868                         (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_1)))
869                         fputs(tmp, stdout);
870         }
871         if (c)
872                 fputs(c + pos,stdout);
873         else
874                 fputs(s + pos,stdout);
875         fflush(stdout);
876         if (complete) {
877                 /* Wake up a poll()ing console */
878                 if (option_console && consolethread != AST_PTHREADT_NULL)
879                         pthread_kill(consolethread, SIGURG);
880         }
881 }
882
883 static int ast_all_zeros(char *s)
884 {
885         while(*s) {
886                 if (*s > 32)
887                         return 0;
888                 s++;  
889         }
890         return 1;
891 }
892
893 static void consolehandler(char *s)
894 {
895         printf(term_end());
896         fflush(stdout);
897         /* Called when readline data is available */
898         if (s && !ast_all_zeros(s))
899                 ast_el_add_history(s);
900         /* Give the console access to the shell */
901         if (s) {
902                 /* The real handler for bang */
903                 if (s[0] == '!') {
904                         if (s[1])
905                                 ast_safe_system(s+1);
906                         else
907                                 ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
908                 } else 
909                 ast_cli_command(STDOUT_FILENO, s);
910         } else
911                 fprintf(stdout, "\nUse \"quit\" to exit\n");
912 }
913
914 static int remoteconsolehandler(char *s)
915 {
916         int ret = 0;
917         /* Called when readline data is available */
918         if (s && !ast_all_zeros(s))
919                 ast_el_add_history(s);
920         /* Give the console access to the shell */
921         if (s) {
922                 /* The real handler for bang */
923                 if (s[0] == '!') {
924                         if (s[1])
925                                 ast_safe_system(s+1);
926                         else
927                                 ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
928                         ret = 1;
929                 }
930                 if ((strncasecmp(s, "quit", 4) == 0 || strncasecmp(s, "exit", 4) == 0) &&
931                     (s[4] == '\0' || isspace(s[4]))) {
932                         quit_handler(0, 0, 0, 0);
933                         ret = 1;
934                 }
935         } else
936                 fprintf(stdout, "\nUse \"quit\" to exit\n");
937
938         return ret;
939 }
940
941 static char abort_halt_help[] = 
942 "Usage: abort shutdown\n"
943 "       Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
944 "       call operations.\n";
945
946 static char shutdown_now_help[] = 
947 "Usage: stop now\n"
948 "       Shuts down a running Asterisk immediately, hanging up all active calls .\n";
949
950 static char shutdown_gracefully_help[] = 
951 "Usage: stop gracefully\n"
952 "       Causes Asterisk to not accept new calls, and exit when all\n"
953 "       active calls have terminated normally.\n";
954
955 static char shutdown_when_convenient_help[] = 
956 "Usage: stop when convenient\n"
957 "       Causes Asterisk to perform a shutdown when all active calls have ended.\n";
958
959 static char restart_now_help[] = 
960 "Usage: restart now\n"
961 "       Causes Asterisk to hangup all calls and exec() itself performing a cold\n"
962 "       restart.\n";
963
964 static char restart_gracefully_help[] = 
965 "Usage: restart gracefully\n"
966 "       Causes Asterisk to stop accepting new calls and exec() itself performing a cold\n"
967 "       restart when all active calls have ended.\n";
968
969 static char restart_when_convenient_help[] = 
970 "Usage: restart when convenient\n"
971 "       Causes Asterisk to perform a cold restart when all active calls have ended.\n";
972
973 static char bang_help[] =
974 "Usage: !<command>\n"
975 "       Executes a given shell command\n";
976
977 #if 0
978 static int handle_quit(int fd, int argc, char *argv[])
979 {
980         if (argc != 1)
981                 return RESULT_SHOWUSAGE;
982         quit_handler(0, 0, 1, 0);
983         return RESULT_SUCCESS;
984 }
985 #endif
986
987 static int handle_shutdown_now(int fd, int argc, char *argv[])
988 {
989         if (argc != 2)
990                 return RESULT_SHOWUSAGE;
991         quit_handler(0, 0 /* Not nice */, 1 /* safely */, 0 /* not restart */);
992         return RESULT_SUCCESS;
993 }
994
995 static int handle_shutdown_gracefully(int fd, int argc, char *argv[])
996 {
997         if (argc != 2)
998                 return RESULT_SHOWUSAGE;
999         quit_handler(0, 1 /* nicely */, 1 /* safely */, 0 /* no restart */);
1000         return RESULT_SUCCESS;
1001 }
1002
1003 static int handle_shutdown_when_convenient(int fd, int argc, char *argv[])
1004 {
1005         if (argc != 3)
1006                 return RESULT_SHOWUSAGE;
1007         quit_handler(0, 2 /* really nicely */, 1 /* safely */, 0 /* don't restart */);
1008         return RESULT_SUCCESS;
1009 }
1010
1011 static int handle_restart_now(int fd, int argc, char *argv[])
1012 {
1013         if (argc != 2)
1014                 return RESULT_SHOWUSAGE;
1015         quit_handler(0, 0 /* not nicely */, 1 /* safely */, 1 /* restart */);
1016         return RESULT_SUCCESS;
1017 }
1018
1019 static int handle_restart_gracefully(int fd, int argc, char *argv[])
1020 {
1021         if (argc != 2)
1022                 return RESULT_SHOWUSAGE;
1023         quit_handler(0, 1 /* nicely */, 1 /* safely */, 1 /* restart */);
1024         return RESULT_SUCCESS;
1025 }
1026
1027 static int handle_restart_when_convenient(int fd, int argc, char *argv[])
1028 {
1029         if (argc != 3)
1030                 return RESULT_SHOWUSAGE;
1031         quit_handler(0, 2 /* really nicely */, 1 /* safely */, 1 /* restart */);
1032         return RESULT_SUCCESS;
1033 }
1034
1035 static int handle_abort_halt(int fd, int argc, char *argv[])
1036 {
1037         if (argc != 2)
1038                 return RESULT_SHOWUSAGE;
1039         ast_cancel_shutdown();
1040         shuttingdown = 0;
1041         return RESULT_SUCCESS;
1042 }
1043
1044 static int handle_bang(int fd, int argc, char *argv[])
1045 {
1046         return RESULT_SUCCESS;
1047 }
1048
1049 #define ASTERISK_PROMPT "*CLI> "
1050
1051 #define ASTERISK_PROMPT2 "%s*CLI> "
1052
1053 static struct ast_cli_entry core_cli[] = {
1054         { { "abort", "halt", NULL }, handle_abort_halt,
1055           "Cancel a running halt", abort_halt_help },
1056         { { "stop", "now", NULL }, handle_shutdown_now,
1057           "Shut down Asterisk immediately", shutdown_now_help },
1058         { { "stop", "gracefully", NULL }, handle_shutdown_gracefully,
1059           "Gracefully shut down Asterisk", shutdown_gracefully_help },
1060         { { "stop", "when","convenient", NULL }, handle_shutdown_when_convenient,
1061           "Shut down Asterisk at empty call volume", shutdown_when_convenient_help },
1062         { { "restart", "now", NULL }, handle_restart_now,
1063           "Restart Asterisk immediately", restart_now_help },
1064         { { "restart", "gracefully", NULL }, handle_restart_gracefully,
1065           "Restart Asterisk gracefully", restart_gracefully_help },
1066         { { "restart", "when", "convenient", NULL }, handle_restart_when_convenient,
1067           "Restart Asterisk at empty call volume", restart_when_convenient_help },
1068         { { "!", NULL }, handle_bang,
1069           "Execute a shell command", bang_help },
1070 #if !defined(LOW_MEMORY)
1071         { { "show", "version", "files", NULL }, handle_show_version_files,
1072           "Show versions of files used to build Asterisk", show_version_files_help, complete_show_version_files },
1073 #endif /* ! LOW_MEMORY */
1074 };
1075
1076 static int ast_el_read_char(EditLine *el, char *cp)
1077 {
1078         int num_read=0;
1079         int lastpos=0;
1080         struct pollfd fds[2];
1081         int res;
1082         int max;
1083         char buf[512];
1084
1085         for (;;) {
1086                 max = 1;
1087                 fds[0].fd = ast_consock;
1088                 fds[0].events = POLLIN;
1089                 if (!option_exec) {
1090                         fds[1].fd = STDIN_FILENO;
1091                         fds[1].events = POLLIN;
1092                         max++;
1093                 }
1094                 res = poll(fds, max, -1);
1095                 if (res < 0) {
1096                         if (errno == EINTR)
1097                                 continue;
1098                         ast_log(LOG_ERROR, "poll failed: %s\n", strerror(errno));
1099                         break;
1100                 }
1101
1102                 if (!option_exec && fds[1].revents) {
1103                         num_read = read(STDIN_FILENO, cp, 1);
1104                         if (num_read < 1) {
1105                                 break;
1106                         } else 
1107                                 return (num_read);
1108                 }
1109                 if (fds[0].revents) {
1110                         res = read(ast_consock, buf, sizeof(buf) - 1);
1111                         /* if the remote side disappears exit */
1112                         if (res < 1) {
1113                                 fprintf(stderr, "\nDisconnected from Asterisk server\n");
1114                                 if (!option_reconnect) {
1115                                         quit_handler(0, 0, 0, 0);
1116                                 } else {
1117                                         int tries;
1118                                         int reconnects_per_second = 20;
1119                                         fprintf(stderr, "Attempting to reconnect for 30 seconds\n");
1120                                         for (tries=0;tries<30 * reconnects_per_second;tries++) {
1121                                                 if (ast_tryconnect()) {
1122                                                         fprintf(stderr, "Reconnect succeeded after %.3f seconds\n", 1.0 / reconnects_per_second * tries);
1123                                                         printf(term_quit());
1124                                                         WELCOME_MESSAGE;
1125                                                         break;
1126                                                 } else {
1127                                                         usleep(1000000 / reconnects_per_second);
1128                                                 }
1129                                         }
1130                                         if (tries >= 30 * reconnects_per_second) {
1131                                                 fprintf(stderr, "Failed to reconnect for 30 seconds.  Quitting.\n");
1132                                                 quit_handler(0, 0, 0, 0);
1133                                         }
1134                                 }
1135                         }
1136
1137                         buf[res] = '\0';
1138
1139                         if (!option_exec && !lastpos)
1140                                 write(STDOUT_FILENO, "\r", 1);
1141                         write(STDOUT_FILENO, buf, res);
1142                         if ((buf[res-1] == '\n') || (buf[res-2] == '\n')) {
1143                                 *cp = CC_REFRESH;
1144                                 return(1);
1145                         } else {
1146                                 lastpos = 1;
1147                         }
1148                 }
1149         }
1150
1151         *cp = '\0';
1152         return (0);
1153 }
1154
1155 static char *cli_prompt(EditLine *el)
1156 {
1157         static char prompt[200];
1158         char *pfmt;
1159         int color_used=0;
1160         char term_code[20];
1161
1162         if ((pfmt = getenv("ASTERISK_PROMPT"))) {
1163                 char *t = pfmt, *p = prompt;
1164                 memset(prompt, 0, sizeof(prompt));
1165                 while (*t != '\0' && *p < sizeof(prompt)) {
1166                         if (*t == '%') {
1167                                 char hostname[MAXHOSTNAMELEN]="";
1168                                 int i;
1169                                 struct timeval tv;
1170                                 struct tm tm;
1171 #ifdef linux
1172                                 FILE *LOADAVG;
1173 #endif
1174                                 int fgcolor = COLOR_WHITE, bgcolor = COLOR_BLACK;
1175
1176                                 t++;
1177                                 switch (*t) {
1178                                         case 'C': /* color */
1179                                                 t++;
1180                                                 if (sscanf(t, "%d;%d%n", &fgcolor, &bgcolor, &i) == 2) {
1181                                                         strncat(p, term_color_code(term_code, fgcolor, bgcolor, sizeof(term_code)),sizeof(prompt) - strlen(prompt) - 1);
1182                                                         t += i - 1;
1183                                                 } else if (sscanf(t, "%d%n", &fgcolor, &i) == 1) {
1184                                                         strncat(p, term_color_code(term_code, fgcolor, 0, sizeof(term_code)),sizeof(prompt) - strlen(prompt) - 1);
1185                                                         t += i - 1;
1186                                                 }
1187
1188                                                 /* If the color has been reset correctly, then there's no need to reset it later */
1189                                                 if ((fgcolor == COLOR_WHITE) && (bgcolor == COLOR_BLACK)) {
1190                                                         color_used = 0;
1191                                                 } else {
1192                                                         color_used = 1;
1193                                                 }
1194                                                 break;
1195                                         case 'd': /* date */
1196                                                 memset(&tm, 0, sizeof(struct tm));
1197                                                 tv = ast_tvnow();
1198                                                 if (localtime_r(&(tv.tv_sec), &tm)) {
1199                                                         strftime(p, sizeof(prompt) - strlen(prompt), "%Y-%m-%d", &tm);
1200                                                 }
1201                                                 break;
1202                                         case 'h': /* hostname */
1203                                                 if (!gethostname(hostname, sizeof(hostname) - 1)) {
1204                                                         strncat(p, hostname, sizeof(prompt) - strlen(prompt) - 1);
1205                                                 } else {
1206                                                         strncat(p, "localhost", sizeof(prompt) - strlen(prompt) - 1);
1207                                                 }
1208                                                 break;
1209                                         case 'H': /* short hostname */
1210                                                 if (!gethostname(hostname, sizeof(hostname) - 1)) {
1211                                                         for (i=0;i<sizeof(hostname);i++) {
1212                                                                 if (hostname[i] == '.') {
1213                                                                         hostname[i] = '\0';
1214                                                                         break;
1215                                                                 }
1216                                                         }
1217                                                         strncat(p, hostname, sizeof(prompt) - strlen(prompt) - 1);
1218                                                 } else {
1219                                                         strncat(p, "localhost", sizeof(prompt) - strlen(prompt) - 1);
1220                                                 }
1221                                                 break;
1222 #ifdef linux
1223                                         case 'l': /* load avg */
1224                                                 t++;
1225                                                 if ((LOADAVG = fopen("/proc/loadavg", "r"))) {
1226                                                         float avg1, avg2, avg3;
1227                                                         int actproc, totproc, npid, which;
1228                                                         fscanf(LOADAVG, "%f %f %f %d/%d %d",
1229                                                                 &avg1, &avg2, &avg3, &actproc, &totproc, &npid);
1230                                                         if (sscanf(t, "%d", &which) == 1) {
1231                                                                 switch (which) {
1232                                                                         case 1:
1233                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg1);
1234                                                                                 break;
1235                                                                         case 2:
1236                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg2);
1237                                                                                 break;
1238                                                                         case 3:
1239                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg3);
1240                                                                                 break;
1241                                                                         case 4:
1242                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%d/%d", actproc, totproc);
1243                                                                                 break;
1244                                                                         case 5:
1245                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%d", npid);
1246                                                                                 break;
1247                                                                 }
1248                                                         }
1249                                                 }
1250                                                 break;
1251 #endif
1252                                         case 't': /* time */
1253                                                 memset(&tm, 0, sizeof(struct tm));
1254                                                 tv = ast_tvnow();
1255                                                 if (localtime_r(&(tv.tv_sec), &tm)) {
1256                                                         strftime(p, sizeof(prompt) - strlen(prompt), "%H:%M:%S", &tm);
1257                                                 }
1258                                                 break;
1259                                         case '#': /* process console or remote? */
1260                                                 if (! option_remote) {
1261                                                         strncat(p, "#", sizeof(prompt) - strlen(prompt) - 1);
1262                                                 } else {
1263                                                         strncat(p, ">", sizeof(prompt) - strlen(prompt) - 1);
1264                                                 }
1265                                                 break;
1266                                         case '%': /* literal % */
1267                                                 strncat(p, "%", sizeof(prompt) - strlen(prompt) - 1);
1268                                                 break;
1269                                         case '\0': /* % is last character - prevent bug */
1270                                                 t--;
1271                                                 break;
1272                                 }
1273                                 while (*p != '\0') {
1274                                         p++;
1275                                 }
1276                                 t++;
1277                         } else {
1278                                 *p = *t;
1279                                 p++;
1280                                 t++;
1281                         }
1282                 }
1283                 if (color_used) {
1284                         /* Force colors back to normal at end */
1285                         term_color_code(term_code, COLOR_WHITE, COLOR_BLACK, sizeof(term_code));
1286                         if (strlen(term_code) > sizeof(prompt) - strlen(prompt)) {
1287                                 strncat(prompt + sizeof(prompt) - strlen(term_code) - 1, term_code, strlen(term_code));
1288                         } else {
1289                                 strncat(p, term_code, sizeof(term_code));
1290                         }
1291                 }
1292         } else if (remotehostname)
1293                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT2, remotehostname);
1294         else
1295                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT);
1296
1297         return(prompt); 
1298 }
1299
1300 static char **ast_el_strtoarr(char *buf)
1301 {
1302         char **match_list = NULL, *retstr;
1303         size_t match_list_len;
1304         int matches = 0;
1305
1306         match_list_len = 1;
1307         while ( (retstr = strsep(&buf, " ")) != NULL) {
1308
1309                 if (!strcmp(retstr, AST_CLI_COMPLETE_EOF))
1310                         break;
1311                 if (matches + 1 >= match_list_len) {
1312                         match_list_len <<= 1;
1313                         match_list = realloc(match_list, match_list_len * sizeof(char *));
1314                 }
1315
1316                 match_list[matches++] = strdup(retstr);
1317         }
1318
1319         if (!match_list)
1320                 return (char **) NULL;
1321
1322         if (matches>= match_list_len)
1323                 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
1324
1325         match_list[matches] = (char *) NULL;
1326
1327         return match_list;
1328 }
1329
1330 static int ast_el_sort_compare(const void *i1, const void *i2)
1331 {
1332         char *s1, *s2;
1333
1334         s1 = ((char **)i1)[0];
1335         s2 = ((char **)i2)[0];
1336
1337         return strcasecmp(s1, s2);
1338 }
1339
1340 static int ast_cli_display_match_list(char **matches, int len, int max)
1341 {
1342         int i, idx, limit, count;
1343         int screenwidth = 0;
1344         int numoutput = 0, numoutputline = 0;
1345
1346         screenwidth = ast_get_termcols(STDOUT_FILENO);
1347
1348         /* find out how many entries can be put on one line, with two spaces between strings */
1349         limit = screenwidth / (max + 2);
1350         if (limit == 0)
1351                 limit = 1;
1352
1353         /* how many lines of output */
1354         count = len / limit;
1355         if (count * limit < len)
1356                 count++;
1357
1358         idx = 1;
1359
1360         qsort(&matches[0], (size_t)(len + 1), sizeof(char *), ast_el_sort_compare);
1361
1362         for (; count > 0; count--) {
1363                 numoutputline = 0;
1364                 for (i=0; i < limit && matches[idx]; i++, idx++) {
1365
1366                         /* Don't print dupes */
1367                         if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
1368                                 i--;
1369                                 free(matches[idx]);
1370                                 matches[idx] = NULL;
1371                                 continue;
1372                         }
1373
1374                         numoutput++;
1375                         numoutputline++;
1376                         fprintf(stdout, "%-*s  ", max, matches[idx]);
1377                         free(matches[idx]);
1378                         matches[idx] = NULL;
1379                 }
1380                 if (numoutputline > 0)
1381                         fprintf(stdout, "\n");
1382         }
1383
1384         return numoutput;
1385 }
1386
1387
1388 static char *cli_complete(EditLine *el, int ch)
1389 {
1390         int len=0;
1391         char *ptr;
1392         int nummatches = 0;
1393         char **matches;
1394         int retval = CC_ERROR;
1395         char buf[2048];
1396         int res;
1397
1398         LineInfo *lf = (LineInfo *)el_line(el);
1399
1400         *(char *)lf->cursor = '\0';
1401         ptr = (char *)lf->cursor;
1402         if (ptr) {
1403                 while (ptr > lf->buffer) {
1404                         if (isspace(*ptr)) {
1405                                 ptr++;
1406                                 break;
1407                         }
1408                         ptr--;
1409                 }
1410         }
1411
1412         len = lf->cursor - ptr;
1413
1414         if (option_remote) {
1415                 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr); 
1416                 fdprint(ast_consock, buf);
1417                 res = read(ast_consock, buf, sizeof(buf));
1418                 buf[res] = '\0';
1419                 nummatches = atoi(buf);
1420
1421                 if (nummatches > 0) {
1422                         char *mbuf;
1423                         int mlen = 0, maxmbuf = 2048;
1424                         /* Start with a 2048 byte buffer */
1425                         mbuf = malloc(maxmbuf);
1426                         if (!mbuf)
1427                                 return (char *)(CC_ERROR);
1428                         snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr); 
1429                         fdprint(ast_consock, buf);
1430                         res = 0;
1431                         mbuf[0] = '\0';
1432                         while (!strstr(mbuf, AST_CLI_COMPLETE_EOF) && res != -1) {
1433                                 if (mlen + 1024 > maxmbuf) {
1434                                         /* Every step increment buffer 1024 bytes */
1435                                         maxmbuf += 1024;
1436                                         mbuf = realloc(mbuf, maxmbuf);
1437                                         if (!mbuf)
1438                                                 return (char *)(CC_ERROR);
1439                                 }
1440                                 /* Only read 1024 bytes at a time */
1441                                 res = read(ast_consock, mbuf + mlen, 1024);
1442                                 if (res > 0)
1443                                         mlen += res;
1444                         }
1445                         mbuf[mlen] = '\0';
1446
1447                         matches = ast_el_strtoarr(mbuf);
1448                         free(mbuf);
1449                 } else
1450                         matches = (char **) NULL;
1451
1452
1453         } else {
1454
1455                 nummatches = ast_cli_generatornummatches((char *)lf->buffer,ptr);
1456                 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
1457         }
1458
1459         if (matches) {
1460                 int i;
1461                 int matches_num, maxlen, match_len;
1462
1463                 if (matches[0][0] != '\0') {
1464                         el_deletestr(el, (int) len);
1465                         el_insertstr(el, matches[0]);
1466                         retval = CC_REFRESH;
1467                 }
1468
1469                 if (nummatches == 1) {
1470                         /* Found an exact match */
1471                         el_insertstr(el, " ");
1472                         retval = CC_REFRESH;
1473                 } else {
1474                         /* Must be more than one match */
1475                         for (i=1, maxlen=0; matches[i]; i++) {
1476                                 match_len = strlen(matches[i]);
1477                                 if (match_len > maxlen)
1478                                         maxlen = match_len;
1479                         }
1480                         matches_num = i - 1;
1481                         if (matches_num >1) {
1482                                 fprintf(stdout, "\n");
1483                                 ast_cli_display_match_list(matches, nummatches, maxlen);
1484                                 retval = CC_REDISPLAY;
1485                         } else { 
1486                                 el_insertstr(el," ");
1487                                 retval = CC_REFRESH;
1488                         }
1489                 }
1490         free(matches);
1491         }
1492
1493         return (char *)(long)retval;
1494 }
1495
1496 static int ast_el_initialize(void)
1497 {
1498         HistEvent ev;
1499         char *editor = getenv("AST_EDITOR");
1500
1501         if (el != NULL)
1502                 el_end(el);
1503         if (el_hist != NULL)
1504                 history_end(el_hist);
1505
1506         el = el_init("asterisk", stdin, stdout, stderr);
1507         el_set(el, EL_PROMPT, cli_prompt);
1508
1509         el_set(el, EL_EDITMODE, 1);             
1510         el_set(el, EL_EDITOR, editor ? editor : "emacs");               
1511         el_hist = history_init();
1512         if (!el || !el_hist)
1513                 return -1;
1514
1515         /* setup history with 100 entries */
1516         history(el_hist, &ev, H_SETSIZE, 100);
1517
1518         el_set(el, EL_HIST, history, el_hist);
1519
1520         el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
1521         /* Bind <tab> to command completion */
1522         el_set(el, EL_BIND, "^I", "ed-complete", NULL);
1523         /* Bind ? to command completion */
1524         el_set(el, EL_BIND, "?", "ed-complete", NULL);
1525         /* Bind ^D to redisplay */
1526         el_set(el, EL_BIND, "^D", "ed-redisplay", NULL);
1527
1528         return 0;
1529 }
1530
1531 static int ast_el_add_history(char *buf)
1532 {
1533         HistEvent ev;
1534
1535         if (el_hist == NULL || el == NULL)
1536                 ast_el_initialize();
1537         if (strlen(buf) > 256)
1538                 return 0;
1539         return (history(el_hist, &ev, H_ENTER, buf));
1540 }
1541
1542 static int ast_el_write_history(char *filename)
1543 {
1544         HistEvent ev;
1545
1546         if (el_hist == NULL || el == NULL)
1547                 ast_el_initialize();
1548
1549         return (history(el_hist, &ev, H_SAVE, filename));
1550 }
1551
1552 static int ast_el_read_history(char *filename)
1553 {
1554         char buf[256];
1555         FILE *f;
1556         int ret = -1;
1557
1558         if (el_hist == NULL || el == NULL)
1559                 ast_el_initialize();
1560
1561         if ((f = fopen(filename, "r")) == NULL)
1562                 return ret;
1563
1564         while (!feof(f)) {
1565                 fgets(buf, sizeof(buf), f);
1566                 if (!strcmp(buf, "_HiStOrY_V2_\n"))
1567                         continue;
1568                 if (ast_all_zeros(buf))
1569                         continue;
1570                 if ((ret = ast_el_add_history(buf)) == -1)
1571                         break;
1572         }
1573         fclose(f);
1574
1575         return ret;
1576 }
1577
1578 static void ast_remotecontrol(char * data)
1579 {
1580         char buf[80];
1581         int res;
1582         char filename[80] = "";
1583         char *hostname;
1584         char *cpid;
1585         char *version;
1586         int pid;
1587         char tmp[80];
1588         char *stringp=NULL;
1589
1590         char *ebuf;
1591         int num = 0;
1592
1593         read(ast_consock, buf, sizeof(buf));
1594         if (data)
1595                 write(ast_consock, data, strlen(data) + 1);
1596         stringp=buf;
1597         hostname = strsep(&stringp, "/");
1598         cpid = strsep(&stringp, "/");
1599         version = strsep(&stringp, "\n");
1600         if (!version)
1601                 version = "<Version Unknown>";
1602         stringp=hostname;
1603         strsep(&stringp, ".");
1604         if (cpid)
1605                 pid = atoi(cpid);
1606         else
1607                 pid = -1;
1608         snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
1609         fdprint(ast_consock, tmp);
1610         snprintf(tmp, sizeof(tmp), "set debug atleast %d", option_debug);
1611         fdprint(ast_consock, tmp);
1612         ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
1613         remotehostname = hostname;
1614         if (getenv("HOME")) 
1615                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1616         if (el_hist == NULL || el == NULL)
1617                 ast_el_initialize();
1618
1619         el_set(el, EL_GETCFN, ast_el_read_char);
1620
1621         if (!ast_strlen_zero(filename))
1622                 ast_el_read_history(filename);
1623
1624         if (option_exec && data) {  /* hack to print output then exit if asterisk -rx is used */
1625                 char tempchar;
1626                 struct pollfd fds[0];
1627                 fds[0].fd = ast_consock;
1628                 fds[0].events = POLLIN;
1629                 fds[0].revents = 0;
1630                 while(poll(fds, 1, 100) > 0) {
1631                         ast_el_read_char(el, &tempchar);
1632                 }
1633                 return;
1634         }
1635         for(;;) {
1636                 ebuf = (char *)el_gets(el, &num);
1637
1638                 if (ebuf && !ast_strlen_zero(ebuf)) {
1639                         if (ebuf[strlen(ebuf)-1] == '\n')
1640                                 ebuf[strlen(ebuf)-1] = '\0';
1641                         if (!remoteconsolehandler(ebuf)) {
1642                                 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
1643                                 if (res < 1) {
1644                                         ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
1645                                         break;
1646                                 }
1647                         }
1648                 }
1649         }
1650         printf("\nDisconnected from Asterisk server\n");
1651 }
1652
1653 static int show_version(void)
1654 {
1655         printf("Asterisk " ASTERISK_VERSION "\n");
1656         return 0;
1657 }
1658
1659 static int show_cli_help(void) {
1660         printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 2000 - 2005, Digium.\n");
1661         printf("Usage: asterisk [OPTIONS]\n");
1662         printf("Valid Options:\n");
1663         printf("   -V              Display version number and exit\n");
1664         printf("   -C <configfile> Use an alternate configuration file\n");
1665         printf("   -G <group>      Run as a group other than the caller\n");
1666         printf("   -U <user>       Run as a user other than the caller\n");
1667         printf("   -c              Provide console CLI\n");
1668         printf("   -d              Enable extra debugging\n");
1669         printf("   -f              Do not fork\n");
1670         printf("   -g              Dump core in case of a crash\n");
1671         printf("   -h              This help screen\n");
1672         printf("   -i              Initialize crypto keys at startup\n");
1673         printf("   -n              Disable console colorization\n");
1674         printf("   -p              Run as pseudo-realtime thread\n");
1675         printf("   -q              Quiet mode (suppress output)\n");
1676         printf("   -r              Connect to Asterisk on this machine\n");
1677         printf("   -R              Connect to Asterisk, and attempt to reconnect if disconnected\n");
1678         printf("   -t              Record soundfiles in /var/tmp and move them where they belong after they are done.\n");
1679         printf("   -T              Display the time in [Mmm dd hh:mm:ss] format for each line of output to the CLI.\n");
1680         printf("   -v              Increase verbosity (multiple v's = more verbose)\n");
1681         printf("   -x <cmd>        Execute command <cmd> (only valid with -r)\n");
1682         printf("\n");
1683         return 0;
1684 }
1685
1686 static void ast_readconfig(void) {
1687         struct ast_config *cfg;
1688         struct ast_variable *v;
1689         char *config = AST_CONFIG_FILE;
1690
1691         if (option_overrideconfig == 1) {
1692                 cfg = ast_config_load(ast_config_AST_CONFIG_FILE);
1693                 if (!cfg)
1694                         ast_log(LOG_WARNING, "Unable to open specified master config file '%s', using built-in defaults\n", ast_config_AST_CONFIG_FILE);
1695         } else {
1696                 cfg = ast_config_load(config);
1697         }
1698
1699         /* init with buildtime config */
1700         ast_copy_string(ast_config_AST_CONFIG_DIR, AST_CONFIG_DIR, sizeof(ast_config_AST_CONFIG_DIR));
1701         ast_copy_string(ast_config_AST_SPOOL_DIR, AST_SPOOL_DIR, sizeof(ast_config_AST_SPOOL_DIR));
1702         ast_copy_string(ast_config_AST_MODULE_DIR, AST_MODULE_DIR, sizeof(ast_config_AST_VAR_DIR));
1703         snprintf(ast_config_AST_MONITOR_DIR, sizeof(ast_config_AST_MONITOR_DIR) - 1, "%s/monitor", ast_config_AST_SPOOL_DIR);
1704         ast_copy_string(ast_config_AST_VAR_DIR, AST_VAR_DIR, sizeof(ast_config_AST_VAR_DIR));
1705         ast_copy_string(ast_config_AST_LOG_DIR, AST_LOG_DIR, sizeof(ast_config_AST_LOG_DIR));
1706         ast_copy_string(ast_config_AST_AGI_DIR, AST_AGI_DIR, sizeof(ast_config_AST_AGI_DIR));
1707         ast_copy_string(ast_config_AST_DB, AST_DB, sizeof(ast_config_AST_DB));
1708         ast_copy_string(ast_config_AST_KEY_DIR, AST_KEY_DIR, sizeof(ast_config_AST_KEY_DIR));
1709         ast_copy_string(ast_config_AST_PID, AST_PID, sizeof(ast_config_AST_PID));
1710         ast_copy_string(ast_config_AST_SOCKET, AST_SOCKET, sizeof(ast_config_AST_SOCKET));
1711         ast_copy_string(ast_config_AST_RUN_DIR, AST_RUN_DIR, sizeof(ast_config_AST_RUN_DIR));
1712
1713         /* no asterisk.conf? no problem, use buildtime config! */
1714         if (!cfg) {
1715                 return;
1716         }
1717         v = ast_variable_browse(cfg, "files");
1718         while (v) {
1719                 if (!strcasecmp(v->name, "astctlpermissions")) {
1720                         ast_copy_string(ast_config_AST_CTL_PERMISSIONS, v->value, sizeof(ast_config_AST_CTL_PERMISSIONS));
1721                 } else if (!strcasecmp(v->name, "astctlowner")) {
1722                         ast_copy_string(ast_config_AST_CTL_OWNER, v->value, sizeof(ast_config_AST_CTL_OWNER));
1723                 } else if (!strcasecmp(v->name, "astctlgroup")) {
1724                         ast_copy_string(ast_config_AST_CTL_GROUP, v->value, sizeof(ast_config_AST_CTL_GROUP));
1725                 } else if (!strcasecmp(v->name, "astctl")) {
1726                         ast_copy_string(ast_config_AST_CTL, v->value, sizeof(ast_config_AST_CTL));
1727                 }
1728                 v = v->next;
1729         }
1730         v = ast_variable_browse(cfg, "directories");
1731         while(v) {
1732                 if (!strcasecmp(v->name, "astetcdir")) {
1733                         ast_copy_string(ast_config_AST_CONFIG_DIR, v->value, sizeof(ast_config_AST_CONFIG_DIR));
1734                 } else if (!strcasecmp(v->name, "astspooldir")) {
1735                         ast_copy_string(ast_config_AST_SPOOL_DIR, v->value, sizeof(ast_config_AST_SPOOL_DIR));
1736                         snprintf(ast_config_AST_MONITOR_DIR, sizeof(ast_config_AST_MONITOR_DIR) - 1, "%s/monitor", v->value);
1737                 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1738                         ast_copy_string(ast_config_AST_VAR_DIR, v->value, sizeof(ast_config_AST_VAR_DIR));
1739                         snprintf(ast_config_AST_DB, sizeof(ast_config_AST_DB), "%s/%s", v->value, "astdb");    
1740                 } else if (!strcasecmp(v->name, "astlogdir")) {
1741                         ast_copy_string(ast_config_AST_LOG_DIR, v->value, sizeof(ast_config_AST_LOG_DIR));
1742                 } else if (!strcasecmp(v->name, "astagidir")) {
1743                         ast_copy_string(ast_config_AST_AGI_DIR, v->value, sizeof(ast_config_AST_AGI_DIR));
1744                 } else if (!strcasecmp(v->name, "astrundir")) {
1745                         snprintf(ast_config_AST_PID, sizeof(ast_config_AST_PID), "%s/%s", v->value, "asterisk.pid");
1746                         snprintf(ast_config_AST_SOCKET, sizeof(ast_config_AST_SOCKET), "%s/%s", v->value, ast_config_AST_CTL);
1747                         ast_copy_string(ast_config_AST_RUN_DIR, v->value, sizeof(ast_config_AST_RUN_DIR));
1748                 } else if (!strcasecmp(v->name, "astmoddir")) {
1749                         ast_copy_string(ast_config_AST_MODULE_DIR, v->value, sizeof(ast_config_AST_MODULE_DIR));
1750                 }
1751                 v = v->next;
1752         }
1753         v = ast_variable_browse(cfg, "options");
1754         while(v) {
1755                 /* verbose level (-v at startup) */
1756                 if (!strcasecmp(v->name, "verbose")) {
1757                         option_verbose = atoi(v->value);
1758                 /* whether or not to force timestamping. (-T at startup) */
1759                 } else if (!strcasecmp(v->name, "timestamp")) {
1760                         option_timestamp = ast_true(v->value);
1761                 /* whether or not to support #exec in config files */
1762                 } else if (!strcasecmp(v->name, "execincludes")) {
1763                         option_exec_includes = ast_true(v->value);
1764                 /* debug level (-d at startup) */
1765                 } else if (!strcasecmp(v->name, "debug")) {
1766                         option_debug = 0;
1767                         if (sscanf(v->value, "%d", &option_debug) != 1) {
1768                                 option_debug = ast_true(v->value);
1769                         }
1770                 /* Disable forking (-f at startup) */
1771                 } else if (!strcasecmp(v->name, "nofork")) {
1772                         option_nofork = ast_true(v->value);
1773                 /* Run quietly (-q at startup ) */
1774                 } else if (!strcasecmp(v->name, "quiet")) {
1775                         option_quiet = ast_true(v->value);
1776                 /* Run as console (-c at startup, implies nofork) */
1777                 } else if (!strcasecmp(v->name, "console")) {
1778                         option_console = ast_true(v->value);
1779                 /* Run with highg priority if the O/S permits (-p at startup) */
1780                 } else if (!strcasecmp(v->name, "highpriority")) {
1781                         option_highpriority = ast_true(v->value);
1782                 /* Initialize RSA auth keys (IAX2) (-i at startup) */
1783                 } else if (!strcasecmp(v->name, "initcrypto")) {
1784                         option_initcrypto = ast_true(v->value);
1785                 /* Disable ANSI colors for console (-c at startup) */
1786                 } else if (!strcasecmp(v->name, "nocolor")) {
1787                         option_nocolor = ast_true(v->value);
1788                 /* Disable some usage warnings for picky people :p */
1789                 } else if (!strcasecmp(v->name, "dontwarn")) {
1790                         option_dontwarn = ast_true(v->value);
1791                 /* Dump core in case of crash (-g) */
1792                 } else if (!strcasecmp(v->name, "dumpcore")) {
1793                         option_dumpcore = ast_true(v->value);
1794                 /* Cache recorded sound files to another directory during recording */
1795                 } else if (!strcasecmp(v->name, "cache_record_files")) {
1796                         option_cache_record_files = ast_true(v->value);
1797                 /* Specify cache directory */
1798                 }  else if (!strcasecmp(v->name, "record_cache_dir")) {
1799                         ast_copy_string(record_cache_dir, v->value, AST_CACHE_DIR_LEN);
1800                 /* Build transcode paths via SLINEAR, instead of directly */
1801                 } else if (!strcasecmp(v->name, "transcode_via_sln")) {
1802                         option_transcode_slin = ast_true(v->value);
1803                 } else if (!strcasecmp(v->name, "maxcalls")) {
1804                         if ((sscanf(v->value, "%d", &option_maxcalls) != 1) || (option_maxcalls < 0)) {
1805                                 option_maxcalls = 0;
1806                         }
1807                 }
1808                 v = v->next;
1809         }
1810         ast_config_destroy(cfg);
1811 }
1812
1813 int main(int argc, char *argv[])
1814 {
1815         int c;
1816         char filename[80] = "";
1817         char hostname[MAXHOSTNAMELEN]="";
1818         char tmp[80];
1819         char * xarg = NULL;
1820         int x;
1821         FILE *f;
1822         sigset_t sigs;
1823         int num;
1824         int is_child_of_nonroot=0;
1825         char *buf;
1826         char *runuser=NULL, *rungroup=NULL;
1827
1828         /* Remember original args for restart */
1829         if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1830                 fprintf(stderr, "Truncating argument size to %d\n", (int)(sizeof(_argv) / sizeof(_argv[0])) - 1);
1831                 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1832         }
1833         for (x=0;x<argc;x++)
1834                 _argv[x] = argv[x];
1835         _argv[x] = NULL;
1836
1837         /* if the progname is rasterisk consider it a remote console */
1838         if (argv[0] && (strstr(argv[0], "rasterisk")) != NULL) {
1839                 option_remote++;
1840                 option_nofork++;
1841         }
1842         if (gethostname(hostname, sizeof(hostname)-1))
1843                 ast_copy_string(hostname, "<Unknown>", sizeof(hostname));
1844         ast_mainpid = getpid();
1845         ast_ulaw_init();
1846         ast_alaw_init();
1847         callerid_init();
1848         ast_utils_init();
1849         tdd_init();
1850         /* When Asterisk restarts after it has dropped the root privileges,
1851          * it can't issue setuid(), setgid(), setgroups() or set_priority() 
1852          * */
1853         if (getenv("ASTERISK_ALREADY_NONROOT"))
1854                 is_child_of_nonroot=1;
1855         if (getenv("HOME")) 
1856                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1857         /* Check if we're root */
1858         /*
1859         if (geteuid()) {
1860                 ast_log(LOG_ERROR, "Must be run as root\n");
1861                 exit(1);
1862         }
1863         */
1864         /* Check for options */
1865         while((c=getopt(argc, argv, "tThfdvVqprRgcinx:U:G:C:M:")) != -1) {
1866                 switch(c) {
1867                 case 'd':
1868                         option_debug++;
1869                         option_nofork++;
1870                         break;
1871                 case 'c':
1872                         option_console++;
1873                         option_nofork++;
1874                         break;
1875                 case 'f':
1876                         option_nofork++;
1877                         break;
1878                 case 'n':
1879                         option_nocolor++;
1880                         break;
1881                 case 'r':
1882                         option_remote++;
1883                         option_nofork++;
1884                         break;
1885                 case 'R':
1886                         option_remote++;
1887                         option_nofork++;
1888                         option_reconnect++;
1889                         break;
1890                 case 'p':
1891                         option_highpriority++;
1892                         break;
1893                 case 'v':
1894                         option_verbose++;
1895                         option_nofork++;
1896                         break;
1897                 case 'M':
1898                         if ((sscanf(optarg, "%d", &option_maxcalls) != 1) || (option_maxcalls < 0))
1899                                 option_maxcalls = 0;
1900                         break;
1901                 case 'q':
1902                         option_quiet++;
1903                         break;
1904                 case 't':
1905                         option_cache_record_files++;
1906                         break;
1907                 case 'T':
1908                         option_timestamp++;
1909                         break;
1910                 case 'x':
1911                         option_exec++;
1912                         xarg = optarg;
1913                         break;
1914                 case 'C':
1915                         ast_copy_string((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE));
1916                         option_overrideconfig++;
1917                         break;
1918                 case 'i':
1919                         option_initcrypto++;
1920                         break;
1921                 case'g':
1922                         option_dumpcore++;
1923                         break;
1924                 case 'h':
1925                         show_cli_help();
1926                         exit(0);
1927                 case 'V':
1928                         show_version();
1929                         exit(0);
1930                 case 'U':
1931                         runuser = optarg;
1932                         break;
1933                 case 'G':
1934                         rungroup = optarg;
1935                         break;
1936                 case '?':
1937                         exit(1);
1938                 }
1939         }
1940
1941         if (option_dumpcore) {
1942                 struct rlimit l;
1943                 memset(&l, 0, sizeof(l));
1944                 l.rlim_cur = RLIM_INFINITY;
1945                 l.rlim_max = RLIM_INFINITY;
1946                 if (setrlimit(RLIMIT_CORE, &l)) {
1947                         ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
1948                 }
1949         }
1950
1951         if (option_console && !option_verbose) 
1952                 ast_verbose("[ Reading Master Configuration ]");
1953         ast_readconfig();
1954
1955         if (!is_child_of_nonroot && ast_set_priority(option_highpriority)) {
1956                 exit(1);
1957         }
1958
1959         if (!is_child_of_nonroot && rungroup) {
1960                 struct group *gr;
1961                 gr = getgrnam(rungroup);
1962                 if (!gr) {
1963                         ast_log(LOG_WARNING, "No such group '%s'!\n", rungroup);
1964                         exit(1);
1965                 }
1966                 if (setgid(gr->gr_gid)) {
1967                         ast_log(LOG_WARNING, "Unable to setgid to %d (%s)\n", gr->gr_gid, rungroup);
1968                         exit(1);
1969                 }
1970                 if (option_verbose)
1971                         ast_verbose("Running as group '%s'\n", rungroup);
1972         }
1973
1974         if (!is_child_of_nonroot && runuser) {
1975                 struct passwd *pw;
1976                 pw = getpwnam(runuser);
1977                 if (!pw) {
1978                         ast_log(LOG_WARNING, "No such user '%s'!\n", runuser);
1979                         exit(1);
1980                 }
1981                 if (setuid(pw->pw_uid)) {
1982                         ast_log(LOG_WARNING, "Unable to setuid to %d (%s)\n", pw->pw_uid, runuser);
1983                         exit(1);
1984                 }
1985                 setenv("ASTERISK_ALREADY_NONROOT","yes",1);
1986                 if (option_verbose)
1987                         ast_verbose("Running as user '%s'\n", runuser);
1988         }
1989
1990         term_init();
1991         printf(term_end());
1992         fflush(stdout);
1993
1994         if (option_console && !option_verbose) 
1995                 ast_verbose("[ Initializing Custom Configuration Options ]");
1996         /* custom config setup */
1997         register_config_cli();
1998         read_config_maps();
1999         
2000
2001         if (option_console) {
2002                 if (el_hist == NULL || el == NULL)
2003                         ast_el_initialize();
2004
2005                 if (!ast_strlen_zero(filename))
2006                         ast_el_read_history(filename);
2007         }
2008
2009         if (ast_tryconnect()) {
2010                 /* One is already running */
2011                 if (option_remote) {
2012                         if (option_exec) {
2013                                 ast_remotecontrol(xarg);
2014                                 quit_handler(0, 0, 0, 0);
2015                                 exit(0);
2016                         }
2017                         printf(term_quit());
2018                         ast_register_verbose(console_verboser);
2019                         WELCOME_MESSAGE;
2020                         ast_remotecontrol(NULL);
2021                         quit_handler(0, 0, 0, 0);
2022                         exit(0);
2023                 } else {
2024                         ast_log(LOG_ERROR, "Asterisk already running on %s.  Use 'asterisk -r' to connect.\n", (char *)ast_config_AST_SOCKET);
2025                         printf(term_quit());
2026                         exit(1);
2027                 }
2028         } else if (option_remote || option_exec) {
2029                 ast_log(LOG_ERROR, "Unable to connect to remote asterisk (does %s exist?)\n",ast_config_AST_SOCKET);
2030                 printf(term_quit());
2031                 exit(1);
2032         }
2033         /* Blindly write pid file since we couldn't connect */
2034         unlink((char *)ast_config_AST_PID);
2035         f = fopen((char *)ast_config_AST_PID, "w");
2036         if (f) {
2037                 fprintf(f, "%d\n", getpid());
2038                 fclose(f);
2039         } else
2040                 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
2041
2042         if (!option_verbose && !option_debug && !option_nofork && !option_console) {
2043                 daemon(0,0);
2044                 /* Blindly re-write pid file since we are forking */
2045                 unlink((char *)ast_config_AST_PID);
2046                 f = fopen((char *)ast_config_AST_PID, "w");
2047                 if (f) {
2048                         fprintf(f, "%d\n", getpid());
2049                         fclose(f);
2050                 } else
2051                         ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
2052         }
2053
2054         /* Test recursive mutex locking. */
2055         if (test_for_thread_safety())
2056                 ast_verbose("Warning! Asterisk is not thread safe.\n");
2057
2058         ast_makesocket();
2059         sigemptyset(&sigs);
2060         sigaddset(&sigs, SIGHUP);
2061         sigaddset(&sigs, SIGTERM);
2062         sigaddset(&sigs, SIGINT);
2063         sigaddset(&sigs, SIGPIPE);
2064         sigaddset(&sigs, SIGWINCH);
2065         pthread_sigmask(SIG_BLOCK, &sigs, NULL);
2066         if (option_console || option_verbose || option_remote)
2067                 ast_register_verbose(console_verboser);
2068         /* Print a welcome message if desired */
2069         if (option_verbose || option_console) {
2070                 WELCOME_MESSAGE;
2071         }
2072         if (option_console && !option_verbose) 
2073                 ast_verbose("[ Booting...");
2074
2075         signal(SIGURG, urg_handler);
2076         signal(SIGINT, __quit_handler);
2077         signal(SIGTERM, __quit_handler);
2078         signal(SIGHUP, hup_handler);
2079         signal(SIGCHLD, child_handler);
2080         signal(SIGPIPE, SIG_IGN);
2081
2082         /* ensure that the random number generators are seeded with a different value every time
2083            Asterisk is started
2084         */
2085         srand((unsigned int) getpid() + (unsigned int) time(NULL));
2086         srandom((unsigned int) getpid() + (unsigned int) time(NULL));
2087
2088         if (init_logger()) {
2089                 printf(term_quit());
2090                 exit(1);
2091         }
2092         if (dnsmgr_init()) {
2093                 printf(term_quit());
2094                 exit(1);
2095         }
2096         /* load 'preload' modules, required for access to Realtime-mapped configuration files */
2097         if (load_modules(1)) {
2098                 printf(term_quit());
2099                 exit(1);
2100         }
2101         ast_channels_init();
2102         if (init_manager()) {
2103                 printf(term_quit());
2104                 exit(1);
2105         }
2106         if (ast_cdr_engine_init()) {
2107                 printf(term_quit());
2108                 exit(1);
2109         }
2110         if (ast_device_state_engine_init()) {
2111                 printf(term_quit());
2112                 exit(1);
2113         }
2114         ast_rtp_init();
2115         if (ast_image_init()) {
2116                 printf(term_quit());
2117                 exit(1);
2118         }
2119         if (ast_file_init()) {
2120                 printf(term_quit());
2121                 exit(1);
2122         }
2123         if (load_pbx()) {
2124                 printf(term_quit());
2125                 exit(1);
2126         }
2127         if (load_modules(0)) {
2128                 printf(term_quit());
2129                 exit(1);
2130         }
2131         if (init_framer()) {
2132                 printf(term_quit());
2133                 exit(1);
2134         }
2135         if (astdb_init()) {
2136                 printf(term_quit());
2137                 exit(1);
2138         }
2139         if (ast_enum_init()) {
2140                 printf(term_quit());
2141                 exit(1);
2142         }
2143 #if 0
2144         /* This should no longer be necessary */
2145         /* sync cust config and reload some internals in case a custom config handler binded to them */
2146         read_ast_cust_config();
2147         reload_logger(0);
2148         reload_manager();
2149         ast_enum_reload();
2150         ast_rtp_reload();
2151 #endif
2152
2153
2154         /* We might have the option of showing a console, but for now just
2155            do nothing... */
2156         if (option_console && !option_verbose)
2157                 ast_verbose(" ]\n");
2158         if (option_verbose || option_console)
2159                 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
2160         if (option_nofork)
2161                 consolethread = pthread_self();
2162         fully_booted = 1;
2163         pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
2164 #ifdef __AST_DEBUG_MALLOC
2165         __ast_mm_init();
2166 #endif  
2167         time(&ast_startuptime);
2168         ast_cli_register_multiple(core_cli, sizeof(core_cli) / sizeof(core_cli[0]));
2169         if (option_console) {
2170                 /* Console stuff now... */
2171                 /* Register our quit function */
2172                 char title[256];
2173                 set_icon("Asterisk");
2174                 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, ast_mainpid);
2175                 set_title(title);
2176
2177                 for (;;) {
2178                         buf = (char *)el_gets(el, &num);
2179                         if (buf) {
2180                                 if (buf[strlen(buf)-1] == '\n')
2181                                         buf[strlen(buf)-1] = '\0';
2182
2183                                 consolehandler((char *)buf);
2184                         } else {
2185                                 if (write(STDOUT_FILENO, "\nUse EXIT or QUIT to exit the asterisk console\n",
2186                                                                   strlen("\nUse EXIT or QUIT to exit the asterisk console\n")) < 0) {
2187                                         /* Whoa, stdout disappeared from under us... Make /dev/null's */
2188                                         int fd;
2189                                         fd = open("/dev/null", O_RDWR);
2190                                         if (fd > -1) {
2191                                                 dup2(fd, STDOUT_FILENO);
2192                                                 dup2(fd, STDIN_FILENO);
2193                                         } else
2194                                                 ast_log(LOG_WARNING, "Failed to open /dev/null to recover from dead console.  Bad things will happen!\n");
2195                                         break;
2196                                 }
2197                         }
2198                 }
2199
2200         }
2201         /* Do nothing */
2202         for(;;)  {      /* apparently needed for the MACos */
2203                 struct pollfd p = { -1 /* no descriptor */, 0, 0 };
2204                 poll(&p, 0, -1);
2205         }
2206         return 0;
2207 }