4f5ada9b0de1378638dcc8691f241f6d48fe13f6
[asterisk/asterisk.git] / main / asterisk.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, 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 - 2006, 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 "asterisk.h"
61
62 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
63
64 #undef sched_setscheduler
65 #undef setpriority
66 #include <unistd.h>
67 #include <stdlib.h>
68 #include <sys/time.h>
69 #include <fcntl.h>
70 #include <stdio.h>
71 #include <signal.h>
72 #include <sched.h>
73 #include <sys/socket.h>
74 #include <sys/un.h>
75 #include <sys/wait.h>
76 #include <string.h>
77 #include <errno.h>
78 #include <ctype.h>
79 #include <sys/resource.h>
80 #include <grp.h>
81 #include <pwd.h>
82 #include <sys/stat.h>
83 #if defined(HAVE_SYSINFO)
84 #include <sys/sysinfo.h>
85 #endif
86 #ifdef linux
87 #include <sys/prctl.h>
88 #ifdef HAVE_CAP
89 #include <sys/capability.h>
90 #endif /* HAVE_CAP */
91 #endif /* linux */
92 #include <regex.h>
93
94 #if  defined(__FreeBSD__) || defined( __NetBSD__ ) || defined(SOLARIS)
95 #include <netdb.h>
96 #if defined(SOLARIS)
97 int daemon(int, int);  /* defined in libresolv of all places */
98 #endif
99 #endif
100
101 #include "asterisk/logger.h"
102 #include "asterisk/options.h"
103 #include "asterisk/cli.h"
104 #include "asterisk/channel.h"
105 #include "asterisk/ulaw.h"
106 #include "asterisk/alaw.h"
107 #include "asterisk/callerid.h"
108 #include "asterisk/image.h"
109 #include "asterisk/tdd.h"
110 #include "asterisk/term.h"
111 #include "asterisk/manager.h"
112 #include "asterisk/cdr.h"
113 #include "asterisk/pbx.h"
114 #include "asterisk/enum.h"
115 #include "asterisk/rtp.h"
116 #include "asterisk/http.h"
117 #include "asterisk/udptl.h"
118 #include "asterisk/app.h"
119 #include "asterisk/lock.h"
120 #include "asterisk/utils.h"
121 #include "asterisk/file.h"
122 #include "asterisk/io.h"
123 #include "asterisk/lock.h"
124 #include "editline/histedit.h"
125 #include "asterisk/config.h"
126 #include "asterisk/version.h"
127 #include "asterisk/linkedlists.h"
128 #include "asterisk/devicestate.h"
129 #include "asterisk/module.h"
130
131 #include "asterisk/doxyref.h"           /* Doxygen documentation */
132
133 #include "../defaults.h"
134
135 #ifndef AF_LOCAL
136 #define AF_LOCAL AF_UNIX
137 #define PF_LOCAL PF_UNIX
138 #endif
139
140 #define AST_MAX_CONNECTS 128
141 #define NUM_MSGS 64
142
143 /*! \brief Welcome message when starting a CLI interface */
144 #define WELCOME_MESSAGE \
145     ast_verbose("Asterisk " ASTERISK_VERSION ", Copyright (C) 1999 - 2007 Digium, Inc. and others.\n" \
146                 "Created by Mark Spencer <markster@digium.com>\n" \
147                 "Asterisk comes with ABSOLUTELY NO WARRANTY; type 'core show warranty' for details.\n" \
148                 "This is free software, with components licensed under the GNU General Public\n" \
149                 "License version 2 and other licenses; you are welcome to redistribute it under\n" \
150                 "certain conditions. Type 'core show license' for details.\n" \
151                 "=========================================================================\n" \
152                 "NOTE: This is a development version of Asterisk, and should not be used in\n" \
153                 "production installations.\n");
154
155 /*! \defgroup main_options Main Configuration Options
156  \brief Main configuration options from \ref Config_ast "asterisk.conf" or 
157   the operating system command line when starting Asterisk 
158   Some of them can be changed in the CLI 
159  */
160 /*! @{ */
161
162 struct ast_flags ast_options = { AST_DEFAULT_OPTIONS };
163
164 int option_verbose;                             /*!< Verbosity level */
165 int option_debug;                               /*!< Debug level */
166
167 double option_maxload;                          /*!< Max load avg on system */
168 int option_maxcalls;                            /*!< Max number of active calls */
169 int option_maxfiles;                            /*!< Max number of open file handles (files, sockets) */
170 #if defined(HAVE_SYSINFO)
171 long option_minmemfree;                         /*!< Minimum amount of free system memory - stop accepting calls if free memory falls below this watermark */
172 #endif
173
174 /*! @} */
175
176 char record_cache_dir[AST_CACHE_DIR_LEN] = AST_TMP_DIR;
177 char debug_filename[AST_FILENAME_MAX] = "";
178
179 static int ast_socket = -1;             /*!< UNIX Socket for allowing remote control */
180 static int ast_consock = -1;            /*!< UNIX Socket for controlling another asterisk */
181 pid_t ast_mainpid;
182 struct console {
183         int fd;                         /*!< File descriptor */
184         int p[2];                       /*!< Pipe */
185         pthread_t t;                    /*!< Thread of handler */
186         int mute;                       /*!< Is the console muted for logs */
187 };
188
189 struct ast_atexit {
190         void (*func)(void);
191         AST_LIST_ENTRY(ast_atexit) list;
192 };
193
194 static AST_LIST_HEAD_STATIC(atexits, ast_atexit);
195
196 time_t ast_startuptime;
197 time_t ast_lastreloadtime;
198
199 static History *el_hist;
200 static EditLine *el;
201 static char *remotehostname;
202
203 struct console consoles[AST_MAX_CONNECTS];
204
205 char defaultlanguage[MAX_LANGUAGE] = DEFAULT_LANGUAGE;
206
207 static int ast_el_add_history(char *);
208 static int ast_el_read_history(char *);
209 static int ast_el_write_history(char *);
210
211 char ast_config_AST_CONFIG_DIR[PATH_MAX];
212 char ast_config_AST_CONFIG_FILE[PATH_MAX];
213 char ast_config_AST_MODULE_DIR[PATH_MAX];
214 char ast_config_AST_SPOOL_DIR[PATH_MAX];
215 char ast_config_AST_MONITOR_DIR[PATH_MAX];
216 char ast_config_AST_VAR_DIR[PATH_MAX];
217 char ast_config_AST_DATA_DIR[PATH_MAX];
218 char ast_config_AST_LOG_DIR[PATH_MAX];
219 char ast_config_AST_AGI_DIR[PATH_MAX];
220 char ast_config_AST_DB[PATH_MAX];
221 char ast_config_AST_KEY_DIR[PATH_MAX];
222 char ast_config_AST_PID[PATH_MAX];
223 char ast_config_AST_SOCKET[PATH_MAX];
224 char ast_config_AST_RUN_DIR[PATH_MAX];
225 char ast_config_AST_RUN_USER[PATH_MAX];
226 char ast_config_AST_RUN_GROUP[PATH_MAX];
227 char ast_config_AST_CTL_PERMISSIONS[PATH_MAX];
228 char ast_config_AST_CTL_OWNER[PATH_MAX] = "\0";
229 char ast_config_AST_CTL_GROUP[PATH_MAX] = "\0";
230 char ast_config_AST_CTL[PATH_MAX] = "asterisk.ctl";
231 char ast_config_AST_SYSTEM_NAME[20] = "";
232
233 extern const char *ast_build_hostname;
234 extern const char *ast_build_kernel;
235 extern const char *ast_build_machine;
236 extern const char *ast_build_os;
237 extern const char *ast_build_date;
238 extern const char *ast_build_user;
239
240 static char *_argv[256];
241 static int shuttingdown;
242 static int restartnow;
243 static pthread_t consolethread = AST_PTHREADT_NULL;
244
245 static char randompool[256];
246
247 static int sig_alert_pipe[2] = { -1, -1 };
248 static struct {
249          unsigned int need_reload:1;
250          unsigned int need_quit:1;
251 } sig_flags;
252
253 #if !defined(LOW_MEMORY)
254 struct file_version {
255         AST_LIST_ENTRY(file_version) list;
256         const char *file;
257         char *version;
258 };
259
260 static AST_LIST_HEAD_STATIC(file_versions, file_version);
261
262 void ast_register_file_version(const char *file, const char *version)
263 {
264         struct file_version *new;
265         char *work;
266         size_t version_length;
267
268         work = ast_strdupa(version);
269         work = ast_strip(ast_strip_quoted(work, "$", "$"));
270         version_length = strlen(work) + 1;
271         
272         if (!(new = ast_calloc(1, sizeof(*new) + version_length)))
273                 return;
274
275         new->file = file;
276         new->version = (char *) new + sizeof(*new);
277         memcpy(new->version, work, version_length);
278         AST_LIST_LOCK(&file_versions);
279         AST_LIST_INSERT_HEAD(&file_versions, new, list);
280         AST_LIST_UNLOCK(&file_versions);
281 }
282
283 void ast_unregister_file_version(const char *file)
284 {
285         struct file_version *find;
286
287         AST_LIST_LOCK(&file_versions);
288         AST_LIST_TRAVERSE_SAFE_BEGIN(&file_versions, find, list) {
289                 if (!strcasecmp(find->file, file)) {
290                         AST_LIST_REMOVE_CURRENT(&file_versions, list);
291                         break;
292                 }
293         }
294         AST_LIST_TRAVERSE_SAFE_END;
295         AST_LIST_UNLOCK(&file_versions);
296
297         if (find)
298                 ast_free(find);
299 }
300
301 struct thread_list_t {
302         AST_LIST_ENTRY(thread_list_t) list;
303         char *name;
304         pthread_t id;
305 };
306
307 static AST_LIST_HEAD_STATIC(thread_list, thread_list_t);
308
309 static const char show_threads_help[] =
310 "Usage: core show threads\n"
311 "       List threads currently active in the system.\n";
312
313 void ast_register_thread(char *name)
314
315         struct thread_list_t *new = ast_calloc(1, sizeof(*new));
316
317         if (!new)
318                 return;
319         new->id = pthread_self();
320         new->name = name; /* steal the allocated memory for the thread name */
321         AST_LIST_LOCK(&thread_list);
322         AST_LIST_INSERT_HEAD(&thread_list, new, list);
323         AST_LIST_UNLOCK(&thread_list);
324 }
325
326 void ast_unregister_thread(void *id)
327 {
328         struct thread_list_t *x;
329
330         AST_LIST_LOCK(&thread_list);
331         AST_LIST_TRAVERSE_SAFE_BEGIN(&thread_list, x, list) {
332                 if ((void *) x->id == id) {
333                         AST_LIST_REMOVE_CURRENT(&thread_list, list);
334                         break;
335                 }
336         }
337         AST_LIST_TRAVERSE_SAFE_END;
338         AST_LIST_UNLOCK(&thread_list);
339         if (x) {
340                 ast_free(x->name);
341                 ast_free(x);
342         }
343 }
344
345 /*! \brief Give an overview of core settings */
346 static int handle_show_settings(int fd, int argc, char *argv[])
347 {
348         char buf[BUFSIZ];
349         struct tm tm;
350
351         ast_cli(fd, "\nPBX Core settings\n");
352         ast_cli(fd, "-----------------\n");
353         ast_cli(fd, "  Version:                     %s\n", "" ASTERISK_VERSION "" );
354         if (option_maxcalls)
355                 ast_cli(fd, "  Max. calls:                  %d (Current %d)\n", option_maxcalls, ast_active_channels());
356         else
357                 ast_cli(fd, "  Max. calls:                  Not set\n");
358         if (option_maxfiles)
359                 ast_cli(fd, "  Max. open file handles:      %d\n", option_maxfiles); 
360         else
361                 ast_cli(fd, "  Max. open file handles:      Not set\n");
362         ast_cli(fd, "  Verbosity:                   %d\n", option_verbose);
363         ast_cli(fd, "  Debug level:                 %d\n", option_debug);
364         ast_cli(fd, "  Max load avg:                %lf\n", option_maxload);
365 #if defined(HAVE_SYSINFO)
366         ast_cli(fd, "  Min Free Memory:             %ld MB\n", option_minmemfree);
367 #endif
368         if (localtime_r(&ast_startuptime, &tm)) {
369                 strftime(buf, sizeof(buf), "%H:%M:%S", &tm);
370                 ast_cli(fd, "  Startup time:                %s\n", buf);
371         }
372         if (localtime_r(&ast_lastreloadtime, &tm)) {
373                 strftime(buf, sizeof(buf), "%H:%M:%S", &tm);
374                 ast_cli(fd, "  Last reload time:            %s\n", buf);
375         }
376         ast_cli(fd, "  System:                      %s/%s built by %s on %s %s\n", ast_build_os, ast_build_kernel, ast_build_user, ast_build_machine, ast_build_date);
377         ast_cli(fd, "  System name:                 %s\n", ast_config_AST_SYSTEM_NAME);
378         ast_cli(fd, "  Default language:            %s\n", defaultlanguage);
379         ast_cli(fd, "  Language prefix:             %s\n", ast_language_is_prefix ? "Enabled" : "Disabled");
380         ast_cli(fd, "  User name and group:         %s/%s\n", ast_config_AST_RUN_USER, ast_config_AST_RUN_GROUP);
381         ast_cli(fd, "  Executable includes:         %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_EXEC_INCLUDES) ? "Enabled" : "Disabled");
382         ast_cli(fd, "  Transcode via SLIN:          %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_TRANSCODE_VIA_SLIN) ? "Enabled" : "Disabled");
383         ast_cli(fd, "  Internal timing:             %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_INTERNAL_TIMING) ? "Enabled" : "Disabled");
384         ast_cli(fd, "  Transmit silence during rec: %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_INTERNAL_TIMING) ? "Enabled" : "Disabled");
385
386         ast_cli(fd, "\n* Subsystems\n");
387         ast_cli(fd, "  -------------\n");
388         ast_cli(fd, "  Manager (AMI):               %s\n", check_manager_enabled() ? "Enabled" : "Disabled");
389         ast_cli(fd, "  Web Manager (AMI/HTTP):      %s\n", check_webmanager_enabled() ? "Enabled" : "Disabled");
390         ast_cli(fd, "  Call data records:           %s\n", check_cdr_enabled() ? "Enabled" : "Disabled");
391         ast_cli(fd, "  Realtime Architecture (ARA): %s\n", ast_realtime_enabled() ? "Enabled" : "Disabled");
392
393         /*! \todo we could check musiconhold, voicemail, smdi, adsi, queues  */
394
395         ast_cli(fd, "\n* Directories\n");
396         ast_cli(fd, "  -------------\n");
397         ast_cli(fd, "  Configuration file:          %s\n", ast_config_AST_CONFIG_FILE);
398         ast_cli(fd, "  Configuration directory:     %s\n", ast_config_AST_CONFIG_DIR);
399         ast_cli(fd, "  Module directory:            %s\n", ast_config_AST_MODULE_DIR);
400         ast_cli(fd, "  Spool directory:             %s\n", ast_config_AST_SPOOL_DIR);
401         ast_cli(fd, "  Log directory:               %s\n", ast_config_AST_LOG_DIR);
402         ast_cli(fd, "\n\n");
403         return 0;
404 }
405
406 static int handle_show_threads(int fd, int argc, char *argv[])
407 {
408         int count = 0;
409         struct thread_list_t *cur;
410
411         AST_LIST_LOCK(&thread_list);
412         AST_LIST_TRAVERSE(&thread_list, cur, list) {
413                 ast_cli(fd, "%p %s\n", (void *)cur->id, cur->name);
414                 count++;
415         }
416         AST_LIST_UNLOCK(&thread_list);
417         ast_cli(fd, "%d threads listed.\n", count);
418         return 0;
419 }
420
421 #if defined(HAVE_SYSINFO)
422 static const char show_sysinfo_help[] =
423 "Usage: core show sysinfo\n"
424 "       List current system information.\n";
425
426 /*! \brief Give an overview of system statistics */
427 static int handle_show_sysinfo(int fd, int argc, char *argv[])
428 {
429         struct sysinfo sys_info;
430
431         if (sysinfo(&sys_info)) {
432                 ast_cli(fd, "FAILED to retrieve system information\n\n");
433                 return 0;
434         }
435         ast_cli(fd, "\nSystem Statistics\n");
436         ast_cli(fd, "-----------------\n");
437         ast_cli(fd, "  System Uptime:             %ld hours\n", sys_info.uptime/3600);
438         ast_cli(fd, "  Total RAM:                 %ld KiB\n", (sys_info.totalram / sys_info.mem_unit)/1024);
439         ast_cli(fd, "  Free RAM:                  %ld KiB\n", (sys_info.freeram / sys_info.mem_unit)/1024);
440         ast_cli(fd, "  Buffer RAM:                %ld KiB\n", (sys_info.bufferram / sys_info.mem_unit)/1024);
441         ast_cli(fd, "  Total Swap Space:          %ld KiB\n", (sys_info.totalswap / sys_info.mem_unit)/1024);
442         ast_cli(fd, "  Free Swap Space:           %ld KiB\n\n", (sys_info.freeswap / sys_info.mem_unit)/1024);
443         ast_cli(fd, "  Number of Processes:       %d \n\n", sys_info.procs);
444         return 0;
445 }
446 #endif
447
448 struct profile_entry {
449         const char *name;
450         uint64_t        scale;  /* if non-zero, values are scaled by this */
451         int64_t mark;
452         int64_t value;
453         int64_t events;
454 };
455
456 struct profile_data {
457         int entries;
458         int max_size;
459         struct profile_entry e[0];
460 };
461
462 static struct profile_data *prof_data;
463
464 /*! \brief allocates a counter with a given name and scale.
465  * \return Returns the identifier of the counter.
466  */
467 int ast_add_profile(const char *name, uint64_t scale)
468 {
469         int l = sizeof(struct profile_data);
470         int n = 10;     /* default entries */
471
472         if (prof_data == NULL) {
473                 prof_data = ast_calloc(1, l + n*sizeof(struct profile_entry));
474                 if (prof_data == NULL)
475                         return -1;
476                 prof_data->entries = 0;
477                 prof_data->max_size = n;
478         }
479         if (prof_data->entries >= prof_data->max_size) {
480                 void *p;
481                 n = prof_data->max_size + 20;
482                 p = ast_realloc(prof_data, l + n*sizeof(struct profile_entry));
483                 if (p == NULL)
484                         return -1;
485                 prof_data = p;
486                 prof_data->max_size = n;
487         }
488         n = prof_data->entries++;
489         prof_data->e[n].name = ast_strdup(name);
490         prof_data->e[n].value = 0;
491         prof_data->e[n].events = 0;
492         prof_data->e[n].mark = 0;
493         prof_data->e[n].scale = scale;
494         return n;
495 }
496
497 int64_t ast_profile(int i, int64_t delta)
498 {
499         if (!prof_data || i < 0 || i > prof_data->entries)      /* invalid index */
500                 return 0;
501         if (prof_data->e[i].scale > 1)
502                 delta /= prof_data->e[i].scale;
503         prof_data->e[i].value += delta;
504         prof_data->e[i].events++;
505         return prof_data->e[i].value;
506 }
507
508 #if defined ( __i386__) && (defined(__FreeBSD__) || defined(linux))
509 #if defined(__FreeBSD__)
510 #include <machine/cpufunc.h>
511 #elif defined(linux)
512 static __inline uint64_t
513 rdtsc(void)
514
515         uint64_t rv;
516
517         __asm __volatile(".byte 0x0f, 0x31" : "=A" (rv));
518         return (rv);
519 }
520 #endif
521 #else   /* supply a dummy function on other platforms */
522 static __inline uint64_t
523 rdtsc(void)
524 {
525         return 0;
526 }
527 #endif
528
529 int64_t ast_mark(int i, int startstop)
530 {
531         if (!prof_data || i < 0 || i > prof_data->entries) /* invalid index */
532                 return 0;
533         if (startstop == 1)
534                 prof_data->e[i].mark = rdtsc();
535         else {
536                 prof_data->e[i].mark = (rdtsc() - prof_data->e[i].mark);
537                 if (prof_data->e[i].scale > 1)
538                         prof_data->e[i].mark /= prof_data->e[i].scale;
539                 prof_data->e[i].value += prof_data->e[i].mark;
540                 prof_data->e[i].events++;
541         }
542         return prof_data->e[i].mark;
543 }
544
545 static int handle_show_profile(int fd, int argc, char *argv[])
546 {
547         int i, min, max;
548         char *search = NULL;
549
550         if (prof_data == NULL)
551                 return 0;
552
553         min = 0;
554         max = prof_data->entries;
555         if  (argc > 3) { /* specific entries */
556                 if (isdigit(argv[3][0])) {
557                         min = atoi(argv[3]);
558                         if (argc == 5 && strcmp(argv[4], "-"))
559                                 max = atoi(argv[4]);
560                 } else
561                         search = argv[3];
562         }
563         if (max > prof_data->entries)
564                 max = prof_data->entries;
565         if (!strcmp(argv[1], "clear")) {
566                 for (i= min; i < max; i++) {
567                         if (!search || strstr(prof_data->e[i].name, search)) {
568                                 prof_data->e[i].value = 0;
569                                 prof_data->e[i].events = 0;
570                         }
571                 }
572                 return 0;
573         }
574         ast_cli(fd, "profile values (%d, allocated %d)\n-------------------\n",
575                 prof_data->entries, prof_data->max_size);
576         ast_cli(fd, "%6s   %8s  %10s %12s %12s  %s\n", "ID", "Scale", "Events",
577                         "Value", "Average", "Name");
578         for (i = min; i < max; i++) {
579                 struct profile_entry *e = &prof_data->e[i];
580                 if (!search || strstr(prof_data->e[i].name, search))
581                     ast_cli(fd, "%6d: [%8ld] %10ld %12lld %12lld  %s\n",
582                         i,
583                         (long)e->scale,
584                         (long)e->events, (long long)e->value,
585                         (long long)(e->events ? e->value / e->events : e->value),
586                         e->name);
587         }
588         return 0;
589 }
590
591 static const char show_version_files_help[] = 
592 "Usage: core show file version [like <pattern>]\n"
593 "       Lists the revision numbers of the files used to build this copy of Asterisk.\n"
594 "       Optional regular expression pattern is used to filter the file list.\n";
595
596 /*! \brief CLI command to list module versions */
597 static int handle_show_version_files(int fd, int argc, char *argv[])
598 {
599 #define FORMAT "%-25.25s %-40.40s\n"
600         struct file_version *iterator;
601         regex_t regexbuf;
602         int havepattern = 0;
603         int havename = 0;
604         int count_files = 0;
605
606         switch (argc) {
607         case 6:
608                 if (!strcasecmp(argv[4], "like")) {
609                         if (regcomp(&regexbuf, argv[5], REG_EXTENDED | REG_NOSUB))
610                                 return RESULT_SHOWUSAGE;
611                         havepattern = 1;
612                 } else
613                         return RESULT_SHOWUSAGE;
614                 break;
615         case 5:
616                 havename = 1;
617                 break;
618         case 4:
619                 break;
620         default:
621                 return RESULT_SHOWUSAGE;
622         }
623
624         ast_cli(fd, FORMAT, "File", "Revision");
625         ast_cli(fd, FORMAT, "----", "--------");
626         AST_LIST_LOCK(&file_versions);
627         AST_LIST_TRAVERSE(&file_versions, iterator, list) {
628                 if (havename && strcasecmp(iterator->file, argv[4]))
629                         continue;
630
631                 if (havepattern && regexec(&regexbuf, iterator->file, 0, NULL, 0))
632                         continue;
633
634                 ast_cli(fd, FORMAT, iterator->file, iterator->version);
635                 count_files++;
636                 if (havename)
637                         break;
638         }
639         AST_LIST_UNLOCK(&file_versions);
640         if (!havename) {
641                 ast_cli(fd, "%d files listed.\n", count_files);
642         }
643
644         if (havepattern)
645                 regfree(&regexbuf);
646
647         return RESULT_SUCCESS;
648 #undef FORMAT
649 }
650
651 static char *complete_show_version_files(const char *line, const char *word, int pos, int state)
652 {
653         struct file_version *find;
654         int which = 0;
655         char *ret = NULL;
656         int matchlen = strlen(word);
657
658         if (pos != 3)
659                 return NULL;
660
661         AST_LIST_LOCK(&file_versions);
662         AST_LIST_TRAVERSE(&file_versions, find, list) {
663                 if (!strncasecmp(word, find->file, matchlen) && ++which > state) {
664                         ret = ast_strdup(find->file);
665                         break;
666                 }
667         }
668         AST_LIST_UNLOCK(&file_versions);
669
670         return ret;
671 }
672 #endif /* ! LOW_MEMORY */
673
674 int ast_register_atexit(void (*func)(void))
675 {
676         int res = -1;
677         struct ast_atexit *ae;
678         ast_unregister_atexit(func);    
679         AST_LIST_LOCK(&atexits);
680         if ((ae = ast_calloc(1, sizeof(*ae)))) {
681                 AST_LIST_INSERT_HEAD(&atexits, ae, list);
682                 ae->func = func;
683                 res = 0;
684         }
685         AST_LIST_UNLOCK(&atexits);
686         return res;
687 }
688
689 void ast_unregister_atexit(void (*func)(void))
690 {
691         struct ast_atexit *ae;
692         AST_LIST_LOCK(&atexits);
693         AST_LIST_TRAVERSE_SAFE_BEGIN(&atexits, ae, list) {
694                 if (ae->func == func) {
695                         AST_LIST_REMOVE_CURRENT(&atexits, list);
696                         break;
697                 }
698         }
699         AST_LIST_TRAVERSE_SAFE_END
700         AST_LIST_UNLOCK(&atexits);
701 }
702
703 static int fdprint(int fd, const char *s)
704 {
705         return write(fd, s, strlen(s) + 1);
706 }
707
708 /*! \brief NULL handler so we can collect the child exit status */
709 static void null_sig_handler(int signal)
710 {
711
712 }
713
714 AST_MUTEX_DEFINE_STATIC(safe_system_lock);
715 /*! \brief Keep track of how many threads are currently trying to wait*() on
716  *  a child process */
717 static unsigned int safe_system_level = 0;
718 static void *safe_system_prev_handler;
719
720 void ast_replace_sigchld(void)
721 {
722         unsigned int level;
723
724         ast_mutex_lock(&safe_system_lock);
725         level = safe_system_level++;
726
727         /* only replace the handler if it has not already been done */
728         if (level == 0)
729                 safe_system_prev_handler = signal(SIGCHLD, null_sig_handler);
730
731         ast_mutex_unlock(&safe_system_lock);
732 }
733
734 void ast_unreplace_sigchld(void)
735 {
736         unsigned int level;
737
738         ast_mutex_lock(&safe_system_lock);
739         level = --safe_system_level;
740
741         /* only restore the handler if we are the last one */
742         if (level == 0)
743                 signal(SIGCHLD, safe_system_prev_handler);
744
745         ast_mutex_unlock(&safe_system_lock);
746 }
747
748 int ast_safe_system(const char *s)
749 {
750         pid_t pid;
751 #ifdef HAVE_WORKING_FORK
752         int x;
753 #endif
754         int res;
755         struct rusage rusage;
756         int status;
757
758 #if defined(HAVE_WORKING_FORK) || defined(HAVE_WORKING_VFORK)
759         ast_replace_sigchld();
760
761 #ifdef HAVE_WORKING_FORK
762         pid = fork();
763 #else
764         pid = vfork();
765 #endif  
766
767         if (pid == 0) {
768 #ifdef HAVE_WORKING_FORK
769                 if (ast_opt_high_priority)
770                         ast_set_priority(0);
771                 /* Close file descriptors and launch system command */
772                 for (x = STDERR_FILENO + 1; x < 4096; x++)
773                         close(x);
774 #endif
775                 execl("/bin/sh", "/bin/sh", "-c", s, (char *) NULL);
776                 _exit(1);
777         } else if (pid > 0) {
778                 for (;;) {
779                         res = wait4(pid, &status, 0, &rusage);
780                         if (res > -1) {
781                                 res = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
782                                 break;
783                         } else if (errno != EINTR) 
784                                 break;
785                 }
786         } else {
787                 ast_log(LOG_WARNING, "Fork failed: %s\n", strerror(errno));
788                 res = -1;
789         }
790
791         ast_unreplace_sigchld();
792 #else
793         res = -1;
794 #endif
795
796         return res;
797 }
798
799 /*!
800  * \brief mute or unmute a console from logging
801  */
802 void ast_console_toggle_mute(int fd) {
803         int x;
804         for (x = 0;x < AST_MAX_CONNECTS; x++) {
805                 if (fd == consoles[x].fd) {
806                         if (consoles[x].mute) {
807                                 consoles[x].mute = 0;
808                                 ast_cli(fd, "Console is not muted anymore.\n");
809                         } else {
810                                 consoles[x].mute = 1;
811                                 ast_cli(fd, "Console is muted.\n");
812                         }
813                         return;
814                 }
815         }
816         ast_cli(fd, "Couldn't find remote console.\n");
817 }
818
819 /*!
820  * \brief log the string to all attached console clients
821  */
822 static void ast_network_puts_mutable(const char *string)
823 {
824         int x;
825         for (x = 0;x < AST_MAX_CONNECTS; x++) {
826                 if (consoles[x].mute)
827                         continue;
828                 if (consoles[x].fd > -1) 
829                         fdprint(consoles[x].p[1], string);
830         }
831 }
832
833 /*!
834  * \brief log the string to the console, and all attached
835  * console clients
836  */
837 void ast_console_puts_mutable(const char *string)
838 {
839         fputs(string, stdout);
840         fflush(stdout);
841         ast_network_puts_mutable(string);
842 }
843
844 /*!
845  * \brief write the string to all attached console clients
846  */
847 static void ast_network_puts(const char *string)
848 {
849         int x;
850         for (x=0; x < AST_MAX_CONNECTS; x++) {
851                 if (consoles[x].fd > -1) 
852                         fdprint(consoles[x].p[1], string);
853         }
854 }
855
856 /*!
857  * write the string to the console, and all attached
858  * console clients
859  */
860 void ast_console_puts(const char *string)
861 {
862         fputs(string, stdout);
863         fflush(stdout);
864         ast_network_puts(string);
865 }
866
867 static void network_verboser(const char *s)
868 {
869         ast_network_puts_mutable(s);
870 }
871
872 static pthread_t lthread;
873
874 static void *netconsole(void *vconsole)
875 {
876         struct console *con = vconsole;
877         char hostname[MAXHOSTNAMELEN] = "";
878         char tmp[512];
879         int res;
880         struct pollfd fds[2];
881         
882         if (gethostname(hostname, sizeof(hostname)-1))
883                 ast_copy_string(hostname, "<Unknown>", sizeof(hostname));
884         snprintf(tmp, sizeof(tmp), "%s/%ld/%s\n", hostname, (long)ast_mainpid, ASTERISK_VERSION);
885         fdprint(con->fd, tmp);
886         for (;;) {
887                 fds[0].fd = con->fd;
888                 fds[0].events = POLLIN;
889                 fds[0].revents = 0;
890                 fds[1].fd = con->p[0];
891                 fds[1].events = POLLIN;
892                 fds[1].revents = 0;
893
894                 res = poll(fds, 2, -1);
895                 if (res < 0) {
896                         if (errno != EINTR)
897                                 ast_log(LOG_WARNING, "poll returned < 0: %s\n", strerror(errno));
898                         continue;
899                 }
900                 if (fds[0].revents) {
901                         res = read(con->fd, tmp, sizeof(tmp));
902                         if (res < 1) {
903                                 break;
904                         }
905                         tmp[res] = 0;
906                         ast_cli_command(con->fd, tmp);
907                 }
908                 if (fds[1].revents) {
909                         res = read(con->p[0], tmp, sizeof(tmp));
910                         if (res < 1) {
911                                 ast_log(LOG_ERROR, "read returned %d\n", res);
912                                 break;
913                         }
914                         res = write(con->fd, tmp, res);
915                         if (res < 1)
916                                 break;
917                 }
918         }
919         if (option_verbose > 2) 
920                 ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection disconnected\n");
921         close(con->fd);
922         close(con->p[0]);
923         close(con->p[1]);
924         con->fd = -1;
925         
926         return NULL;
927 }
928
929 static void *listener(void *unused)
930 {
931         struct sockaddr_un sunaddr;
932         int s;
933         socklen_t len;
934         int x;
935         int flags;
936         struct pollfd fds[1];
937         for (;;) {
938                 if (ast_socket < 0)
939                         return NULL;
940                 fds[0].fd = ast_socket;
941                 fds[0].events = POLLIN;
942                 s = poll(fds, 1, -1);
943                 pthread_testcancel();
944                 if (s < 0) {
945                         if (errno != EINTR)
946                                 ast_log(LOG_WARNING, "poll returned error: %s\n", strerror(errno));
947                         continue;
948                 }
949                 len = sizeof(sunaddr);
950                 s = accept(ast_socket, (struct sockaddr *)&sunaddr, &len);
951                 if (s < 0) {
952                         if (errno != EINTR)
953                                 ast_log(LOG_WARNING, "Accept returned %d: %s\n", s, strerror(errno));
954                 } else {
955                         for (x = 0; x < AST_MAX_CONNECTS; x++) {
956                                 if (consoles[x].fd < 0) {
957                                         if (socketpair(AF_LOCAL, SOCK_STREAM, 0, consoles[x].p)) {
958                                                 ast_log(LOG_ERROR, "Unable to create pipe: %s\n", strerror(errno));
959                                                 consoles[x].fd = -1;
960                                                 fdprint(s, "Server failed to create pipe\n");
961                                                 close(s);
962                                                 break;
963                                         }
964                                         flags = fcntl(consoles[x].p[1], F_GETFL);
965                                         fcntl(consoles[x].p[1], F_SETFL, flags | O_NONBLOCK);
966                                         consoles[x].fd = s;
967                                         consoles[x].mute = ast_opt_mute;
968                                         if (ast_pthread_create_detached_background(&consoles[x].t, NULL, netconsole, &consoles[x])) {
969                                                 ast_log(LOG_ERROR, "Unable to spawn thread to handle connection: %s\n", strerror(errno));
970                                                 close(consoles[x].p[0]);
971                                                 close(consoles[x].p[1]);
972                                                 consoles[x].fd = -1;
973                                                 fdprint(s, "Server failed to spawn thread\n");
974                                                 close(s);
975                                         }
976                                         break;
977                                 }
978                         }
979                         if (x >= AST_MAX_CONNECTS) {
980                                 fdprint(s, "No more connections allowed\n");
981                                 ast_log(LOG_WARNING, "No more connections allowed\n");
982                                 close(s);
983                         } else if (consoles[x].fd > -1) {
984                                 if (option_verbose > 2) 
985                                         ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection\n");
986                         }
987                 }
988         }
989         return NULL;
990 }
991
992 static int ast_makesocket(void)
993 {
994         struct sockaddr_un sunaddr;
995         int res;
996         int x;
997         uid_t uid = -1;
998         gid_t gid = -1;
999
1000         for (x = 0; x < AST_MAX_CONNECTS; x++)  
1001                 consoles[x].fd = -1;
1002         unlink(ast_config_AST_SOCKET);
1003         ast_socket = socket(PF_LOCAL, SOCK_STREAM, 0);
1004         if (ast_socket < 0) {
1005                 ast_log(LOG_WARNING, "Unable to create control socket: %s\n", strerror(errno));
1006                 return -1;
1007         }               
1008         memset(&sunaddr, 0, sizeof(sunaddr));
1009         sunaddr.sun_family = AF_LOCAL;
1010         ast_copy_string(sunaddr.sun_path, ast_config_AST_SOCKET, sizeof(sunaddr.sun_path));
1011         res = bind(ast_socket, (struct sockaddr *)&sunaddr, sizeof(sunaddr));
1012         if (res) {
1013                 ast_log(LOG_WARNING, "Unable to bind socket to %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
1014                 close(ast_socket);
1015                 ast_socket = -1;
1016                 return -1;
1017         }
1018         res = listen(ast_socket, 2);
1019         if (res < 0) {
1020                 ast_log(LOG_WARNING, "Unable to listen on socket %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
1021                 close(ast_socket);
1022                 ast_socket = -1;
1023                 return -1;
1024         }
1025         ast_register_verbose(network_verboser);
1026         ast_pthread_create_background(&lthread, NULL, listener, NULL);
1027
1028         if (!ast_strlen_zero(ast_config_AST_CTL_OWNER)) {
1029                 struct passwd *pw;
1030                 if ((pw = getpwnam(ast_config_AST_CTL_OWNER)) == NULL)
1031                         ast_log(LOG_WARNING, "Unable to find uid of user %s\n", ast_config_AST_CTL_OWNER);
1032                 else
1033                         uid = pw->pw_uid;
1034         }
1035                 
1036         if (!ast_strlen_zero(ast_config_AST_CTL_GROUP)) {
1037                 struct group *grp;
1038                 if ((grp = getgrnam(ast_config_AST_CTL_GROUP)) == NULL)
1039                         ast_log(LOG_WARNING, "Unable to find gid of group %s\n", ast_config_AST_CTL_GROUP);
1040                 else
1041                         gid = grp->gr_gid;
1042         }
1043
1044         if (chown(ast_config_AST_SOCKET, uid, gid) < 0)
1045                 ast_log(LOG_WARNING, "Unable to change ownership of %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
1046
1047         if (!ast_strlen_zero(ast_config_AST_CTL_PERMISSIONS)) {
1048                 int p1;
1049                 mode_t p;
1050                 sscanf(ast_config_AST_CTL_PERMISSIONS, "%o", &p1);
1051                 p = p1;
1052                 if ((chmod(ast_config_AST_SOCKET, p)) < 0)
1053                         ast_log(LOG_WARNING, "Unable to change file permissions of %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
1054         }
1055
1056         return 0;
1057 }
1058
1059 static int ast_tryconnect(void)
1060 {
1061         struct sockaddr_un sunaddr;
1062         int res;
1063         ast_consock = socket(PF_LOCAL, SOCK_STREAM, 0);
1064         if (ast_consock < 0) {
1065                 ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
1066                 return 0;
1067         }
1068         memset(&sunaddr, 0, sizeof(sunaddr));
1069         sunaddr.sun_family = AF_LOCAL;
1070         ast_copy_string(sunaddr.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sunaddr.sun_path));
1071         res = connect(ast_consock, (struct sockaddr *)&sunaddr, sizeof(sunaddr));
1072         if (res) {
1073                 close(ast_consock);
1074                 ast_consock = -1;
1075                 return 0;
1076         } else
1077                 return 1;
1078 }
1079
1080 /*! \brief Urgent handler
1081
1082  Called by soft_hangup to interrupt the poll, read, or other
1083  system call.  We don't actually need to do anything though.  
1084  Remember: Cannot EVER ast_log from within a signal handler 
1085  */
1086 static void urg_handler(int num)
1087 {
1088         signal(num, urg_handler);
1089         return;
1090 }
1091
1092 static void hup_handler(int num)
1093 {
1094         int a = 0;
1095         if (option_verbose > 1) 
1096                 printf("Received HUP signal -- Reloading configs\n");
1097         if (restartnow)
1098                 execvp(_argv[0], _argv);
1099         sig_flags.need_reload = 1;
1100         if (sig_alert_pipe[1] != -1)
1101                 write(sig_alert_pipe[1], &a, sizeof(a));
1102         signal(num, hup_handler);
1103 }
1104
1105 static void child_handler(int sig)
1106 {
1107         /* Must not ever ast_log or ast_verbose within signal handler */
1108         int n, status;
1109
1110         /*
1111          * Reap all dead children -- not just one
1112          */
1113         for (n = 0; wait4(-1, &status, WNOHANG, NULL) > 0; n++)
1114                 ;
1115         if (n == 0 && option_debug)     
1116                 printf("Huh?  Child handler, but nobody there?\n");
1117         signal(sig, child_handler);
1118 }
1119
1120 /*! \brief Set maximum open files */
1121 static void set_ulimit(int value)
1122 {
1123         struct rlimit l = {0, 0};
1124         
1125         if (value <= 0) {
1126                 ast_log(LOG_WARNING, "Unable to change max files open to invalid value %i\n",value);
1127                 return;
1128         }
1129         
1130         l.rlim_cur = value;
1131         l.rlim_max = value;
1132         
1133         if (setrlimit(RLIMIT_NOFILE, &l)) {
1134                 ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n",strerror(errno));
1135                 return;
1136         }
1137         
1138         ast_log(LOG_NOTICE, "Setting max files open to %d\n",value);
1139         
1140         return;
1141 }
1142
1143 /*! \brief Set an X-term or screen title */
1144 static void set_title(char *text)
1145 {
1146         if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
1147                 fprintf(stdout, "\033]2;%s\007", text);
1148 }
1149
1150 static void set_icon(char *text)
1151 {
1152         if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
1153                 fprintf(stdout, "\033]1;%s\007", text);
1154 }
1155
1156 /*! \brief We set ourselves to a high priority, that we might pre-empt everything
1157    else.  If your PBX has heavy activity on it, this is a good thing.  */
1158 int ast_set_priority(int pri)
1159 {
1160         struct sched_param sched;
1161         memset(&sched, 0, sizeof(sched));
1162 #ifdef __linux__
1163         if (pri) {  
1164                 sched.sched_priority = 10;
1165                 if (sched_setscheduler(0, SCHED_RR, &sched)) {
1166                         ast_log(LOG_WARNING, "Unable to set high priority\n");
1167                         return -1;
1168                 } else
1169                         if (option_verbose)
1170                                 ast_verbose("Set to realtime thread\n");
1171         } else {
1172                 sched.sched_priority = 0;
1173                 /* According to the manpage, these parameters can never fail. */
1174                 sched_setscheduler(0, SCHED_OTHER, &sched);
1175         }
1176 #else
1177         if (pri) {
1178                 if (setpriority(PRIO_PROCESS, 0, -10) == -1) {
1179                         ast_log(LOG_WARNING, "Unable to set high priority\n");
1180                         return -1;
1181                 } else
1182                         if (option_verbose)
1183                                 ast_verbose("Set to high priority\n");
1184         } else {
1185                 /* According to the manpage, these parameters can never fail. */
1186                 setpriority(PRIO_PROCESS, 0, 0);
1187         }
1188 #endif
1189         return 0;
1190 }
1191
1192 static void ast_run_atexits(void)
1193 {
1194         struct ast_atexit *ae;
1195         AST_LIST_LOCK(&atexits);
1196         AST_LIST_TRAVERSE(&atexits, ae, list) {
1197                 if (ae->func) 
1198                         ae->func();
1199         }
1200         AST_LIST_UNLOCK(&atexits);
1201 }
1202
1203 static void quit_handler(int num, int nice, int safeshutdown, int restart)
1204 {
1205         char filename[80] = "";
1206         time_t s,e;
1207         int x;
1208         /* Try to get as many CDRs as possible submitted to the backend engines (if in batch mode) */
1209         ast_cdr_engine_term();
1210         if (safeshutdown) {
1211                 shuttingdown = 1;
1212                 if (!nice) {
1213                         /* Begin shutdown routine, hanging up active channels */
1214                         ast_begin_shutdown(1);
1215                         if (option_verbose && ast_opt_console)
1216                                 ast_verbose("Beginning asterisk %s....\n", restart ? "restart" : "shutdown");
1217                         time(&s);
1218                         for (;;) {
1219                                 time(&e);
1220                                 /* Wait up to 15 seconds for all channels to go away */
1221                                 if ((e - s) > 15)
1222                                         break;
1223                                 if (!ast_active_channels())
1224                                         break;
1225                                 if (!shuttingdown)
1226                                         break;
1227                                 /* Sleep 1/10 of a second */
1228                                 usleep(100000);
1229                         }
1230                 } else {
1231                         if (nice < 2)
1232                                 ast_begin_shutdown(0);
1233                         if (option_verbose && ast_opt_console)
1234                                 ast_verbose("Waiting for inactivity to perform %s...\n", restart ? "restart" : "halt");
1235                         for (;;) {
1236                                 if (!ast_active_channels())
1237                                         break;
1238                                 if (!shuttingdown)
1239                                         break;
1240                                 sleep(1);
1241                         }
1242                 }
1243
1244                 if (!shuttingdown) {
1245                         if (option_verbose && ast_opt_console)
1246                                 ast_verbose("Asterisk %s cancelled.\n", restart ? "restart" : "shutdown");
1247                         return;
1248                 }
1249
1250                 if (nice)
1251                         ast_module_shutdown();
1252         }
1253         if (ast_opt_console || ast_opt_remote) {
1254                 if (getenv("HOME")) 
1255                         snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
1256                 if (!ast_strlen_zero(filename))
1257                         ast_el_write_history(filename);
1258                 if (el != NULL)
1259                         el_end(el);
1260                 if (el_hist != NULL)
1261                         history_end(el_hist);
1262         }
1263         if (option_verbose)
1264                 ast_verbose("Executing last minute cleanups\n");
1265         ast_run_atexits();
1266         /* Called on exit */
1267         if (option_verbose && ast_opt_console)
1268                 ast_verbose("Asterisk %s ending (%d).\n", ast_active_channels() ? "uncleanly" : "cleanly", num);
1269         ast_debug(1, "Asterisk ending (%d).\n", num);
1270         manager_event(EVENT_FLAG_SYSTEM, "Shutdown", "Shutdown: %s\r\nRestart: %s\r\n", ast_active_channels() ? "Uncleanly" : "Cleanly", restart ? "True" : "False");
1271         if (ast_socket > -1) {
1272                 pthread_cancel(lthread);
1273                 close(ast_socket);
1274                 ast_socket = -1;
1275                 unlink(ast_config_AST_SOCKET);
1276         }
1277         if (ast_consock > -1)
1278                 close(ast_consock);
1279         if (!ast_opt_remote)
1280                 unlink(ast_config_AST_PID);
1281         printf(term_quit());
1282         if (restart) {
1283                 if (option_verbose || ast_opt_console)
1284                         ast_verbose("Preparing for Asterisk restart...\n");
1285                 /* Mark all FD's for closing on exec */
1286                 for (x=3; x < 32768; x++) {
1287                         fcntl(x, F_SETFD, FD_CLOEXEC);
1288                 }
1289                 if (option_verbose || ast_opt_console)
1290                         ast_verbose("Asterisk is now restarting...\n");
1291                 restartnow = 1;
1292
1293                 /* close logger */
1294                 close_logger();
1295
1296                 /* If there is a consolethread running send it a SIGHUP 
1297                    so it can execvp, otherwise we can do it ourselves */
1298                 if ((consolethread != AST_PTHREADT_NULL) && (consolethread != pthread_self())) {
1299                         pthread_kill(consolethread, SIGHUP);
1300                         /* Give the signal handler some time to complete */
1301                         sleep(2);
1302                 } else
1303                         execvp(_argv[0], _argv);
1304         
1305         } else {
1306                 /* close logger */
1307                 close_logger();
1308         }
1309         exit(0);
1310 }
1311
1312 static void __quit_handler(int num)
1313 {
1314         int a = 0;
1315         sig_flags.need_quit = 1;
1316         if (sig_alert_pipe[1] != -1)
1317                 write(sig_alert_pipe[1], &a, sizeof(a));
1318         /* There is no need to restore the signal handler here, since the app
1319          * is going to exit */
1320 }
1321
1322 static const char *fix_header(char *outbuf, int maxout, const char *s, char *cmp)
1323 {
1324         const char *c;
1325         if (!strncmp(s, cmp, strlen(cmp))) {
1326                 c = s + strlen(cmp);
1327                 term_color(outbuf, cmp, COLOR_GRAY, 0, maxout);
1328                 return c;
1329         }
1330         return NULL;
1331 }
1332
1333 static void console_verboser(const char *s)
1334 {
1335         char tmp[80];
1336         const char *c = NULL;
1337
1338         if ((c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_4)) ||
1339             (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_3)) ||
1340             (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_2)) ||
1341             (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_1))) {
1342                 fputs(tmp, stdout);
1343                 fputs(c, stdout);
1344         } else
1345                 fputs(s, stdout);
1346
1347         fflush(stdout);
1348         
1349         /* Wake up a poll()ing console */
1350         if (ast_opt_console && consolethread != AST_PTHREADT_NULL)
1351                 pthread_kill(consolethread, SIGURG);
1352 }
1353
1354 static int ast_all_zeros(char *s)
1355 {
1356         while (*s) {
1357                 if (*s > 32)
1358                         return 0;
1359                 s++;  
1360         }
1361         return 1;
1362 }
1363
1364 static void consolehandler(char *s)
1365 {
1366         printf(term_end());
1367         fflush(stdout);
1368
1369         /* Called when readline data is available */
1370         if (!ast_all_zeros(s))
1371                 ast_el_add_history(s);
1372         /* The real handler for bang */
1373         if (s[0] == '!') {
1374                 if (s[1])
1375                         ast_safe_system(s+1);
1376                 else
1377                         ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
1378         } else 
1379                 ast_cli_command(STDOUT_FILENO, s);
1380 }
1381
1382 static int remoteconsolehandler(char *s)
1383 {
1384         int ret = 0;
1385
1386         /* Called when readline data is available */
1387         if (!ast_all_zeros(s))
1388                 ast_el_add_history(s);
1389         /* The real handler for bang */
1390         if (s[0] == '!') {
1391                 if (s[1])
1392                         ast_safe_system(s+1);
1393                 else
1394                         ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
1395                 ret = 1;
1396         }
1397         if ((strncasecmp(s, "quit", 4) == 0 || strncasecmp(s, "exit", 4) == 0) &&
1398             (s[4] == '\0' || isspace(s[4]))) {
1399                 quit_handler(0, 0, 0, 0);
1400                 ret = 1;
1401         }
1402
1403         return ret;
1404 }
1405
1406 static const char abort_halt_help[] = 
1407 "Usage: abort shutdown\n"
1408 "       Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
1409 "       call operations.\n";
1410
1411 static const char shutdown_now_help[] = 
1412 "Usage: stop now\n"
1413 "       Shuts down a running Asterisk immediately, hanging up all active calls .\n";
1414
1415 static const char shutdown_gracefully_help[] = 
1416 "Usage: stop gracefully\n"
1417 "       Causes Asterisk to not accept new calls, and exit when all\n"
1418 "       active calls have terminated normally.\n";
1419
1420 static const char shutdown_when_convenient_help[] = 
1421 "Usage: stop when convenient\n"
1422 "       Causes Asterisk to perform a shutdown when all active calls have ended.\n";
1423
1424 static const char restart_now_help[] = 
1425 "Usage: restart now\n"
1426 "       Causes Asterisk to hangup all calls and exec() itself performing a cold\n"
1427 "       restart.\n";
1428
1429 static const char restart_gracefully_help[] = 
1430 "Usage: restart gracefully\n"
1431 "       Causes Asterisk to stop accepting new calls and exec() itself performing a cold\n"
1432 "       restart when all active calls have ended.\n";
1433
1434 static const char restart_when_convenient_help[] = 
1435 "Usage: restart when convenient\n"
1436 "       Causes Asterisk to perform a cold restart when all active calls have ended.\n";
1437
1438 static const char bang_help[] =
1439 "Usage: !<command>\n"
1440 "       Executes a given shell command\n";
1441
1442 static const char show_warranty_help[] =
1443 "Usage: core show warranty\n"
1444 "       Shows the warranty (if any) for this copy of Asterisk.\n";
1445
1446 static const char show_license_help[] =
1447 "Usage: core show license\n"
1448 "       Shows the license(s) for this copy of Asterisk.\n";
1449
1450 static const char version_help[] =
1451 "Usage: core show version\n"
1452 "       Shows Asterisk version information.\n";
1453
1454 #if defined(MARKO_BDAY)
1455 static const char markobday_help[] =
1456 "Usage: marko show birthday\n"
1457 "       Shows time until/since Mark Spencer's 30th birthday.\n";
1458 #endif
1459
1460 static int handle_version(int fd, int argc, char *argv[])
1461 {
1462         if (argc != 3)
1463                 return RESULT_SHOWUSAGE;
1464         ast_cli(fd, "Asterisk %s built by %s @ %s on a %s running %s on %s\n",
1465                 ASTERISK_VERSION, ast_build_user, ast_build_hostname,
1466                 ast_build_machine, ast_build_os, ast_build_date);
1467         return RESULT_SUCCESS;
1468 }
1469
1470 #if defined(MARKO_BDAY)
1471 static void print_markobdaystr(int fd, time_t timeval, const char *prefix)
1472 {
1473         int x; /* the main part - years, weeks, etc. */
1474         struct ast_str *out;
1475
1476 #define SECOND (1)
1477 #define MINUTE (SECOND*60)
1478 #define HOUR (MINUTE*60)
1479 #define DAY (HOUR*24)
1480 #define WEEK (DAY*7)
1481 #define YEAR (DAY*365)
1482 #define NEEDCOMMA(x) ((x)? ",": "")     /* define if we need a comma */
1483         if (timeval < 0)        /* invalid, nothing to show */
1484                 return;
1485
1486         out = ast_str_alloca(256);
1487         if (timeval > YEAR) {
1488                 x = (timeval / YEAR);
1489                 timeval -= (x * YEAR);
1490                 ast_str_append(&out, 0, "%d year%s%s ", x, ESS(x),NEEDCOMMA(timeval));
1491         }
1492         if (timeval > WEEK) {
1493                 x = (timeval / WEEK);
1494                 timeval -= (x * WEEK);
1495                 ast_str_append(&out, 0, "%d week%s%s ", x, ESS(x),NEEDCOMMA(timeval));
1496         }
1497         if (timeval > DAY) {
1498                 x = (timeval / DAY);
1499                 timeval -= (x * DAY);
1500                 ast_str_append(&out, 0, "%d day%s%s ", x, ESS(x),NEEDCOMMA(timeval));
1501         }
1502         if (timeval > HOUR) {
1503                 x = (timeval / HOUR);
1504                 timeval -= (x * HOUR);
1505                 ast_str_append(&out, 0, "%d hour%s%s ", x, ESS(x),NEEDCOMMA(timeval));
1506         }
1507         if (timeval > MINUTE) {
1508                 x = (timeval / MINUTE);
1509                 timeval -= (x * MINUTE);
1510                 ast_str_append(&out, 0, "%d minute%s%s ", x, ESS(x),NEEDCOMMA(timeval));
1511         }
1512         x = timeval;
1513         if (x > 0 || out->used == 0)    /* if there is nothing, print 0 seconds */
1514                 ast_str_append(&out, 0, "%d second%s ", x, ESS(x));
1515         ast_cli(fd, "%s: %s\n", prefix, out->str);
1516 }
1517
1518 static int handle_markobday(int fd, int argc, char *argv[])
1519 {
1520         time_t markobdaystarttime = 1176008400; /* 2007-04-08 00:00:00 */
1521         time_t markobdayendtime = 1176094799;   /* 2007-04-08 23:59:59 */
1522         time_t curtime;
1523
1524         curtime = time(NULL);
1525         if (markobdaystarttime && markobdayendtime) {
1526                 if (curtime >= markobdaystarttime && curtime <= markobdayendtime)
1527                         ast_cli(fd, "Happy 30th birthday Marko!\n");
1528                 else if (curtime > markobdayendtime)
1529                         print_markobdaystr(fd, curtime - markobdayendtime, "Time since Mark Spencer's 30th birthday");
1530                 else
1531                         print_markobdaystr(fd, markobdaystarttime - curtime, "Time until Mark Spencer's 30th birthday");
1532         }
1533         return RESULT_SUCCESS;
1534 }
1535 #endif
1536
1537 #if 0
1538 static int handle_quit(int fd, int argc, char *argv[])
1539 {
1540         if (argc != 1)
1541                 return RESULT_SHOWUSAGE;
1542         quit_handler(0, 0, 1, 0);
1543         return RESULT_SUCCESS;
1544 }
1545 #endif
1546
1547 static int handle_shutdown_now(int fd, int argc, char *argv[])
1548 {
1549         if (argc != 2)
1550                 return RESULT_SHOWUSAGE;
1551         quit_handler(0, 0 /* Not nice */, 1 /* safely */, 0 /* not restart */);
1552         return RESULT_SUCCESS;
1553 }
1554
1555 static int handle_shutdown_gracefully(int fd, int argc, char *argv[])
1556 {
1557         if (argc != 2)
1558                 return RESULT_SHOWUSAGE;
1559         quit_handler(0, 1 /* nicely */, 1 /* safely */, 0 /* no restart */);
1560         return RESULT_SUCCESS;
1561 }
1562
1563 static int handle_shutdown_when_convenient(int fd, int argc, char *argv[])
1564 {
1565         if (argc != 3)
1566                 return RESULT_SHOWUSAGE;
1567         ast_cli(fd, "Waiting for inactivity to perform halt\n");
1568         quit_handler(0, 2 /* really nicely */, 1 /* safely */, 0 /* don't restart */);
1569         return RESULT_SUCCESS;
1570 }
1571
1572 static int handle_restart_now(int fd, int argc, char *argv[])
1573 {
1574         if (argc != 2)
1575                 return RESULT_SHOWUSAGE;
1576         quit_handler(0, 0 /* not nicely */, 1 /* safely */, 1 /* restart */);
1577         return RESULT_SUCCESS;
1578 }
1579
1580 static int handle_restart_gracefully(int fd, int argc, char *argv[])
1581 {
1582         if (argc != 2)
1583                 return RESULT_SHOWUSAGE;
1584         quit_handler(0, 1 /* nicely */, 1 /* safely */, 1 /* restart */);
1585         return RESULT_SUCCESS;
1586 }
1587
1588 static int handle_restart_when_convenient(int fd, int argc, char *argv[])
1589 {
1590         if (argc != 3)
1591                 return RESULT_SHOWUSAGE;
1592         ast_cli(fd, "Waiting for inactivity to perform restart\n");
1593         quit_handler(0, 2 /* really nicely */, 1 /* safely */, 1 /* restart */);
1594         return RESULT_SUCCESS;
1595 }
1596
1597 static int handle_abort_halt(int fd, int argc, char *argv[])
1598 {
1599         if (argc != 2)
1600                 return RESULT_SHOWUSAGE;
1601         ast_cancel_shutdown();
1602         shuttingdown = 0;
1603         return RESULT_SUCCESS;
1604 }
1605
1606 static int handle_bang(int fd, int argc, char *argv[])
1607 {
1608         return RESULT_SUCCESS;
1609 }
1610 static const char warranty_lines[] = {
1611         "\n"
1612         "                           NO WARRANTY\n"
1613         "\n"
1614         "BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\n"
1615         "FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\n"
1616         "OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\n"
1617         "PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\n"
1618         "OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n"
1619         "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\n"
1620         "TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\n"
1621         "PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\n"
1622         "REPAIR OR CORRECTION.\n"
1623         "\n"
1624         "IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\n"
1625         "WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\n"
1626         "REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\n"
1627         "INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\n"
1628         "OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\n"
1629         "TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\n"
1630         "YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\n"
1631         "PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\n"
1632         "POSSIBILITY OF SUCH DAMAGES.\n"
1633 };
1634
1635 static int show_warranty(int fd, int argc, char *argv[])
1636 {
1637         ast_cli(fd, warranty_lines);
1638
1639         return RESULT_SUCCESS;
1640 }
1641
1642 static const char license_lines[] = {
1643         "\n"
1644         "This program is free software; you can redistribute it and/or modify\n"
1645         "it under the terms of the GNU General Public License version 2 as\n"
1646         "published by the Free Software Foundation.\n"
1647         "\n"
1648         "This program also contains components licensed under other licenses.\n"
1649         "They include:\n"
1650         "\n"
1651         "This program is distributed in the hope that it will be useful,\n"
1652         "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1653         "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
1654         "GNU General Public License for more details.\n"
1655         "\n"
1656         "You should have received a copy of the GNU General Public License\n"
1657         "along with this program; if not, write to the Free Software\n"
1658         "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
1659 };
1660
1661 static int show_license(int fd, int argc, char *argv[])
1662 {
1663         ast_cli(fd, license_lines);
1664
1665         return RESULT_SUCCESS;
1666 }
1667
1668 #define ASTERISK_PROMPT "*CLI> "
1669
1670 #define ASTERISK_PROMPT2 "%s*CLI> "
1671
1672 static struct ast_cli_entry cli_asterisk[] = {
1673         { { "abort", "halt", NULL },
1674         handle_abort_halt, "Cancel a running halt",
1675         abort_halt_help },
1676
1677         { { "stop", "now", NULL },
1678         handle_shutdown_now, "Shut down Asterisk immediately",
1679         shutdown_now_help },
1680
1681         { { "stop", "gracefully", NULL },
1682         handle_shutdown_gracefully, "Gracefully shut down Asterisk",
1683         shutdown_gracefully_help },
1684
1685         { { "stop", "when", "convenient", NULL },
1686         handle_shutdown_when_convenient, "Shut down Asterisk at empty call volume",
1687         shutdown_when_convenient_help },
1688
1689         { { "restart", "now", NULL },
1690         handle_restart_now, "Restart Asterisk immediately", restart_now_help },
1691
1692         { { "restart", "gracefully", NULL },
1693         handle_restart_gracefully, "Restart Asterisk gracefully",
1694         restart_gracefully_help },
1695
1696         { { "restart", "when", "convenient", NULL },
1697         handle_restart_when_convenient, "Restart Asterisk at empty call volume",
1698         restart_when_convenient_help },
1699
1700         { { "core", "show", "warranty", NULL },
1701         show_warranty, "Show the warranty (if any) for this copy of Asterisk",
1702         show_warranty_help },
1703
1704         { { "core", "show", "license", NULL },
1705         show_license, "Show the license(s) for this copy of Asterisk",
1706         show_license_help },
1707
1708         { { "core", "show", "version", NULL },
1709         handle_version, "Display version info",
1710         version_help },
1711
1712 #if defined(MARKO_BDAY)
1713         { { "marko", "show", "birthday", NULL },
1714         handle_markobday, "Display time until/since Mark Spencer's 30th birthday",
1715         markobday_help },
1716 #endif
1717
1718         { { "!", NULL },
1719         handle_bang, "Execute a shell command",
1720         bang_help },
1721
1722 #if !defined(LOW_MEMORY)
1723         { { "core", "show", "file", "version", NULL },
1724         handle_show_version_files, "List versions of files used to build Asterisk",
1725         show_version_files_help, complete_show_version_files },
1726
1727         { { "core", "show", "threads", NULL },
1728         handle_show_threads, "Show running threads",
1729         show_threads_help },
1730
1731 #if defined(HAVE_SYSINFO)
1732         { { "core", "show", "sysinfo", NULL },
1733         handle_show_sysinfo, "Show System Information",
1734         show_sysinfo_help },
1735 #endif
1736
1737         { { "core", "show", "profile", NULL },
1738         handle_show_profile, "Display profiling info",
1739         NULL },
1740
1741         { { "core", "show", "settings", NULL },
1742         handle_show_settings, "Show some core settings",
1743         NULL },
1744
1745         { { "core", "clear", "profile", NULL },
1746         handle_show_profile, "Clear profiling info",
1747         NULL },
1748 #endif /* ! LOW_MEMORY */
1749 };
1750
1751 static int ast_el_read_char(EditLine *el, char *cp)
1752 {
1753         int num_read = 0;
1754         int lastpos = 0;
1755         struct pollfd fds[2];
1756         int res;
1757         int max;
1758         char buf[512];
1759
1760         for (;;) {
1761                 max = 1;
1762                 fds[0].fd = ast_consock;
1763                 fds[0].events = POLLIN;
1764                 if (!ast_opt_exec) {
1765                         fds[1].fd = STDIN_FILENO;
1766                         fds[1].events = POLLIN;
1767                         max++;
1768                 }
1769                 res = poll(fds, max, -1);
1770                 if (res < 0) {
1771                         if (errno == EINTR)
1772                                 continue;
1773                         ast_log(LOG_ERROR, "poll failed: %s\n", strerror(errno));
1774                         break;
1775                 }
1776
1777                 if (!ast_opt_exec && fds[1].revents) {
1778                         num_read = read(STDIN_FILENO, cp, 1);
1779                         if (num_read < 1) {
1780                                 break;
1781                         } else 
1782                                 return (num_read);
1783                 }
1784                 if (fds[0].revents) {
1785                         res = read(ast_consock, buf, sizeof(buf) - 1);
1786                         /* if the remote side disappears exit */
1787                         if (res < 1) {
1788                                 fprintf(stderr, "\nDisconnected from Asterisk server\n");
1789                                 if (!ast_opt_reconnect) {
1790                                         quit_handler(0, 0, 0, 0);
1791                                 } else {
1792                                         int tries;
1793                                         int reconnects_per_second = 20;
1794                                         fprintf(stderr, "Attempting to reconnect for 30 seconds\n");
1795                                         for (tries=0; tries < 30 * reconnects_per_second; tries++) {
1796                                                 if (ast_tryconnect()) {
1797                                                         fprintf(stderr, "Reconnect succeeded after %.3f seconds\n", 1.0 / reconnects_per_second * tries);
1798                                                         printf(term_quit());
1799                                                         WELCOME_MESSAGE;
1800                                                         break;
1801                                                 } else
1802                                                         usleep(1000000 / reconnects_per_second);
1803                                         }
1804                                         if (tries >= 30 * reconnects_per_second) {
1805                                                 fprintf(stderr, "Failed to reconnect for 30 seconds.  Quitting.\n");
1806                                                 quit_handler(0, 0, 0, 0);
1807                                         }
1808                                 }
1809                         }
1810
1811                         buf[res] = '\0';
1812
1813                         if (!ast_opt_exec && !lastpos)
1814                                 write(STDOUT_FILENO, "\r", 1);
1815                         write(STDOUT_FILENO, buf, res);
1816                         if ((buf[res-1] == '\n') || (buf[res-2] == '\n')) {
1817                                 *cp = CC_REFRESH;
1818                                 return(1);
1819                         } else
1820                                 lastpos = 1;
1821                 }
1822         }
1823
1824         *cp = '\0';
1825         return (0);
1826 }
1827
1828 static char *cli_prompt(EditLine *el)
1829 {
1830         static char prompt[200];
1831         char *pfmt;
1832         int color_used = 0;
1833         char term_code[20];
1834
1835         if ((pfmt = getenv("ASTERISK_PROMPT"))) {
1836                 char *t = pfmt, *p = prompt;
1837                 memset(prompt, 0, sizeof(prompt));
1838                 while (*t != '\0' && *p < sizeof(prompt)) {
1839                         if (*t == '%') {
1840                                 char hostname[MAXHOSTNAMELEN]="";
1841                                 int i;
1842                                 time_t ts;
1843                                 struct tm tm;
1844 #ifdef linux
1845                                 FILE *LOADAVG;
1846 #endif
1847                                 int fgcolor = COLOR_WHITE, bgcolor = COLOR_BLACK;
1848
1849                                 t++;
1850                                 switch (*t) {
1851                                 case 'C': /* color */
1852                                         t++;
1853                                         if (sscanf(t, "%d;%d%n", &fgcolor, &bgcolor, &i) == 2) {
1854                                                 strncat(p, term_color_code(term_code, fgcolor, bgcolor, sizeof(term_code)),sizeof(prompt) - strlen(prompt) - 1);
1855                                                 t += i - 1;
1856                                         } else if (sscanf(t, "%d%n", &fgcolor, &i) == 1) {
1857                                                 strncat(p, term_color_code(term_code, fgcolor, 0, sizeof(term_code)),sizeof(prompt) - strlen(prompt) - 1);
1858                                                 t += i - 1;
1859                                         }
1860
1861                                         /* If the color has been reset correctly, then there's no need to reset it later */
1862                                         color_used = ((fgcolor == COLOR_WHITE) && (bgcolor == COLOR_BLACK)) ? 0 : 1;
1863                                         break;
1864                                 case 'd': /* date */
1865                                         memset(&tm, 0, sizeof(tm));
1866                                         time(&ts);
1867                                         if (localtime_r(&ts, &tm)) 
1868                                                 strftime(p, sizeof(prompt) - strlen(prompt), "%Y-%m-%d", &tm);
1869                                         break;
1870                                 case 'h': /* hostname */
1871                                         if (!gethostname(hostname, sizeof(hostname) - 1))
1872                                                 strncat(p, hostname, sizeof(prompt) - strlen(prompt) - 1);
1873                                         else
1874                                                 strncat(p, "localhost", sizeof(prompt) - strlen(prompt) - 1);
1875                                         break;
1876                                 case 'H': /* short hostname */
1877                                         if (!gethostname(hostname, sizeof(hostname) - 1)) {
1878                                                 for (i = 0; i < sizeof(hostname); i++) {
1879                                                         if (hostname[i] == '.') {
1880                                                                 hostname[i] = '\0';
1881                                                                 break;
1882                                                         }
1883                                                 }
1884                                                 strncat(p, hostname, sizeof(prompt) - strlen(prompt) - 1);
1885                                         } else
1886                                                 strncat(p, "localhost", sizeof(prompt) - strlen(prompt) - 1);
1887                                         break;
1888 #ifdef linux
1889                                 case 'l': /* load avg */
1890                                         t++;
1891                                         if ((LOADAVG = fopen("/proc/loadavg", "r"))) {
1892                                                 float avg1, avg2, avg3;
1893                                                 int actproc, totproc, npid, which;
1894                                                 fscanf(LOADAVG, "%f %f %f %d/%d %d",
1895                                                         &avg1, &avg2, &avg3, &actproc, &totproc, &npid);
1896                                                 if (sscanf(t, "%d", &which) == 1) {
1897                                                         switch (which) {
1898                                                         case 1:
1899                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg1);
1900                                                                 break;
1901                                                         case 2:
1902                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg2);
1903                                                                 break;
1904                                                         case 3:
1905                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg3);
1906                                                                 break;
1907                                                         case 4:
1908                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%d/%d", actproc, totproc);
1909                                                                 break;
1910                                                         case 5:
1911                                                                 snprintf(p, sizeof(prompt) - strlen(prompt), "%d", npid);
1912                                                                 break;
1913                                                         }
1914                                                 }
1915                                         }
1916                                         break;
1917 #endif
1918                                 case 's': /* Asterisk system name (from asterisk.conf) */
1919                                         strncat(p, ast_config_AST_SYSTEM_NAME, sizeof(prompt) - strlen(prompt) - 1);
1920                                         break;
1921                                 case 't': /* time */
1922                                         memset(&tm, 0, sizeof(tm));
1923                                         time(&ts);
1924                                         if (localtime_r(&ts, &tm))
1925                                                 strftime(p, sizeof(prompt) - strlen(prompt), "%H:%M:%S", &tm);
1926                                         break;
1927                                 case '#': /* process console or remote? */
1928                                         if (!ast_opt_remote) 
1929                                                 strncat(p, "#", sizeof(prompt) - strlen(prompt) - 1);
1930                                         else
1931                                                 strncat(p, ">", sizeof(prompt) - strlen(prompt) - 1);
1932                                         break;
1933                                 case '%': /* literal % */
1934                                         strncat(p, "%", sizeof(prompt) - strlen(prompt) - 1);
1935                                         break;
1936                                 case '\0': /* % is last character - prevent bug */
1937                                         t--;
1938                                         break;
1939                                 }
1940                                 while (*p != '\0')
1941                                         p++;
1942                                 t++;
1943                         } else {
1944                                 *p = *t;
1945                                 p++;
1946                                 t++;
1947                         }
1948                 }
1949                 if (color_used) {
1950                         /* Force colors back to normal at end */
1951                         term_color_code(term_code, COLOR_WHITE, COLOR_BLACK, sizeof(term_code));
1952                         if (strlen(term_code) > sizeof(prompt) - strlen(prompt))
1953                                 strncat(prompt + sizeof(prompt) - strlen(term_code) - 1, term_code, strlen(term_code));
1954                         else
1955                                 strncat(p, term_code, sizeof(term_code));
1956                 }
1957         } else if (remotehostname)
1958                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT2, remotehostname);
1959         else
1960                 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT);
1961
1962         return(prompt); 
1963 }
1964
1965 static char **ast_el_strtoarr(char *buf)
1966 {
1967         char **match_list = NULL, *retstr;
1968         size_t match_list_len;
1969         int matches = 0;
1970
1971         match_list_len = 1;
1972         while ( (retstr = strsep(&buf, " ")) != NULL) {
1973
1974                 if (!strcmp(retstr, AST_CLI_COMPLETE_EOF))
1975                         break;
1976                 if (matches + 1 >= match_list_len) {
1977                         match_list_len <<= 1;
1978                         if (!(match_list = ast_realloc(match_list, match_list_len * sizeof(char *)))) {
1979                                 /* TODO: Handle memory allocation failure */
1980                         }
1981                 }
1982
1983                 match_list[matches++] = strdup(retstr);
1984         }
1985
1986         if (!match_list)
1987                 return (char **) NULL;
1988
1989         if (matches >= match_list_len) {
1990                 if (!(match_list = ast_realloc(match_list, (match_list_len + 1) * sizeof(char *)))) {
1991                         /* TODO: Handle memory allocation failure */
1992                 }
1993         }
1994
1995         match_list[matches] = (char *) NULL;
1996
1997         return match_list;
1998 }
1999
2000 static int ast_el_sort_compare(const void *i1, const void *i2)
2001 {
2002         char *s1, *s2;
2003
2004         s1 = ((char **)i1)[0];
2005         s2 = ((char **)i2)[0];
2006
2007         return strcasecmp(s1, s2);
2008 }
2009
2010 static int ast_cli_display_match_list(char **matches, int len, int max)
2011 {
2012         int i, idx, limit, count;
2013         int screenwidth = 0;
2014         int numoutput = 0, numoutputline = 0;
2015
2016         screenwidth = ast_get_termcols(STDOUT_FILENO);
2017
2018         /* find out how many entries can be put on one line, with two spaces between strings */
2019         limit = screenwidth / (max + 2);
2020         if (limit == 0)
2021                 limit = 1;
2022
2023         /* how many lines of output */
2024         count = len / limit;
2025         if (count * limit < len)
2026                 count++;
2027
2028         idx = 1;
2029
2030         qsort(&matches[0], (size_t)(len), sizeof(char *), ast_el_sort_compare);
2031
2032         for (; count > 0; count--) {
2033                 numoutputline = 0;
2034                 for (i=0; i < limit && matches[idx]; i++, idx++) {
2035
2036                         /* Don't print dupes */
2037                         if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
2038                                 i--;
2039                                 ast_free(matches[idx]);
2040                                 matches[idx] = NULL;
2041                                 continue;
2042                         }
2043
2044                         numoutput++;
2045                         numoutputline++;
2046                         fprintf(stdout, "%-*s  ", max, matches[idx]);
2047                         ast_free(matches[idx]);
2048                         matches[idx] = NULL;
2049                 }
2050                 if (numoutputline > 0)
2051                         fprintf(stdout, "\n");
2052         }
2053
2054         return numoutput;
2055 }
2056
2057
2058 static char *cli_complete(EditLine *el, int ch)
2059 {
2060         int len = 0;
2061         char *ptr;
2062         int nummatches = 0;
2063         char **matches;
2064         int retval = CC_ERROR;
2065         char buf[2048];
2066         int res;
2067
2068         LineInfo *lf = (LineInfo *)el_line(el);
2069
2070         *(char *)lf->cursor = '\0';
2071         ptr = (char *)lf->cursor;
2072         if (ptr) {
2073                 while (ptr > lf->buffer) {
2074                         if (isspace(*ptr)) {
2075                                 ptr++;
2076                                 break;
2077                         }
2078                         ptr--;
2079                 }
2080         }
2081
2082         len = lf->cursor - ptr;
2083
2084         if (ast_opt_remote) {
2085                 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr); 
2086                 fdprint(ast_consock, buf);
2087                 res = read(ast_consock, buf, sizeof(buf));
2088                 buf[res] = '\0';
2089                 nummatches = atoi(buf);
2090
2091                 if (nummatches > 0) {
2092                         char *mbuf;
2093                         int mlen = 0, maxmbuf = 2048;
2094                         /* Start with a 2048 byte buffer */                     
2095                         if (!(mbuf = ast_malloc(maxmbuf)))
2096                                 return (char *)(CC_ERROR);
2097                         snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr); 
2098                         fdprint(ast_consock, buf);
2099                         res = 0;
2100                         mbuf[0] = '\0';
2101                         while (!strstr(mbuf, AST_CLI_COMPLETE_EOF) && res != -1) {
2102                                 if (mlen + 1024 > maxmbuf) {
2103                                         /* Every step increment buffer 1024 bytes */
2104                                         maxmbuf += 1024;                                        
2105                                         if (!(mbuf = ast_realloc(mbuf, maxmbuf)))
2106                                                 return (char *)(CC_ERROR);
2107                                 }
2108                                 /* Only read 1024 bytes at a time */
2109                                 res = read(ast_consock, mbuf + mlen, 1024);
2110                                 if (res > 0)
2111                                         mlen += res;
2112                         }
2113                         mbuf[mlen] = '\0';
2114
2115                         matches = ast_el_strtoarr(mbuf);
2116                         ast_free(mbuf);
2117                 } else
2118                         matches = (char **) NULL;
2119         } else {
2120                 char **p, *oldbuf=NULL;
2121                 nummatches = 0;
2122                 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
2123                 for (p = matches; p && *p; p++) {
2124                         if (!oldbuf || strcmp(*p,oldbuf))
2125                                 nummatches++;
2126                         oldbuf = *p;
2127                 }
2128         }
2129
2130         if (matches) {
2131                 int i;
2132                 int matches_num, maxlen, match_len;
2133
2134                 if (matches[0][0] != '\0') {
2135                         el_deletestr(el, (int) len);
2136                         el_insertstr(el, matches[0]);
2137                         retval = CC_REFRESH;
2138                 }
2139
2140                 if (nummatches == 1) {
2141                         /* Found an exact match */
2142                         el_insertstr(el, " ");
2143                         retval = CC_REFRESH;
2144                 } else {
2145                         /* Must be more than one match */
2146                         for (i=1, maxlen=0; matches[i]; i++) {
2147                                 match_len = strlen(matches[i]);
2148                                 if (match_len > maxlen)
2149                                         maxlen = match_len;
2150                         }
2151                         matches_num = i - 1;
2152                         if (matches_num >1) {
2153                                 fprintf(stdout, "\n");
2154                                 ast_cli_display_match_list(matches, nummatches, maxlen);
2155                                 retval = CC_REDISPLAY;
2156                         } else { 
2157                                 el_insertstr(el," ");
2158                                 retval = CC_REFRESH;
2159                         }
2160                 }
2161                 for (i = 0; matches[i]; i++)
2162                         ast_free(matches[i]);
2163                 ast_free(matches);
2164         }
2165
2166         return (char *)(long)retval;
2167 }
2168
2169 static int ast_el_initialize(void)
2170 {
2171         HistEvent ev;
2172         char *editor = getenv("AST_EDITOR");
2173
2174         if (el != NULL)
2175                 el_end(el);
2176         if (el_hist != NULL)
2177                 history_end(el_hist);
2178
2179         el = el_init("asterisk", stdin, stdout, stderr);
2180         el_set(el, EL_PROMPT, cli_prompt);
2181
2182         el_set(el, EL_EDITMODE, 1);             
2183         el_set(el, EL_EDITOR, editor ? editor : "emacs");               
2184         el_hist = history_init();
2185         if (!el || !el_hist)
2186                 return -1;
2187
2188         /* setup history with 100 entries */
2189         history(el_hist, &ev, H_SETSIZE, 100);
2190
2191         el_set(el, EL_HIST, history, el_hist);
2192
2193         el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
2194         /* Bind <tab> to command completion */
2195         el_set(el, EL_BIND, "^I", "ed-complete", NULL);
2196         /* Bind ? to command completion */
2197         el_set(el, EL_BIND, "?", "ed-complete", NULL);
2198         /* Bind ^D to redisplay */
2199         el_set(el, EL_BIND, "^D", "ed-redisplay", NULL);
2200
2201         return 0;
2202 }
2203
2204 static int ast_el_add_history(char *buf)
2205 {
2206         HistEvent ev;
2207
2208         if (el_hist == NULL || el == NULL)
2209                 ast_el_initialize();
2210         if (strlen(buf) > 256)
2211                 return 0;
2212         return (history(el_hist, &ev, H_ENTER, buf));
2213 }
2214
2215 static int ast_el_write_history(char *filename)
2216 {
2217         HistEvent ev;
2218
2219         if (el_hist == NULL || el == NULL)
2220                 ast_el_initialize();
2221
2222         return (history(el_hist, &ev, H_SAVE, filename));
2223 }
2224
2225 static int ast_el_read_history(char *filename)
2226 {
2227         char buf[256];
2228         FILE *f;
2229         int ret = -1;
2230
2231         if (el_hist == NULL || el == NULL)
2232                 ast_el_initialize();
2233
2234         if ((f = fopen(filename, "r")) == NULL)
2235                 return ret;
2236
2237         while (!feof(f)) {
2238                 fgets(buf, sizeof(buf), f);
2239                 if (!strcmp(buf, "_HiStOrY_V2_\n"))
2240                         continue;
2241                 if (ast_all_zeros(buf))
2242                         continue;
2243                 if ((ret = ast_el_add_history(buf)) == -1)
2244                         break;
2245         }
2246         fclose(f);
2247
2248         return ret;
2249 }
2250
2251 static void ast_remotecontrol(char * data)
2252 {
2253         char buf[80];
2254         int res;
2255         char filename[80] = "";
2256         char *hostname;
2257         char *cpid;
2258         char *version;
2259         int pid;
2260         char tmp[80];
2261         char *stringp = NULL;
2262
2263         char *ebuf;
2264         int num = 0;
2265
2266         read(ast_consock, buf, sizeof(buf));
2267         if (data)
2268                 write(ast_consock, data, strlen(data) + 1);
2269         stringp = buf;
2270         hostname = strsep(&stringp, "/");
2271         cpid = strsep(&stringp, "/");
2272         version = strsep(&stringp, "\n");
2273         if (!version)
2274                 version = "<Version Unknown>";
2275         stringp = hostname;
2276         strsep(&stringp, ".");
2277         if (cpid)
2278                 pid = atoi(cpid);
2279         else
2280                 pid = -1;
2281         snprintf(tmp, sizeof(tmp), "core set verbose atleast %d", option_verbose);
2282         fdprint(ast_consock, tmp);
2283         snprintf(tmp, sizeof(tmp), "core set debug atleast %d", option_debug);
2284         fdprint(ast_consock, tmp);
2285 #if defined(MARKO_BDAY)
2286         snprintf(tmp, sizeof(tmp), "marko show birthday");
2287         fdprint(ast_consock, tmp);
2288 #endif
2289         if (ast_opt_mute) {
2290                 snprintf(tmp, sizeof(tmp), "log and verbose output currently muted ('logger unmute' to unmute)");
2291                 fdprint(ast_consock, tmp);
2292         }
2293         ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
2294         remotehostname = hostname;
2295         if (getenv("HOME")) 
2296                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
2297         if (el_hist == NULL || el == NULL)
2298                 ast_el_initialize();
2299
2300         el_set(el, EL_GETCFN, ast_el_read_char);
2301
2302         if (!ast_strlen_zero(filename))
2303                 ast_el_read_history(filename);
2304
2305         if (ast_opt_exec && data) {  /* hack to print output then exit if asterisk -rx is used */
2306                 char tempchar;
2307                 struct pollfd fds;
2308                 fds.fd = ast_consock;
2309                 fds.events = POLLIN;
2310                 fds.revents = 0;
2311                 while (poll(&fds, 1, 100) > 0)
2312                         ast_el_read_char(el, &tempchar);
2313                 return;
2314         }
2315         for (;;) {
2316                 ebuf = (char *)el_gets(el, &num);
2317
2318                 if (!ast_strlen_zero(ebuf)) {
2319                         if (ebuf[strlen(ebuf)-1] == '\n')
2320                                 ebuf[strlen(ebuf)-1] = '\0';
2321                         if (!remoteconsolehandler(ebuf)) {
2322                                 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
2323                                 if (res < 1) {
2324                                         ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
2325                                         break;
2326                                 }
2327                         }
2328                 }
2329         }
2330         printf("\nDisconnected from Asterisk server\n");
2331 }
2332
2333 static int show_version(void)
2334 {
2335         printf("Asterisk " ASTERISK_VERSION "\n");
2336         return 0;
2337 }
2338
2339 static int show_cli_help(void) {
2340         printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 1999 - 2007, Digium, Inc. and others.\n");
2341         printf("Usage: asterisk [OPTIONS]\n");
2342         printf("Valid Options:\n");
2343         printf("   -V              Display version number and exit\n");
2344         printf("   -C <configfile> Use an alternate configuration file\n");
2345         printf("   -G <group>      Run as a group other than the caller\n");
2346         printf("   -U <user>       Run as a user other than the caller\n");
2347         printf("   -c              Provide console CLI\n");
2348         printf("   -d              Enable extra debugging\n");
2349 #if HAVE_WORKING_FORK
2350         printf("   -f              Do not fork\n");
2351         printf("   -F              Always fork\n");
2352 #endif
2353         printf("   -g              Dump core in case of a crash\n");
2354         printf("   -h              This help screen\n");
2355         printf("   -i              Initialize crypto keys at startup\n");
2356         printf("   -I              Enable internal timing if Zaptel timer is available\n");
2357         printf("   -L <load>       Limit the maximum load average before rejecting new calls\n");
2358         printf("   -M <value>      Limit the maximum number of calls to the specified value\n");
2359         printf("   -m              Mute the console from debugging and verbose output\n");
2360         printf("   -n              Disable console colorization\n");
2361         printf("   -p              Run as pseudo-realtime thread\n");
2362         printf("   -q              Quiet mode (suppress output)\n");
2363         printf("   -r              Connect to Asterisk on this machine\n");
2364         printf("   -R              Connect to Asterisk, and attempt to reconnect if disconnected\n");
2365         printf("   -t              Record soundfiles in /var/tmp and move them where they belong after they are done.\n");
2366         printf("   -T              Display the time in [Mmm dd hh:mm:ss] format for each line of output to the CLI.\n");
2367         printf("   -v              Increase verbosity (multiple v's = more verbose)\n");
2368         printf("   -x <cmd>        Execute command <cmd> (only valid with -r)\n");
2369         printf("\n");
2370         return 0;
2371 }
2372
2373 static void ast_readconfig(void) 
2374 {
2375         struct ast_config *cfg;
2376         struct ast_variable *v;
2377         char *config = AST_CONFIG_FILE;
2378         char hostname[MAXHOSTNAMELEN] = "";
2379
2380         if (ast_opt_override_config) {
2381                 cfg = ast_config_load(ast_config_AST_CONFIG_FILE);
2382                 if (!cfg)
2383                         ast_log(LOG_WARNING, "Unable to open specified master config file '%s', using built-in defaults\n", ast_config_AST_CONFIG_FILE);
2384         } else 
2385                 cfg = ast_config_load(config);
2386
2387         /* init with buildtime config */
2388         ast_copy_string(ast_config_AST_CONFIG_DIR, AST_CONFIG_DIR, sizeof(ast_config_AST_CONFIG_DIR));
2389         ast_copy_string(ast_config_AST_SPOOL_DIR, AST_SPOOL_DIR, sizeof(ast_config_AST_SPOOL_DIR));
2390         ast_copy_string(ast_config_AST_MODULE_DIR, AST_MODULE_DIR, sizeof(ast_config_AST_MODULE_DIR));
2391         snprintf(ast_config_AST_MONITOR_DIR, sizeof(ast_config_AST_MONITOR_DIR) - 1, "%s/monitor", ast_config_AST_SPOOL_DIR);
2392         ast_copy_string(ast_config_AST_VAR_DIR, AST_VAR_DIR, sizeof(ast_config_AST_VAR_DIR));
2393         ast_copy_string(ast_config_AST_DATA_DIR, AST_DATA_DIR, sizeof(ast_config_AST_DATA_DIR));
2394         ast_copy_string(ast_config_AST_LOG_DIR, AST_LOG_DIR, sizeof(ast_config_AST_LOG_DIR));
2395         ast_copy_string(ast_config_AST_AGI_DIR, AST_AGI_DIR, sizeof(ast_config_AST_AGI_DIR));
2396         ast_copy_string(ast_config_AST_DB, AST_DB, sizeof(ast_config_AST_DB));
2397         ast_copy_string(ast_config_AST_KEY_DIR, AST_KEY_DIR, sizeof(ast_config_AST_KEY_DIR));
2398         ast_copy_string(ast_config_AST_PID, AST_PID, sizeof(ast_config_AST_PID));
2399         ast_copy_string(ast_config_AST_SOCKET, AST_SOCKET, sizeof(ast_config_AST_SOCKET));
2400         ast_copy_string(ast_config_AST_RUN_DIR, AST_RUN_DIR, sizeof(ast_config_AST_RUN_DIR));
2401
2402         /* no asterisk.conf? no problem, use buildtime config! */
2403         if (!cfg) {
2404                 return;
2405         }
2406
2407         for (v = ast_variable_browse(cfg, "files"); v; v = v->next) {
2408                 if (!strcasecmp(v->name, "astctlpermissions"))
2409                         ast_copy_string(ast_config_AST_CTL_PERMISSIONS, v->value, sizeof(ast_config_AST_CTL_PERMISSIONS));
2410                 else if (!strcasecmp(v->name, "astctlowner"))
2411                         ast_copy_string(ast_config_AST_CTL_OWNER, v->value, sizeof(ast_config_AST_CTL_OWNER));
2412                 else if (!strcasecmp(v->name, "astctlgroup"))
2413                         ast_copy_string(ast_config_AST_CTL_GROUP, v->value, sizeof(ast_config_AST_CTL_GROUP));
2414                 else if (!strcasecmp(v->name, "astctl"))
2415                         ast_copy_string(ast_config_AST_CTL, v->value, sizeof(ast_config_AST_CTL));
2416         }
2417
2418         for (v = ast_variable_browse(cfg, "directories"); v; v = v->next) {
2419                 if (!strcasecmp(v->name, "astetcdir")) {
2420                         ast_copy_string(ast_config_AST_CONFIG_DIR, v->value, sizeof(ast_config_AST_CONFIG_DIR));
2421                 } else if (!strcasecmp(v->name, "astspooldir")) {
2422                         ast_copy_string(ast_config_AST_SPOOL_DIR, v->value, sizeof(ast_config_AST_SPOOL_DIR));
2423                         snprintf(ast_config_AST_MONITOR_DIR, sizeof(ast_config_AST_MONITOR_DIR) - 1, "%s/monitor", v->value);
2424                 } else if (!strcasecmp(v->name, "astvarlibdir")) {
2425                         ast_copy_string(ast_config_AST_VAR_DIR, v->value, sizeof(ast_config_AST_VAR_DIR));
2426                         snprintf(ast_config_AST_DB, sizeof(ast_config_AST_DB), "%s/astdb", v->value);
2427                 } else if (!strcasecmp(v->name, "astdatadir")) {
2428                         ast_copy_string(ast_config_AST_DATA_DIR, v->value, sizeof(ast_config_AST_DATA_DIR));
2429                         snprintf(ast_config_AST_KEY_DIR, sizeof(ast_config_AST_KEY_DIR), "%s/keys", v->value);
2430                 } else if (!strcasecmp(v->name, "astlogdir")) {
2431                         ast_copy_string(ast_config_AST_LOG_DIR, v->value, sizeof(ast_config_AST_LOG_DIR));
2432                 } else if (!strcasecmp(v->name, "astagidir")) {
2433                         ast_copy_string(ast_config_AST_AGI_DIR, v->value, sizeof(ast_config_AST_AGI_DIR));
2434                 } else if (!strcasecmp(v->name, "astrundir")) {
2435                         snprintf(ast_config_AST_PID, sizeof(ast_config_AST_PID), "%s/%s", v->value, "asterisk.pid");
2436                         snprintf(ast_config_AST_SOCKET, sizeof(ast_config_AST_SOCKET), "%s/%s", v->value, ast_config_AST_CTL);
2437                         ast_copy_string(ast_config_AST_RUN_DIR, v->value, sizeof(ast_config_AST_RUN_DIR));
2438                 } else if (!strcasecmp(v->name, "astmoddir")) {
2439                         ast_copy_string(ast_config_AST_MODULE_DIR, v->value, sizeof(ast_config_AST_MODULE_DIR));
2440                 }
2441         }
2442
2443         for (v = ast_variable_browse(cfg, "options"); v; v = v->next) {
2444                 /* verbose level (-v at startup) */
2445                 if (!strcasecmp(v->name, "verbose")) {
2446                         option_verbose = atoi(v->value);
2447                 /* whether or not to force timestamping in CLI verbose output. (-T at startup) */
2448                 } else if (!strcasecmp(v->name, "timestamp")) {
2449                         ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_TIMESTAMP);
2450                 /* whether or not to support #exec in config files */
2451                 } else if (!strcasecmp(v->name, "execincludes")) {
2452                         ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_EXEC_INCLUDES);
2453                 /* debug level (-d at startup) */
2454                 } else if (!strcasecmp(v->name, "debug")) {
2455                         option_debug = 0;
2456                         if (sscanf(v->value, "%d", &option_debug) != 1) {
2457                                 option_debug = ast_true(v->value);
2458                         }
2459 #if HAVE_WORKING_FORK
2460                 /* Disable forking (-f at startup) */
2461                 } else if (!strcasecmp(v->name, "nofork")) {
2462                         ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_NO_FORK);
2463                 /* Always fork, even if verbose or debug are enabled (-F at startup) */
2464                 } else if (!strcasecmp(v->name, "alwaysfork")) {
2465                         ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_ALWAYS_FORK);
2466 #endif
2467                 /* Run quietly (-q at startup ) */
2468                 } else if (!strcasecmp(v->name, "quiet")) {
2469                         ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_QUIET);
2470                 /* Run as console (-c at startup, implies nofork) */
2471                 } else if (!strcasecmp(v->name, "console")) {
2472                         ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_CONSOLE);
2473                 /* Run with high priority if the O/S permits (-p at startup) */
2474                 } else if (!strcasecmp(v->name, "highpriority")) {
2475                         ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_HIGH_PRIORITY);
2476                 /* Initialize RSA auth keys (IAX2) (-i at startup) */
2477                 } else if (!strcasecmp(v->name, "initcrypto")) {
2478                         ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_INIT_KEYS);
2479                 /* Disable ANSI colors for console (-c at startup) */
2480                 } else if (!strcasecmp(v->name, "nocolor")) {
2481                         ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_NO_COLOR);
2482                 /* Disable some usage warnings for picky people :p */
2483                 } else if (!strcasecmp(v->name, "dontwarn")) {
2484                         ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_DONT_WARN);
2485                 /* Dump core in case of crash (-g) */
2486                 } else if (!strcasecmp(v->name, "dumpcore")) {
2487                         ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_DUMP_CORE);
2488                 /* Cache recorded sound files to another directory during recording */
2489                 } else if (!strcasecmp(v->name, "cache_record_files")) {
2490                         ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_CACHE_RECORD_FILES);
2491                 /* Specify cache directory */
2492                 }  else if (!strcasecmp(v->name, "record_cache_dir")) {
2493                         ast_copy_string(record_cache_dir, v->value, AST_CACHE_DIR_LEN);
2494                 /* Build transcode paths via SLINEAR, instead of directly */
2495                 } else if (!strcasecmp(v->name, "transcode_via_sln")) {
2496                         ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_TRANSCODE_VIA_SLIN);
2497                 /* Transmit SLINEAR silence while a channel is being recorded */
2498                 } else if (!strcasecmp(v->name, "transmit_silence_during_record")) {
2499                         ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_TRANSMIT_SILENCE);
2500                 /* Enable internal timing */
2501                 } else if (!strcasecmp(v->name, "internal_timing")) {
2502                         ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_INTERNAL_TIMING);
2503                 } else if (!strcasecmp(v->name, "maxcalls")) {
2504                         if ((sscanf(v->value, "%d", &option_maxcalls) != 1) || (option_maxcalls < 0)) {
2505                                 option_maxcalls = 0;
2506                         }
2507                 } else if (!strcasecmp(v->name, "maxload")) {
2508                         double test[1];
2509
2510                         if (getloadavg(test, 1) == -1) {
2511                                 ast_log(LOG_ERROR, "Cannot obtain load average on this system. 'maxload' option disabled.\n");
2512                                 option_maxload = 0.0;
2513                         } else if ((sscanf(v->value, "%lf", &option_maxload) != 1) || (option_maxload < 0.0)) {
2514                                 option_maxload = 0.0;
2515                         }
2516                 /* Set the maximum amount of open files */
2517                 } else if (!strcasecmp(v->name, "maxfiles")) {
2518                         option_maxfiles = atoi(v->value);
2519                         set_ulimit(option_maxfiles);
2520                 /* What user to run as */
2521                 } else if (!strcasecmp(v->name, "runuser")) {
2522                         ast_copy_string(ast_config_AST_RUN_USER, v->value, sizeof(ast_config_AST_RUN_USER));
2523                 /* What group to run as */
2524                 } else if (!strcasecmp(v->name, "rungroup")) {
2525                         ast_copy_string(ast_config_AST_RUN_GROUP, v->value, sizeof(ast_config_AST_RUN_GROUP));
2526                 } else if (!strcasecmp(v->name, "systemname")) {
2527                         ast_copy_string(ast_config_AST_SYSTEM_NAME, v->value, sizeof(ast_config_AST_SYSTEM_NAME));
2528                 } else if (!strcasecmp(v->name, "autosystemname")) {
2529                         if (ast_true(v->value)) {
2530                                 if (!gethostname(hostname, sizeof(hostname) - 1))
2531                                         ast_copy_string(ast_config_AST_SYSTEM_NAME, hostname, sizeof(ast_config_AST_SYSTEM_NAME));
2532                                 else {
2533                                         if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)){
2534                                                 ast_copy_string(ast_config_AST_SYSTEM_NAME, "localhost", sizeof(ast_config_AST_SYSTEM_NAME));
2535                                         }
2536                                         ast_log(LOG_ERROR, "Cannot obtain hostname for this system.  Using '%s' instead.\n", ast_config_AST_SYSTEM_NAME);
2537                                 }
2538                         }
2539                 } else if (!strcasecmp(v->name, "languageprefix")) {
2540                         ast_language_is_prefix = ast_true(v->value);
2541 #if defined(HAVE_SYSINFO)
2542                 } else if (!strcasecmp(v->name, "minmemfree")) {
2543                         /* specify the minimum amount of free memory to retain.  Asterisk should stop accepting new calls
2544                          * if the amount of free memory falls below this watermark */
2545                         if ((sscanf(v->value, "%ld", &option_minmemfree) != 1) || (option_minmemfree < 0)) {
2546                                 option_minmemfree = 0;
2547                         }
2548 #endif
2549                 }
2550         }
2551         ast_config_destroy(cfg);
2552 }
2553
2554 static void *monitor_sig_flags(void *unused)
2555 {
2556         for (;;) {
2557                 struct pollfd p = { sig_alert_pipe[0], POLLIN, 0 };
2558                 int a;
2559                 poll(&p, 1, -1);
2560                 if (sig_flags.need_reload) {
2561                         sig_flags.need_reload = 0;
2562                         ast_module_reload(NULL);
2563                 }
2564                 if (sig_flags.need_quit) {
2565                         sig_flags.need_quit = 0;
2566                         quit_handler(0, 0, 1, 0);
2567                 }
2568                 read(sig_alert_pipe[0], &a, sizeof(a));
2569         }
2570
2571         return NULL;
2572 }
2573
2574 int main(int argc, char *argv[])
2575 {
2576         int c;
2577         char filename[80] = "";
2578         char hostname[MAXHOSTNAMELEN] = "";
2579         char tmp[80];
2580         char * xarg = NULL;
2581         int x;
2582         FILE *f;
2583         sigset_t sigs;
2584         int num;
2585         int is_child_of_nonroot = 0;
2586         char *buf;
2587         char *runuser = NULL, *rungroup = NULL;
2588
2589         /* Remember original args for restart */
2590         if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
2591                 fprintf(stderr, "Truncating argument size to %d\n", (int)(sizeof(_argv) / sizeof(_argv[0])) - 1);
2592                 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
2593         }
2594         for (x=0; x<argc; x++)
2595                 _argv[x] = argv[x];
2596         _argv[x] = NULL;
2597
2598         /* if the progname is rasterisk consider it a remote console */
2599         if (argv[0] && (strstr(argv[0], "rasterisk")) != NULL) {
2600                 ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK | AST_OPT_FLAG_REMOTE);
2601         }
2602         if (gethostname(hostname, sizeof(hostname)-1))
2603                 ast_copy_string(hostname, "<Unknown>", sizeof(hostname));
2604         ast_mainpid = getpid();
2605         ast_ulaw_init();
2606         ast_alaw_init();
2607         callerid_init();
2608         ast_builtins_init();
2609         ast_event_init();
2610         ast_utils_init();
2611         tdd_init();
2612         /* When Asterisk restarts after it has dropped the root privileges,
2613          * it can't issue setuid(), setgid(), setgroups() or set_priority() 
2614          */
2615         if (getenv("ASTERISK_ALREADY_NONROOT"))
2616                 is_child_of_nonroot=1;
2617         if (getenv("HOME")) 
2618                 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
2619         /* Check for options */
2620         while ((c = getopt(argc, argv, "mtThfFdvVqprRgciInx:U:G:C:L:M:e:")) != -1) {
2621                 switch (c) {
2622 #if defined(HAVE_SYSINFO)
2623                 case 'e':
2624                         if ((sscanf(&optarg[1], "%ld", &option_minmemfree) != 1) || (option_minmemfree < 0)) {
2625                                 option_minmemfree = 0;
2626                         }
2627                         break;
2628 #endif
2629 #if HAVE_WORKING_FORK
2630                 case 'F':
2631                         ast_set_flag(&ast_options, AST_OPT_FLAG_ALWAYS_FORK);
2632                         break;
2633                 case 'f':
2634                         ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK);
2635                         break;
2636 #endif
2637                 case 'd':
2638                         option_debug++;
2639                         ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK);
2640                         break;
2641                 case 'c':
2642                         ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK | AST_OPT_FLAG_CONSOLE);
2643                         break;
2644                 case 'n':
2645                         ast_set_flag(&ast_options, AST_OPT_FLAG_NO_COLOR);
2646                         break;
2647                 case 'r':
2648                         ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK | AST_OPT_FLAG_REMOTE);
2649                         break;
2650                 case 'R':
2651                         ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK | AST_OPT_FLAG_REMOTE | AST_OPT_FLAG_RECONNECT);
2652                         break;
2653                 case 'p':
2654                         ast_set_flag(&ast_options, AST_OPT_FLAG_HIGH_PRIORITY);
2655                         break;
2656                 case 'v':
2657                         option_verbose++;
2658                         ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK);
2659                         break;
2660                 case 'm':
2661                         ast_set_flag(&ast_options, AST_OPT_FLAG_MUTE);
2662                         break;
2663                 case 'M':
2664                         if ((sscanf(optarg, "%d", &option_maxcalls) != 1) || (option_maxcalls < 0))
2665                                 option_maxcalls = 0;
2666                         break;
2667                 case 'L':
2668                         if ((sscanf(optarg, "%lf", &option_maxload) != 1) || (option_maxload < 0.0))
2669                                 option_maxload = 0.0;
2670                         break;
2671                 case 'q':
2672                         ast_set_flag(&ast_options, AST_OPT_FLAG_QUIET);
2673                         break;
2674                 case 't':
2675                         ast_set_flag(&ast_options, AST_OPT_FLAG_CACHE_RECORD_FILES);
2676                         break;
2677                 case 'T':
2678                         ast_set_flag(&ast_options, AST_OPT_FLAG_TIMESTAMP);
2679                         break;
2680                 case 'x':
2681                         ast_set_flag(&ast_options, AST_OPT_FLAG_EXEC);
2682                         xarg = optarg;
2683                         break;
2684                 case 'C':
2685                         ast_copy_string(ast_config_AST_CONFIG_FILE, optarg, sizeof(ast_config_AST_CONFIG_FILE));
2686                         ast_set_flag(&ast_options, AST_OPT_FLAG_OVERRIDE_CONFIG);
2687                         break;
2688                 case 'I':
2689                         ast_set_flag(&ast_options, AST_OPT_FLAG_INTERNAL_TIMING);
2690                         break;
2691                 case 'i':
2692                         ast_set_flag(&ast_options, AST_OPT_FLAG_INIT_KEYS);
2693                         break;
2694                 case 'g':
2695                         ast_set_flag(&ast_options, AST_OPT_FLAG_DUMP_CORE);
2696                         break;
2697                 case 'h':
2698                         show_cli_help();
2699                         exit(0);
2700                 case 'V':
2701                         show_version();
2702                         exit(0);
2703                 case 'U':
2704                         runuser = optarg;
2705                         break;
2706                 case 'G':
2707                         rungroup = optarg;
2708                         break;
2709                 case '?':
2710                         exit(1);
2711                 }
2712         }
2713
2714         if (ast_opt_console || option_verbose || (ast_opt_remote && !ast_opt_exec)) {
2715                 ast_register_verbose(console_verboser);
2716                 WELCOME_MESSAGE;
2717         }
2718
2719         if (ast_opt_console && !option_verbose) 
2720                 ast_verbose("[ Booting...\n");
2721
2722         if (ast_opt_always_fork && (ast_opt_remote || ast_opt_console)) {
2723                 ast_log(LOG_WARNING, "'alwaysfork' is not compatible with console or remote console mode; ignored\n");
2724                 ast_clear_flag(&ast_options, AST_OPT_FLAG_ALWAYS_FORK);
2725         }
2726
2727         /* For remote connections, change the name of the remote connection.
2728          * We do this for the benefit of init scripts (which need to know if/when
2729          * the main asterisk process has died yet). */
2730         if (ast_opt_remote) {
2731                 strcpy(argv[0], "rasterisk");
2732                 for (x = 1; x < argc; x++) {
2733                         argv[x] = argv[0] + 10;
2734                 }
2735         }
2736
2737         if (ast_opt_console && !option_verbose) 
2738                 ast_verbose("[ Reading Master Configuration ]\n");
2739         ast_readconfig();
2740
2741         if (!ast_language_is_prefix && !ast_opt_remote)
2742                 ast_log(LOG_WARNING, "The 'languageprefix' option in asterisk.conf is deprecated; in a future release it will be removed, and your sound files will need to be organized in the 'new style' language layout.\n");
2743
2744         if (ast_opt_dump_core) {
2745                 struct rlimit l;
2746                 memset(&l, 0, sizeof(l));
2747                 l.rlim_cur = RLIM_INFINITY;
2748                 l.rlim_max = RLIM_INFINITY;
2749                 if (setrlimit(RLIMIT_CORE, &l)) {
2750                         ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
2751                 }
2752         }
2753
2754         if ((!rungroup) && !ast_strlen_zero(ast_config_AST_RUN_GROUP))
2755                 rungroup = ast_config_AST_RUN_GROUP;
2756         if ((!runuser) && !ast_strlen_zero(ast_config_AST_RUN_USER))
2757                 runuser = ast_config_AST_RUN_USER;
2758
2759 #ifndef __CYGWIN__
2760
2761         if (!is_child_of_nonroot) 
2762                 ast_set_priority(ast_opt_high_priority);
2763
2764         if (!is_child_of_nonroot && rungroup) {
2765                 struct group *gr;
2766                 gr = getgrnam(rungroup);
2767                 if (!gr) {
2768                         ast_log(LOG_WARNING, "No such group '%s'!\n", rungroup);
2769                         exit(1);
2770                 }
2771                 if (setgid(gr->gr_gid)) {
2772                         ast_log(LOG_WARNING, "Unable to setgid to %d (%s)\n", (int)gr->gr_gid, rungroup);
2773                         exit(1);
2774                 }
2775                 if (setgroups(0, NULL)) {
2776                         ast_log(LOG_WARNING, "Unable to drop unneeded groups\n");
2777                         exit(1);
2778                 }
2779                 if (option_verbose)
2780                         ast_verbose("Running as group '%s'\n", rungroup);
2781         }
2782
2783         if (!is_child_of_nonroot && runuser) {
2784 #ifdef HAVE_CAP
2785                 int has_cap = 1;
2786 #endif /* HAVE_CAP */
2787                 struct passwd *pw;
2788                 pw = getpwnam(runuser);
2789                 if (!pw) {
2790                         ast_log(LOG_WARNING, "No such user '%s'!\n", runuser);
2791                         exit(1);
2792                 }
2793 #ifdef HAVE_CAP
2794                 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0)) {
2795                         ast_log(LOG_WARNING, "Unable to keep capabilities.\n");
2796                         has_cap = 0;
2797                 }
2798 #endif /* HAVE_CAP */
2799                 if (!rungroup) {
2800                         if (setgid(pw->pw_gid)) {
2801                                 ast_log(LOG_WARNING, "Unable to setgid to %d!\n", (int)pw->pw_gid);
2802                                 exit(1);
2803                         }
2804                         if (initgroups(pw->pw_name, pw->pw_gid)) {
2805                                 ast_log(LOG_WARNING, "Unable to init groups for '%s'\n", runuser);
2806                                 exit(1);
2807                         }
2808                 }
2809                 if (setuid(pw->pw_uid)) {
2810                         ast_log(LOG_WARNING, "Unable to setuid to %d (%s)\n", (int)pw->pw_uid, runuser);
2811                         exit(1);
2812                 }
2813                 setenv("ASTERISK_ALREADY_NONROOT", "yes", 1);
2814                 if (option_verbose)
2815                         ast_verbose("Running as user '%s'\n", runuser);
2816 #ifdef HAVE_CAP
2817                 if (has_cap) {
2818                         cap_t cap;
2819
2820                         cap = cap_from_text("cap_net_admin=ep");
2821
2822                         if (cap_set_proc(cap))
2823                                 ast_log(LOG_WARNING, "Unable to install capabilities.\n");
2824
2825                         if (cap_free(cap))
2826                                 ast_log(LOG_WARNING, "Unable to drop capabilities.\n");
2827                 }
2828 #endif /* HAVE_CAP */
2829         }
2830
2831 #endif /* __CYGWIN__ */
2832
2833 #ifdef linux
2834         if (geteuid() && ast_opt_dump_core) {
2835                 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) < 0) {
2836                         ast_log(LOG_WARNING, "Unable to set the process for core dumps after changing to a non-root user. %s\n", strerror(errno));
2837                 }       
2838         }
2839 #endif
2840
2841         ast_term_init();
2842         printf(term_end());
2843         fflush(stdout);
2844
2845         if (ast_opt_console && !option_verbose) 
2846                 ast_verbose("[ Initializing Custom Configuration Options ]\n");
2847         /* custom config setup */
2848         register_config_cli();
2849         read_config_maps();
2850         
2851         if (ast_opt_console) {
2852                 if (el_hist == NULL || el == NULL)
2853                         ast_el_initialize();
2854
2855                 if (!ast_strlen_zero(filename))
2856                         ast_el_read_history(filename);
2857         }
2858
2859         if (ast_tryconnect()) {
2860                 /* One is already running */
2861                 if (ast_opt_remote) {
2862                         if (ast_opt_exec) {
2863                                 ast_remotecontrol(xarg);
2864                                 quit_handler(0, 0, 0, 0);
2865                                 exit(0);
2866                         }
2867                         printf(term_quit());
2868                         ast_remotecontrol(NULL);
2869                         quit_handler(0, 0, 0, 0);
2870                         exit(0);
2871                 } else {
2872                         ast_log(LOG_ERROR, "Asterisk already running on %s.  Use 'asterisk -r' to connect.\n", ast_config_AST_SOCKET);
2873                         printf(term_quit());
2874                         exit(1);
2875                 }
2876         } else if (ast_opt_remote || ast_opt_exec) {
2877                 ast_log(LOG_ERROR, "Unable to connect to remote asterisk (does %s exist?)\n", ast_config_AST_SOCKET);
2878                 printf(term_quit());
2879                 exit(1);
2880         }
2881         /* Blindly write pid file since we couldn't connect */
2882         unlink(ast_config_AST_PID);
2883         f = fopen(ast_config_AST_PID, "w");
2884         if (f) {
2885                 fprintf(f, "%ld\n", (long)getpid());
2886                 fclose(f);
2887         } else
2888                 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", ast_config_AST_PID, strerror(errno));
2889
2890 #if HAVE_WORKING_FORK
2891         if (ast_opt_always_fork || !ast_opt_no_fork) {
2892                 daemon(0, 0);
2893                 ast_mainpid = getpid();
2894                 /* Blindly re-write pid file since we are forking */
2895                 unlink(ast_config_AST_PID);
2896                 f = fopen(ast_config_AST_PID, "w");
2897                 if (f) {
2898                         fprintf(f, "%ld\n", (long)ast_mainpid);
2899                         fclose(f);
2900                 } else
2901                         ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", ast_config_AST_PID, strerror(errno));
2902         }
2903 #endif
2904
2905         /* Test recursive mutex locking. */
2906         if (test_for_thread_safety())
2907                 ast_verbose("Warning! Asterisk is not thread safe.\n");
2908
2909         ast_makesocket();
2910         sigemptyset(&sigs);
2911         sigaddset(&sigs, SIGHUP);
2912         sigaddset(&sigs, SIGTERM);
2913         sigaddset(&sigs, SIGINT);
2914         sigaddset(&sigs, SIGPIPE);
2915         sigaddset(&sigs, SIGWINCH);
2916         pthread_sigmask(SIG_BLOCK, &sigs, NULL);
2917         signal(SIGURG, urg_handler);
2918         signal(SIGINT, __quit_handler);
2919         signal(SIGTERM, __quit_handler);
2920         signal(SIGHUP, hup_handler);
2921         signal(SIGCHLD, child_handler);
2922         signal(SIGPIPE, SIG_IGN);
2923
2924         /* ensure that the random number generators are seeded with a different value every time
2925            Asterisk is started
2926         */
2927         srand((unsigned int) getpid() + (unsigned int) time(NULL));
2928         initstate((unsigned int) getpid() * 65536 + (unsigned int) time(NULL), randompool, sizeof(randompool));
2929
2930         if (init_logger()) {            /* Start logging subsystem */
2931                 printf(term_quit());
2932                 exit(1);
2933         }
2934
2935         threadstorage_init();
2936
2937         if (load_modules(1)) {          /* Load modules, pre-load only */
2938                 printf(term_quit());
2939                 exit(1);
2940         }
2941
2942         if (dnsmgr_init()) {            /* Initialize the DNS manager */
2943                 printf(term_quit());
2944                 exit(1);
2945         }
2946
2947         ast_http_init();                /* Start the HTTP server, if needed */
2948
2949         ast_channels_init();
2950
2951         if (init_manager()) {
2952                 printf(term_quit());
2953                 exit(1);
2954         }
2955
2956         if (ast_cdr_engine_init()) {
2957                 printf(term_quit());
2958                 exit(1);
2959         }
2960
2961         if (ast_device_state_engine_init()) {
2962                 printf(term_quit());
2963                 exit(1);
2964         }
2965
2966         ast_rtp_init();
2967
2968         ast_udptl_init();
2969
2970         if (ast_image_init()) {
2971                 printf(term_quit());
2972                 exit(1);
2973         }
2974
2975         if (ast_file_init()) {
2976                 printf(term_quit());
2977                 exit(1);
2978         }
2979
2980         if (load_pbx()) {
2981                 printf(term_quit());
2982                 exit(1);
2983         }
2984
2985         if (init_framer()) {
2986                 printf(term_quit());
2987                 exit(1);
2988         }
2989
2990         if (astdb_init()) {
2991                 printf(term_quit());
2992                 exit(1);
2993         }
2994
2995         if (ast_enum_init()) {
2996                 printf(term_quit());
2997                 exit(1);
2998         }
2999
3000         if (load_modules(0)) {
3001                 printf(term_quit());
3002                 exit(1);
3003         }
3004
3005         dnsmgr_start_refresh();
3006
3007         /* We might have the option of showing a console, but for now just
3008            do nothing... */
3009         if (ast_opt_console && !option_verbose)
3010                 ast_verbose(" ]\n");
3011         if (option_verbose || ast_opt_console)
3012                 ast_verbose(term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
3013         if (ast_opt_no_fork)
3014                 consolethread = pthread_self();
3015
3016         if (pipe(sig_alert_pipe))
3017                 sig_alert_pipe[0] = sig_alert_pipe[1] = -1;
3018
3019         ast_set_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED);
3020         pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
3021
3022 #ifdef __AST_DEBUG_MALLOC
3023         __ast_mm_init();
3024 #endif  
3025
3026         time(&ast_startuptime);
3027         ast_cli_register_multiple(cli_asterisk, sizeof(cli_asterisk) / sizeof(struct ast_cli_entry));
3028
3029         if (ast_opt_console) {
3030                 /* Console stuff now... */
3031                 /* Register our quit function */
3032                 char title[256];
3033                 pthread_t dont_care;
3034
3035                 ast_pthread_create_detached(&dont_care, NULL, monitor_sig_flags, NULL);
3036
3037                 set_icon("Asterisk");
3038                 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %ld)", hostname, (long)ast_mainpid);
3039                 set_title(title);
3040
3041                 for (;;) {
3042                         buf = (char *)el_gets(el, &num);
3043                         if (buf) {
3044                                 if (buf[strlen(buf)-1] == '\n')
3045                                         buf[strlen(buf)-1] = '\0';
3046
3047                                 consolehandler((char *)buf);
3048                         } else if (ast_opt_remote && (write(STDOUT_FILENO, "\nUse EXIT or QUIT to exit the asterisk console\n",
3049                                    strlen("\nUse EXIT or QUIT to exit the asterisk console\n")) < 0)) {
3050                                 /* Whoa, stdout disappeared from under us... Make /dev/null's */
3051                                 int fd;
3052                                 fd = open("/dev/null", O_RDWR);
3053                                 if (fd > -1) {
3054                                         dup2(fd, STDOUT_FILENO);
3055                                         dup2(fd, STDIN_FILENO);
3056                                 } else
3057                                         ast_log(LOG_WARNING, "Failed to open /dev/null to recover from dead console. Bad things will happen!\n");
3058                                 break;
3059                         }
3060                 }
3061         }
3062
3063         monitor_sig_flags(NULL);
3064
3065         return 0;
3066 }