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