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