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