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