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