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