ensure revents fields are initialized before calling poll()
[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         if (option_debug > 2) 
635                 printf("-- Asterisk Urgent handler\n");
636         signal(num, urg_handler);
637         return;
638 }
639
640 static void hup_handler(int num)
641 {
642         if (option_verbose > 1) 
643                 printf("Received HUP signal -- Reloading configs\n");
644         if (restartnow)
645                 execvp(_argv[0], _argv);
646         /* XXX This could deadlock XXX */
647         ast_module_reload(NULL);
648         signal(num, hup_handler);
649 }
650
651 static void child_handler(int sig)
652 {
653         /* Must not ever ast_log or ast_verbose within signal handler */
654         int n, status;
655
656         /*
657          * Reap all dead children -- not just one
658          */
659         for (n = 0; wait4(-1, &status, WNOHANG, NULL) > 0; n++)
660                 ;
661         if (n == 0 && option_debug)     
662                 printf("Huh?  Child handler, but nobody there?\n");
663         signal(sig, child_handler);
664 }
665
666 static void set_title(char *text)
667 {
668         /* Set an X-term or screen title */
669         if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
670                 fprintf(stdout, "\033]2;%s\007", text);
671 }
672
673 static void set_icon(char *text)
674 {
675         if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
676                 fprintf(stdout, "\033]1;%s\007", text);
677 }
678
679 int ast_set_priority(int pri)
680 {
681         struct sched_param sched;
682         memset(&sched, 0, sizeof(sched));
683         /* We set ourselves to a high priority, that we might pre-empt everything
684            else.  If your PBX has heavy activity on it, this is a good thing.  */
685 #ifdef __linux__
686         if (pri) {  
687                 sched.sched_priority = 10;
688                 if (sched_setscheduler(0, SCHED_RR, &sched)) {
689                         ast_log(LOG_WARNING, "Unable to set high priority\n");
690                         return -1;
691                 } else
692                         if (option_verbose)
693                                 ast_verbose("Set to realtime thread\n");
694         } else {
695                 sched.sched_priority = 0;
696                 if (sched_setscheduler(0, SCHED_OTHER, &sched)) {
697                         ast_log(LOG_WARNING, "Unable to set normal priority\n");
698                         return -1;
699                 }
700         }
701 #else
702         if (pri) {
703                 if (setpriority(PRIO_PROCESS, 0, -10) == -1) {
704                         ast_log(LOG_WARNING, "Unable to set high priority\n");
705                         return -1;
706                 } else
707                         if (option_verbose)
708                                 ast_verbose("Set to high priority\n");
709         } else {
710                 if (setpriority(PRIO_PROCESS, 0, 0) == -1) {
711                         ast_log(LOG_WARNING, "Unable to set normal priority\n");
712                         return -1;
713                 }
714         }
715 #endif
716         return 0;
717 }
718
719 static void ast_run_atexits(void)
720 {
721         struct ast_atexit *ae;
722         ast_mutex_lock(&atexitslock);
723         ae = atexits;
724         while(ae) {
725                 if (ae->func) 
726                         ae->func();
727                 ae = ae->next;
728         }
729         ast_mutex_unlock(&atexitslock);
730 }
731
732 static void quit_handler(int num, int nice, int safeshutdown, int restart)
733 {
734         char filename[80] = "";
735         time_t s,e;
736         int x;
737         /* Try to get as many CDRs as possible submitted to the backend engines (if in batch mode) */
738         ast_cdr_engine_term();
739         if (safeshutdown) {
740                 shuttingdown = 1;
741                 if (!nice) {
742                         /* Begin shutdown routine, hanging up active channels */
743                         ast_begin_shutdown(1);
744                         if (option_verbose && option_console)
745                                 ast_verbose("Beginning asterisk %s....\n", restart ? "restart" : "shutdown");
746                         time(&s);
747                         for(;;) {
748                                 time(&e);
749                                 /* Wait up to 15 seconds for all channels to go away */
750                                 if ((e - s) > 15)
751                                         break;
752                                 if (!ast_active_channels())
753                                         break;
754                                 if (!shuttingdown)
755                                         break;
756                                 /* Sleep 1/10 of a second */
757                                 usleep(100000);
758                         }
759                 } else {
760                         if (nice < 2)
761                                 ast_begin_shutdown(0);
762                         if (option_verbose && option_console)
763                                 ast_verbose("Waiting for inactivity to perform %s...\n", restart ? "restart" : "halt");
764                         for(;;) {
765                                 if (!ast_active_channels())
766                                         break;
767                                 if (!shuttingdown)
768                                         break;
769                                 sleep(1);
770                         }
771                 }
772
773                 if (!shuttingdown) {
774                         if (option_verbose && option_console)
775                                 ast_verbose("Asterisk %s cancelled.\n", restart ? "restart" : "shutdown");
776                         return;
777                 }
778         }
779         if (option_console || option_remote) {
780                 if (getenv("HOME")) 
781                         snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
782                 if (!ast_strlen_zero(filename))
783                         ast_el_write_history(filename);
784                 if (el != NULL)
785                         el_end(el);
786                 if (el_hist != NULL)
787                         history_end(el_hist);
788         }
789         if (option_verbose)
790                 ast_verbose("Executing last minute cleanups\n");
791         ast_run_atexits();
792         /* Called on exit */
793         if (option_verbose && option_console)
794                 ast_verbose("Asterisk %s ending (%d).\n", ast_active_channels() ? "uncleanly" : "cleanly", num);
795         else if (option_debug)
796                 ast_log(LOG_DEBUG, "Asterisk ending (%d).\n", num);
797         manager_event(EVENT_FLAG_SYSTEM, "Shutdown", "Shutdown: %s\r\nRestart: %s\r\n", ast_active_channels() ? "Uncleanly" : "Cleanly", restart ? "True" : "False");
798         if (ast_socket > -1) {
799                 close(ast_socket);
800                 ast_socket = -1;
801         }
802         if (ast_consock > -1)
803                 close(ast_consock);
804         if (ast_socket > -1)
805                 unlink((char *)ast_config_AST_SOCKET);
806         if (!option_remote) unlink((char *)ast_config_AST_PID);
807         printf(term_quit());
808         if (restart) {
809                 if (option_verbose || option_console)
810                         ast_verbose("Preparing for Asterisk restart...\n");
811                 /* Mark all FD's for closing on exec */
812                 for (x=3;x<32768;x++) {
813                         fcntl(x, F_SETFD, FD_CLOEXEC);
814                 }
815                 if (option_verbose || option_console)
816                         ast_verbose("Restarting Asterisk NOW...\n");
817                 restartnow = 1;
818
819                 /* close logger */
820                 close_logger();
821
822                 /* If there is a consolethread running send it a SIGHUP 
823                    so it can execvp, otherwise we can do it ourselves */
824                 if (consolethread != AST_PTHREADT_NULL) {
825                         pthread_kill(consolethread, SIGHUP);
826                         /* Give the signal handler some time to complete */
827                         sleep(2);
828                 } else
829                         execvp(_argv[0], _argv);
830         
831         } else {
832                 /* close logger */
833                 close_logger();
834         }
835         exit(0);
836 }
837
838 static void __quit_handler(int num)
839 {
840         quit_handler(num, 0, 1, 0);
841 }
842
843 static const char *fix_header(char *outbuf, int maxout, const char *s, char *cmp)
844 {
845         const char *c;
846         if (!strncmp(s, cmp, strlen(cmp))) {
847                 c = s + strlen(cmp);
848                 term_color(outbuf, cmp, COLOR_GRAY, 0, maxout);
849                 return c;
850         }
851         return NULL;
852 }
853
854 static void console_verboser(const char *s, int pos, int replace, int complete)
855 {
856         char tmp[80];
857         const char *c=NULL;
858         /* Return to the beginning of the line */
859         if (!pos) {
860                 fprintf(stdout, "\r");
861                 if ((c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_4)) ||
862                         (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_3)) ||
863                         (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_2)) ||
864                         (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_1)))
865                         fputs(tmp, stdout);
866         }
867         if (c)
868                 fputs(c + pos,stdout);
869         else
870                 fputs(s + pos,stdout);
871         fflush(stdout);
872         if (complete) {
873                 /* Wake up a poll()ing console */
874                 if (option_console && consolethread != AST_PTHREADT_NULL)
875                         pthread_kill(consolethread, SIGURG);
876         }
877 }
878
879 static int ast_all_zeros(char *s)
880 {
881         while(*s) {
882                 if (*s > 32)
883                         return 0;
884                 s++;  
885         }
886         return 1;
887 }
888
889 static void consolehandler(char *s)
890 {
891         printf(term_end());
892         fflush(stdout);
893         /* Called when readline data is available */
894         if (s && !ast_all_zeros(s))
895                 ast_el_add_history(s);
896         /* Give the console access to the shell */
897         if (s) {
898                 /* The real handler for bang */
899                 if (s[0] == '!') {
900                         if (s[1])
901                                 ast_safe_system(s+1);
902                         else
903                                 ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
904                 } else 
905                 ast_cli_command(STDOUT_FILENO, s);
906         } else
907                 fprintf(stdout, "\nUse \"quit\" to exit\n");
908 }
909
910 static int remoteconsolehandler(char *s)
911 {
912         int ret = 0;
913         /* Called when readline data is available */
914         if (s && !ast_all_zeros(s))
915                 ast_el_add_history(s);
916         /* Give the console access to the shell */
917         if (s) {
918                 /* The real handler for bang */
919                 if (s[0] == '!') {
920                         if (s[1])
921                                 ast_safe_system(s+1);
922                         else
923                                 ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
924                         ret = 1;
925                 }
926                 if ((strncasecmp(s, "quit", 4) == 0 || strncasecmp(s, "exit", 4) == 0) &&
927                     (s[4] == '\0' || isspace(s[4]))) {
928                         quit_handler(0, 0, 0, 0);
929                         ret = 1;
930                 }
931         } else
932                 fprintf(stdout, "\nUse \"quit\" to exit\n");
933
934         return ret;
935 }
936
937 static char abort_halt_help[] = 
938 "Usage: abort shutdown\n"
939 "       Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
940 "       call operations.\n";
941
942 static char shutdown_now_help[] = 
943 "Usage: stop now\n"
944 "       Shuts down a running Asterisk immediately, hanging up all active calls .\n";
945
946 static char shutdown_gracefully_help[] = 
947 "Usage: stop gracefully\n"
948 "       Causes Asterisk to not accept new calls, and exit when all\n"
949 "       active calls have terminated normally.\n";
950
951 static char shutdown_when_convenient_help[] = 
952 "Usage: stop when convenient\n"
953 "       Causes Asterisk to perform a shutdown when all active calls have ended.\n";
954
955 static char restart_now_help[] = 
956 "Usage: restart now\n"
957 "       Causes Asterisk to hangup all calls and exec() itself performing a cold\n"
958 "       restart.\n";
959
960 static char restart_gracefully_help[] = 
961 "Usage: restart gracefully\n"
962 "       Causes Asterisk to stop accepting new calls and exec() itself performing a cold\n"
963 "       restart when all active calls have ended.\n";
964
965 static char restart_when_convenient_help[] = 
966 "Usage: restart when convenient\n"
967 "       Causes Asterisk to perform a cold restart when all active calls have ended.\n";
968
969 static char bang_help[] =
970 "Usage: !<command>\n"
971 "       Executes a given shell command\n";
972
973 #if 0
974 static int handle_quit(int fd, int argc, char *argv[])
975 {
976         if (argc != 1)
977                 return RESULT_SHOWUSAGE;
978         quit_handler(0, 0, 1, 0);
979         return RESULT_SUCCESS;
980 }
981 #endif
982
983 static int handle_shutdown_now(int fd, int argc, char *argv[])
984 {
985         if (argc != 2)
986                 return RESULT_SHOWUSAGE;
987         quit_handler(0, 0 /* Not nice */, 1 /* safely */, 0 /* not restart */);
988         return RESULT_SUCCESS;
989 }
990
991 static int handle_shutdown_gracefully(int fd, int argc, char *argv[])
992 {
993         if (argc != 2)
994                 return RESULT_SHOWUSAGE;
995         quit_handler(0, 1 /* nicely */, 1 /* safely */, 0 /* no restart */);
996         return RESULT_SUCCESS;
997 }
998
999 static int handle_shutdown_when_convenient(int fd, int argc, char *argv[])
1000 {
1001         if (argc != 3)
1002                 return RESULT_SHOWUSAGE;
1003         quit_handler(0, 2 /* really nicely */, 1 /* safely */, 0 /* don't restart */);
1004         return RESULT_SUCCESS;
1005 }
1006
1007 static int handle_restart_now(int fd, int argc, char *argv[])
1008 {
1009         if (argc != 2)
1010                 return RESULT_SHOWUSAGE;
1011         quit_handler(0, 0 /* not nicely */, 1 /* safely */, 1 /* restart */);
1012         return RESULT_SUCCESS;
1013 }
1014
1015 static int handle_restart_gracefully(int fd, int argc, char *argv[])
1016 {
1017         if (argc != 2)
1018                 return RESULT_SHOWUSAGE;
1019         quit_handler(0, 1 /* nicely */, 1 /* safely */, 1 /* restart */);
1020         return RESULT_SUCCESS;
1021 }
1022
1023 static int handle_restart_when_convenient(int fd, int argc, char *argv[])
1024 {
1025         if (argc != 3)
1026                 return RESULT_SHOWUSAGE;
1027         quit_handler(0, 2 /* really nicely */, 1 /* safely */, 1 /* restart */);
1028         return RESULT_SUCCESS;
1029 }
1030
1031 static int handle_abort_halt(int fd, int argc, char *argv[])
1032 {
1033         if (argc != 2)
1034                 return RESULT_SHOWUSAGE;
1035         ast_cancel_shutdown();
1036         shuttingdown = 0;
1037         return RESULT_SUCCESS;
1038 }
1039
1040 static int handle_bang(int fd, int argc, char *argv[])
1041 {
1042         return RESULT_SUCCESS;
1043 }
1044
1045 #define ASTERISK_PROMPT "*CLI> "
1046
1047 #define ASTERISK_PROMPT2 "%s*CLI> "
1048
1049 static struct ast_cli_entry core_cli[] = {
1050         { { "abort", "halt", NULL }, handle_abort_halt,
1051           "Cancel a running halt", abort_halt_help },
1052         { { "stop", "now", NULL }, handle_shutdown_now,
1053           "Shut down Asterisk immediately", shutdown_now_help },
1054         { { "stop", "gracefully", NULL }, handle_shutdown_gracefully,
1055           "Gracefully shut down Asterisk", shutdown_gracefully_help },
1056         { { "stop", "when","convenient", NULL }, handle_shutdown_when_convenient,
1057           "Shut down Asterisk at empty call volume", shutdown_when_convenient_help },
1058         { { "restart", "now", NULL }, handle_restart_now,
1059           "Restart Asterisk immediately", restart_now_help },
1060         { { "restart", "gracefully", NULL }, handle_restart_gracefully,
1061           "Restart Asterisk gracefully", restart_gracefully_help },
1062         { { "restart", "when", "convenient", NULL }, handle_restart_when_convenient,
1063           "Restart Asterisk at empty call volume", restart_when_convenient_help },
1064         { { "!", NULL }, handle_bang,
1065           "Execute a shell command", bang_help },
1066 #if !defined(LOW_MEMORY)
1067         { { "show", "version", "files", NULL }, handle_show_version_files,
1068           "Show versions of files used to build Asterisk", show_version_files_help, complete_show_version_files },
1069 #endif /* ! LOW_MEMORY */
1070 };
1071
1072 static int ast_el_read_char(EditLine *el, char *cp)
1073 {
1074         int num_read=0;
1075         int lastpos=0;
1076         struct pollfd fds[2];
1077         int res;
1078         int max;
1079         char buf[512];
1080
1081         for (;;) {
1082                 max = 1;
1083                 fds[0].fd = ast_consock;
1084                 fds[0].events = POLLIN;
1085                 if (!option_exec) {
1086                         fds[1].fd = STDIN_FILENO;
1087                         fds[1].events = POLLIN;
1088                         max++;
1089                 }
1090                 res = poll(fds, max, -1);
1091                 if (res < 0) {
1092                         if (errno == EINTR)
1093                                 continue;
1094                         ast_log(LOG_ERROR, "poll failed: %s\n", strerror(errno));
1095                         break;
1096                 }
1097
1098                 if (!option_exec && fds[1].revents) {
1099                         num_read = read(STDIN_FILENO, cp, 1);
1100                         if (num_read < 1) {
1101                                 break;
1102                         } else 
1103                                 return (num_read);
1104                 }
1105                 if (fds[0].revents) {
1106                         res = read(ast_consock, buf, sizeof(buf) - 1);
1107                         /* if the remote side disappears exit */
1108                         if (res < 1) {
1109                                 fprintf(stderr, "\nDisconnected from Asterisk server\n");
1110                                 if (!option_reconnect) {
1111                                         quit_handler(0, 0, 0, 0);
1112                                 } else {
1113                                         int tries;
1114                                         int reconnects_per_second = 20;
1115                                         fprintf(stderr, "Attempting to reconnect for 30 seconds\n");
1116                                         for (tries=0;tries<30 * reconnects_per_second;tries++) {
1117                                                 if (ast_tryconnect()) {
1118                                                         fprintf(stderr, "Reconnect succeeded after %.3f seconds\n", 1.0 / reconnects_per_second * tries);
1119                                                         printf(term_quit());
1120                                                         WELCOME_MESSAGE;
1121                                                         break;
1122                                                 } else {
1123                                                         usleep(1000000 / reconnects_per_second);
1124                                                 }
1125                                         }
1126                                         if (tries >= 30 * reconnects_per_second) {
1127                                                 fprintf(stderr, "Failed to reconnect for 30 seconds.  Quitting.\n");
1128                                                 quit_handler(0, 0, 0, 0);
1129                                         }
1130                                 }
1131                         }
1132
1133                         buf[res] = '\0';
1134
1135                         if (!option_exec && !lastpos)
1136                                 write(STDOUT_FILENO, "\r", 1);
1137                         write(STDOUT_FILENO, buf, res);
1138                         if ((buf[res-1] == '\n') || (buf[res-2] == '\n')) {
1139                                 *cp = CC_REFRESH;
1140                                 return(1);
1141                         } else {
1142                                 lastpos = 1;
1143                         }
1144                 }
1145         }
1146
1147         *cp = '\0';
1148         return (0);
1149 }
1150
1151 static char *cli_prompt(EditLine *el)
1152 {
1153         static char prompt[200];
1154         char *pfmt;
1155         int color_used=0;
1156         char term_code[20];
1157
1158         if ((pfmt = getenv("ASTERISK_PROMPT"))) {
1159                 char *t = pfmt, *p = prompt;
1160                 memset(prompt, 0, sizeof(prompt));
1161                 while (*t != '\0' && *p < sizeof(prompt)) {
1162                         if (*t == '%') {
1163                                 char hostname[MAXHOSTNAMELEN]="";
1164                                 int i;
1165                                 struct timeval tv;
1166                                 struct tm tm;
1167 #ifdef linux
1168                                 FILE *LOADAVG;
1169 #endif
1170                                 int fgcolor = COLOR_WHITE, bgcolor = COLOR_BLACK;
1171
1172                                 t++;
1173                                 switch (*t) {
1174                                         case 'C': /* color */
1175                                                 t++;
1176                                                 if (sscanf(t, "%d;%d%n", &fgcolor, &bgcolor, &i) == 2) {
1177                                                         strncat(p, term_color_code(term_code, fgcolor, bgcolor, sizeof(term_code)),sizeof(prompt) - strlen(prompt) - 1);
1178                                                         t += i - 1;
1179                                                 } else if (sscanf(t, "%d%n", &fgcolor, &i) == 1) {
1180                                                         strncat(p, term_color_code(term_code, fgcolor, 0, sizeof(term_code)),sizeof(prompt) - strlen(prompt) - 1);
1181                                                         t += i - 1;
1182                                                 }
1183
1184                                                 /* If the color has been reset correctly, then there's no need to reset it later */
1185                                                 if ((fgcolor == COLOR_WHITE) && (bgcolor == COLOR_BLACK)) {
1186                                                         color_used = 0;
1187                                                 } else {
1188                                                         color_used = 1;
1189                                                 }
1190                                                 break;
1191                                         case 'd': /* date */
1192                                                 memset(&tm, 0, sizeof(struct tm));
1193                                                 tv = ast_tvnow();
1194                                                 if (localtime_r(&(tv.tv_sec), &tm)) {
1195                                                         strftime(p, sizeof(prompt) - strlen(prompt), "%Y-%m-%d", &tm);
1196                                                 }
1197                                                 break;
1198                                         case 'h': /* hostname */
1199                                                 if (!gethostname(hostname, sizeof(hostname) - 1)) {
1200                                                         strncat(p, hostname, sizeof(prompt) - strlen(prompt) - 1);
1201                                                 } else {
1202                                                         strncat(p, "localhost", sizeof(prompt) - strlen(prompt) - 1);
1203                                                 }
1204                                                 break;
1205                                         case 'H': /* short hostname */
1206                                                 if (!gethostname(hostname, sizeof(hostname) - 1)) {
1207                                                         for (i=0;i<sizeof(hostname);i++) {
1208                                                                 if (hostname[i] == '.') {
1209                                                                         hostname[i] = '\0';
1210                                                                         break;
1211                                                                 }
1212                                                         }
1213                                                         strncat(p, hostname, sizeof(prompt) - strlen(prompt) - 1);
1214                                                 } else {
1215                                                         strncat(p, "localhost", sizeof(prompt) - strlen(prompt) - 1);
1216                                                 }
1217                                                 break;
1218 #ifdef linux
1219                                         case 'l': /* load avg */
1220                                                 t++;
1221                                                 if ((LOADAVG = fopen("/proc/loadavg", "r"))) {
1222                                                         float avg1, avg2, avg3;
1223                                                         int actproc, totproc, npid, which;
1224                                                         fscanf(LOADAVG, "%f %f %f %d/%d %d",
1225                                                                 &avg1, &avg2, &avg3, &actproc, &totproc, &npid);
1226                                                         if (sscanf(t, "%d", &which) == 1) {
1227                                                                 switch (which) {
1228                                                                         case 1:
1229                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg1);
1230                                                                                 break;
1231                                                                         case 2:
1232                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg2);
1233                                                                                 break;
1234                                                                         case 3:
1235                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg3);
1236                                                                                 break;
1237                                                                         case 4:
1238                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%d/%d", actproc, totproc);
1239                                                                                 break;
1240                                                                         case 5:
1241                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%d", npid);
1242                                                                                 break;
1243                                                                 }
1244                                                         }
1245                                                 }
1246                                                 break;
1247 #endif
1248                                         case 't': /* time */
1249                                                 memset(&tm, 0, sizeof(struct tm));
1250                                                 tv = ast_tvnow();
1251                                                 if (localtime_r(&(tv.tv_sec), &tm)) {
1252                                                         strftime(p, sizeof(prompt) - strlen(prompt), "%H:%M:%S", &tm);
1253                                                 }
1254                                                 break;
1255                                         case '#': /* process console or remote? */
1256                                                 if (! option_remote) {
1257                                                         strncat(p, "#", sizeof(prompt) - strlen(prompt) - 1);
1258                                                 } else {
1259                                                         strncat(p, ">", sizeof(prompt) - strlen(prompt) - 1);
1260                                                 }
1261                                                 break;
1262                                         case '%': /* literal % */
1263                                                 strncat(p, "%", sizeof(prompt) - strlen(prompt) - 1);
1264                                                 break;
1265                                         case '\0': /* % is last character - prevent bug */
1266                                                 t--;
1267                                                 break;
1268                                 }
1269                                 while (*p != '\0') {
1270                                         p++;
1271                                 }
1272                                 t++;
1273                         } else {
1274                                 *p = *t;
1275                                 p++;
1276                                 t++;
1277                         }
1278                 }
1279                 if (color_used) {
1280                         /* Force colors back to normal at end */
1281                         term_color_code(term_code, COLOR_WHITE, COLOR_BLACK, sizeof(term_code));
1282                         if (strlen(term_code) > sizeof(prompt) - strlen(prompt)) {
1283                                 strncat(prompt + sizeof(prompt) - strlen(term_code) - 1, term_code, strlen(term_code));
1284                         } else {
1285                                 strncat(p, term_code, sizeof(term_code));
1286                         }
1287                 }
1288         } else if (remotehostname)
1289                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT2, remotehostname);
1290         else
1291                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT);
1292
1293         return(prompt); 
1294 }
1295
1296 static char **ast_el_strtoarr(char *buf)
1297 {
1298         char **match_list = NULL, *retstr;
1299         size_t match_list_len;
1300         int matches = 0;
1301
1302         match_list_len = 1;
1303         while ( (retstr = strsep(&buf, " ")) != NULL) {
1304
1305                 if (!strcmp(retstr, AST_CLI_COMPLETE_EOF))
1306                         break;
1307                 if (matches + 1 >= match_list_len) {
1308                         match_list_len <<= 1;
1309                         match_list = realloc(match_list, match_list_len * sizeof(char *));
1310                 }
1311
1312                 match_list[matches++] = strdup(retstr);
1313         }
1314
1315         if (!match_list)
1316                 return (char **) NULL;
1317
1318         if (matches>= match_list_len)
1319                 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
1320
1321         match_list[matches] = (char *) NULL;
1322
1323         return match_list;
1324 }
1325
1326 static int ast_el_sort_compare(const void *i1, const void *i2)
1327 {
1328         char *s1, *s2;
1329
1330         s1 = ((char **)i1)[0];
1331         s2 = ((char **)i2)[0];
1332
1333         return strcasecmp(s1, s2);
1334 }
1335
1336 static int ast_cli_display_match_list(char **matches, int len, int max)
1337 {
1338         int i, idx, limit, count;
1339         int screenwidth = 0;
1340         int numoutput = 0, numoutputline = 0;
1341
1342         screenwidth = ast_get_termcols(STDOUT_FILENO);
1343
1344         /* find out how many entries can be put on one line, with two spaces between strings */
1345         limit = screenwidth / (max + 2);
1346         if (limit == 0)
1347                 limit = 1;
1348
1349         /* how many lines of output */
1350         count = len / limit;
1351         if (count * limit < len)
1352                 count++;
1353
1354         idx = 1;
1355
1356         qsort(&matches[0], (size_t)(len + 1), sizeof(char *), ast_el_sort_compare);
1357
1358         for (; count > 0; count--) {
1359                 numoutputline = 0;
1360                 for (i=0; i < limit && matches[idx]; i++, idx++) {
1361
1362                         /* Don't print dupes */
1363                         if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
1364                                 i--;
1365                                 free(matches[idx]);
1366                                 matches[idx] = NULL;
1367                                 continue;
1368                         }
1369
1370                         numoutput++;
1371                         numoutputline++;
1372                         fprintf(stdout, "%-*s  ", max, matches[idx]);
1373                         free(matches[idx]);
1374                         matches[idx] = NULL;
1375                 }
1376                 if (numoutputline > 0)
1377                         fprintf(stdout, "\n");
1378         }
1379
1380         return numoutput;
1381 }
1382
1383
1384 static char *cli_complete(EditLine *el, int ch)
1385 {
1386         int len=0;
1387         char *ptr;
1388         int nummatches = 0;
1389         char **matches;
1390         int retval = CC_ERROR;
1391         char buf[2048];
1392         int res;
1393
1394         LineInfo *lf = (LineInfo *)el_line(el);
1395
1396         *(char *)lf->cursor = '\0';
1397         ptr = (char *)lf->cursor;
1398         if (ptr) {
1399                 while (ptr > lf->buffer) {
1400                         if (isspace(*ptr)) {
1401                                 ptr++;
1402                                 break;
1403                         }
1404                         ptr--;
1405                 }
1406         }
1407
1408         len = lf->cursor - ptr;
1409
1410         if (option_remote) {
1411                 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr); 
1412                 fdprint(ast_consock, buf);
1413                 res = read(ast_consock, buf, sizeof(buf));
1414                 buf[res] = '\0';
1415                 nummatches = atoi(buf);
1416
1417                 if (nummatches > 0) {
1418                         char *mbuf;
1419                         int mlen = 0, maxmbuf = 2048;
1420                         /* Start with a 2048 byte buffer */
1421                         mbuf = malloc(maxmbuf);
1422                         if (!mbuf)
1423                                 return (char *)(CC_ERROR);
1424                         snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr); 
1425                         fdprint(ast_consock, buf);
1426                         res = 0;
1427                         mbuf[0] = '\0';
1428                         while (!strstr(mbuf, AST_CLI_COMPLETE_EOF) && res != -1) {
1429                                 if (mlen + 1024 > maxmbuf) {
1430                                         /* Every step increment buffer 1024 bytes */
1431                                         maxmbuf += 1024;
1432                                         mbuf = realloc(mbuf, maxmbuf);
1433                                         if (!mbuf)
1434                                                 return (char *)(CC_ERROR);
1435                                 }
1436                                 /* Only read 1024 bytes at a time */
1437                                 res = read(ast_consock, mbuf + mlen, 1024);
1438                                 if (res > 0)
1439                                         mlen += res;
1440                         }
1441                         mbuf[mlen] = '\0';
1442
1443                         matches = ast_el_strtoarr(mbuf);
1444                         free(mbuf);
1445                 } else
1446                         matches = (char **) NULL;
1447
1448
1449         } else {
1450
1451                 nummatches = ast_cli_generatornummatches((char *)lf->buffer,ptr);
1452                 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
1453         }
1454
1455         if (matches) {
1456                 int i;
1457                 int matches_num, maxlen, match_len;
1458
1459                 if (matches[0][0] != '\0') {
1460                         el_deletestr(el, (int) len);
1461                         el_insertstr(el, matches[0]);
1462                         retval = CC_REFRESH;
1463                 }
1464
1465                 if (nummatches == 1) {
1466                         /* Found an exact match */
1467                         el_insertstr(el, " ");
1468                         retval = CC_REFRESH;
1469                 } else {
1470                         /* Must be more than one match */
1471                         for (i=1, maxlen=0; matches[i]; i++) {
1472                                 match_len = strlen(matches[i]);
1473                                 if (match_len > maxlen)
1474                                         maxlen = match_len;
1475                         }
1476                         matches_num = i - 1;
1477                         if (matches_num >1) {
1478                                 fprintf(stdout, "\n");
1479                                 ast_cli_display_match_list(matches, nummatches, maxlen);
1480                                 retval = CC_REDISPLAY;
1481                         } else { 
1482                                 el_insertstr(el," ");
1483                                 retval = CC_REFRESH;
1484                         }
1485                 }
1486         free(matches);
1487         }
1488
1489         return (char *)(long)retval;
1490 }
1491
1492 static int ast_el_initialize(void)
1493 {
1494         HistEvent ev;
1495         char *editor = getenv("AST_EDITOR");
1496
1497         if (el != NULL)
1498                 el_end(el);
1499         if (el_hist != NULL)
1500                 history_end(el_hist);
1501
1502         el = el_init("asterisk", stdin, stdout, stderr);
1503         el_set(el, EL_PROMPT, cli_prompt);
1504
1505         el_set(el, EL_EDITMODE, 1);             
1506         el_set(el, EL_EDITOR, editor ? editor : "emacs");               
1507         el_hist = history_init();
1508         if (!el || !el_hist)
1509                 return -1;
1510
1511         /* setup history with 100 entries */
1512         history(el_hist, &ev, H_SETSIZE, 100);
1513
1514         el_set(el, EL_HIST, history, el_hist);
1515
1516         el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
1517         /* Bind <tab> to command completion */
1518         el_set(el, EL_BIND, "^I", "ed-complete", NULL);
1519         /* Bind ? to command completion */
1520         el_set(el, EL_BIND, "?", "ed-complete", NULL);
1521         /* Bind ^D to redisplay */
1522         el_set(el, EL_BIND, "^D", "ed-redisplay", NULL);
1523
1524         return 0;
1525 }
1526
1527 static int ast_el_add_history(char *buf)
1528 {
1529         HistEvent ev;
1530
1531         if (el_hist == NULL || el == NULL)
1532                 ast_el_initialize();
1533         if (strlen(buf) > 256)
1534                 return 0;
1535         return (history(el_hist, &ev, H_ENTER, buf));
1536 }
1537
1538 static int ast_el_write_history(char *filename)
1539 {
1540         HistEvent ev;
1541
1542         if (el_hist == NULL || el == NULL)
1543                 ast_el_initialize();
1544
1545         return (history(el_hist, &ev, H_SAVE, filename));
1546 }
1547
1548 static int ast_el_read_history(char *filename)
1549 {
1550         char buf[256];
1551         FILE *f;
1552         int ret = -1;
1553
1554         if (el_hist == NULL || el == NULL)
1555                 ast_el_initialize();
1556
1557         if ((f = fopen(filename, "r")) == NULL)
1558                 return ret;
1559
1560         while (!feof(f)) {
1561                 fgets(buf, sizeof(buf), f);
1562                 if (!strcmp(buf, "_HiStOrY_V2_\n"))
1563                         continue;
1564                 if (ast_all_zeros(buf))
1565                         continue;
1566                 if ((ret = ast_el_add_history(buf)) == -1)
1567                         break;
1568         }
1569         fclose(f);
1570
1571         return ret;
1572 }
1573
1574 static void ast_remotecontrol(char * data)
1575 {
1576         char buf[80];
1577         int res;
1578         char filename[80] = "";
1579         char *hostname;
1580         char *cpid;
1581         char *version;
1582         int pid;
1583         char tmp[80];
1584         char *stringp=NULL;
1585
1586         char *ebuf;
1587         int num = 0;
1588
1589         read(ast_consock, buf, sizeof(buf));
1590         if (data)
1591                 write(ast_consock, data, strlen(data) + 1);
1592         stringp=buf;
1593         hostname = strsep(&stringp, "/");
1594         cpid = strsep(&stringp, "/");
1595         version = strsep(&stringp, "\n");
1596         if (!version)
1597                 version = "<Version Unknown>";
1598         stringp=hostname;
1599         strsep(&stringp, ".");
1600         if (cpid)
1601                 pid = atoi(cpid);
1602         else
1603                 pid = -1;
1604         snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
1605         fdprint(ast_consock, tmp);
1606         snprintf(tmp, sizeof(tmp), "set debug atleast %d", option_debug);
1607         fdprint(ast_consock, tmp);
1608         ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
1609         remotehostname = hostname;
1610         if (getenv("HOME")) 
1611                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1612         if (el_hist == NULL || el == NULL)
1613                 ast_el_initialize();
1614
1615         el_set(el, EL_GETCFN, ast_el_read_char);
1616
1617         if (!ast_strlen_zero(filename))
1618                 ast_el_read_history(filename);
1619
1620         if (option_exec && data) {  /* hack to print output then exit if asterisk -rx is used */
1621                 char tempchar;
1622                 struct pollfd fds[0];
1623                 fds[0].fd = ast_consock;
1624                 fds[0].events = POLLIN;
1625                 fds[0].revents = 0;
1626                 while(poll(fds, 1, 100) > 0) {
1627                         ast_el_read_char(el, &tempchar);
1628                 }
1629                 return;
1630         }
1631         for(;;) {
1632                 ebuf = (char *)el_gets(el, &num);
1633
1634                 if (ebuf && !ast_strlen_zero(ebuf)) {
1635                         if (ebuf[strlen(ebuf)-1] == '\n')
1636                                 ebuf[strlen(ebuf)-1] = '\0';
1637                         if (!remoteconsolehandler(ebuf)) {
1638                                 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
1639                                 if (res < 1) {
1640                                         ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
1641                                         break;
1642                                 }
1643                         }
1644                 }
1645         }
1646         printf("\nDisconnected from Asterisk server\n");
1647 }
1648
1649 static int show_version(void)
1650 {
1651         printf("Asterisk " ASTERISK_VERSION "\n");
1652         return 0;
1653 }
1654
1655 static int show_cli_help(void) {
1656         printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 2000 - 2005, Digium.\n");
1657         printf("Usage: asterisk [OPTIONS]\n");
1658         printf("Valid Options:\n");
1659         printf("   -V              Display version number and exit\n");
1660         printf("   -C <configfile> Use an alternate configuration file\n");
1661         printf("   -G <group>      Run as a group other than the caller\n");
1662         printf("   -U <user>       Run as a user other than the caller\n");
1663         printf("   -c              Provide console CLI\n");
1664         printf("   -d              Enable extra debugging\n");
1665         printf("   -f              Do not fork\n");
1666         printf("   -g              Dump core in case of a crash\n");
1667         printf("   -h              This help screen\n");
1668         printf("   -i              Initialize crypto keys at startup\n");
1669         printf("   -n              Disable console colorization\n");
1670         printf("   -p              Run as pseudo-realtime thread\n");
1671         printf("   -q              Quiet mode (suppress output)\n");
1672         printf("   -r              Connect to Asterisk on this machine\n");
1673         printf("   -R              Connect to Asterisk, and attempt to reconnect if disconnected\n");
1674         printf("   -t              Record soundfiles in /var/tmp and move them where they belong after they are done.\n");
1675         printf("   -T              Display the time in [Mmm dd hh:mm:ss] format for each line of output to the CLI.\n");
1676         printf("   -v              Increase verbosity (multiple v's = more verbose)\n");
1677         printf("   -x <cmd>        Execute command <cmd> (only valid with -r)\n");
1678         printf("\n");
1679         return 0;
1680 }
1681
1682 static void ast_readconfig(void) {
1683         struct ast_config *cfg;
1684         struct ast_variable *v;
1685         char *config = AST_CONFIG_FILE;
1686
1687         if (option_overrideconfig == 1) {
1688                 cfg = ast_config_load(ast_config_AST_CONFIG_FILE);
1689                 if (!cfg)
1690                         ast_log(LOG_WARNING, "Unable to open specified master config file '%s', using built-in defaults\n", ast_config_AST_CONFIG_FILE);
1691         } else {
1692                 cfg = ast_config_load(config);
1693         }
1694
1695         /* init with buildtime config */
1696         ast_copy_string(ast_config_AST_CONFIG_DIR, AST_CONFIG_DIR, sizeof(ast_config_AST_CONFIG_DIR));
1697         ast_copy_string(ast_config_AST_SPOOL_DIR, AST_SPOOL_DIR, sizeof(ast_config_AST_SPOOL_DIR));
1698         ast_copy_string(ast_config_AST_MODULE_DIR, AST_MODULE_DIR, sizeof(ast_config_AST_VAR_DIR));
1699         snprintf(ast_config_AST_MONITOR_DIR, sizeof(ast_config_AST_MONITOR_DIR) - 1, "%s/monitor", ast_config_AST_SPOOL_DIR);
1700         ast_copy_string(ast_config_AST_VAR_DIR, AST_VAR_DIR, sizeof(ast_config_AST_VAR_DIR));
1701         ast_copy_string(ast_config_AST_LOG_DIR, AST_LOG_DIR, sizeof(ast_config_AST_LOG_DIR));
1702         ast_copy_string(ast_config_AST_AGI_DIR, AST_AGI_DIR, sizeof(ast_config_AST_AGI_DIR));
1703         ast_copy_string(ast_config_AST_DB, AST_DB, sizeof(ast_config_AST_DB));
1704         ast_copy_string(ast_config_AST_KEY_DIR, AST_KEY_DIR, sizeof(ast_config_AST_KEY_DIR));
1705         ast_copy_string(ast_config_AST_PID, AST_PID, sizeof(ast_config_AST_PID));
1706         ast_copy_string(ast_config_AST_SOCKET, AST_SOCKET, sizeof(ast_config_AST_SOCKET));
1707         ast_copy_string(ast_config_AST_RUN_DIR, AST_RUN_DIR, sizeof(ast_config_AST_RUN_DIR));
1708
1709         /* no asterisk.conf? no problem, use buildtime config! */
1710         if (!cfg) {
1711                 return;
1712         }
1713         v = ast_variable_browse(cfg, "files");
1714         while (v) {
1715                 if (!strcasecmp(v->name, "astctlpermissions")) {
1716                         ast_copy_string(ast_config_AST_CTL_PERMISSIONS, v->value, sizeof(ast_config_AST_CTL_PERMISSIONS));
1717                 } else if (!strcasecmp(v->name, "astctlowner")) {
1718                         ast_copy_string(ast_config_AST_CTL_OWNER, v->value, sizeof(ast_config_AST_CTL_OWNER));
1719                 } else if (!strcasecmp(v->name, "astctlgroup")) {
1720                         ast_copy_string(ast_config_AST_CTL_GROUP, v->value, sizeof(ast_config_AST_CTL_GROUP));
1721                 } else if (!strcasecmp(v->name, "astctl")) {
1722                         ast_copy_string(ast_config_AST_CTL, v->value, sizeof(ast_config_AST_CTL));
1723                 }
1724                 v = v->next;
1725         }
1726         v = ast_variable_browse(cfg, "directories");
1727         while(v) {
1728                 if (!strcasecmp(v->name, "astetcdir")) {
1729                         ast_copy_string(ast_config_AST_CONFIG_DIR, v->value, sizeof(ast_config_AST_CONFIG_DIR));
1730                 } else if (!strcasecmp(v->name, "astspooldir")) {
1731                         ast_copy_string(ast_config_AST_SPOOL_DIR, v->value, sizeof(ast_config_AST_SPOOL_DIR));
1732                         snprintf(ast_config_AST_MONITOR_DIR, sizeof(ast_config_AST_MONITOR_DIR) - 1, "%s/monitor", v->value);
1733                 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1734                         ast_copy_string(ast_config_AST_VAR_DIR, v->value, sizeof(ast_config_AST_VAR_DIR));
1735                         snprintf(ast_config_AST_DB, sizeof(ast_config_AST_DB), "%s/%s", v->value, "astdb");    
1736                 } else if (!strcasecmp(v->name, "astlogdir")) {
1737                         ast_copy_string(ast_config_AST_LOG_DIR, v->value, sizeof(ast_config_AST_LOG_DIR));
1738                 } else if (!strcasecmp(v->name, "astagidir")) {
1739                         ast_copy_string(ast_config_AST_AGI_DIR, v->value, sizeof(ast_config_AST_AGI_DIR));
1740                 } else if (!strcasecmp(v->name, "astrundir")) {
1741                         snprintf(ast_config_AST_PID, sizeof(ast_config_AST_PID), "%s/%s", v->value, "asterisk.pid");
1742                         snprintf(ast_config_AST_SOCKET, sizeof(ast_config_AST_SOCKET), "%s/%s", v->value, ast_config_AST_CTL);
1743                         ast_copy_string(ast_config_AST_RUN_DIR, v->value, sizeof(ast_config_AST_RUN_DIR));
1744                 } else if (!strcasecmp(v->name, "astmoddir")) {
1745                         ast_copy_string(ast_config_AST_MODULE_DIR, v->value, sizeof(ast_config_AST_MODULE_DIR));
1746                 }
1747                 v = v->next;
1748         }
1749         v = ast_variable_browse(cfg, "options");
1750         while(v) {
1751                 /* verbose level (-v at startup) */
1752                 if (!strcasecmp(v->name, "verbose")) {
1753                         option_verbose = atoi(v->value);
1754                 /* whether or not to force timestamping. (-T at startup) */
1755                 } else if (!strcasecmp(v->name, "timestamp")) {
1756                         option_timestamp = ast_true(v->value);
1757                 /* whether or not to support #exec in config files */
1758                 } else if (!strcasecmp(v->name, "execincludes")) {
1759                         option_exec_includes = ast_true(v->value);
1760                 /* debug level (-d at startup) */
1761                 } else if (!strcasecmp(v->name, "debug")) {
1762                         option_debug = 0;
1763                         if (sscanf(v->value, "%d", &option_debug) != 1) {
1764                                 option_debug = ast_true(v->value);
1765                         }
1766                 /* Disable forking (-f at startup) */
1767                 } else if (!strcasecmp(v->name, "nofork")) {
1768                         option_nofork = ast_true(v->value);
1769                 /* Run quietly (-q at startup ) */
1770                 } else if (!strcasecmp(v->name, "quiet")) {
1771                         option_quiet = ast_true(v->value);
1772                 /* Run as console (-c at startup, implies nofork) */
1773                 } else if (!strcasecmp(v->name, "console")) {
1774                         option_console = ast_true(v->value);
1775                 /* Run with highg priority if the O/S permits (-p at startup) */
1776                 } else if (!strcasecmp(v->name, "highpriority")) {
1777                         option_highpriority = ast_true(v->value);
1778                 /* Initialize RSA auth keys (IAX2) (-i at startup) */
1779                 } else if (!strcasecmp(v->name, "initcrypto")) {
1780                         option_initcrypto = ast_true(v->value);
1781                 /* Disable ANSI colors for console (-c at startup) */
1782                 } else if (!strcasecmp(v->name, "nocolor")) {
1783                         option_nocolor = ast_true(v->value);
1784                 /* Disable some usage warnings for picky people :p */
1785                 } else if (!strcasecmp(v->name, "dontwarn")) {
1786                         option_dontwarn = ast_true(v->value);
1787                 /* Dump core in case of crash (-g) */
1788                 } else if (!strcasecmp(v->name, "dumpcore")) {
1789                         option_dumpcore = ast_true(v->value);
1790                 /* Cache recorded sound files to another directory during recording */
1791                 } else if (!strcasecmp(v->name, "cache_record_files")) {
1792                         option_cache_record_files = ast_true(v->value);
1793                 /* Specify cache directory */
1794                 }  else if (!strcasecmp(v->name, "record_cache_dir")) {
1795                         ast_copy_string(record_cache_dir, v->value, AST_CACHE_DIR_LEN);
1796                 /* Build transcode paths via SLINEAR, instead of directly */
1797                 } else if (!strcasecmp(v->name, "transcode_via_sln")) {
1798                         option_transcode_slin = ast_true(v->value);
1799                 } else if (!strcasecmp(v->name, "maxcalls")) {
1800                         if ((sscanf(v->value, "%d", &option_maxcalls) != 1) || (option_maxcalls < 0)) {
1801                                 option_maxcalls = 0;
1802                         }
1803                 }
1804                 v = v->next;
1805         }
1806         ast_config_destroy(cfg);
1807 }
1808
1809 int main(int argc, char *argv[])
1810 {
1811         int c;
1812         char filename[80] = "";
1813         char hostname[MAXHOSTNAMELEN]="";
1814         char tmp[80];
1815         char * xarg = NULL;
1816         int x;
1817         FILE *f;
1818         sigset_t sigs;
1819         int num;
1820         int is_child_of_nonroot=0;
1821         char *buf;
1822         char *runuser=NULL, *rungroup=NULL;
1823
1824         /* Remember original args for restart */
1825         if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1826                 fprintf(stderr, "Truncating argument size to %d\n", (int)(sizeof(_argv) / sizeof(_argv[0])) - 1);
1827                 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1828         }
1829         for (x=0;x<argc;x++)
1830                 _argv[x] = argv[x];
1831         _argv[x] = NULL;
1832
1833         /* if the progname is rasterisk consider it a remote console */
1834         if (argv[0] && (strstr(argv[0], "rasterisk")) != NULL) {
1835                 option_remote++;
1836                 option_nofork++;
1837         }
1838         if (gethostname(hostname, sizeof(hostname)-1))
1839                 ast_copy_string(hostname, "<Unknown>", sizeof(hostname));
1840         ast_mainpid = getpid();
1841         ast_ulaw_init();
1842         ast_alaw_init();
1843         callerid_init();
1844         ast_utils_init();
1845         tdd_init();
1846         /* When Asterisk restarts after it has dropped the root privileges,
1847          * it can't issue setuid(), setgid(), setgroups() or set_priority() 
1848          * */
1849         if (getenv("ASTERISK_ALREADY_NONROOT"))
1850                 is_child_of_nonroot=1;
1851         if (getenv("HOME")) 
1852                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1853         /* Check if we're root */
1854         /*
1855         if (geteuid()) {
1856                 ast_log(LOG_ERROR, "Must be run as root\n");
1857                 exit(1);
1858         }
1859         */
1860         /* Check for options */
1861         while((c=getopt(argc, argv, "tThfdvVqprRgcinx:U:G:C:M:")) != -1) {
1862                 switch(c) {
1863                 case 'd':
1864                         option_debug++;
1865                         option_nofork++;
1866                         break;
1867                 case 'c':
1868                         option_console++;
1869                         option_nofork++;
1870                         break;
1871                 case 'f':
1872                         option_nofork++;
1873                         break;
1874                 case 'n':
1875                         option_nocolor++;
1876                         break;
1877                 case 'r':
1878                         option_remote++;
1879                         option_nofork++;
1880                         break;
1881                 case 'R':
1882                         option_remote++;
1883                         option_nofork++;
1884                         option_reconnect++;
1885                         break;
1886                 case 'p':
1887                         option_highpriority++;
1888                         break;
1889                 case 'v':
1890                         option_verbose++;
1891                         option_nofork++;
1892                         break;
1893                 case 'M':
1894                         if ((sscanf(optarg, "%d", &option_maxcalls) != 1) || (option_maxcalls < 0))
1895                                 option_maxcalls = 0;
1896                         break;
1897                 case 'q':
1898                         option_quiet++;
1899                         break;
1900                 case 't':
1901                         option_cache_record_files++;
1902                         break;
1903                 case 'T':
1904                         option_timestamp++;
1905                         break;
1906                 case 'x':
1907                         option_exec++;
1908                         xarg = optarg;
1909                         break;
1910                 case 'C':
1911                         ast_copy_string((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE));
1912                         option_overrideconfig++;
1913                         break;
1914                 case 'i':
1915                         option_initcrypto++;
1916                         break;
1917                 case'g':
1918                         option_dumpcore++;
1919                         break;
1920                 case 'h':
1921                         show_cli_help();
1922                         exit(0);
1923                 case 'V':
1924                         show_version();
1925                         exit(0);
1926                 case 'U':
1927                         runuser = optarg;
1928                         break;
1929                 case 'G':
1930                         rungroup = optarg;
1931                         break;
1932                 case '?':
1933                         exit(1);
1934                 }
1935         }
1936
1937         if (option_dumpcore) {
1938                 struct rlimit l;
1939                 memset(&l, 0, sizeof(l));
1940                 l.rlim_cur = RLIM_INFINITY;
1941                 l.rlim_max = RLIM_INFINITY;
1942                 if (setrlimit(RLIMIT_CORE, &l)) {
1943                         ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
1944                 }
1945         }
1946
1947         if (option_console && !option_verbose) 
1948                 ast_verbose("[ Reading Master Configuration ]");
1949         ast_readconfig();
1950
1951         if (!is_child_of_nonroot && ast_set_priority(option_highpriority)) {
1952                 exit(1);
1953         }
1954
1955         if (!is_child_of_nonroot && rungroup) {
1956                 struct group *gr;
1957                 gr = getgrnam(rungroup);
1958                 if (!gr) {
1959                         ast_log(LOG_WARNING, "No such group '%s'!\n", rungroup);
1960                         exit(1);
1961                 }
1962                 if (setgid(gr->gr_gid)) {
1963                         ast_log(LOG_WARNING, "Unable to setgid to %d (%s)\n", gr->gr_gid, rungroup);
1964                         exit(1);
1965                 }
1966                 if (option_verbose)
1967                         ast_verbose("Running as group '%s'\n", rungroup);
1968         }
1969
1970         if (!is_child_of_nonroot && runuser) {
1971                 struct passwd *pw;
1972                 pw = getpwnam(runuser);
1973                 if (!pw) {
1974                         ast_log(LOG_WARNING, "No such user '%s'!\n", runuser);
1975                         exit(1);
1976                 }
1977                 if (setuid(pw->pw_uid)) {
1978                         ast_log(LOG_WARNING, "Unable to setuid to %d (%s)\n", pw->pw_uid, runuser);
1979                         exit(1);
1980                 }
1981                 setenv("ASTERISK_ALREADY_NONROOT","yes",1);
1982                 if (option_verbose)
1983                         ast_verbose("Running as user '%s'\n", runuser);
1984         }
1985
1986         term_init();
1987         printf(term_end());
1988         fflush(stdout);
1989
1990         if (option_console && !option_verbose) 
1991                 ast_verbose("[ Initializing Custom Configuration Options ]");
1992         /* custom config setup */
1993         register_config_cli();
1994         read_config_maps();
1995         
1996
1997         if (option_console) {
1998                 if (el_hist == NULL || el == NULL)
1999                         ast_el_initialize();
2000
2001                 if (!ast_strlen_zero(filename))
2002                         ast_el_read_history(filename);
2003         }
2004
2005         if (ast_tryconnect()) {
2006                 /* One is already running */
2007                 if (option_remote) {
2008                         if (option_exec) {
2009                                 ast_remotecontrol(xarg);
2010                                 quit_handler(0, 0, 0, 0);
2011                                 exit(0);
2012                         }
2013                         printf(term_quit());
2014                         ast_register_verbose(console_verboser);
2015                         WELCOME_MESSAGE;
2016                         ast_remotecontrol(NULL);
2017                         quit_handler(0, 0, 0, 0);
2018                         exit(0);
2019                 } else {
2020                         ast_log(LOG_ERROR, "Asterisk already running on %s.  Use 'asterisk -r' to connect.\n", (char *)ast_config_AST_SOCKET);
2021                         printf(term_quit());
2022                         exit(1);
2023                 }
2024         } else if (option_remote || option_exec) {
2025                 ast_log(LOG_ERROR, "Unable to connect to remote asterisk (does %s exist?)\n",ast_config_AST_SOCKET);
2026                 printf(term_quit());
2027                 exit(1);
2028         }
2029         /* Blindly write pid file since we couldn't connect */
2030         unlink((char *)ast_config_AST_PID);
2031         f = fopen((char *)ast_config_AST_PID, "w");
2032         if (f) {
2033                 fprintf(f, "%d\n", getpid());
2034                 fclose(f);
2035         } else
2036                 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
2037
2038         if (!option_verbose && !option_debug && !option_nofork && !option_console) {
2039                 daemon(0,0);
2040                 /* Blindly re-write pid file since we are forking */
2041                 unlink((char *)ast_config_AST_PID);
2042                 f = fopen((char *)ast_config_AST_PID, "w");
2043                 if (f) {
2044                         fprintf(f, "%d\n", getpid());
2045                         fclose(f);
2046                 } else
2047                         ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
2048         }
2049
2050         /* Test recursive mutex locking. */
2051         if (test_for_thread_safety())
2052                 ast_verbose("Warning! Asterisk is not thread safe.\n");
2053
2054         ast_makesocket();
2055         sigemptyset(&sigs);
2056         sigaddset(&sigs, SIGHUP);
2057         sigaddset(&sigs, SIGTERM);
2058         sigaddset(&sigs, SIGINT);
2059         sigaddset(&sigs, SIGPIPE);
2060         sigaddset(&sigs, SIGWINCH);
2061         pthread_sigmask(SIG_BLOCK, &sigs, NULL);
2062         if (option_console || option_verbose || option_remote)
2063                 ast_register_verbose(console_verboser);
2064         /* Print a welcome message if desired */
2065         if (option_verbose || option_console) {
2066                 WELCOME_MESSAGE;
2067         }
2068         if (option_console && !option_verbose) 
2069                 ast_verbose("[ Booting...");
2070
2071         signal(SIGURG, urg_handler);
2072         signal(SIGINT, __quit_handler);
2073         signal(SIGTERM, __quit_handler);
2074         signal(SIGHUP, hup_handler);
2075         signal(SIGCHLD, child_handler);
2076         signal(SIGPIPE, SIG_IGN);
2077
2078         /* ensure that the random number generators are seeded with a different value every time
2079            Asterisk is started
2080         */
2081         srand((unsigned int) getpid() + (unsigned int) time(NULL));
2082         srandom((unsigned int) getpid() + (unsigned int) time(NULL));
2083
2084         if (init_logger()) {
2085                 printf(term_quit());
2086                 exit(1);
2087         }
2088         if (dnsmgr_init()) {
2089                 printf(term_quit());
2090                 exit(1);
2091         }
2092         /* load 'preload' modules, required for access to Realtime-mapped configuration files */
2093         if (load_modules(1)) {
2094                 printf(term_quit());
2095                 exit(1);
2096         }
2097         ast_channels_init();
2098         if (init_manager()) {
2099                 printf(term_quit());
2100                 exit(1);
2101         }
2102         if (ast_cdr_engine_init()) {
2103                 printf(term_quit());
2104                 exit(1);
2105         }
2106         if (ast_device_state_engine_init()) {
2107                 printf(term_quit());
2108                 exit(1);
2109         }
2110         ast_rtp_init();
2111         if (ast_image_init()) {
2112                 printf(term_quit());
2113                 exit(1);
2114         }
2115         if (ast_file_init()) {
2116                 printf(term_quit());
2117                 exit(1);
2118         }
2119         if (load_pbx()) {
2120                 printf(term_quit());
2121                 exit(1);
2122         }
2123         if (load_modules(0)) {
2124                 printf(term_quit());
2125                 exit(1);
2126         }
2127         if (init_framer()) {
2128                 printf(term_quit());
2129                 exit(1);
2130         }
2131         if (astdb_init()) {
2132                 printf(term_quit());
2133                 exit(1);
2134         }
2135         if (ast_enum_init()) {
2136                 printf(term_quit());
2137                 exit(1);
2138         }
2139 #if 0
2140         /* This should no longer be necessary */
2141         /* sync cust config and reload some internals in case a custom config handler binded to them */
2142         read_ast_cust_config();
2143         reload_logger(0);
2144         reload_manager();
2145         ast_enum_reload();
2146         ast_rtp_reload();
2147 #endif
2148
2149
2150         /* We might have the option of showing a console, but for now just
2151            do nothing... */
2152         if (option_console && !option_verbose)
2153                 ast_verbose(" ]\n");
2154         if (option_verbose || option_console)
2155                 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
2156         if (option_nofork)
2157                 consolethread = pthread_self();
2158         fully_booted = 1;
2159         pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
2160 #ifdef __AST_DEBUG_MALLOC
2161         __ast_mm_init();
2162 #endif  
2163         time(&ast_startuptime);
2164         ast_cli_register_multiple(core_cli, sizeof(core_cli) / sizeof(core_cli[0]));
2165         if (option_console) {
2166                 /* Console stuff now... */
2167                 /* Register our quit function */
2168                 char title[256];
2169                 set_icon("Asterisk");
2170                 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, ast_mainpid);
2171                 set_title(title);
2172
2173                 for (;;) {
2174                         buf = (char *)el_gets(el, &num);
2175                         if (buf) {
2176                                 if (buf[strlen(buf)-1] == '\n')
2177                                         buf[strlen(buf)-1] = '\0';
2178
2179                                 consolehandler((char *)buf);
2180                         } else {
2181                                 if (write(STDOUT_FILENO, "\nUse EXIT or QUIT to exit the asterisk console\n",
2182                                                                   strlen("\nUse EXIT or QUIT to exit the asterisk console\n")) < 0) {
2183                                         /* Whoa, stdout disappeared from under us... Make /dev/null's */
2184                                         int fd;
2185                                         fd = open("/dev/null", O_RDWR);
2186                                         if (fd > -1) {
2187                                                 dup2(fd, STDOUT_FILENO);
2188                                                 dup2(fd, STDIN_FILENO);
2189                                         } else
2190                                                 ast_log(LOG_WARNING, "Failed to open /dev/null to recover from dead console.  Bad things will happen!\n");
2191                                         break;
2192                                 }
2193                         }
2194                 }
2195
2196         }
2197         /* Do nothing */
2198         for(;;)  {      /* apparently needed for the MACos */
2199                 struct pollfd p = { -1 /* no descriptor */, 0, 0 };
2200                 poll(&p, 0, -1);
2201         }
2202         return 0;
2203 }