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