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