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