201c9fd6b53be48548e494799047b13d50ea7023
[asterisk/asterisk.git] / asterisk.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19
20 /* Doxygenified Copyright Header */
21 /*!
22  * \mainpage Asterisk -- An Open Source Telephony Toolkit
23  *
24  * \arg \ref DevDoc 
25  * \arg \ref ConfigFiles
26  *
27  * \section copyright Copyright and author
28  *
29  * Copyright (C) 1999 - 2005, Digium, Inc.
30  * Asterisk is a trade mark registered by Digium, Inc.
31  *
32  * \author Mark Spencer <markster@digium.com>
33  * Also see \ref AstCREDITS
34  *
35  * \section license License
36  * See http://www.asterisk.org for more information about
37  * the Asterisk project. Please do not directly contact
38  * any of the maintainers of this project for assistance;
39  * the project provides a web site, mailing lists and IRC
40  * channels for your use.
41  *
42  * This program is free software, distributed under the terms of
43  * the GNU General Public License Version 2. See the LICENSE file
44  * at the top of the source tree.
45  *
46  * \verbinclude LICENSE
47  *
48  */
49
50 /*! \file
51   \brief Top level source file for Asterisk  - the Open Source PBX. Implementation
52   of PBX core functions and CLI interface.
53   
54  */
55
56 #include <unistd.h>
57 #include <stdlib.h>
58 #include <sys/time.h>
59 #include <fcntl.h>
60 #include <stdio.h>
61 #include <signal.h>
62 #include <sched.h>
63 #include <sys/socket.h>
64 #include <sys/un.h>
65 #include <sys/wait.h>
66 #include <string.h>
67 #include <errno.h>
68 #include <ctype.h>
69 #include <sys/resource.h>
70 #include <grp.h>
71 #include <pwd.h>
72 #include <sys/stat.h>
73 #include <regex.h>
74
75 #if  defined(__FreeBSD__) || defined( __NetBSD__ ) || defined(SOLARIS)
76 #include <netdb.h>
77 #endif
78
79 #include "asterisk.h"
80
81 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
82
83 #include "asterisk/logger.h"
84 #include "asterisk/options.h"
85 #include "asterisk/cli.h"
86 #include "asterisk/channel.h"
87 #include "asterisk/ulaw.h"
88 #include "asterisk/alaw.h"
89 #include "asterisk/callerid.h"
90 #include "asterisk/module.h"
91 #include "asterisk/image.h"
92 #include "asterisk/tdd.h"
93 #include "asterisk/term.h"
94 #include "asterisk/manager.h"
95 #include "asterisk/cdr.h"
96 #include "asterisk/pbx.h"
97 #include "asterisk/enum.h"
98 #include "asterisk/rtp.h"
99 #include "asterisk/app.h"
100 #include "asterisk/lock.h"
101 #include "asterisk/utils.h"
102 #include "asterisk/file.h"
103 #include "asterisk/io.h"
104 #include "asterisk/lock.h"
105 #include "editline/histedit.h"
106 #include "asterisk/config.h"
107 #include "asterisk/version.h"
108 #include "asterisk/linkedlists.h"
109 #include "asterisk/devicestate.h"
110
111 #include "asterisk/doxyref.h"           /* Doxygen documentation */
112
113 #include "defaults.h"
114
115 #ifndef AF_LOCAL
116 #define AF_LOCAL AF_UNIX
117 #define PF_LOCAL PF_UNIX
118 #endif
119
120 #define AST_MAX_CONNECTS 128
121 #define NUM_MSGS 64
122
123 #define WELCOME_MESSAGE ast_verbose( "Asterisk " ASTERISK_VERSION ", Copyright (C) 1999 - 2005 Digium.\n"); \
124                 ast_verbose( "Written by Mark Spencer <markster@digium.com>\n"); \
125                 ast_verbose( "=========================================================================\n")
126
127 int option_verbose=0;
128 int option_debug=0;
129 int option_exec_includes=0;
130 int option_nofork=0;
131 int option_quiet=0;
132 int option_console=0;
133 int option_highpriority=0;
134 int option_remote=0;
135 int option_exec=0;
136 int option_initcrypto=0;
137 int option_nocolor;
138 int option_dumpcore = 0;
139 int option_cache_record_files = 0;
140 int option_timestamp = 0;
141 int option_overrideconfig = 0;
142 int option_reconnect = 0;
143 int option_transcode_slin = 1;
144 int option_transmit_silence_during_record = 0;
145 int option_maxcalls = 0;
146 double option_maxload = 0.0;
147 int option_dontwarn = 0;
148 int option_priority_jumping = 1;
149 int fully_booted = 0;
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 && option_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 && option_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 && option_console)
850                                 ast_verbose("Asterisk %s cancelled.\n", restart ? "restart" : "shutdown");
851                         return;
852                 }
853         }
854         if (option_console || option_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 && option_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((char *)ast_config_AST_SOCKET);
881         if (!option_remote) unlink((char *)ast_config_AST_PID);
882         printf(term_quit());
883         if (restart) {
884                 if (option_verbose || option_console)
885                         ast_verbose("Preparing for Asterisk restart...\n");
886                 /* Mark all FD's for closing on exec */
887                 for (x=3;x<32768;x++) {
888                         fcntl(x, F_SETFD, FD_CLOEXEC);
889                 }
890                 if (option_verbose || option_console)
891                         ast_verbose("Restarting Asterisk NOW...\n");
892                 restartnow = 1;
893
894                 /* close logger */
895                 close_logger();
896
897                 /* If there is a consolethread running send it a SIGHUP 
898                    so it can execvp, otherwise we can do it ourselves */
899                 if ((consolethread != AST_PTHREADT_NULL) && (consolethread != pthread_self())) {
900                         pthread_kill(consolethread, SIGHUP);
901                         /* Give the signal handler some time to complete */
902                         sleep(2);
903                 } else
904                         execvp(_argv[0], _argv);
905         
906         } else {
907                 /* close logger */
908                 close_logger();
909         }
910         exit(0);
911 }
912
913 static void __quit_handler(int num)
914 {
915         quit_handler(num, 0, 1, 0);
916 }
917
918 static const char *fix_header(char *outbuf, int maxout, const char *s, char *cmp)
919 {
920         const char *c;
921         if (!strncmp(s, cmp, strlen(cmp))) {
922                 c = s + strlen(cmp);
923                 term_color(outbuf, cmp, COLOR_GRAY, 0, maxout);
924                 return c;
925         }
926         return NULL;
927 }
928
929 static void console_verboser(const char *s, int pos, int replace, int complete)
930 {
931         char tmp[80];
932         const char *c=NULL;
933         /* Return to the beginning of the line */
934         if (!pos) {
935                 fprintf(stdout, "\r");
936                 if ((c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_4)) ||
937                         (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_3)) ||
938                         (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_2)) ||
939                         (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_1)))
940                         fputs(tmp, stdout);
941         }
942         if (c)
943                 fputs(c + pos,stdout);
944         else
945                 fputs(s + pos,stdout);
946         fflush(stdout);
947         if (complete) {
948                 /* Wake up a poll()ing console */
949                 if (option_console && consolethread != AST_PTHREADT_NULL)
950                         pthread_kill(consolethread, SIGURG);
951         }
952 }
953
954 static int ast_all_zeros(char *s)
955 {
956         while(*s) {
957                 if (*s > 32)
958                         return 0;
959                 s++;  
960         }
961         return 1;
962 }
963
964 static void consolehandler(char *s)
965 {
966         printf(term_end());
967         fflush(stdout);
968         /* Called when readline data is available */
969         if (s && !ast_all_zeros(s))
970                 ast_el_add_history(s);
971         /* Give the console access to the shell */
972         if (s) {
973                 /* The real handler for bang */
974                 if (s[0] == '!') {
975                         if (s[1])
976                                 ast_safe_system(s+1);
977                         else
978                                 ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
979                 } else 
980                 ast_cli_command(STDOUT_FILENO, s);
981         } else
982                 fprintf(stdout, "\nUse \"quit\" to exit\n");
983 }
984
985 static int remoteconsolehandler(char *s)
986 {
987         int ret = 0;
988         /* Called when readline data is available */
989         if (s && !ast_all_zeros(s))
990                 ast_el_add_history(s);
991         /* Give the console access to the shell */
992         if (s) {
993                 /* The real handler for bang */
994                 if (s[0] == '!') {
995                         if (s[1])
996                                 ast_safe_system(s+1);
997                         else
998                                 ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
999                         ret = 1;
1000                 }
1001                 if ((strncasecmp(s, "quit", 4) == 0 || strncasecmp(s, "exit", 4) == 0) &&
1002                     (s[4] == '\0' || isspace(s[4]))) {
1003                         quit_handler(0, 0, 0, 0);
1004                         ret = 1;
1005                 }
1006         } else
1007                 fprintf(stdout, "\nUse \"quit\" to exit\n");
1008
1009         return ret;
1010 }
1011
1012 static char abort_halt_help[] = 
1013 "Usage: abort shutdown\n"
1014 "       Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
1015 "       call operations.\n";
1016
1017 static char shutdown_now_help[] = 
1018 "Usage: stop now\n"
1019 "       Shuts down a running Asterisk immediately, hanging up all active calls .\n";
1020
1021 static char shutdown_gracefully_help[] = 
1022 "Usage: stop gracefully\n"
1023 "       Causes Asterisk to not accept new calls, and exit when all\n"
1024 "       active calls have terminated normally.\n";
1025
1026 static char shutdown_when_convenient_help[] = 
1027 "Usage: stop when convenient\n"
1028 "       Causes Asterisk to perform a shutdown when all active calls have ended.\n";
1029
1030 static char restart_now_help[] = 
1031 "Usage: restart now\n"
1032 "       Causes Asterisk to hangup all calls and exec() itself performing a cold\n"
1033 "       restart.\n";
1034
1035 static char restart_gracefully_help[] = 
1036 "Usage: restart gracefully\n"
1037 "       Causes Asterisk to stop accepting new calls and exec() itself performing a cold\n"
1038 "       restart when all active calls have ended.\n";
1039
1040 static char restart_when_convenient_help[] = 
1041 "Usage: restart when convenient\n"
1042 "       Causes Asterisk to perform a cold restart when all active calls have ended.\n";
1043
1044 static char bang_help[] =
1045 "Usage: !<command>\n"
1046 "       Executes a given shell command\n";
1047
1048 #if 0
1049 static int handle_quit(int fd, int argc, char *argv[])
1050 {
1051         if (argc != 1)
1052                 return RESULT_SHOWUSAGE;
1053         quit_handler(0, 0, 1, 0);
1054         return RESULT_SUCCESS;
1055 }
1056 #endif
1057
1058 static int handle_shutdown_now(int fd, int argc, char *argv[])
1059 {
1060         if (argc != 2)
1061                 return RESULT_SHOWUSAGE;
1062         quit_handler(0, 0 /* Not nice */, 1 /* safely */, 0 /* not restart */);
1063         return RESULT_SUCCESS;
1064 }
1065
1066 static int handle_shutdown_gracefully(int fd, int argc, char *argv[])
1067 {
1068         if (argc != 2)
1069                 return RESULT_SHOWUSAGE;
1070         quit_handler(0, 1 /* nicely */, 1 /* safely */, 0 /* no restart */);
1071         return RESULT_SUCCESS;
1072 }
1073
1074 static int handle_shutdown_when_convenient(int fd, int argc, char *argv[])
1075 {
1076         if (argc != 3)
1077                 return RESULT_SHOWUSAGE;
1078         quit_handler(0, 2 /* really nicely */, 1 /* safely */, 0 /* don't restart */);
1079         return RESULT_SUCCESS;
1080 }
1081
1082 static int handle_restart_now(int fd, int argc, char *argv[])
1083 {
1084         if (argc != 2)
1085                 return RESULT_SHOWUSAGE;
1086         quit_handler(0, 0 /* not nicely */, 1 /* safely */, 1 /* restart */);
1087         return RESULT_SUCCESS;
1088 }
1089
1090 static int handle_restart_gracefully(int fd, int argc, char *argv[])
1091 {
1092         if (argc != 2)
1093                 return RESULT_SHOWUSAGE;
1094         quit_handler(0, 1 /* nicely */, 1 /* safely */, 1 /* restart */);
1095         return RESULT_SUCCESS;
1096 }
1097
1098 static int handle_restart_when_convenient(int fd, int argc, char *argv[])
1099 {
1100         if (argc != 3)
1101                 return RESULT_SHOWUSAGE;
1102         quit_handler(0, 2 /* really nicely */, 1 /* safely */, 1 /* restart */);
1103         return RESULT_SUCCESS;
1104 }
1105
1106 static int handle_abort_halt(int fd, int argc, char *argv[])
1107 {
1108         if (argc != 2)
1109                 return RESULT_SHOWUSAGE;
1110         ast_cancel_shutdown();
1111         shuttingdown = 0;
1112         return RESULT_SUCCESS;
1113 }
1114
1115 static int handle_bang(int fd, int argc, char *argv[])
1116 {
1117         return RESULT_SUCCESS;
1118 }
1119
1120 #define ASTERISK_PROMPT "*CLI> "
1121
1122 #define ASTERISK_PROMPT2 "%s*CLI> "
1123
1124 static struct ast_cli_entry core_cli[] = {
1125         { { "abort", "halt", NULL }, handle_abort_halt,
1126           "Cancel a running halt", abort_halt_help },
1127         { { "stop", "now", NULL }, handle_shutdown_now,
1128           "Shut down Asterisk immediately", shutdown_now_help },
1129         { { "stop", "gracefully", NULL }, handle_shutdown_gracefully,
1130           "Gracefully shut down Asterisk", shutdown_gracefully_help },
1131         { { "stop", "when","convenient", NULL }, handle_shutdown_when_convenient,
1132           "Shut down Asterisk at empty call volume", shutdown_when_convenient_help },
1133         { { "restart", "now", NULL }, handle_restart_now,
1134           "Restart Asterisk immediately", restart_now_help },
1135         { { "restart", "gracefully", NULL }, handle_restart_gracefully,
1136           "Restart Asterisk gracefully", restart_gracefully_help },
1137         { { "restart", "when", "convenient", NULL }, handle_restart_when_convenient,
1138           "Restart Asterisk at empty call volume", restart_when_convenient_help },
1139         { { "!", NULL }, handle_bang,
1140           "Execute a shell command", bang_help },
1141 #if !defined(LOW_MEMORY)
1142         { { "show", "version", "files", NULL }, handle_show_version_files,
1143           "Show versions of files used to build Asterisk", show_version_files_help, complete_show_version_files },
1144 #endif /* ! LOW_MEMORY */
1145 };
1146
1147 static int ast_el_read_char(EditLine *el, char *cp)
1148 {
1149         int num_read=0;
1150         int lastpos=0;
1151         struct pollfd fds[2];
1152         int res;
1153         int max;
1154         char buf[512];
1155
1156         for (;;) {
1157                 max = 1;
1158                 fds[0].fd = ast_consock;
1159                 fds[0].events = POLLIN;
1160                 if (!option_exec) {
1161                         fds[1].fd = STDIN_FILENO;
1162                         fds[1].events = POLLIN;
1163                         max++;
1164                 }
1165                 res = poll(fds, max, -1);
1166                 if (res < 0) {
1167                         if (errno == EINTR)
1168                                 continue;
1169                         ast_log(LOG_ERROR, "poll failed: %s\n", strerror(errno));
1170                         break;
1171                 }
1172
1173                 if (!option_exec && fds[1].revents) {
1174                         num_read = read(STDIN_FILENO, cp, 1);
1175                         if (num_read < 1) {
1176                                 break;
1177                         } else 
1178                                 return (num_read);
1179                 }
1180                 if (fds[0].revents) {
1181                         res = read(ast_consock, buf, sizeof(buf) - 1);
1182                         /* if the remote side disappears exit */
1183                         if (res < 1) {
1184                                 fprintf(stderr, "\nDisconnected from Asterisk server\n");
1185                                 if (!option_reconnect) {
1186                                         quit_handler(0, 0, 0, 0);
1187                                 } else {
1188                                         int tries;
1189                                         int reconnects_per_second = 20;
1190                                         fprintf(stderr, "Attempting to reconnect for 30 seconds\n");
1191                                         for (tries=0;tries<30 * reconnects_per_second;tries++) {
1192                                                 if (ast_tryconnect()) {
1193                                                         fprintf(stderr, "Reconnect succeeded after %.3f seconds\n", 1.0 / reconnects_per_second * tries);
1194                                                         printf(term_quit());
1195                                                         WELCOME_MESSAGE;
1196                                                         break;
1197                                                 } else {
1198                                                         usleep(1000000 / reconnects_per_second);
1199                                                 }
1200                                         }
1201                                         if (tries >= 30 * reconnects_per_second) {
1202                                                 fprintf(stderr, "Failed to reconnect for 30 seconds.  Quitting.\n");
1203                                                 quit_handler(0, 0, 0, 0);
1204                                         }
1205                                 }
1206                         }
1207
1208                         buf[res] = '\0';
1209
1210                         if (!option_exec && !lastpos)
1211                                 write(STDOUT_FILENO, "\r", 1);
1212                         write(STDOUT_FILENO, buf, res);
1213                         if ((buf[res-1] == '\n') || (buf[res-2] == '\n')) {
1214                                 *cp = CC_REFRESH;
1215                                 return(1);
1216                         } else {
1217                                 lastpos = 1;
1218                         }
1219                 }
1220         }
1221
1222         *cp = '\0';
1223         return (0);
1224 }
1225
1226 static char *cli_prompt(EditLine *el)
1227 {
1228         static char prompt[200];
1229         char *pfmt;
1230         int color_used=0;
1231         char term_code[20];
1232
1233         if ((pfmt = getenv("ASTERISK_PROMPT"))) {
1234                 char *t = pfmt, *p = prompt;
1235                 memset(prompt, 0, sizeof(prompt));
1236                 while (*t != '\0' && *p < sizeof(prompt)) {
1237                         if (*t == '%') {
1238                                 char hostname[MAXHOSTNAMELEN]="";
1239                                 int i;
1240                                 struct timeval tv;
1241                                 struct tm tm;
1242 #ifdef linux
1243                                 FILE *LOADAVG;
1244 #endif
1245                                 int fgcolor = COLOR_WHITE, bgcolor = COLOR_BLACK;
1246
1247                                 t++;
1248                                 switch (*t) {
1249                                         case 'C': /* color */
1250                                                 t++;
1251                                                 if (sscanf(t, "%d;%d%n", &fgcolor, &bgcolor, &i) == 2) {
1252                                                         strncat(p, term_color_code(term_code, fgcolor, bgcolor, sizeof(term_code)),sizeof(prompt) - strlen(prompt) - 1);
1253                                                         t += i - 1;
1254                                                 } else if (sscanf(t, "%d%n", &fgcolor, &i) == 1) {
1255                                                         strncat(p, term_color_code(term_code, fgcolor, 0, sizeof(term_code)),sizeof(prompt) - strlen(prompt) - 1);
1256                                                         t += i - 1;
1257                                                 }
1258
1259                                                 /* If the color has been reset correctly, then there's no need to reset it later */
1260                                                 if ((fgcolor == COLOR_WHITE) && (bgcolor == COLOR_BLACK)) {
1261                                                         color_used = 0;
1262                                                 } else {
1263                                                         color_used = 1;
1264                                                 }
1265                                                 break;
1266                                         case 'd': /* date */
1267                                                 memset(&tm, 0, sizeof(struct tm));
1268                                                 tv = ast_tvnow();
1269                                                 if (localtime_r(&(tv.tv_sec), &tm)) {
1270                                                         strftime(p, sizeof(prompt) - strlen(prompt), "%Y-%m-%d", &tm);
1271                                                 }
1272                                                 break;
1273                                         case 'h': /* hostname */
1274                                                 if (!gethostname(hostname, sizeof(hostname) - 1)) {
1275                                                         strncat(p, hostname, sizeof(prompt) - strlen(prompt) - 1);
1276                                                 } else {
1277                                                         strncat(p, "localhost", sizeof(prompt) - strlen(prompt) - 1);
1278                                                 }
1279                                                 break;
1280                                         case 'H': /* short hostname */
1281                                                 if (!gethostname(hostname, sizeof(hostname) - 1)) {
1282                                                         for (i=0;i<sizeof(hostname);i++) {
1283                                                                 if (hostname[i] == '.') {
1284                                                                         hostname[i] = '\0';
1285                                                                         break;
1286                                                                 }
1287                                                         }
1288                                                         strncat(p, hostname, sizeof(prompt) - strlen(prompt) - 1);
1289                                                 } else {
1290                                                         strncat(p, "localhost", sizeof(prompt) - strlen(prompt) - 1);
1291                                                 }
1292                                                 break;
1293 #ifdef linux
1294                                         case 'l': /* load avg */
1295                                                 t++;
1296                                                 if ((LOADAVG = fopen("/proc/loadavg", "r"))) {
1297                                                         float avg1, avg2, avg3;
1298                                                         int actproc, totproc, npid, which;
1299                                                         fscanf(LOADAVG, "%f %f %f %d/%d %d",
1300                                                                 &avg1, &avg2, &avg3, &actproc, &totproc, &npid);
1301                                                         if (sscanf(t, "%d", &which) == 1) {
1302                                                                 switch (which) {
1303                                                                         case 1:
1304                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg1);
1305                                                                                 break;
1306                                                                         case 2:
1307                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg2);
1308                                                                                 break;
1309                                                                         case 3:
1310                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg3);
1311                                                                                 break;
1312                                                                         case 4:
1313                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%d/%d", actproc, totproc);
1314                                                                                 break;
1315                                                                         case 5:
1316                                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%d", npid);
1317                                                                                 break;
1318                                                                 }
1319                                                         }
1320                                                 }
1321                                                 break;
1322 #endif
1323                                         case 't': /* time */
1324                                                 memset(&tm, 0, sizeof(struct tm));
1325                                                 tv = ast_tvnow();
1326                                                 if (localtime_r(&(tv.tv_sec), &tm)) {
1327                                                         strftime(p, sizeof(prompt) - strlen(prompt), "%H:%M:%S", &tm);
1328                                                 }
1329                                                 break;
1330                                         case '#': /* process console or remote? */
1331                                                 if (! option_remote) {
1332                                                         strncat(p, "#", sizeof(prompt) - strlen(prompt) - 1);
1333                                                 } else {
1334                                                         strncat(p, ">", sizeof(prompt) - strlen(prompt) - 1);
1335                                                 }
1336                                                 break;
1337                                         case '%': /* literal % */
1338                                                 strncat(p, "%", sizeof(prompt) - strlen(prompt) - 1);
1339                                                 break;
1340                                         case '\0': /* % is last character - prevent bug */
1341                                                 t--;
1342                                                 break;
1343                                 }
1344                                 while (*p != '\0') {
1345                                         p++;
1346                                 }
1347                                 t++;
1348                         } else {
1349                                 *p = *t;
1350                                 p++;
1351                                 t++;
1352                         }
1353                 }
1354                 if (color_used) {
1355                         /* Force colors back to normal at end */
1356                         term_color_code(term_code, COLOR_WHITE, COLOR_BLACK, sizeof(term_code));
1357                         if (strlen(term_code) > sizeof(prompt) - strlen(prompt)) {
1358                                 strncat(prompt + sizeof(prompt) - strlen(term_code) - 1, term_code, strlen(term_code));
1359                         } else {
1360                                 strncat(p, term_code, sizeof(term_code));
1361                         }
1362                 }
1363         } else if (remotehostname)
1364                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT2, remotehostname);
1365         else
1366                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT);
1367
1368         return(prompt); 
1369 }
1370
1371 static char **ast_el_strtoarr(char *buf)
1372 {
1373         char **match_list = NULL, *retstr;
1374         size_t match_list_len;
1375         int matches = 0;
1376
1377         match_list_len = 1;
1378         while ( (retstr = strsep(&buf, " ")) != NULL) {
1379
1380                 if (!strcmp(retstr, AST_CLI_COMPLETE_EOF))
1381                         break;
1382                 if (matches + 1 >= match_list_len) {
1383                         match_list_len <<= 1;
1384                         match_list = realloc(match_list, match_list_len * sizeof(char *));
1385                 }
1386
1387                 match_list[matches++] = strdup(retstr);
1388         }
1389
1390         if (!match_list)
1391                 return (char **) NULL;
1392
1393         if (matches>= match_list_len)
1394                 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
1395
1396         match_list[matches] = (char *) NULL;
1397
1398         return match_list;
1399 }
1400
1401 static int ast_el_sort_compare(const void *i1, const void *i2)
1402 {
1403         char *s1, *s2;
1404
1405         s1 = ((char **)i1)[0];
1406         s2 = ((char **)i2)[0];
1407
1408         return strcasecmp(s1, s2);
1409 }
1410
1411 static int ast_cli_display_match_list(char **matches, int len, int max)
1412 {
1413         int i, idx, limit, count;
1414         int screenwidth = 0;
1415         int numoutput = 0, numoutputline = 0;
1416
1417         screenwidth = ast_get_termcols(STDOUT_FILENO);
1418
1419         /* find out how many entries can be put on one line, with two spaces between strings */
1420         limit = screenwidth / (max + 2);
1421         if (limit == 0)
1422                 limit = 1;
1423
1424         /* how many lines of output */
1425         count = len / limit;
1426         if (count * limit < len)
1427                 count++;
1428
1429         idx = 1;
1430
1431         qsort(&matches[0], (size_t)(len + 1), sizeof(char *), ast_el_sort_compare);
1432
1433         for (; count > 0; count--) {
1434                 numoutputline = 0;
1435                 for (i=0; i < limit && matches[idx]; i++, idx++) {
1436
1437                         /* Don't print dupes */
1438                         if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
1439                                 i--;
1440                                 free(matches[idx]);
1441                                 matches[idx] = NULL;
1442                                 continue;
1443                         }
1444
1445                         numoutput++;
1446                         numoutputline++;
1447                         fprintf(stdout, "%-*s  ", max, matches[idx]);
1448                         free(matches[idx]);
1449                         matches[idx] = NULL;
1450                 }
1451                 if (numoutputline > 0)
1452                         fprintf(stdout, "\n");
1453         }
1454
1455         return numoutput;
1456 }
1457
1458
1459 static char *cli_complete(EditLine *el, int ch)
1460 {
1461         int len=0;
1462         char *ptr;
1463         int nummatches = 0;
1464         char **matches;
1465         int retval = CC_ERROR;
1466         char buf[2048];
1467         int res;
1468
1469         LineInfo *lf = (LineInfo *)el_line(el);
1470
1471         *(char *)lf->cursor = '\0';
1472         ptr = (char *)lf->cursor;
1473         if (ptr) {
1474                 while (ptr > lf->buffer) {
1475                         if (isspace(*ptr)) {
1476                                 ptr++;
1477                                 break;
1478                         }
1479                         ptr--;
1480                 }
1481         }
1482
1483         len = lf->cursor - ptr;
1484
1485         if (option_remote) {
1486                 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr); 
1487                 fdprint(ast_consock, buf);
1488                 res = read(ast_consock, buf, sizeof(buf));
1489                 buf[res] = '\0';
1490                 nummatches = atoi(buf);
1491
1492                 if (nummatches > 0) {
1493                         char *mbuf;
1494                         int mlen = 0, maxmbuf = 2048;
1495                         /* Start with a 2048 byte buffer */
1496                         mbuf = malloc(maxmbuf);
1497                         if (!mbuf)
1498                                 return (char *)(CC_ERROR);
1499                         snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr); 
1500                         fdprint(ast_consock, buf);
1501                         res = 0;
1502                         mbuf[0] = '\0';
1503                         while (!strstr(mbuf, AST_CLI_COMPLETE_EOF) && res != -1) {
1504                                 if (mlen + 1024 > maxmbuf) {
1505                                         /* Every step increment buffer 1024 bytes */
1506                                         maxmbuf += 1024;
1507                                         mbuf = realloc(mbuf, maxmbuf);
1508                                         if (!mbuf)
1509                                                 return (char *)(CC_ERROR);
1510                                 }
1511                                 /* Only read 1024 bytes at a time */
1512                                 res = read(ast_consock, mbuf + mlen, 1024);
1513                                 if (res > 0)
1514                                         mlen += res;
1515                         }
1516                         mbuf[mlen] = '\0';
1517
1518                         matches = ast_el_strtoarr(mbuf);
1519                         free(mbuf);
1520                 } else
1521                         matches = (char **) NULL;
1522
1523
1524         } else {
1525
1526                 nummatches = ast_cli_generatornummatches((char *)lf->buffer,ptr);
1527                 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
1528         }
1529
1530         if (matches) {
1531                 int i;
1532                 int matches_num, maxlen, match_len;
1533
1534                 if (matches[0][0] != '\0') {
1535                         el_deletestr(el, (int) len);
1536                         el_insertstr(el, matches[0]);
1537                         retval = CC_REFRESH;
1538                 }
1539
1540                 if (nummatches == 1) {
1541                         /* Found an exact match */
1542                         el_insertstr(el, " ");
1543                         retval = CC_REFRESH;
1544                 } else {
1545                         /* Must be more than one match */
1546                         for (i=1, maxlen=0; matches[i]; i++) {
1547                                 match_len = strlen(matches[i]);
1548                                 if (match_len > maxlen)
1549                                         maxlen = match_len;
1550                         }
1551                         matches_num = i - 1;
1552                         if (matches_num >1) {
1553                                 fprintf(stdout, "\n");
1554                                 ast_cli_display_match_list(matches, nummatches, maxlen);
1555                                 retval = CC_REDISPLAY;
1556                         } else { 
1557                                 el_insertstr(el," ");
1558                                 retval = CC_REFRESH;
1559                         }
1560                 }
1561         free(matches);
1562         }
1563
1564         return (char *)(long)retval;
1565 }
1566
1567 static int ast_el_initialize(void)
1568 {
1569         HistEvent ev;
1570         char *editor = getenv("AST_EDITOR");
1571
1572         if (el != NULL)
1573                 el_end(el);
1574         if (el_hist != NULL)
1575                 history_end(el_hist);
1576
1577         el = el_init("asterisk", stdin, stdout, stderr);
1578         el_set(el, EL_PROMPT, cli_prompt);
1579
1580         el_set(el, EL_EDITMODE, 1);             
1581         el_set(el, EL_EDITOR, editor ? editor : "emacs");               
1582         el_hist = history_init();
1583         if (!el || !el_hist)
1584                 return -1;
1585
1586         /* setup history with 100 entries */
1587         history(el_hist, &ev, H_SETSIZE, 100);
1588
1589         el_set(el, EL_HIST, history, el_hist);
1590
1591         el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
1592         /* Bind <tab> to command completion */
1593         el_set(el, EL_BIND, "^I", "ed-complete", NULL);
1594         /* Bind ? to command completion */
1595         el_set(el, EL_BIND, "?", "ed-complete", NULL);
1596         /* Bind ^D to redisplay */
1597         el_set(el, EL_BIND, "^D", "ed-redisplay", NULL);
1598
1599         return 0;
1600 }
1601
1602 static int ast_el_add_history(char *buf)
1603 {
1604         HistEvent ev;
1605
1606         if (el_hist == NULL || el == NULL)
1607                 ast_el_initialize();
1608         if (strlen(buf) > 256)
1609                 return 0;
1610         return (history(el_hist, &ev, H_ENTER, buf));
1611 }
1612
1613 static int ast_el_write_history(char *filename)
1614 {
1615         HistEvent ev;
1616
1617         if (el_hist == NULL || el == NULL)
1618                 ast_el_initialize();
1619
1620         return (history(el_hist, &ev, H_SAVE, filename));
1621 }
1622
1623 static int ast_el_read_history(char *filename)
1624 {
1625         char buf[256];
1626         FILE *f;
1627         int ret = -1;
1628
1629         if (el_hist == NULL || el == NULL)
1630                 ast_el_initialize();
1631
1632         if ((f = fopen(filename, "r")) == NULL)
1633                 return ret;
1634
1635         while (!feof(f)) {
1636                 fgets(buf, sizeof(buf), f);
1637                 if (!strcmp(buf, "_HiStOrY_V2_\n"))
1638                         continue;
1639                 if (ast_all_zeros(buf))
1640                         continue;
1641                 if ((ret = ast_el_add_history(buf)) == -1)
1642                         break;
1643         }
1644         fclose(f);
1645
1646         return ret;
1647 }
1648
1649 static void ast_remotecontrol(char * data)
1650 {
1651         char buf[80];
1652         int res;
1653         char filename[80] = "";
1654         char *hostname;
1655         char *cpid;
1656         char *version;
1657         int pid;
1658         char tmp[80];
1659         char *stringp=NULL;
1660
1661         char *ebuf;
1662         int num = 0;
1663
1664         read(ast_consock, buf, sizeof(buf));
1665         if (data)
1666                 write(ast_consock, data, strlen(data) + 1);
1667         stringp=buf;
1668         hostname = strsep(&stringp, "/");
1669         cpid = strsep(&stringp, "/");
1670         version = strsep(&stringp, "\n");
1671         if (!version)
1672                 version = "<Version Unknown>";
1673         stringp=hostname;
1674         strsep(&stringp, ".");
1675         if (cpid)
1676                 pid = atoi(cpid);
1677         else
1678                 pid = -1;
1679         snprintf(tmp, sizeof(tmp), "set verbose atleast %d", option_verbose);
1680         fdprint(ast_consock, tmp);
1681         snprintf(tmp, sizeof(tmp), "set debug atleast %d", option_debug);
1682         fdprint(ast_consock, tmp);
1683         ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
1684         remotehostname = hostname;
1685         if (getenv("HOME")) 
1686                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1687         if (el_hist == NULL || el == NULL)
1688                 ast_el_initialize();
1689
1690         el_set(el, EL_GETCFN, ast_el_read_char);
1691
1692         if (!ast_strlen_zero(filename))
1693                 ast_el_read_history(filename);
1694
1695         if (option_exec && data) {  /* hack to print output then exit if asterisk -rx is used */
1696                 char tempchar;
1697                 struct pollfd fds[0];
1698                 fds[0].fd = ast_consock;
1699                 fds[0].events = POLLIN;
1700                 fds[0].revents = 0;
1701                 while(poll(fds, 1, 100) > 0) {
1702                         ast_el_read_char(el, &tempchar);
1703                 }
1704                 return;
1705         }
1706         for(;;) {
1707                 ebuf = (char *)el_gets(el, &num);
1708
1709                 if (!ast_strlen_zero(ebuf)) {
1710                         if (ebuf[strlen(ebuf)-1] == '\n')
1711                                 ebuf[strlen(ebuf)-1] = '\0';
1712                         if (!remoteconsolehandler(ebuf)) {
1713                                 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
1714                                 if (res < 1) {
1715                                         ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
1716                                         break;
1717                                 }
1718                         }
1719                 }
1720         }
1721         printf("\nDisconnected from Asterisk server\n");
1722 }
1723
1724 static int show_version(void)
1725 {
1726         printf("Asterisk " ASTERISK_VERSION "\n");
1727         return 0;
1728 }
1729
1730 static int show_cli_help(void) {
1731         printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 2000 - 2005, Digium.\n");
1732         printf("Usage: asterisk [OPTIONS]\n");
1733         printf("Valid Options:\n");
1734         printf("   -V              Display version number and exit\n");
1735         printf("   -C <configfile> Use an alternate configuration file\n");
1736         printf("   -G <group>      Run as a group other than the caller\n");
1737         printf("   -U <user>       Run as a user other than the caller\n");
1738         printf("   -c              Provide console CLI\n");
1739         printf("   -d              Enable extra debugging\n");
1740         printf("   -f              Do not fork\n");
1741         printf("   -g              Dump core in case of a crash\n");
1742         printf("   -h              This help screen\n");
1743         printf("   -i              Initialize crypto keys at startup\n");
1744         printf("   -n              Disable console colorization\n");
1745         printf("   -p              Run as pseudo-realtime thread\n");
1746         printf("   -q              Quiet mode (suppress output)\n");
1747         printf("   -r              Connect to Asterisk on this machine\n");
1748         printf("   -R              Connect to Asterisk, and attempt to reconnect if disconnected\n");
1749         printf("   -t              Record soundfiles in /var/tmp and move them where they belong after they are done.\n");
1750         printf("   -T              Display the time in [Mmm dd hh:mm:ss] format for each line of output to the CLI.\n");
1751         printf("   -v              Increase verbosity (multiple v's = more verbose)\n");
1752         printf("   -x <cmd>        Execute command <cmd> (only valid with -r)\n");
1753         printf("\n");
1754         return 0;
1755 }
1756
1757 static void ast_readconfig(void) {
1758         struct ast_config *cfg;
1759         struct ast_variable *v;
1760         char *config = AST_CONFIG_FILE;
1761
1762         if (option_overrideconfig == 1) {
1763                 cfg = ast_config_load(ast_config_AST_CONFIG_FILE);
1764                 if (!cfg)
1765                         ast_log(LOG_WARNING, "Unable to open specified master config file '%s', using built-in defaults\n", ast_config_AST_CONFIG_FILE);
1766         } else {
1767                 cfg = ast_config_load(config);
1768         }
1769
1770         /* init with buildtime config */
1771         ast_copy_string(ast_config_AST_CONFIG_DIR, AST_CONFIG_DIR, sizeof(ast_config_AST_CONFIG_DIR));
1772         ast_copy_string(ast_config_AST_SPOOL_DIR, AST_SPOOL_DIR, sizeof(ast_config_AST_SPOOL_DIR));
1773         ast_copy_string(ast_config_AST_MODULE_DIR, AST_MODULE_DIR, sizeof(ast_config_AST_VAR_DIR));
1774         snprintf(ast_config_AST_MONITOR_DIR, sizeof(ast_config_AST_MONITOR_DIR) - 1, "%s/monitor", ast_config_AST_SPOOL_DIR);
1775         ast_copy_string(ast_config_AST_VAR_DIR, AST_VAR_DIR, sizeof(ast_config_AST_VAR_DIR));
1776         ast_copy_string(ast_config_AST_LOG_DIR, AST_LOG_DIR, sizeof(ast_config_AST_LOG_DIR));
1777         ast_copy_string(ast_config_AST_AGI_DIR, AST_AGI_DIR, sizeof(ast_config_AST_AGI_DIR));
1778         ast_copy_string(ast_config_AST_DB, AST_DB, sizeof(ast_config_AST_DB));
1779         ast_copy_string(ast_config_AST_KEY_DIR, AST_KEY_DIR, sizeof(ast_config_AST_KEY_DIR));
1780         ast_copy_string(ast_config_AST_PID, AST_PID, sizeof(ast_config_AST_PID));
1781         ast_copy_string(ast_config_AST_SOCKET, AST_SOCKET, sizeof(ast_config_AST_SOCKET));
1782         ast_copy_string(ast_config_AST_RUN_DIR, AST_RUN_DIR, sizeof(ast_config_AST_RUN_DIR));
1783
1784         /* no asterisk.conf? no problem, use buildtime config! */
1785         if (!cfg) {
1786                 return;
1787         }
1788         v = ast_variable_browse(cfg, "files");
1789         while (v) {
1790                 if (!strcasecmp(v->name, "astctlpermissions")) {
1791                         ast_copy_string(ast_config_AST_CTL_PERMISSIONS, v->value, sizeof(ast_config_AST_CTL_PERMISSIONS));
1792                 } else if (!strcasecmp(v->name, "astctlowner")) {
1793                         ast_copy_string(ast_config_AST_CTL_OWNER, v->value, sizeof(ast_config_AST_CTL_OWNER));
1794                 } else if (!strcasecmp(v->name, "astctlgroup")) {
1795                         ast_copy_string(ast_config_AST_CTL_GROUP, v->value, sizeof(ast_config_AST_CTL_GROUP));
1796                 } else if (!strcasecmp(v->name, "astctl")) {
1797                         ast_copy_string(ast_config_AST_CTL, v->value, sizeof(ast_config_AST_CTL));
1798                 }
1799                 v = v->next;
1800         }
1801         v = ast_variable_browse(cfg, "directories");
1802         while(v) {
1803                 if (!strcasecmp(v->name, "astetcdir")) {
1804                         ast_copy_string(ast_config_AST_CONFIG_DIR, v->value, sizeof(ast_config_AST_CONFIG_DIR));
1805                 } else if (!strcasecmp(v->name, "astspooldir")) {
1806                         ast_copy_string(ast_config_AST_SPOOL_DIR, v->value, sizeof(ast_config_AST_SPOOL_DIR));
1807                         snprintf(ast_config_AST_MONITOR_DIR, sizeof(ast_config_AST_MONITOR_DIR) - 1, "%s/monitor", v->value);
1808                 } else if (!strcasecmp(v->name, "astvarlibdir")) {
1809                         ast_copy_string(ast_config_AST_VAR_DIR, v->value, sizeof(ast_config_AST_VAR_DIR));
1810                         snprintf(ast_config_AST_DB, sizeof(ast_config_AST_DB), "%s/%s", v->value, "astdb");    
1811                 } else if (!strcasecmp(v->name, "astlogdir")) {
1812                         ast_copy_string(ast_config_AST_LOG_DIR, v->value, sizeof(ast_config_AST_LOG_DIR));
1813                 } else if (!strcasecmp(v->name, "astagidir")) {
1814                         ast_copy_string(ast_config_AST_AGI_DIR, v->value, sizeof(ast_config_AST_AGI_DIR));
1815                 } else if (!strcasecmp(v->name, "astrundir")) {
1816                         snprintf(ast_config_AST_PID, sizeof(ast_config_AST_PID), "%s/%s", v->value, "asterisk.pid");
1817                         snprintf(ast_config_AST_SOCKET, sizeof(ast_config_AST_SOCKET), "%s/%s", v->value, ast_config_AST_CTL);
1818                         ast_copy_string(ast_config_AST_RUN_DIR, v->value, sizeof(ast_config_AST_RUN_DIR));
1819                 } else if (!strcasecmp(v->name, "astmoddir")) {
1820                         ast_copy_string(ast_config_AST_MODULE_DIR, v->value, sizeof(ast_config_AST_MODULE_DIR));
1821                 }
1822                 v = v->next;
1823         }
1824         v = ast_variable_browse(cfg, "options");
1825         while(v) {
1826                 /* verbose level (-v at startup) */
1827                 if (!strcasecmp(v->name, "verbose")) {
1828                         option_verbose = atoi(v->value);
1829                 /* whether or not to force timestamping. (-T at startup) */
1830                 } else if (!strcasecmp(v->name, "timestamp")) {
1831                         option_timestamp = ast_true(v->value);
1832                 /* whether or not to support #exec in config files */
1833                 } else if (!strcasecmp(v->name, "execincludes")) {
1834                         option_exec_includes = ast_true(v->value);
1835                 /* debug level (-d at startup) */
1836                 } else if (!strcasecmp(v->name, "debug")) {
1837                         option_debug = 0;
1838                         if (sscanf(v->value, "%d", &option_debug) != 1) {
1839                                 option_debug = ast_true(v->value);
1840                         }
1841                 /* Disable forking (-f at startup) */
1842                 } else if (!strcasecmp(v->name, "nofork")) {
1843                         option_nofork = ast_true(v->value);
1844                 /* Run quietly (-q at startup ) */
1845                 } else if (!strcasecmp(v->name, "quiet")) {
1846                         option_quiet = ast_true(v->value);
1847                 /* Run as console (-c at startup, implies nofork) */
1848                 } else if (!strcasecmp(v->name, "console")) {
1849                         option_console = ast_true(v->value);
1850                 /* Run with highg priority if the O/S permits (-p at startup) */
1851                 } else if (!strcasecmp(v->name, "highpriority")) {
1852                         option_highpriority = ast_true(v->value);
1853                 /* Initialize RSA auth keys (IAX2) (-i at startup) */
1854                 } else if (!strcasecmp(v->name, "initcrypto")) {
1855                         option_initcrypto = ast_true(v->value);
1856                 /* Disable ANSI colors for console (-c at startup) */
1857                 } else if (!strcasecmp(v->name, "nocolor")) {
1858                         option_nocolor = ast_true(v->value);
1859                 /* Disable some usage warnings for picky people :p */
1860                 } else if (!strcasecmp(v->name, "dontwarn")) {
1861                         option_dontwarn = ast_true(v->value);
1862                 /* Dump core in case of crash (-g) */
1863                 } else if (!strcasecmp(v->name, "dumpcore")) {
1864                         option_dumpcore = ast_true(v->value);
1865                 /* Cache recorded sound files to another directory during recording */
1866                 } else if (!strcasecmp(v->name, "cache_record_files")) {
1867                         option_cache_record_files = ast_true(v->value);
1868                 /* Specify cache directory */
1869                 }  else if (!strcasecmp(v->name, "record_cache_dir")) {
1870                         ast_copy_string(record_cache_dir, v->value, AST_CACHE_DIR_LEN);
1871                 /* Build transcode paths via SLINEAR, instead of directly */
1872                 } else if (!strcasecmp(v->name, "transcode_via_sln")) {
1873                         option_transcode_slin = ast_true(v->value);
1874                 /* Transmit SLINEAR silence while a channel is being recorded */
1875                 } else if (!strcasecmp(v->name, "transmit_silence_during_record")) {
1876                         option_transmit_silence_during_record = ast_true(v->value);
1877                 } else if (!strcasecmp(v->name, "maxcalls")) {
1878                         if ((sscanf(v->value, "%d", &option_maxcalls) != 1) || (option_maxcalls < 0)) {
1879                                 option_maxcalls = 0;
1880                         }
1881                 } else if (!strcasecmp(v->name, "maxload")) {
1882                         double test[1];
1883
1884                         if (getloadavg(test, 1) == -1) {
1885                                 ast_log(LOG_ERROR, "Cannot obtain load average on this system. 'maxload' option disabled.\n");
1886                                 option_maxload = 0.0;
1887                         } else if ((sscanf(v->value, "%lf", &option_maxload) != 1) || (option_maxload < 0.0)) {
1888                                 option_maxload = 0.0;
1889                         }
1890                 /* What user to run as */
1891                 } else if (!strcasecmp(v->name, "runuser")) {
1892                         ast_copy_string(ast_config_AST_RUN_USER, v->value, sizeof(ast_config_AST_RUN_USER));
1893                 /* What group to run as */
1894                 } else if (!strcasecmp(v->name, "rungroup")) {
1895                         ast_copy_string(ast_config_AST_RUN_GROUP, v->value, sizeof(ast_config_AST_RUN_GROUP));
1896                 }
1897                 v = v->next;
1898         }
1899         ast_config_destroy(cfg);
1900 }
1901
1902 int main(int argc, char *argv[])
1903 {
1904         int c;
1905         char filename[80] = "";
1906         char hostname[MAXHOSTNAMELEN]="";
1907         char tmp[80];
1908         char * xarg = NULL;
1909         int x;
1910         FILE *f;
1911         sigset_t sigs;
1912         int num;
1913         int is_child_of_nonroot=0;
1914         char *buf;
1915         char *runuser=NULL, *rungroup=NULL;
1916
1917         /* Remember original args for restart */
1918         if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
1919                 fprintf(stderr, "Truncating argument size to %d\n", (int)(sizeof(_argv) / sizeof(_argv[0])) - 1);
1920                 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
1921         }
1922         for (x=0;x<argc;x++)
1923                 _argv[x] = argv[x];
1924         _argv[x] = NULL;
1925
1926         /* if the progname is rasterisk consider it a remote console */
1927         if (argv[0] && (strstr(argv[0], "rasterisk")) != NULL) {
1928                 option_remote++;
1929                 option_nofork++;
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                         option_nofork++;
1959                         break;
1960                 case 'c':
1961                         option_console++;
1962                         option_nofork++;
1963                         break;
1964                 case 'f':
1965                         option_nofork++;
1966                         break;
1967                 case 'n':
1968                         option_nocolor++;
1969                         break;
1970                 case 'r':
1971                         option_remote++;
1972                         option_nofork++;
1973                         break;
1974                 case 'R':
1975                         option_remote++;
1976                         option_nofork++;
1977                         option_reconnect++;
1978                         break;
1979                 case 'p':
1980                         option_highpriority++;
1981                         break;
1982                 case 'v':
1983                         option_verbose++;
1984                         option_nofork++;
1985                         break;
1986                 case 'M':
1987                         if ((sscanf(optarg, "%d", &option_maxcalls) != 1) || (option_maxcalls < 0))
1988                                 option_maxcalls = 0;
1989                         break;
1990                 case 'L':
1991                         if ((sscanf(optarg, "%lf", &option_maxload) != 1) || (option_maxload < 0.0))
1992                                 option_maxload = 0.0;
1993                         break;
1994                 case 'q':
1995                         option_quiet++;
1996                         break;
1997                 case 't':
1998                         option_cache_record_files++;
1999                         break;
2000                 case 'T':
2001                         option_timestamp++;
2002                         break;
2003                 case 'x':
2004                         option_exec++;
2005                         xarg = optarg;
2006                         break;
2007                 case 'C':
2008                         ast_copy_string((char *)ast_config_AST_CONFIG_FILE,optarg,sizeof(ast_config_AST_CONFIG_FILE));
2009                         option_overrideconfig++;
2010                         break;
2011                 case 'i':
2012                         option_initcrypto++;
2013                         break;
2014                 case'g':
2015                         option_dumpcore++;
2016                         break;
2017                 case 'h':
2018                         show_cli_help();
2019                         exit(0);
2020                 case 'V':
2021                         show_version();
2022                         exit(0);
2023                 case 'U':
2024                         runuser = optarg;
2025                         break;
2026                 case 'G':
2027                         rungroup = optarg;
2028                         break;
2029                 case '?':
2030                         exit(1);
2031                 }
2032         }
2033
2034         /* For remote connections, change the name of the remote connection.
2035          * We do this for the benefit of init scripts (which need to know if/when
2036          * the main asterisk process has died yet). */
2037         if (option_remote) {
2038                 strcpy(argv[0], "rasterisk");
2039                 for (x = 1; x < argc; x++) {
2040                         argv[x] = argv[0] + 10;
2041                 }
2042         }
2043
2044         if (option_dumpcore) {
2045                 struct rlimit l;
2046                 memset(&l, 0, sizeof(l));
2047                 l.rlim_cur = RLIM_INFINITY;
2048                 l.rlim_max = RLIM_INFINITY;
2049                 if (setrlimit(RLIMIT_CORE, &l)) {
2050                         ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
2051                 }
2052         }
2053
2054         if (option_console && !option_verbose) 
2055                 ast_verbose("[ Reading Master Configuration ]");
2056         ast_readconfig();
2057
2058         if ((!rungroup) && !ast_strlen_zero(ast_config_AST_RUN_GROUP))
2059                 rungroup = ast_config_AST_RUN_GROUP;
2060         if ((!runuser) && !ast_strlen_zero(ast_config_AST_RUN_USER))
2061                 runuser = ast_config_AST_RUN_USER;
2062 #ifndef __CYGWIN__
2063
2064         if (!is_child_of_nonroot && ast_set_priority(option_highpriority)) {
2065                 exit(1);
2066         }
2067
2068         if (!is_child_of_nonroot && rungroup) {
2069                 struct group *gr;
2070                 gr = getgrnam(rungroup);
2071                 if (!gr) {
2072                         ast_log(LOG_WARNING, "No such group '%s'!\n", rungroup);
2073                         exit(1);
2074                 }
2075                 if (setgid(gr->gr_gid)) {
2076                         ast_log(LOG_WARNING, "Unable to setgid to %d (%s)\n", gr->gr_gid, rungroup);
2077                         exit(1);
2078                 }
2079                 if (setgroups(0, NULL)) {
2080                         ast_log(LOG_WARNING, "Unable to drop unneeded groups\n");
2081                         exit(1);
2082                 }
2083                 if (option_verbose)
2084                         ast_verbose("Running as group '%s'\n", rungroup);
2085         }
2086
2087         if (!is_child_of_nonroot && runuser) {
2088                 struct passwd *pw;
2089                 pw = getpwnam(runuser);
2090                 if (!pw) {
2091                         ast_log(LOG_WARNING, "No such user '%s'!\n", runuser);
2092                         exit(1);
2093                 }
2094                 if (setuid(pw->pw_uid)) {
2095                         ast_log(LOG_WARNING, "Unable to setuid to %d (%s)\n", pw->pw_uid, runuser);
2096                         exit(1);
2097                 }
2098                 setenv("ASTERISK_ALREADY_NONROOT","yes",1);
2099                 if (option_verbose)
2100                         ast_verbose("Running as user '%s'\n", runuser);
2101         }
2102
2103 #endif /* __CYGWIN__ */
2104
2105         term_init();
2106         printf(term_end());
2107         fflush(stdout);
2108
2109         if (option_console && !option_verbose) 
2110                 ast_verbose("[ Initializing Custom Configuration Options ]");
2111         /* custom config setup */
2112         register_config_cli();
2113         read_config_maps();
2114         
2115
2116         if (option_console) {
2117                 if (el_hist == NULL || el == NULL)
2118                         ast_el_initialize();
2119
2120                 if (!ast_strlen_zero(filename))
2121                         ast_el_read_history(filename);
2122         }
2123
2124         if (ast_tryconnect()) {
2125                 /* One is already running */
2126                 if (option_remote) {
2127                         if (option_exec) {
2128                                 ast_remotecontrol(xarg);
2129                                 quit_handler(0, 0, 0, 0);
2130                                 exit(0);
2131                         }
2132                         printf(term_quit());
2133                         ast_register_verbose(console_verboser);
2134                         WELCOME_MESSAGE;
2135                         ast_remotecontrol(NULL);
2136                         quit_handler(0, 0, 0, 0);
2137                         exit(0);
2138                 } else {
2139                         ast_log(LOG_ERROR, "Asterisk already running on %s.  Use 'asterisk -r' to connect.\n", (char *)ast_config_AST_SOCKET);
2140                         printf(term_quit());
2141                         exit(1);
2142                 }
2143         } else if (option_remote || option_exec) {
2144                 ast_log(LOG_ERROR, "Unable to connect to remote asterisk (does %s exist?)\n",ast_config_AST_SOCKET);
2145                 printf(term_quit());
2146                 exit(1);
2147         }
2148         /* Blindly write pid file since we couldn't connect */
2149         unlink((char *)ast_config_AST_PID);
2150         f = fopen((char *)ast_config_AST_PID, "w");
2151         if (f) {
2152                 fprintf(f, "%d\n", getpid());
2153                 fclose(f);
2154         } else
2155                 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
2156
2157         if (!option_verbose && !option_debug && !option_nofork && !option_console) {
2158                 daemon(0,0);
2159                 /* Blindly re-write pid file since we are forking */
2160                 unlink((char *)ast_config_AST_PID);
2161                 f = fopen((char *)ast_config_AST_PID, "w");
2162                 if (f) {
2163                         fprintf(f, "%d\n", getpid());
2164                         fclose(f);
2165                 } else
2166                         ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", (char *)ast_config_AST_PID, strerror(errno));
2167         }
2168
2169         /* Test recursive mutex locking. */
2170         if (test_for_thread_safety())
2171                 ast_verbose("Warning! Asterisk is not thread safe.\n");
2172
2173         ast_makesocket();
2174         sigemptyset(&sigs);
2175         sigaddset(&sigs, SIGHUP);
2176         sigaddset(&sigs, SIGTERM);
2177         sigaddset(&sigs, SIGINT);
2178         sigaddset(&sigs, SIGPIPE);
2179         sigaddset(&sigs, SIGWINCH);
2180         pthread_sigmask(SIG_BLOCK, &sigs, NULL);
2181         if (option_console || option_verbose || option_remote)
2182                 ast_register_verbose(console_verboser);
2183         /* Print a welcome message if desired */
2184         if (option_verbose || option_console) {
2185                 WELCOME_MESSAGE;
2186         }
2187         if (option_console && !option_verbose) 
2188                 ast_verbose("[ Booting...");
2189
2190         signal(SIGURG, urg_handler);
2191         signal(SIGINT, __quit_handler);
2192         signal(SIGTERM, __quit_handler);
2193         signal(SIGHUP, hup_handler);
2194         signal(SIGCHLD, child_handler);
2195         signal(SIGPIPE, SIG_IGN);
2196
2197         /* ensure that the random number generators are seeded with a different value every time
2198            Asterisk is started
2199         */
2200         srand((unsigned int) getpid() + (unsigned int) time(NULL));
2201         srandom((unsigned int) getpid() + (unsigned int) time(NULL));
2202
2203         if (init_logger()) {
2204                 printf(term_quit());
2205                 exit(1);
2206         }
2207         if (dnsmgr_init()) {
2208                 printf(term_quit());
2209                 exit(1);
2210         }
2211         /* load 'preload' modules, required for access to Realtime-mapped configuration files */
2212         if (load_modules(1)) {
2213                 printf(term_quit());
2214                 exit(1);
2215         }
2216         ast_channels_init();
2217         if (init_manager()) {
2218                 printf(term_quit());
2219                 exit(1);
2220         }
2221         if (ast_cdr_engine_init()) {
2222                 printf(term_quit());
2223                 exit(1);
2224         }
2225         if (ast_device_state_engine_init()) {
2226                 printf(term_quit());
2227                 exit(1);
2228         }
2229         ast_rtp_init();
2230         if (ast_image_init()) {
2231                 printf(term_quit());
2232                 exit(1);
2233         }
2234         if (ast_file_init()) {
2235                 printf(term_quit());
2236                 exit(1);
2237         }
2238         if (load_pbx()) {
2239                 printf(term_quit());
2240                 exit(1);
2241         }
2242         if (load_modules(0)) {
2243                 printf(term_quit());
2244                 exit(1);
2245         }
2246         if (init_framer()) {
2247                 printf(term_quit());
2248                 exit(1);
2249         }
2250         if (astdb_init()) {
2251                 printf(term_quit());
2252                 exit(1);
2253         }
2254         if (ast_enum_init()) {
2255                 printf(term_quit());
2256                 exit(1);
2257         }
2258
2259         dnsmgr_start_refresh();
2260
2261 #if 0
2262         /* This should no longer be necessary */
2263         /* sync cust config and reload some internals in case a custom config handler binded to them */
2264         read_ast_cust_config();
2265         reload_logger(0);
2266         reload_manager();
2267         ast_enum_reload();
2268         ast_rtp_reload();
2269 #endif
2270
2271
2272         /* We might have the option of showing a console, but for now just
2273            do nothing... */
2274         if (option_console && !option_verbose)
2275                 ast_verbose(" ]\n");
2276         if (option_verbose || option_console)
2277                 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
2278         if (option_nofork)
2279                 consolethread = pthread_self();
2280         fully_booted = 1;
2281         pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
2282 #ifdef __AST_DEBUG_MALLOC
2283         __ast_mm_init();
2284 #endif  
2285         time(&ast_startuptime);
2286         ast_cli_register_multiple(core_cli, sizeof(core_cli) / sizeof(core_cli[0]));
2287         if (option_console) {
2288                 /* Console stuff now... */
2289                 /* Register our quit function */
2290                 char title[256];
2291                 set_icon("Asterisk");
2292                 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %d)", hostname, ast_mainpid);
2293                 set_title(title);
2294
2295                 for (;;) {
2296                         buf = (char *)el_gets(el, &num);
2297                         if (buf) {
2298                                 if (buf[strlen(buf)-1] == '\n')
2299                                         buf[strlen(buf)-1] = '\0';
2300
2301                                 consolehandler((char *)buf);
2302                         } else {
2303                                 if (write(STDOUT_FILENO, "\nUse EXIT or QUIT to exit the asterisk console\n",
2304                                                                   strlen("\nUse EXIT or QUIT to exit the asterisk console\n")) < 0) {
2305                                         /* Whoa, stdout disappeared from under us... Make /dev/null's */
2306                                         int fd;
2307                                         fd = open("/dev/null", O_RDWR);
2308                                         if (fd > -1) {
2309                                                 dup2(fd, STDOUT_FILENO);
2310                                                 dup2(fd, STDIN_FILENO);
2311                                         } else
2312                                                 ast_log(LOG_WARNING, "Failed to open /dev/null to recover from dead console.  Bad things will happen!\n");
2313                                         break;
2314                                 }
2315                         }
2316                 }
2317
2318         }
2319         /* Do nothing */
2320         for(;;)  {      /* apparently needed for the MACos */
2321                 struct pollfd p = { -1 /* no descriptor */, 0, 0 };
2322                 poll(&p, 0, -1);
2323         }
2324         return 0;
2325 }