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