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