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