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