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