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