core: fix getopt(3) usage
[asterisk/asterisk.git] / main / asterisk.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2016, 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 -- The Open Source Telephony Project
23  *
24  * \par Welcome
25  *
26  * This documentation created by the Doxygen project clearly explains the
27  * internals of the Asterisk software. This documentation contains basic
28  * examples, developer documentation, support information, and information
29  * for upgrading.
30  *
31  * \section community Community
32  * Asterisk is a big project and has a busy community. Look at the
33  * resources for questions and stick around to help answer questions.
34  * \li \ref asterisk_community_resources
35  *
36  * \par Developer Documentation for Asterisk
37  *
38  * This is the main developer documentation for Asterisk. It is
39  * generated by running "make progdocs" from the Asterisk source tree.
40  *
41  * In addition to the information available on the Asterisk source code,
42  * please see the appendices for information on coding guidelines,
43  * release management, commit policies, and more.
44  *
45  * \arg \ref AsteriskArchitecture
46  *
47  * \par Additional documentation
48  * \arg \ref Licensing
49  * \arg \ref DevDoc
50  * \arg \ref configuration_file
51  * \arg \ref channel_drivers
52  * \arg \ref applications
53  *
54  * \section copyright Copyright and Author
55  *
56  * Copyright (C) 1999 - 2016, Digium, Inc.
57  * Asterisk is a <a href="http://www.digium.com/en/company/view-policy.php?id=Trademark-Policy">registered trademark</a>
58  * of <a rel="nofollow" href="http://www.digium.com">Digium, Inc</a>.
59  *
60  * \author Mark Spencer <markster@digium.com>
61  *
62  * See http://www.asterisk.org for more information about
63  * the Asterisk project. Please do not directly contact
64  * any of the maintainers of this project for assistance;
65  * the project provides a web site, mailing lists, and IRC
66  * channels for your use.
67  *
68  */
69
70 /*!
71  * \page asterisk_community_resources Asterisk Community Resources
72  * \par Websites
73  * \li http://www.asterisk.org Asterisk Homepage
74  * \li http://wiki.asterisk.org Asterisk Wiki
75  *
76  * \par Mailing Lists
77  * \par
78  * All lists: http://lists.digium.com/mailman/listinfo
79  * \li aadk-commits     SVN commits to the AADK repository
80  * \li asterisk-addons-commits  SVN commits to the Asterisk addons project
81  * \li asterisk-announce        [no description available]
82  * \li asterisk-biz     Commercial and Business-Oriented Asterisk Discussion
83  * \li Asterisk-BSD     Asterisk on BSD discussion
84  * \li asterisk-bugs    [no description available]
85  * \li asterisk-commits SVN commits to the Asterisk project
86  * \li asterisk-dev     Asterisk Developers Mailing List
87  * \li asterisk-doc     Discussions regarding The Asterisk Documentation Project
88  * \li asterisk-embedded        Asterisk Embedded Development
89  * \li asterisk-gui     Asterisk GUI project discussion
90  * \li asterisk-gui-commits     SVN commits to the Asterisk-GUI project
91  * \li asterisk-ha-clustering   Asterisk High Availability and Clustering List - Non-Commercial Discussion
92  * \li Asterisk-i18n    Discussion of Asterisk internationalization
93  * \li asterisk-r2      [no description available]
94  * \li asterisk-scf-commits     Commits to the Asterisk SCF project code repositories
95  * \li asterisk-scf-committee   Asterisk SCF Steering Committee discussions
96  * \li asterisk-scf-dev Asterisk SCF Developers Mailing List
97  * \li asterisk-scf-wiki-changes        Changes to the Asterisk SCF space on wiki.asterisk.org
98  * \li asterisk-security        Asterisk Security Discussion
99  * \li asterisk-speech-rec      Use of speech recognition in Asterisk
100  * \li asterisk-ss7     [no description available]
101  * \li asterisk-users   Asterisk Users Mailing List - Non-Commercial Discussion
102  * \li asterisk-video   Development discussion of video media support in Asterisk
103  * \li asterisk-wiki-changes    Changes to the Asterisk space on wiki.asterisk.org
104  * \li asterisknow      AsteriskNOW Discussion
105  * \li dahdi-commits    SVN commits to the DAHDI project
106  * \li digium-announce  Digium Product Announcements
107  * \li Dundi    Distributed Universal Number Discovery
108  * \li libiax2-commits  SVN commits to the libiax2 project
109  * \li libpri-commits   SVN commits to the libpri project
110  * \li libss7-commits   SVN commits to the libss7 project
111  * \li svn-commits      SVN commits to the Digium repositories
112  * \li Test-results     Results from automated testing
113  * \li thirdparty-commits       SVN commits to the Digium third-party software repository
114  * \li zaptel-commits   SVN commits to the Zaptel project
115  *
116  * \par Forums
117  * \li Forums are located at http://forums.asterisk.org/
118  *
119  * \par IRC
120  * \par
121  * Use http://www.freenode.net IRC server to connect with Asterisk
122  * developers and users in realtime.
123  *
124  * \li \verbatim #asterisk \endverbatim Asterisk Users Room
125  * \li \verbatim #asterisk-dev \endverbatim Asterisk Developers Room
126  *
127  * \par More
128  * \par
129  * If you would like to add a resource to this list please create an issue
130  * on the issue tracker with a patch.
131  */
132
133 /*! \file
134  * \brief Top level source file for Asterisk - the Open Source PBX.
135  *      Implementation of PBX core functions and CLI interface.
136  */
137
138 /*! \li \ref asterisk.c uses the configuration file \ref asterisk.conf
139  * \addtogroup configuration_file
140  */
141
142 /*! \page asterisk.conf asterisk.conf
143  * \verbinclude asterisk.conf.sample
144  */
145
146 /*** MODULEINFO
147         <support_level>core</support_level>
148  ***/
149
150 #include "asterisk.h"
151
152 #include "asterisk/_private.h"
153
154 #undef sched_setscheduler
155 #undef setpriority
156 #include <sys/time.h>
157 #include <fcntl.h>
158 #include <signal.h>
159 #include <sched.h>
160 #include <sys/un.h>
161 #include <sys/wait.h>
162 #include <ctype.h>
163 #include <sys/resource.h>
164 #include <grp.h>
165 #include <pwd.h>
166 #include <sys/stat.h>
167 #if defined(HAVE_SYSINFO)
168 #include <sys/sysinfo.h>
169 #elif defined(HAVE_SYSCTL)
170 #include <sys/param.h>
171 #include <sys/sysctl.h>
172 #include <sys/vmmeter.h>
173 #if defined(__FreeBSD__)
174 #include <vm/vm_param.h>
175 #endif
176 #if defined(HAVE_SWAPCTL)
177 #include <sys/swap.h>
178 #endif
179 #endif
180 #include <regex.h>
181 #include <histedit.h>
182
183 #if defined(SOLARIS)
184 int daemon(int, int);  /* defined in libresolv of all places */
185 #include <sys/loadavg.h>
186 #endif
187
188 #ifdef linux
189 #include <sys/prctl.h>
190 #ifdef HAVE_CAP
191 #include <sys/capability.h>
192 #endif /* HAVE_CAP */
193 #endif /* linux */
194
195 /* we define here the variables so to better agree on the prototype */
196 #include "asterisk/paths.h"
197 #include "asterisk/network.h"
198 #include "asterisk/cli.h"
199 #include "asterisk/channel.h"
200 #include "asterisk/translate.h"
201 #include "asterisk/pickup.h"
202 #include "asterisk/acl.h"
203 #include "asterisk/ulaw.h"
204 #include "asterisk/alaw.h"
205 #include "asterisk/callerid.h"
206 #include "asterisk/image.h"
207 #include "asterisk/tdd.h"
208 #include "asterisk/term.h"
209 #include "asterisk/manager.h"
210 #include "asterisk/cdr.h"
211 #include "asterisk/pbx.h"
212 #include "asterisk/app.h"
213 #include "asterisk/lock.h"
214 #include "asterisk/utils.h"
215 #include "asterisk/file.h"
216 #include "asterisk/io.h"
217 #include "asterisk/config.h"
218 #include "asterisk/ast_version.h"
219 #include "asterisk/linkedlists.h"
220 #include "asterisk/devicestate.h"
221 #include "asterisk/presencestate.h"
222 #include "asterisk/module.h"
223 #include "asterisk/buildinfo.h"
224 #include "asterisk/xmldoc.h"
225 #include "asterisk/poll-compat.h"
226 #include "asterisk/test.h"
227 #include "asterisk/rtp_engine.h"
228 #include "asterisk/format.h"
229 #include "asterisk/aoc.h"
230 #include "asterisk/uuid.h"
231 #include "asterisk/sorcery.h"
232 #include "asterisk/bucket.h"
233 #include "asterisk/stasis.h"
234 #include "asterisk/json.h"
235 #include "asterisk/stasis_endpoints.h"
236 #include "asterisk/stasis_system.h"
237 #include "asterisk/security_events.h"
238 #include "asterisk/endpoints.h"
239 #include "asterisk/codec.h"
240 #include "asterisk/format_cache.h"
241 #include "asterisk/media_cache.h"
242 #include "asterisk/astdb.h"
243 #include "asterisk/options.h"
244
245 #include "../defaults.h"
246
247 /*** DOCUMENTATION
248         <managerEvent language="en_US" name="FullyBooted">
249                 <managerEventInstance class="EVENT_FLAG_SYSTEM">
250                         <synopsis>Raised when all Asterisk initialization procedures have finished.</synopsis>
251                         <syntax>
252                                 <parameter name="Status">
253                                         <para>Informational message</para>
254                                 </parameter>
255                                 <parameter name="Uptime">
256                                         <para>Seconds since start</para>
257                                 </parameter>
258                                 <parameter name="LastReload">
259                                         <para>Seconds since last reload</para>
260                                 </parameter>
261                         </syntax>
262                 </managerEventInstance>
263         </managerEvent>
264         <managerEvent language="en_US" name="Shutdown">
265                 <managerEventInstance class="EVENT_FLAG_SYSTEM">
266                         <synopsis>Raised when Asterisk is shutdown or restarted.</synopsis>
267                         <syntax>
268                                 <parameter name="Shutdown">
269                                         <para>Whether the shutdown is proceeding cleanly (all channels
270                                         were hungup successfully) or uncleanly (channels will be
271                                         terminated)</para>
272                                         <enumlist>
273                                                 <enum name="Uncleanly"/>
274                                                 <enum name="Cleanly"/>
275                                         </enumlist>
276                                 </parameter>
277                                 <parameter name="Restart">
278                                         <para>Whether or not a restart will occur.</para>
279                                         <enumlist>
280                                                 <enum name="True"/>
281                                                 <enum name="False"/>
282                                         </enumlist>
283                                 </parameter>
284                         </syntax>
285                 </managerEventInstance>
286         </managerEvent>
287  ***/
288
289 #ifndef AF_LOCAL
290 #define AF_LOCAL AF_UNIX
291 #define PF_LOCAL PF_UNIX
292 #endif
293
294 #define AST_MAX_CONNECTS 128
295 #define NUM_MSGS 64
296
297 /*! Default minimum DTMF digit length - 80ms */
298 #define AST_MIN_DTMF_DURATION 80
299
300
301 /*! \brief Welcome message when starting a CLI interface */
302 #define WELCOME_MESSAGE \
303     ast_verbose("Asterisk %s, Copyright (C) 1999 - 2016, Digium, Inc. and others.\n" \
304                 "Created by Mark Spencer <markster@digium.com>\n" \
305                 "Asterisk comes with ABSOLUTELY NO WARRANTY; type 'core show warranty' for details.\n" \
306                 "This is free software, with components licensed under the GNU General Public\n" \
307                 "License version 2 and other licenses; you are welcome to redistribute it under\n" \
308                 "certain conditions. Type 'core show license' for details.\n" \
309                 "=========================================================================\n", ast_get_version()) \
310
311 /*! \defgroup main_options Main Configuration Options
312  * \brief Main configuration options from asterisk.conf or OS command line on starting Asterisk.
313  * \arg \ref Config_ast "asterisk.conf"
314  * \note Some of them can be changed in the CLI
315  */
316 /*! @{ */
317
318 struct ast_flags ast_options = { AST_DEFAULT_OPTIONS };
319
320 /*! Maximum active system verbosity level. */
321 int ast_verb_sys_level;
322
323 int option_verbose;                             /*!< Verbosity level */
324 int option_debug;                               /*!< Debug level */
325 int ast_pjproject_max_log_level = -1;/* Default to -1 to know if we have read the level from pjproject yet. */
326 int ast_option_pjproject_log_level;
327 int ast_option_pjproject_cache_pools;
328 double ast_option_maxload;                      /*!< Max load avg on system */
329 int ast_option_maxcalls;                        /*!< Max number of active calls */
330 int ast_option_maxfiles;                        /*!< Max number of open file handles (files, sockets) */
331 unsigned int option_dtmfminduration;            /*!< Minimum duration of DTMF. */
332 #if defined(HAVE_SYSINFO)
333 long option_minmemfree;                         /*!< Minimum amount of free system memory - stop accepting calls if free memory falls below this watermark */
334 #endif
335 int ast_option_rtpusedynamic;
336 unsigned int ast_option_rtpptdynamic;
337
338 /*! @} */
339
340 struct ast_eid ast_eid_default;
341
342 /* XXX tmpdir is a subdir of the spool directory, and no way to remap it */
343 char record_cache_dir[AST_CACHE_DIR_LEN] = DEFAULT_TMP_DIR;
344
345 static int ast_socket = -1;             /*!< UNIX Socket for allowing remote control */
346 static int ast_socket_is_sd = 0; /*!< Is socket activation responsible for ast_socket? */
347 static int ast_consock = -1;            /*!< UNIX Socket for controlling another asterisk */
348 pid_t ast_mainpid;
349 struct console {
350         int fd;                         /*!< File descriptor */
351         int p[2];                       /*!< Pipe */
352         pthread_t t;                    /*!< Thread of handler */
353         int mute;                       /*!< Is the console muted for logs */
354         int uid;                        /*!< Remote user ID. */
355         int gid;                        /*!< Remote group ID. */
356         int levels[NUMLOGLEVELS];       /*!< Which log levels are enabled for the console */
357         /*! Verbosity level of this console. */
358         int option_verbose;
359 };
360
361 struct ast_atexit {
362         void (*func)(void);
363         int is_cleanup;
364         AST_LIST_ENTRY(ast_atexit) list;
365 };
366
367 static AST_LIST_HEAD_STATIC(atexits, ast_atexit);
368
369 struct timeval ast_startuptime;
370 struct timeval ast_lastreloadtime;
371
372 static History *el_hist;
373 static EditLine *el;
374 static char *remotehostname;
375
376 struct console consoles[AST_MAX_CONNECTS];
377
378 char ast_defaultlanguage[MAX_LANGUAGE] = DEFAULT_LANGUAGE;
379
380 static int ast_el_add_history(const char *);
381 static int ast_el_read_history(const char *);
382 static int ast_el_write_history(const char *);
383
384 static void ast_el_read_default_histfile(void);
385 static void ast_el_write_default_histfile(void);
386
387 static void asterisk_daemon(int isroot, const char *runuser, const char *rungroup);
388
389 #define DEFAULT_MONITOR_DIR DEFAULT_SPOOL_DIR "/monitor"
390 #define DEFAULT_RECORDING_DIR DEFAULT_SPOOL_DIR "/recording"
391
392 struct _cfg_paths {
393         char config_dir[PATH_MAX];
394         char module_dir[PATH_MAX];
395         char spool_dir[PATH_MAX];
396         char monitor_dir[PATH_MAX];
397         char recording_dir[PATH_MAX];
398         char var_dir[PATH_MAX];
399         char data_dir[PATH_MAX];
400         char log_dir[PATH_MAX];
401         char agi_dir[PATH_MAX];
402         char run_dir[PATH_MAX];
403         char key_dir[PATH_MAX];
404
405         char config_file[PATH_MAX];
406         char db_path[PATH_MAX];
407         char sbin_dir[PATH_MAX];
408         char pid_path[PATH_MAX];
409         char socket_path[PATH_MAX];
410         char run_user[PATH_MAX];
411         char run_group[PATH_MAX];
412         char system_name[128];
413 };
414
415 static struct _cfg_paths cfg_paths;
416
417 const char *ast_config_AST_CONFIG_DIR   = cfg_paths.config_dir;
418 const char *ast_config_AST_CONFIG_FILE  = cfg_paths.config_file;
419 const char *ast_config_AST_MODULE_DIR   = cfg_paths.module_dir;
420 const char *ast_config_AST_SPOOL_DIR    = cfg_paths.spool_dir;
421 const char *ast_config_AST_MONITOR_DIR  = cfg_paths.monitor_dir;
422 const char *ast_config_AST_RECORDING_DIR        = cfg_paths.recording_dir;
423 const char *ast_config_AST_VAR_DIR      = cfg_paths.var_dir;
424 const char *ast_config_AST_DATA_DIR     = cfg_paths.data_dir;
425 const char *ast_config_AST_LOG_DIR      = cfg_paths.log_dir;
426 const char *ast_config_AST_AGI_DIR      = cfg_paths.agi_dir;
427 const char *ast_config_AST_KEY_DIR      = cfg_paths.key_dir;
428 const char *ast_config_AST_RUN_DIR      = cfg_paths.run_dir;
429 const char *ast_config_AST_SBIN_DIR = cfg_paths.sbin_dir;
430
431 const char *ast_config_AST_DB           = cfg_paths.db_path;
432 const char *ast_config_AST_PID          = cfg_paths.pid_path;
433 const char *ast_config_AST_SOCKET       = cfg_paths.socket_path;
434 const char *ast_config_AST_RUN_USER     = cfg_paths.run_user;
435 const char *ast_config_AST_RUN_GROUP    = cfg_paths.run_group;
436 const char *ast_config_AST_SYSTEM_NAME  = cfg_paths.system_name;
437
438 static char ast_config_AST_CTL_PERMISSIONS[PATH_MAX];
439 static char ast_config_AST_CTL_OWNER[PATH_MAX] = "\0";
440 static char ast_config_AST_CTL_GROUP[PATH_MAX] = "\0";
441 static char ast_config_AST_CTL[PATH_MAX] = "asterisk.ctl";
442
443 extern unsigned int ast_FD_SETSIZE;
444
445 static char *_argv[256];
446
447 typedef enum {
448         /*! Normal operation */
449         NOT_SHUTTING_DOWN,
450         /*! Committed to shutting down.  Final phase */
451         SHUTTING_DOWN_FINAL,
452         /*! Committed to shutting down.  Initial phase */
453         SHUTTING_DOWN,
454         /*!
455          * Valid values for quit_handler() niceness below.
456          * These shutdown/restart levels can be cancelled.
457          *
458          * Remote console exit right now
459          */
460         SHUTDOWN_FAST,
461         /*! core stop/restart now */
462         SHUTDOWN_NORMAL,
463         /*! core stop/restart gracefully */
464         SHUTDOWN_NICE,
465         /*! core stop/restart when convenient */
466         SHUTDOWN_REALLY_NICE
467 } shutdown_nice_t;
468
469 static shutdown_nice_t shuttingdown = NOT_SHUTTING_DOWN;
470
471 /*! Prevent new channel allocation for shutdown. */
472 static int shutdown_pending;
473
474 static int restartnow;
475 static pthread_t consolethread = AST_PTHREADT_NULL;
476 static pthread_t mon_sig_flags;
477 static int canary_pid = 0;
478 static char canary_filename[128];
479 static int multi_thread_safe;
480
481 static char randompool[256];
482
483 static int sig_alert_pipe[2] = { -1, -1 };
484 static struct {
485          unsigned int need_reload:1;
486          unsigned int need_quit:1;
487          unsigned int need_quit_handler:1;
488 } sig_flags;
489
490 #if !defined(LOW_MEMORY)
491 struct thread_list_t {
492         AST_RWLIST_ENTRY(thread_list_t) list;
493         char *name;
494         pthread_t id;
495         int lwp;
496 };
497
498 static AST_RWLIST_HEAD_STATIC(thread_list, thread_list_t);
499
500 void ast_register_thread(char *name)
501 {
502         struct thread_list_t *new = ast_calloc(1, sizeof(*new));
503
504         if (!new)
505                 return;
506
507         ast_assert(multi_thread_safe);
508         new->id = pthread_self();
509         new->lwp = ast_get_tid();
510         new->name = name; /* steal the allocated memory for the thread name */
511         AST_RWLIST_WRLOCK(&thread_list);
512         AST_RWLIST_INSERT_HEAD(&thread_list, new, list);
513         AST_RWLIST_UNLOCK(&thread_list);
514 }
515
516 void ast_unregister_thread(void *id)
517 {
518         struct thread_list_t *x;
519
520         AST_RWLIST_WRLOCK(&thread_list);
521         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&thread_list, x, list) {
522                 if ((void *) x->id == id) {
523                         AST_RWLIST_REMOVE_CURRENT(list);
524                         break;
525                 }
526         }
527         AST_RWLIST_TRAVERSE_SAFE_END;
528         AST_RWLIST_UNLOCK(&thread_list);
529         if (x) {
530                 ast_free(x->name);
531                 ast_free(x);
532         }
533 }
534
535 /*! \brief Give an overview of core settings */
536 static char *handle_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
537 {
538         char buf[BUFSIZ];
539         struct ast_tm tm;
540         char eid_str[128];
541         struct rlimit limits;
542         char pbx_uuid[AST_UUID_STR_LEN];
543
544         switch (cmd) {
545         case CLI_INIT:
546                 e->command = "core show settings";
547                 e->usage = "Usage: core show settings\n"
548                            "       Show core misc settings";
549                 return NULL;
550         case CLI_GENERATE:
551                 return NULL;
552         }
553
554         ast_eid_to_str(eid_str, sizeof(eid_str), &ast_eid_default);
555         ast_pbx_uuid_get(pbx_uuid, sizeof(pbx_uuid));
556
557         ast_cli(a->fd, "\nPBX Core settings\n");
558         ast_cli(a->fd, "-----------------\n");
559         ast_cli(a->fd, "  Version:                     %s\n", ast_get_version());
560         ast_cli(a->fd, "  Build Options:               %s\n", S_OR(ast_get_build_opts(), "(none)"));
561         if (ast_option_maxcalls)
562                 ast_cli(a->fd, "  Maximum calls:               %d (Current %d)\n", ast_option_maxcalls, ast_active_channels());
563         else
564                 ast_cli(a->fd, "  Maximum calls:               Not set\n");
565
566         if (getrlimit(RLIMIT_NOFILE, &limits)) {
567                 ast_cli(a->fd, "  Maximum open file handles:   Error because of %s\n", strerror(errno));
568         } else if (limits.rlim_cur == RLIM_INFINITY) {
569                 ast_cli(a->fd, "  Maximum open file handles:   Unlimited\n");
570         } else if (limits.rlim_cur < ast_option_maxfiles) {
571                 ast_cli(a->fd, "  Maximum open file handles:   %d (is) %d (requested)\n", (int) limits.rlim_cur, ast_option_maxfiles);
572         } else {
573                 ast_cli(a->fd, "  Maximum open file handles:   %d\n", (int) limits.rlim_cur);
574         }
575
576         ast_cli(a->fd, "  Root console verbosity:      %d\n", option_verbose);
577         ast_cli(a->fd, "  Current console verbosity:   %d\n", ast_verb_console_get());
578         ast_cli(a->fd, "  Debug level:                 %d\n", option_debug);
579         ast_cli(a->fd, "  Maximum load average:        %lf\n", ast_option_maxload);
580 #if defined(HAVE_SYSINFO)
581         ast_cli(a->fd, "  Minimum free memory:         %ld MB\n", option_minmemfree);
582 #endif
583         if (ast_localtime(&ast_startuptime, &tm, NULL)) {
584                 ast_strftime(buf, sizeof(buf), "%H:%M:%S", &tm);
585                 ast_cli(a->fd, "  Startup time:                %s\n", buf);
586         }
587         if (ast_localtime(&ast_lastreloadtime, &tm, NULL)) {
588                 ast_strftime(buf, sizeof(buf), "%H:%M:%S", &tm);
589                 ast_cli(a->fd, "  Last reload time:            %s\n", buf);
590         }
591         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);
592         ast_cli(a->fd, "  System name:                 %s\n", ast_config_AST_SYSTEM_NAME);
593         ast_cli(a->fd, "  Entity ID:                   %s\n", eid_str);
594         ast_cli(a->fd, "  PBX UUID:                    %s\n", pbx_uuid);
595         ast_cli(a->fd, "  Default language:            %s\n", ast_defaultlanguage);
596         ast_cli(a->fd, "  Language prefix:             %s\n", ast_language_is_prefix ? "Enabled" : "Disabled");
597         ast_cli(a->fd, "  User name and group:         %s/%s\n", ast_config_AST_RUN_USER, ast_config_AST_RUN_GROUP);
598         ast_cli(a->fd, "  Executable includes:         %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_EXEC_INCLUDES) ? "Enabled" : "Disabled");
599         ast_cli(a->fd, "  Transcode via SLIN:          %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_TRANSCODE_VIA_SLIN) ? "Enabled" : "Disabled");
600         ast_cli(a->fd, "  Transmit silence during rec: %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_TRANSMIT_SILENCE) ? "Enabled" : "Disabled");
601         ast_cli(a->fd, "  Generic PLC:                 %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_GENERIC_PLC) ? "Enabled" : "Disabled");
602         ast_cli(a->fd, "  Generic PLC on equal codecs: %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_GENERIC_PLC_ON_EQUAL_CODECS) ? "Enabled" : "Disabled");
603         ast_cli(a->fd, "  Min DTMF duration::          %u\n", option_dtmfminduration);
604 #if !defined(LOW_MEMORY)
605         ast_cli(a->fd, "  Cache media frames:          %s\n", ast_opt_cache_media_frames ? "Enabled" : "Disabled");
606 #endif
607         ast_cli(a->fd, "  RTP use dynamic payloads:    %u\n", ast_option_rtpusedynamic);
608
609         if (ast_option_rtpptdynamic == AST_RTP_PT_LAST_REASSIGN) {
610                 ast_cli(a->fd, "  RTP dynamic payload types:   %u,%u-%u\n",
611                         ast_option_rtpptdynamic,
612                         AST_RTP_PT_FIRST_DYNAMIC, AST_RTP_MAX_PT - 1);
613         } else if (ast_option_rtpptdynamic < AST_RTP_PT_LAST_REASSIGN) {
614                 ast_cli(a->fd, "  RTP dynamic payload types:   %u-%u,%u-%u\n",
615                         ast_option_rtpptdynamic, AST_RTP_PT_LAST_REASSIGN,
616                         AST_RTP_PT_FIRST_DYNAMIC, AST_RTP_MAX_PT - 1);
617         } else {
618                 ast_cli(a->fd, "  RTP dynamic payload types:   %u-%u\n",
619                         AST_RTP_PT_FIRST_DYNAMIC, AST_RTP_MAX_PT - 1);
620         }
621
622         ast_cli(a->fd, "\n* Subsystems\n");
623         ast_cli(a->fd, "  -------------\n");
624         ast_cli(a->fd, "  Manager (AMI):               %s\n", check_manager_enabled() ? "Enabled" : "Disabled");
625         ast_cli(a->fd, "  Web Manager (AMI/HTTP):      %s\n", check_webmanager_enabled() ? "Enabled" : "Disabled");
626         ast_cli(a->fd, "  Call data records:           %s\n", ast_cdr_is_enabled() ? "Enabled" : "Disabled");
627         ast_cli(a->fd, "  Realtime Architecture (ARA): %s\n", ast_realtime_enabled() ? "Enabled" : "Disabled");
628
629         /*! \todo we could check musiconhold, voicemail, smdi, adsi, queues  */
630
631         ast_cli(a->fd, "\n* Directories\n");
632         ast_cli(a->fd, "  -------------\n");
633         ast_cli(a->fd, "  Configuration file:          %s\n", ast_config_AST_CONFIG_FILE);
634         ast_cli(a->fd, "  Configuration directory:     %s\n", ast_config_AST_CONFIG_DIR);
635         ast_cli(a->fd, "  Module directory:            %s\n", ast_config_AST_MODULE_DIR);
636         ast_cli(a->fd, "  Spool directory:             %s\n", ast_config_AST_SPOOL_DIR);
637         ast_cli(a->fd, "  Log directory:               %s\n", ast_config_AST_LOG_DIR);
638         ast_cli(a->fd, "  Run/Sockets directory:       %s\n", ast_config_AST_RUN_DIR);
639         ast_cli(a->fd, "  PID file:                    %s\n", ast_config_AST_PID);
640         ast_cli(a->fd, "  VarLib directory:            %s\n", ast_config_AST_VAR_DIR);
641         ast_cli(a->fd, "  Data directory:              %s\n", ast_config_AST_DATA_DIR);
642         ast_cli(a->fd, "  ASTDB:                       %s\n", ast_config_AST_DB);
643         ast_cli(a->fd, "  IAX2 Keys directory:         %s\n", ast_config_AST_KEY_DIR);
644         ast_cli(a->fd, "  AGI Scripts directory:       %s\n", ast_config_AST_AGI_DIR);
645         ast_cli(a->fd, "\n\n");
646         return CLI_SUCCESS;
647 }
648
649 static char *handle_show_threads(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
650 {
651         int count = 0;
652         struct thread_list_t *cur;
653         switch (cmd) {
654         case CLI_INIT:
655                 e->command = "core show threads";
656                 e->usage =
657                         "Usage: core show threads\n"
658                         "       List threads currently active in the system.\n";
659                 return NULL;
660         case CLI_GENERATE:
661                 return NULL;
662         }
663
664         AST_RWLIST_RDLOCK(&thread_list);
665         AST_RWLIST_TRAVERSE(&thread_list, cur, list) {
666                 ast_cli(a->fd, "%p %d %s\n", (void *)cur->id, cur->lwp, cur->name);
667                 count++;
668         }
669         AST_RWLIST_UNLOCK(&thread_list);
670         ast_cli(a->fd, "%d threads listed.\n", count);
671         return CLI_SUCCESS;
672 }
673
674 #if defined (HAVE_SYSCTL) && defined(HAVE_SWAPCTL)
675 /*
676  * swapmode is rewritten by Tobias Weingartner <weingart@openbsd.org>
677  * to be based on the new swapctl(2) system call.
678  */
679 static int swapmode(int *used, int *total)
680 {
681         struct swapent *swdev;
682         int nswap, rnswap, i;
683
684         nswap = swapctl(SWAP_NSWAP, 0, 0);
685         if (nswap == 0)
686                 return 0;
687
688         swdev = ast_calloc(nswap, sizeof(*swdev));
689         if (swdev == NULL)
690                 return 0;
691
692         rnswap = swapctl(SWAP_STATS, swdev, nswap);
693         if (rnswap == -1) {
694                 ast_free(swdev);
695                 return 0;
696         }
697
698         /* if rnswap != nswap, then what? */
699
700         /* Total things up */
701         *total = *used = 0;
702         for (i = 0; i < nswap; i++) {
703                 if (swdev[i].se_flags & SWF_ENABLE) {
704                         *used += (swdev[i].se_inuse / (1024 / DEV_BSIZE));
705                         *total += (swdev[i].se_nblks / (1024 / DEV_BSIZE));
706                 }
707         }
708         ast_free(swdev);
709         return 1;
710 }
711 #endif
712
713 #if defined(HAVE_SYSINFO) || defined(HAVE_SYSCTL)
714 /*! \brief Give an overview of system statistics */
715 static char *handle_show_sysinfo(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
716 {
717         uint64_t physmem, freeram;
718 #if defined(HAVE_SYSINFO) || defined(HAVE_SWAPCTL)
719         int totalswap = 0;
720         uint64_t freeswap = 0;
721 #endif
722         int nprocs = 0;
723         long uptime = 0;
724 #if defined(HAVE_SYSINFO)
725         struct sysinfo sys_info;
726 #elif defined(HAVE_SYSCTL)
727         static int pageshift;
728         struct vmtotal vmtotal;
729         struct timeval  boottime;
730         time_t  now;
731         int mib[2], pagesize;
732 #if defined(HAVE_SWAPCTL)
733         int usedswap = 0;
734 #endif
735         size_t len;
736 #endif
737
738         switch (cmd) {
739         case CLI_INIT:
740                 e->command = "core show sysinfo";
741                 e->usage =
742                         "Usage: core show sysinfo\n"
743                         "       List current system information.\n";
744                 return NULL;
745         case CLI_GENERATE:
746                 return NULL;
747         }
748
749 #if defined(HAVE_SYSINFO)
750         sysinfo(&sys_info);
751         uptime = sys_info.uptime / 3600;
752         physmem = sys_info.totalram * sys_info.mem_unit;
753         freeram = (sys_info.freeram * sys_info.mem_unit) / 1024;
754         totalswap = (sys_info.totalswap * sys_info.mem_unit) / 1024;
755         freeswap = (sys_info.freeswap * sys_info.mem_unit) / 1024;
756         nprocs = sys_info.procs;
757 #elif defined(HAVE_SYSCTL)
758         /* calculate the uptime by looking at boottime */
759         time(&now);
760         mib[0] = CTL_KERN;
761         mib[1] = KERN_BOOTTIME;
762         len = sizeof(boottime);
763         if (sysctl(mib, 2, &boottime, &len, NULL, 0) != -1) {
764                 uptime = now - boottime.tv_sec;
765         }
766         uptime = uptime/3600;
767         /* grab total physical memory  */
768         mib[0] = CTL_HW;
769 #if defined(HW_PHYSMEM64)
770         mib[1] = HW_PHYSMEM64;
771 #else
772         mib[1] = HW_PHYSMEM;
773 #endif
774         len = sizeof(physmem);
775         sysctl(mib, 2, &physmem, &len, NULL, 0);
776
777         pagesize = getpagesize();
778         pageshift = 0;
779         while (pagesize > 1) {
780                 pageshift++;
781                 pagesize >>= 1;
782         }
783
784         /* we only need the amount of log(2)1024 for our conversion */
785         pageshift -= 10;
786
787         /* grab vm totals */
788         mib[0] = CTL_VM;
789         mib[1] = VM_METER;
790         len = sizeof(vmtotal);
791         sysctl(mib, 2, &vmtotal, &len, NULL, 0);
792         freeram = (vmtotal.t_free << pageshift);
793         /* generate swap usage and totals */
794 #if defined(HAVE_SWAPCTL)
795         swapmode(&usedswap, &totalswap);
796         freeswap = (totalswap - usedswap);
797 #endif
798         /* grab number of processes */
799 #if defined(__OpenBSD__)
800         mib[0] = CTL_KERN;
801         mib[1] = KERN_NPROCS;
802         len = sizeof(nprocs);
803         sysctl(mib, 2, &nprocs, &len, NULL, 0);
804 #endif
805 #endif
806
807         ast_cli(a->fd, "\nSystem Statistics\n");
808         ast_cli(a->fd, "-----------------\n");
809         ast_cli(a->fd, "  System Uptime:             %ld hours\n", uptime);
810         ast_cli(a->fd, "  Total RAM:                 %" PRIu64 " KiB\n", physmem / 1024);
811         ast_cli(a->fd, "  Free RAM:                  %" PRIu64 " KiB\n", freeram);
812 #if defined(HAVE_SYSINFO)
813         ast_cli(a->fd, "  Buffer RAM:                %" PRIu64 " KiB\n", ((uint64_t) sys_info.bufferram * sys_info.mem_unit) / 1024);
814 #endif
815 #if defined(HAVE_SYSINFO) || defined(HAVE_SWAPCTL)
816         ast_cli(a->fd, "  Total Swap Space:          %d KiB\n", totalswap);
817         ast_cli(a->fd, "  Free Swap Space:           %" PRIu64 " KiB\n\n", freeswap);
818 #endif
819         ast_cli(a->fd, "  Number of Processes:       %d \n\n", nprocs);
820         return CLI_SUCCESS;
821 }
822 #endif
823
824 struct profile_entry {
825         const char *name;
826         uint64_t        scale;  /* if non-zero, values are scaled by this */
827         int64_t mark;
828         int64_t value;
829         int64_t events;
830 };
831
832 struct profile_data {
833         int entries;
834         int max_size;
835         struct profile_entry e[0];
836 };
837
838 static struct profile_data *prof_data;
839 #endif /* ! LOW_MEMORY */
840
841 /*! \brief allocates a counter with a given name and scale.
842  * \return Returns the identifier of the counter.
843  */
844 int ast_add_profile(const char *name, uint64_t scale)
845 {
846 #if !defined(LOW_MEMORY)
847         int l = sizeof(struct profile_data);
848         int n = 10;     /* default entries */
849
850         if (prof_data == NULL) {
851                 prof_data = ast_calloc(1, l + n*sizeof(struct profile_entry));
852                 if (prof_data == NULL)
853                         return -1;
854                 prof_data->entries = 0;
855                 prof_data->max_size = n;
856         }
857         if (prof_data->entries >= prof_data->max_size) {
858                 void *p;
859                 n = prof_data->max_size + 20;
860                 p = ast_realloc(prof_data, l + n*sizeof(struct profile_entry));
861                 if (p == NULL)
862                         return -1;
863                 prof_data = p;
864                 prof_data->max_size = n;
865         }
866         n = prof_data->entries++;
867         prof_data->e[n].name = ast_strdup(name);
868         prof_data->e[n].value = 0;
869         prof_data->e[n].events = 0;
870         prof_data->e[n].mark = 0;
871         prof_data->e[n].scale = scale;
872         return n;
873 #else /* if defined(LOW_MEMORY) */
874         return 0;
875 #endif
876 }
877
878 int64_t ast_profile(int i, int64_t delta)
879 {
880 #if !defined(LOW_MEMORY)
881         if (!prof_data || i < 0 || i > prof_data->entries)      /* invalid index */
882                 return 0;
883         if (prof_data->e[i].scale > 1)
884                 delta /= prof_data->e[i].scale;
885         prof_data->e[i].value += delta;
886         prof_data->e[i].events++;
887         return prof_data->e[i].value;
888 #else /* if defined(LOW_MEMORY) */
889         return 0;
890 #endif
891 }
892
893 #if !defined(LOW_MEMORY)
894 /* The RDTSC instruction was introduced on the Pentium processor and is not
895  * implemented on certain clones, like the Cyrix 586. Hence, the previous
896  * expectation of __i386__ was in error. */
897 #if defined ( __i686__) && (defined(__FreeBSD__) || defined(linux))
898 #if defined(__FreeBSD__)
899 #include <machine/cpufunc.h>
900 #elif defined(linux)
901 static __inline uint64_t
902 rdtsc(void)
903 {
904         uint64_t rv;
905
906         __asm __volatile(".byte 0x0f, 0x31" : "=A" (rv));
907         return (rv);
908 }
909 #endif
910 #else   /* supply a dummy function on other platforms */
911 static __inline uint64_t
912 rdtsc(void)
913 {
914         return 0;
915 }
916 #endif
917 #endif /* ! LOW_MEMORY */
918
919 int64_t ast_mark(int i, int startstop)
920 {
921 #if !defined(LOW_MEMORY)
922         if (!prof_data || i < 0 || i > prof_data->entries) /* invalid index */
923                 return 0;
924         if (startstop == 1)
925                 prof_data->e[i].mark = rdtsc();
926         else {
927                 prof_data->e[i].mark = (rdtsc() - prof_data->e[i].mark);
928                 if (prof_data->e[i].scale > 1)
929                         prof_data->e[i].mark /= prof_data->e[i].scale;
930                 prof_data->e[i].value += prof_data->e[i].mark;
931                 prof_data->e[i].events++;
932         }
933         return prof_data->e[i].mark;
934 #else /* if defined(LOW_MEMORY) */
935         return 0;
936 #endif
937 }
938
939 #if !defined(LOW_MEMORY)
940 #define DEFINE_PROFILE_MIN_MAX_VALUES min = 0; \
941         max = prof_data->entries;\
942         if  (a->argc > 3) { /* specific entries */ \
943                 if (isdigit(a->argv[3][0])) { \
944                         min = atoi(a->argv[3]); \
945                         if (a->argc == 5 && strcmp(a->argv[4], "-")) \
946                                 max = atoi(a->argv[4]); \
947                 } else \
948                         search = a->argv[3]; \
949         } \
950         if (max > prof_data->entries) \
951                 max = prof_data->entries;
952
953 static char *handle_show_profile(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
954 {
955         int i, min, max;
956         const char *search = NULL;
957         switch (cmd) {
958         case CLI_INIT:
959                 e->command = "core show profile";
960                 e->usage = "Usage: core show profile\n"
961                            "       show profile information";
962                 return NULL;
963         case CLI_GENERATE:
964                 return NULL;
965         }
966
967         if (prof_data == NULL)
968                 return 0;
969
970         DEFINE_PROFILE_MIN_MAX_VALUES;
971         ast_cli(a->fd, "profile values (%d, allocated %d)\n-------------------\n",
972                 prof_data->entries, prof_data->max_size);
973         ast_cli(a->fd, "%6s   %8s  %10s %12s %12s  %s\n", "ID", "Scale", "Events",
974                         "Value", "Average", "Name");
975         for (i = min; i < max; i++) {
976                 struct profile_entry *entry = &prof_data->e[i];
977                 if (!search || strstr(entry->name, search))
978                     ast_cli(a->fd, "%6d: [%8ld] %10ld %12lld %12lld  %s\n",
979                         i,
980                         (long)entry->scale,
981                         (long)entry->events, (long long)entry->value,
982                         (long long)(entry->events ? entry->value / entry->events : entry->value),
983                         entry->name);
984         }
985         return CLI_SUCCESS;
986 }
987
988 static char *handle_clear_profile(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
989 {
990         int i, min, max;
991         const char *search = NULL;
992         switch (cmd) {
993         case CLI_INIT:
994                 e->command = "core clear profile";
995                 e->usage = "Usage: core clear profile\n"
996                            "       clear profile information";
997                 return NULL;
998         case CLI_GENERATE:
999                 return NULL;
1000         }
1001
1002         if (prof_data == NULL)
1003                 return 0;
1004
1005         DEFINE_PROFILE_MIN_MAX_VALUES;
1006         for (i= min; i < max; i++) {
1007                 if (!search || strstr(prof_data->e[i].name, search)) {
1008                         prof_data->e[i].value = 0;
1009                         prof_data->e[i].events = 0;
1010                 }
1011         }
1012         return CLI_SUCCESS;
1013 }
1014 #undef DEFINE_PROFILE_MIN_MAX_VALUES
1015
1016 #endif /* ! LOW_MEMORY */
1017
1018 int ast_pbx_uuid_get(char *pbx_uuid, int length)
1019 {
1020         return ast_db_get("pbx", "UUID", pbx_uuid, length);
1021 }
1022
1023 static void publish_fully_booted(void)
1024 {
1025         struct ast_json *json_object;
1026         int uptime = 0;
1027         int lastreloaded = 0;
1028         struct timeval tmp;
1029         struct timeval curtime = ast_tvnow();
1030
1031         if (ast_startuptime.tv_sec) {
1032                 tmp = ast_tvsub(curtime, ast_startuptime);
1033                 uptime = (int) tmp.tv_sec;
1034         }
1035
1036         if (ast_lastreloadtime.tv_sec) {
1037                 tmp = ast_tvsub(curtime, ast_lastreloadtime);
1038                 lastreloaded = (int) tmp.tv_sec;
1039         }
1040
1041         json_object = ast_json_pack("{s: s, s: i, s: i}",
1042                         "Status", "Fully Booted",
1043                         "Uptime", uptime,
1044                         "LastReload", lastreloaded);
1045         ast_manager_publish_event("FullyBooted", EVENT_FLAG_SYSTEM, json_object);
1046         ast_json_unref(json_object);
1047 }
1048
1049 static void ast_run_atexits(int run_cleanups)
1050 {
1051         struct ast_atexit *ae;
1052
1053         AST_LIST_LOCK(&atexits);
1054         while ((ae = AST_LIST_REMOVE_HEAD(&atexits, list))) {
1055                 if (ae->func && (!ae->is_cleanup || run_cleanups)) {
1056                         ae->func();
1057                 }
1058                 ast_free(ae);
1059         }
1060         AST_LIST_UNLOCK(&atexits);
1061 }
1062
1063 static void __ast_unregister_atexit(void (*func)(void))
1064 {
1065         struct ast_atexit *ae;
1066
1067         AST_LIST_TRAVERSE_SAFE_BEGIN(&atexits, ae, list) {
1068                 if (ae->func == func) {
1069                         AST_LIST_REMOVE_CURRENT(list);
1070                         ast_free(ae);
1071                         break;
1072                 }
1073         }
1074         AST_LIST_TRAVERSE_SAFE_END;
1075 }
1076
1077 static int register_atexit(void (*func)(void), int is_cleanup)
1078 {
1079         struct ast_atexit *ae;
1080
1081         ae = ast_calloc(1, sizeof(*ae));
1082         if (!ae) {
1083                 return -1;
1084         }
1085         ae->func = func;
1086         ae->is_cleanup = is_cleanup;
1087
1088         AST_LIST_LOCK(&atexits);
1089         __ast_unregister_atexit(func);
1090         AST_LIST_INSERT_HEAD(&atexits, ae, list);
1091         AST_LIST_UNLOCK(&atexits);
1092
1093         return 0;
1094 }
1095
1096 int ast_register_atexit(void (*func)(void))
1097 {
1098         return register_atexit(func, 0);
1099 }
1100
1101 int ast_register_cleanup(void (*func)(void))
1102 {
1103         return register_atexit(func, 1);
1104 }
1105
1106 void ast_unregister_atexit(void (*func)(void))
1107 {
1108         AST_LIST_LOCK(&atexits);
1109         __ast_unregister_atexit(func);
1110         AST_LIST_UNLOCK(&atexits);
1111 }
1112
1113 /* Sending commands from consoles back to the daemon requires a terminating NULL */
1114 static int fdsend(int fd, const char *s)
1115 {
1116         return write(fd, s, strlen(s) + 1);
1117 }
1118
1119 /* Sending messages from the daemon back to the display requires _excluding_ the terminating NULL */
1120 static int fdprint(int fd, const char *s)
1121 {
1122         return write(fd, s, strlen(s));
1123 }
1124
1125 /*! \brief NULL handler so we can collect the child exit status */
1126 static void _null_sig_handler(int sig)
1127 {
1128 }
1129
1130 static struct sigaction null_sig_handler = {
1131         .sa_handler = _null_sig_handler,
1132         .sa_flags = SA_RESTART,
1133 };
1134
1135 static struct sigaction ignore_sig_handler = {
1136         .sa_handler = SIG_IGN,
1137 };
1138
1139 AST_MUTEX_DEFINE_STATIC(safe_system_lock);
1140 /*! \brief Keep track of how many threads are currently trying to wait*() on
1141  *  a child process
1142  */
1143 static unsigned int safe_system_level = 0;
1144 static struct sigaction safe_system_prev_handler;
1145
1146 void ast_replace_sigchld(void)
1147 {
1148         unsigned int level;
1149
1150         ast_mutex_lock(&safe_system_lock);
1151         level = safe_system_level++;
1152
1153         /* only replace the handler if it has not already been done */
1154         if (level == 0) {
1155                 sigaction(SIGCHLD, &null_sig_handler, &safe_system_prev_handler);
1156         }
1157
1158         ast_mutex_unlock(&safe_system_lock);
1159 }
1160
1161 void ast_unreplace_sigchld(void)
1162 {
1163         unsigned int level;
1164
1165         ast_mutex_lock(&safe_system_lock);
1166         level = --safe_system_level;
1167
1168         /* only restore the handler if we are the last one */
1169         if (level == 0) {
1170                 sigaction(SIGCHLD, &safe_system_prev_handler, NULL);
1171         }
1172
1173         ast_mutex_unlock(&safe_system_lock);
1174 }
1175
1176 /*! \brief fork and perform other preparations for spawning applications */
1177 static pid_t safe_exec_prep(int dualfork)
1178 {
1179         pid_t pid;
1180
1181 #if defined(HAVE_WORKING_FORK) || defined(HAVE_WORKING_VFORK)
1182         ast_replace_sigchld();
1183
1184 #ifdef HAVE_WORKING_FORK
1185         pid = fork();
1186 #else
1187         pid = vfork();
1188 #endif
1189
1190         if (pid == 0) {
1191 #ifdef HAVE_CAP
1192                 cap_t cap = cap_from_text("cap_net_admin-eip");
1193
1194                 if (cap_set_proc(cap)) {
1195                         /* Careful with order! Logging cannot happen after we close FDs */
1196                         ast_log(LOG_WARNING, "Unable to remove capabilities.\n");
1197                 }
1198                 cap_free(cap);
1199 #endif
1200 #ifdef HAVE_WORKING_FORK
1201                 if (ast_opt_high_priority) {
1202                         ast_set_priority(0);
1203                 }
1204                 /* Close file descriptors and launch system command */
1205                 ast_close_fds_above_n(STDERR_FILENO);
1206 #endif
1207                 if (dualfork) {
1208 #ifdef HAVE_WORKING_FORK
1209                         pid = fork();
1210 #else
1211                         pid = vfork();
1212 #endif
1213                         if (pid < 0) {
1214                                 /* Second fork failed. */
1215                                 /* No logger available. */
1216                                 _exit(1);
1217                         }
1218
1219                         if (pid > 0) {
1220                                 /* This is the first fork, exit so the reaper finishes right away. */
1221                                 _exit(0);
1222                         }
1223
1224                         /* This is the second fork.  The first fork will exit immediately so
1225                          * Asterisk doesn't have to wait for completion.
1226                          * ast_safe_system("cmd &") would run in the background, but the '&'
1227                          * cannot be added with ast_safe_execvp, so we have to double fork.
1228                          */
1229                 }
1230         }
1231
1232         if (pid < 0) {
1233                 ast_log(LOG_WARNING, "Fork failed: %s\n", strerror(errno));
1234         }
1235 #else
1236         ast_log(LOG_WARNING, "Fork failed: %s\n", strerror(ENOTSUP));
1237         pid = -1;
1238 #endif
1239
1240         return pid;
1241 }
1242
1243 /*! \brief wait for spawned application to complete and unreplace sigchld */
1244 static int safe_exec_wait(pid_t pid)
1245 {
1246         int res = -1;
1247
1248 #if defined(HAVE_WORKING_FORK) || defined(HAVE_WORKING_VFORK)
1249         if (pid > 0) {
1250                 for (;;) {
1251                         int status;
1252
1253                         res = waitpid(pid, &status, 0);
1254                         if (res > -1) {
1255                                 res = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
1256                                 break;
1257                         }
1258                         if (errno != EINTR) {
1259                                 break;
1260                         }
1261                 }
1262         }
1263
1264         ast_unreplace_sigchld();
1265 #endif
1266
1267         return res;
1268 }
1269
1270 int ast_safe_execvp(int dualfork, const char *file, char *const argv[])
1271 {
1272         pid_t pid = safe_exec_prep(dualfork);
1273
1274         if (pid == 0) {
1275                 execvp(file, argv);
1276                 _exit(1);
1277                 /* noreturn from _exit */
1278         }
1279
1280         return safe_exec_wait(pid);
1281 }
1282
1283 int ast_safe_system(const char *s)
1284 {
1285         pid_t pid = safe_exec_prep(0);
1286
1287         if (pid == 0) {
1288                 execl("/bin/sh", "/bin/sh", "-c", s, (char *) NULL);
1289                 _exit(1);
1290                 /* noreturn from _exit */
1291         }
1292
1293         return safe_exec_wait(pid);
1294 }
1295
1296 /*!
1297  * \brief enable or disable a logging level to a specified console
1298  */
1299 void ast_console_toggle_loglevel(int fd, int level, int state)
1300 {
1301         int x;
1302
1303         if (level >= NUMLOGLEVELS) {
1304                 level = NUMLOGLEVELS - 1;
1305         }
1306
1307         for (x = 0;x < AST_MAX_CONNECTS; x++) {
1308                 if (fd == consoles[x].fd) {
1309                         /*
1310                          * Since the logging occurs when levels are false, set to
1311                          * flipped iinput because this function accepts 0 as off and 1 as on
1312                          */
1313                         consoles[x].levels[level] = state ? 0 : 1;
1314                         return;
1315                 }
1316         }
1317 }
1318
1319 /*!
1320  * \brief mute or unmute a console from logging
1321  */
1322 void ast_console_toggle_mute(int fd, int silent)
1323 {
1324         int x;
1325         for (x = 0;x < AST_MAX_CONNECTS; x++) {
1326                 if (fd == consoles[x].fd) {
1327                         if (consoles[x].mute) {
1328                                 consoles[x].mute = 0;
1329                                 if (!silent)
1330                                         ast_cli(fd, "Console is not muted anymore.\n");
1331                         } else {
1332                                 consoles[x].mute = 1;
1333                                 if (!silent)
1334                                         ast_cli(fd, "Console is muted.\n");
1335                         }
1336                         return;
1337                 }
1338         }
1339         ast_cli(fd, "Couldn't find remote console.\n");
1340 }
1341
1342 /*!
1343  * \brief log the string to all attached network console clients
1344  */
1345 static void ast_network_puts_mutable(const char *string, int level, int sublevel)
1346 {
1347         int x;
1348
1349         for (x = 0; x < AST_MAX_CONNECTS; ++x) {
1350                 if (consoles[x].fd < 0
1351                         || consoles[x].mute
1352                         || consoles[x].levels[level]
1353                         || (level == __LOG_VERBOSE && consoles[x].option_verbose < sublevel)) {
1354                         continue;
1355                 }
1356                 fdprint(consoles[x].p[1], string);
1357         }
1358 }
1359
1360 /*!
1361  * \brief log the string to the root console, and all attached
1362  * network console clients
1363  */
1364 void ast_console_puts_mutable(const char *string, int level)
1365 {
1366         ast_console_puts_mutable_full(string, level, 0);
1367 }
1368
1369 static int console_print(const char *s);
1370
1371 void ast_console_puts_mutable_full(const char *message, int level, int sublevel)
1372 {
1373         /* Send to the root console */
1374         console_print(message);
1375
1376         /* Wake up a poll()ing console */
1377         if (ast_opt_console && consolethread != AST_PTHREADT_NULL) {
1378                 pthread_kill(consolethread, SIGURG);
1379         }
1380
1381         /* Send to any network console clients */
1382         ast_network_puts_mutable(message, level, sublevel);
1383 }
1384
1385 /*!
1386  * \brief write the string to all attached console clients
1387  */
1388 static void ast_network_puts(const char *string)
1389 {
1390         int x;
1391
1392         for (x = 0; x < AST_MAX_CONNECTS; ++x) {
1393                 if (consoles[x].fd < 0) {
1394                         continue;
1395                 }
1396                 fdprint(consoles[x].p[1], string);
1397         }
1398 }
1399
1400 /*!
1401  * \brief write the string to the root console, and all attached
1402  * network console clients
1403  */
1404 void ast_console_puts(const char *string)
1405 {
1406         /* Send to the root console */
1407         fputs(string, stdout);
1408         fflush(stdout);
1409
1410         /* Send to any network console clients */
1411         ast_network_puts(string);
1412 }
1413
1414 static pthread_t lthread;
1415
1416 /*!
1417  * \brief read() function supporting the reception of user credentials.
1418  *
1419  * \param fd Socket file descriptor.
1420  * \param buffer Receive buffer.
1421  * \param size 'buffer' size.
1422  * \param con Console structure to set received credentials
1423  * \retval -1 on error
1424  * \retval the number of bytes received on success.
1425  */
1426 static int read_credentials(int fd, char *buffer, size_t size, struct console *con)
1427 {
1428 #if defined(SO_PEERCRED)
1429 #ifdef HAVE_STRUCT_SOCKPEERCRED_UID
1430 #define HAVE_STRUCT_UCRED_UID
1431         struct sockpeercred cred;
1432 #else
1433         struct ucred cred;
1434 #endif
1435         socklen_t len = sizeof(cred);
1436 #endif
1437 #if defined(HAVE_GETPEEREID)
1438         uid_t uid;
1439         gid_t gid;
1440 #else
1441         int uid, gid;
1442 #endif
1443         int result;
1444
1445         result = read(fd, buffer, size);
1446         if (result < 0) {
1447                 return result;
1448         }
1449
1450 #if defined(SO_PEERCRED) && (defined(HAVE_STRUCT_UCRED_UID) || defined(HAVE_STRUCT_UCRED_CR_UID))
1451         if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &len)) {
1452                 return result;
1453         }
1454 #if defined(HAVE_STRUCT_UCRED_UID)
1455         uid = cred.uid;
1456         gid = cred.gid;
1457 #else /* defined(HAVE_STRUCT_UCRED_CR_UID) */
1458         uid = cred.cr_uid;
1459         gid = cred.cr_gid;
1460 #endif /* defined(HAVE_STRUCT_UCRED_UID) */
1461
1462 #elif defined(HAVE_GETPEEREID)
1463         if (getpeereid(fd, &uid, &gid)) {
1464                 return result;
1465         }
1466 #else
1467         return result;
1468 #endif
1469         con->uid = uid;
1470         con->gid = gid;
1471
1472         return result;
1473 }
1474
1475 /* This is the thread running the remote console on the main process. */
1476 static void *netconsole(void *vconsole)
1477 {
1478         struct console *con = vconsole;
1479         char hostname[MAXHOSTNAMELEN] = "";
1480         char inbuf[512];
1481         char outbuf[512];
1482         const char * const end_buf = inbuf + sizeof(inbuf);
1483         char *start_read = inbuf;
1484         int res;
1485         struct pollfd fds[2];
1486
1487         if (gethostname(hostname, sizeof(hostname)-1))
1488                 ast_copy_string(hostname, "<Unknown>", sizeof(hostname));
1489         snprintf(outbuf, sizeof(outbuf), "%s/%ld/%s\n", hostname, (long)ast_mainpid, ast_get_version());
1490         fdprint(con->fd, outbuf);
1491         ast_verb_console_register(&con->option_verbose);
1492         for (;;) {
1493                 fds[0].fd = con->fd;
1494                 fds[0].events = POLLIN;
1495                 fds[0].revents = 0;
1496                 fds[1].fd = con->p[0];
1497                 fds[1].events = POLLIN;
1498                 fds[1].revents = 0;
1499
1500                 res = ast_poll(fds, 2, -1);
1501                 if (res < 0) {
1502                         if (errno != EINTR)
1503                                 ast_log(LOG_WARNING, "poll returned < 0: %s\n", strerror(errno));
1504                         continue;
1505                 }
1506                 if (fds[0].revents) {
1507                         int cmds_read, bytes_read;
1508                         if ((bytes_read = read_credentials(con->fd, start_read, end_buf - start_read, con)) < 1) {
1509                                 break;
1510                         }
1511                         /* XXX This will only work if it is the first command, and I'm not sure fixing it is worth the effort. */
1512                         if (strncmp(inbuf, "cli quit after ", 15) == 0) {
1513                                 ast_cli_command_multiple_full(con->uid, con->gid, con->fd, bytes_read - 15, inbuf + 15);
1514                                 break;
1515                         }
1516                         /* ast_cli_command_multiple_full will only process individual commands terminated by a
1517                          * NULL and not trailing partial commands. */
1518                         if (!(cmds_read = ast_cli_command_multiple_full(con->uid, con->gid, con->fd, bytes_read + start_read - inbuf, inbuf))) {
1519                                 /* No commands were read. We either have a short read on the first command
1520                                  * with space left, or a command that is too long */
1521                                 if (start_read + bytes_read < end_buf) {
1522                                         start_read += bytes_read;
1523                                 } else {
1524                                         ast_log(LOG_ERROR, "Command too long! Skipping\n");
1525                                         start_read = inbuf;
1526                                 }
1527                                 continue;
1528                         }
1529                         if (start_read[bytes_read - 1] == '\0') {
1530                                 /* The read ended on a command boundary, start reading again at the head of inbuf */
1531                                 start_read = inbuf;
1532                                 continue;
1533                         }
1534                         /* If we get this far, we have left over characters that have not been processed.
1535                          * Advance to the character after the last command read by ast_cli_command_multiple_full.
1536                          * We are guaranteed to have at least cmds_read NULLs */
1537                         while (cmds_read-- && (start_read = strchr(start_read, '\0'))) {
1538                                 start_read++;
1539                         }
1540                         memmove(inbuf, start_read, end_buf - start_read);
1541                         start_read = end_buf - start_read + inbuf;
1542                 }
1543                 if (fds[1].revents) {
1544                         res = read_credentials(con->p[0], outbuf, sizeof(outbuf), con);
1545                         if (res < 1) {
1546                                 ast_log(LOG_ERROR, "read returned %d\n", res);
1547                                 break;
1548                         }
1549                         res = write(con->fd, outbuf, res);
1550                         if (res < 1)
1551                                 break;
1552                 }
1553         }
1554         ast_verb_console_unregister();
1555         if (!ast_opt_hide_connect) {
1556                 ast_verb(3, "Remote UNIX connection disconnected\n");
1557         }
1558         close(con->fd);
1559         close(con->p[0]);
1560         close(con->p[1]);
1561         con->fd = -1;
1562
1563         return NULL;
1564 }
1565
1566 static void *listener(void *unused)
1567 {
1568         struct sockaddr_un sunaddr;
1569         int s;
1570         socklen_t len;
1571         int x;
1572         int poll_result;
1573         struct pollfd fds[1];
1574
1575         for (;;) {
1576                 if (ast_socket < 0) {
1577                         return NULL;
1578                 }
1579                 fds[0].fd = ast_socket;
1580                 fds[0].events = POLLIN;
1581                 poll_result = ast_poll(fds, 1, -1);
1582                 pthread_testcancel();
1583                 if (poll_result < 0) {
1584                         if (errno != EINTR) {
1585                                 ast_log(LOG_WARNING, "poll returned error: %s\n", strerror(errno));
1586                         }
1587                         continue;
1588                 }
1589                 len = sizeof(sunaddr);
1590                 s = accept(ast_socket, (struct sockaddr *)&sunaddr, &len);
1591                 if (s < 0) {
1592                         if (errno != EINTR)
1593                                 ast_log(LOG_WARNING, "Accept returned %d: %s\n", s, strerror(errno));
1594                 } else {
1595 #if defined(SO_PASSCRED)
1596                         int sckopt = 1;
1597                         /* turn on socket credentials passing. */
1598                         if (setsockopt(s, SOL_SOCKET, SO_PASSCRED, &sckopt, sizeof(sckopt)) < 0) {
1599                                 ast_log(LOG_WARNING, "Unable to turn on socket credentials passing\n");
1600                                 close(s);
1601                         } else
1602 #endif
1603                         {
1604                                 for (x = 0; x < AST_MAX_CONNECTS; x++) {
1605                                         if (consoles[x].fd >= 0) {
1606                                                 continue;
1607                                         }
1608                                         if (socketpair(AF_LOCAL, SOCK_STREAM, 0, consoles[x].p)) {
1609                                                 ast_log(LOG_ERROR, "Unable to create pipe: %s\n", strerror(errno));
1610                                                 fdprint(s, "Server failed to create pipe\n");
1611                                                 close(s);
1612                                                 break;
1613                                         }
1614                                         ast_fd_set_flags(consoles[x].p[1], O_NONBLOCK);
1615                                         consoles[x].mute = 1; /* Default is muted, we will un-mute if necessary */
1616                                         /* Default uid and gid to -2, so then in cli.c/cli_has_permissions() we will be able
1617                                            to know if the user didn't send the credentials. */
1618                                         consoles[x].uid = -2;
1619                                         consoles[x].gid = -2;
1620                                         /* Server default of remote console verbosity level is OFF. */
1621                                         consoles[x].option_verbose = 0;
1622                                         consoles[x].fd = s;
1623                                         if (ast_pthread_create_detached_background(&consoles[x].t, NULL, netconsole, &consoles[x])) {
1624                                                 consoles[x].fd = -1;
1625                                                 ast_log(LOG_ERROR, "Unable to spawn thread to handle connection: %s\n", strerror(errno));
1626                                                 close(consoles[x].p[0]);
1627                                                 close(consoles[x].p[1]);
1628                                                 fdprint(s, "Server failed to spawn thread\n");
1629                                                 close(s);
1630                                         }
1631                                         break;
1632                                 }
1633                                 if (x >= AST_MAX_CONNECTS) {
1634                                         fdprint(s, "No more connections allowed\n");
1635                                         ast_log(LOG_WARNING, "No more connections allowed\n");
1636                                         close(s);
1637                                 } else if ((consoles[x].fd > -1) && (!ast_opt_hide_connect)) {
1638                                         ast_verb(3, "Remote UNIX connection\n");
1639                                 }
1640                         }
1641                 }
1642         }
1643         return NULL;
1644 }
1645
1646 static int ast_makesocket(void)
1647 {
1648         struct sockaddr_un sunaddr;
1649         int res;
1650         int x;
1651         uid_t uid = -1;
1652         gid_t gid = -1;
1653
1654         for (x = 0; x < AST_MAX_CONNECTS; x++) {
1655                 consoles[x].fd = -1;
1656         }
1657
1658         if (ast_socket_is_sd) {
1659                 ast_socket = ast_sd_get_fd_un(SOCK_STREAM, ast_config_AST_SOCKET);
1660
1661                 goto start_lthread;
1662         }
1663
1664         unlink(ast_config_AST_SOCKET);
1665         ast_socket = socket(PF_LOCAL, SOCK_STREAM, 0);
1666         if (ast_socket < 0) {
1667                 ast_log(LOG_WARNING, "Unable to create control socket: %s\n", strerror(errno));
1668                 return -1;
1669         }
1670         memset(&sunaddr, 0, sizeof(sunaddr));
1671         sunaddr.sun_family = AF_LOCAL;
1672         ast_copy_string(sunaddr.sun_path, ast_config_AST_SOCKET, sizeof(sunaddr.sun_path));
1673         res = bind(ast_socket, (struct sockaddr *)&sunaddr, sizeof(sunaddr));
1674         if (res) {
1675                 ast_log(LOG_WARNING, "Unable to bind socket to %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
1676                 close(ast_socket);
1677                 ast_socket = -1;
1678                 return -1;
1679         }
1680         res = listen(ast_socket, 2);
1681         if (res < 0) {
1682                 ast_log(LOG_WARNING, "Unable to listen on socket %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
1683                 close(ast_socket);
1684                 ast_socket = -1;
1685                 return -1;
1686         }
1687
1688 start_lthread:
1689         if (ast_pthread_create_background(&lthread, NULL, listener, NULL)) {
1690                 ast_log(LOG_WARNING, "Unable to create listener thread.\n");
1691                 close(ast_socket);
1692                 return -1;
1693         }
1694
1695         if (ast_socket_is_sd) {
1696                 /* owner/group/permissions are set by systemd, we might not even have access
1697                  * to socket file so leave it alone */
1698                 return 0;
1699         }
1700
1701         if (!ast_strlen_zero(ast_config_AST_CTL_OWNER)) {
1702                 struct passwd *pw;
1703                 if ((pw = getpwnam(ast_config_AST_CTL_OWNER)) == NULL)
1704                         ast_log(LOG_WARNING, "Unable to find uid of user %s\n", ast_config_AST_CTL_OWNER);
1705                 else
1706                         uid = pw->pw_uid;
1707         }
1708
1709         if (!ast_strlen_zero(ast_config_AST_CTL_GROUP)) {
1710                 struct group *grp;
1711                 if ((grp = getgrnam(ast_config_AST_CTL_GROUP)) == NULL)
1712                         ast_log(LOG_WARNING, "Unable to find gid of group %s\n", ast_config_AST_CTL_GROUP);
1713                 else
1714                         gid = grp->gr_gid;
1715         }
1716
1717         if (chown(ast_config_AST_SOCKET, uid, gid) < 0)
1718                 ast_log(LOG_WARNING, "Unable to change ownership of %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
1719
1720         if (!ast_strlen_zero(ast_config_AST_CTL_PERMISSIONS)) {
1721                 unsigned int p1;
1722                 mode_t p;
1723                 sscanf(ast_config_AST_CTL_PERMISSIONS, "%30o", &p1);
1724                 p = p1;
1725                 if ((chmod(ast_config_AST_SOCKET, p)) < 0)
1726                         ast_log(LOG_WARNING, "Unable to change file permissions of %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
1727         }
1728
1729         return 0;
1730 }
1731
1732 static int ast_tryconnect(void)
1733 {
1734         struct sockaddr_un sunaddr;
1735         int res;
1736         ast_consock = socket(PF_LOCAL, SOCK_STREAM, 0);
1737         if (ast_consock < 0) {
1738                 fprintf(stderr, "Unable to create socket: %s\n", strerror(errno));
1739                 return 0;
1740         }
1741         memset(&sunaddr, 0, sizeof(sunaddr));
1742         sunaddr.sun_family = AF_LOCAL;
1743         ast_copy_string(sunaddr.sun_path, ast_config_AST_SOCKET, sizeof(sunaddr.sun_path));
1744         res = connect(ast_consock, (struct sockaddr *)&sunaddr, sizeof(sunaddr));
1745         if (res) {
1746                 close(ast_consock);
1747                 ast_consock = -1;
1748                 return 0;
1749         } else
1750                 return 1;
1751 }
1752
1753 /*! \brief Urgent handler
1754  *
1755  * Called by soft_hangup to interrupt the poll, read, or other
1756  * system call.  We don't actually need to do anything though.
1757  * Remember: Cannot EVER ast_log from within a signal handler
1758  */
1759 static void _urg_handler(int num)
1760 {
1761         return;
1762 }
1763
1764 static struct sigaction urg_handler = {
1765         .sa_handler = _urg_handler,
1766 };
1767
1768 static void _hup_handler(int num)
1769 {
1770         int save_errno = errno;
1771         printf("Received HUP signal -- Reloading configs\n");
1772         if (restartnow)
1773                 execvp(_argv[0], _argv);
1774         sig_flags.need_reload = 1;
1775         if (ast_alertpipe_write(sig_alert_pipe)) {
1776                 fprintf(stderr, "hup_handler: write() failed: %s\n", strerror(errno));
1777         }
1778         errno = save_errno;
1779 }
1780
1781 static struct sigaction hup_handler = {
1782         .sa_handler = _hup_handler,
1783         .sa_flags = SA_RESTART,
1784 };
1785
1786 static void _child_handler(int sig)
1787 {
1788         /* Must not ever ast_log or ast_verbose within signal handler */
1789         int n, status, save_errno = errno;
1790
1791         /*
1792          * Reap all dead children -- not just one
1793          */
1794         for (n = 0; waitpid(-1, &status, WNOHANG) > 0; n++)
1795                 ;
1796         if (n == 0 && option_debug)
1797                 printf("Huh?  Child handler, but nobody there?\n");
1798         errno = save_errno;
1799 }
1800
1801 static struct sigaction child_handler = {
1802         .sa_handler = _child_handler,
1803         .sa_flags = SA_RESTART,
1804 };
1805
1806 /*! \brief Set maximum open files */
1807 static void set_ulimit(int value)
1808 {
1809         struct rlimit l = {0, 0};
1810
1811         if (value <= 0) {
1812                 ast_log(LOG_WARNING, "Unable to change max files open to invalid value %i\n",value);
1813                 return;
1814         }
1815
1816         l.rlim_cur = value;
1817         l.rlim_max = value;
1818
1819         if (setrlimit(RLIMIT_NOFILE, &l)) {
1820                 ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n",strerror(errno));
1821                 return;
1822         }
1823
1824         ast_log(LOG_NOTICE, "Setting max files open to %d\n",value);
1825
1826         return;
1827 }
1828
1829 /*! \brief Set an X-term or screen title */
1830 static void set_title(char *text)
1831 {
1832         if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
1833                 fprintf(stdout, "\033]2;%s\007", text);
1834 }
1835
1836 static void set_icon(char *text)
1837 {
1838         if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
1839                 fprintf(stdout, "\033]1;%s\007", text);
1840 }
1841
1842 /*! \brief Check whether we were set to high(er) priority. */
1843 static int has_priority(void)
1844 {
1845         /* Neither of these calls should fail with these arguments. */
1846 #ifdef __linux__
1847         /* For SCHED_OTHER, SCHED_BATCH and SCHED_IDLE, this will return
1848          * 0. For the realtime priorities SCHED_RR and SCHED_FIFO, it
1849          * will return something >= 1. */
1850         return sched_getscheduler(0);
1851 #else
1852         /* getpriority() can return a value in -20..19 (or even -INF..20)
1853          * where negative numbers are high priority. We don't bother
1854          * checking errno. If the query fails and it returns -1, we'll
1855          * assume that we're running at high prio; a safe assumption
1856          * that will enable the resource starvation monitor (canary)
1857          * just in case. */
1858         return (getpriority(PRIO_PROCESS, 0) < 0);
1859 #endif
1860 }
1861
1862 /*! \brief Set priority on all known threads. */
1863 static int set_priority_all(int pri)
1864 {
1865 #if !defined(__linux__)
1866         /* The non-linux version updates the entire process prio. */
1867         return ast_set_priority(pri);
1868 #elif defined(LOW_MEMORY)
1869         ast_log(LOG_WARNING, "Unable to enumerate all threads to update priority\n");
1870         return ast_set_priority(pri);
1871 #else
1872         struct thread_list_t *cur;
1873         struct sched_param sched;
1874         char const *policy_str;
1875         int policy;
1876
1877         memset(&sched, 0, sizeof(sched));
1878         if (pri) {
1879                 policy = SCHED_RR;
1880                 policy_str = "realtime";
1881                 sched.sched_priority = 10;
1882         } else {
1883                 policy = SCHED_OTHER;
1884                 policy_str = "regular";
1885                 sched.sched_priority = 0;
1886         }
1887         if (sched_setscheduler(getpid(), policy, &sched)) {
1888                 ast_log(LOG_WARNING, "Unable to set %s thread priority on main thread\n", policy_str);
1889                 return -1;
1890         }
1891         ast_verb(1, "Setting %s thread priority on all threads\n", policy_str);
1892         AST_RWLIST_RDLOCK(&thread_list);
1893         AST_RWLIST_TRAVERSE(&thread_list, cur, list) {
1894                 /* Don't care about the return value. It should work. */
1895                 sched_setscheduler(cur->lwp, policy, &sched);
1896         }
1897         AST_RWLIST_UNLOCK(&thread_list);
1898         return 0;
1899 #endif
1900 }
1901
1902 /*! \brief We set ourselves to a high priority, that we might pre-empt
1903  * everything else.  If your PBX has heavy activity on it, this is a
1904  * good thing.
1905  */
1906 int ast_set_priority(int pri)
1907 {
1908         struct sched_param sched;
1909         memset(&sched, 0, sizeof(sched));
1910 #ifdef __linux__
1911         if (pri) {
1912                 sched.sched_priority = 10;
1913                 if (sched_setscheduler(0, SCHED_RR, &sched)) {
1914                         ast_log(LOG_WARNING, "Unable to set high priority\n");
1915                         return -1;
1916                 } else
1917                         ast_verb(1, "Set to realtime thread\n");
1918         } else {
1919                 sched.sched_priority = 0;
1920                 /* According to the manpage, these parameters can never fail. */
1921                 sched_setscheduler(0, SCHED_OTHER, &sched);
1922         }
1923 #else
1924         if (pri) {
1925                 if (setpriority(PRIO_PROCESS, 0, -10) == -1) {
1926                         ast_log(LOG_WARNING, "Unable to set high priority\n");
1927                         return -1;
1928                 } else
1929                         ast_verb(1, "Set to high priority\n");
1930         } else {
1931                 /* According to the manpage, these parameters can never fail. */
1932                 setpriority(PRIO_PROCESS, 0, 0);
1933         }
1934 #endif
1935         return 0;
1936 }
1937
1938 int ast_shutdown_final(void)
1939 {
1940         return shuttingdown == SHUTTING_DOWN_FINAL;
1941 }
1942
1943 int ast_shutting_down(void)
1944 {
1945         return shutdown_pending;
1946 }
1947
1948 int ast_cancel_shutdown(void)
1949 {
1950         int shutdown_aborted = 0;
1951
1952         ast_mutex_lock(&safe_system_lock);
1953         if (shuttingdown >= SHUTDOWN_FAST) {
1954                 shuttingdown = NOT_SHUTTING_DOWN;
1955                 shutdown_pending = 0;
1956                 shutdown_aborted = 1;
1957         }
1958         ast_mutex_unlock(&safe_system_lock);
1959         return shutdown_aborted;
1960 }
1961
1962 /*!
1963  * \internal
1964  * \brief Initiate system shutdown -- prevents new channels from being allocated.
1965  */
1966 static void ast_begin_shutdown(void)
1967 {
1968         ast_mutex_lock(&safe_system_lock);
1969         if (shuttingdown != NOT_SHUTTING_DOWN) {
1970                 shutdown_pending = 1;
1971         }
1972         ast_mutex_unlock(&safe_system_lock);
1973 }
1974
1975 static int can_safely_quit(shutdown_nice_t niceness, int restart);
1976 static void really_quit(int num, shutdown_nice_t niceness, int restart);
1977
1978 static void quit_handler(int num, shutdown_nice_t niceness, int restart)
1979 {
1980         if (can_safely_quit(niceness, restart)) {
1981                 really_quit(num, niceness, restart);
1982                 /* No one gets here. */
1983         }
1984         /* It wasn't our time. */
1985 }
1986
1987 #define SHUTDOWN_TIMEOUT        15      /* Seconds */
1988
1989 /*!
1990  * \internal
1991  * \brief Wait for all channels to die, a timeout, or shutdown cancelled.
1992  * \since 13.3.0
1993  *
1994  * \param niceness Shutdown niceness in effect
1995  * \param seconds Number of seconds to wait or less than zero if indefinitely.
1996  *
1997  * \retval zero if waiting wasn't necessary.  We were idle.
1998  * \retval non-zero if we had to wait.
1999  */
2000 static int wait_for_channels_to_die(shutdown_nice_t niceness, int seconds)
2001 {
2002         time_t start;
2003         time_t now;
2004         int waited = 0;
2005
2006         time(&start);
2007         for (;;) {
2008                 if (!ast_undestroyed_channels() || shuttingdown != niceness) {
2009                         break;
2010                 }
2011                 if (seconds < 0) {
2012                         /* No timeout so just poll every second */
2013                         sleep(1);
2014                 } else {
2015                         time(&now);
2016
2017                         /* Wait up to the given seconds for all channels to go away */
2018                         if (seconds < (now - start)) {
2019                                 break;
2020                         }
2021
2022                         /* Sleep 1/10 of a second */
2023                         usleep(100000);
2024                 }
2025                 waited = 1;
2026         }
2027         return waited;
2028 }
2029
2030 static int can_safely_quit(shutdown_nice_t niceness, int restart)
2031 {
2032         int waited = 0;
2033
2034         /* Check if someone else isn't already doing this. */
2035         ast_mutex_lock(&safe_system_lock);
2036         if (shuttingdown != NOT_SHUTTING_DOWN && niceness >= shuttingdown) {
2037                 /* Already in progress and other request was less nice. */
2038                 ast_mutex_unlock(&safe_system_lock);
2039                 ast_verbose("Ignoring asterisk %s request, already in progress.\n", restart ? "restart" : "shutdown");
2040                 return 0;
2041         }
2042         shuttingdown = niceness;
2043         ast_mutex_unlock(&safe_system_lock);
2044
2045         /* Try to get as many CDRs as possible submitted to the backend engines
2046          * (if in batch mode). really_quit happens to call it again when running
2047          * the atexit handlers, otherwise this would be a bit early. */
2048         ast_cdr_engine_term();
2049
2050         /*
2051          * Shutdown the message queue for the technology agnostic message channel.
2052          * This has to occur before we pause shutdown pending ast_undestroyed_channels.
2053          *
2054          * XXX This is not reversed on shutdown cancel.
2055          */
2056         ast_msg_shutdown();
2057
2058         if (niceness == SHUTDOWN_NORMAL) {
2059                 /* Begin shutdown routine, hanging up active channels */
2060                 ast_begin_shutdown();
2061                 if (ast_opt_console) {
2062                         ast_verb(0, "Beginning asterisk %s....\n", restart ? "restart" : "shutdown");
2063                 }
2064                 ast_softhangup_all();
2065                 waited |= wait_for_channels_to_die(niceness, SHUTDOWN_TIMEOUT);
2066         } else if (niceness >= SHUTDOWN_NICE) {
2067                 if (niceness != SHUTDOWN_REALLY_NICE) {
2068                         ast_begin_shutdown();
2069                 }
2070                 if (ast_opt_console) {
2071                         ast_verb(0, "Waiting for inactivity to perform %s...\n", restart ? "restart" : "halt");
2072                 }
2073                 waited |= wait_for_channels_to_die(niceness, -1);
2074         }
2075
2076         /* Re-acquire lock and check if someone changed the niceness, in which
2077          * case someone else has taken over the shutdown.
2078          */
2079         ast_mutex_lock(&safe_system_lock);
2080         if (shuttingdown != niceness) {
2081                 if (shuttingdown == NOT_SHUTTING_DOWN && ast_opt_console) {
2082                         ast_verb(0, "Asterisk %s cancelled.\n", restart ? "restart" : "shutdown");
2083                 }
2084                 ast_mutex_unlock(&safe_system_lock);
2085                 return 0;
2086         }
2087
2088         if (niceness >= SHUTDOWN_REALLY_NICE) {
2089                 shuttingdown = SHUTTING_DOWN;
2090                 ast_mutex_unlock(&safe_system_lock);
2091
2092                 /* No more Mr. Nice guy.  We are committed to shutting down now. */
2093                 ast_begin_shutdown();
2094                 ast_softhangup_all();
2095                 waited |= wait_for_channels_to_die(SHUTTING_DOWN, SHUTDOWN_TIMEOUT);
2096
2097                 ast_mutex_lock(&safe_system_lock);
2098         }
2099         shuttingdown = SHUTTING_DOWN_FINAL;
2100         ast_mutex_unlock(&safe_system_lock);
2101
2102         if (niceness >= SHUTDOWN_NORMAL && waited) {
2103                 /*
2104                  * We were not idle.  Give things in progress a chance to
2105                  * recognize the final shutdown phase.
2106                  */
2107                 sleep(1);
2108         }
2109         return 1;
2110 }
2111
2112 /*! Called when exiting is certain. */
2113 static void really_quit(int num, shutdown_nice_t niceness, int restart)
2114 {
2115         int active_channels;
2116         struct ast_json *json_object = NULL;
2117         int run_cleanups = niceness >= SHUTDOWN_NICE;
2118
2119         if (run_cleanups && modules_shutdown()) {
2120                 ast_verb(0, "Some modules could not be unloaded, switching to fast shutdown\n");
2121                 run_cleanups = 0;
2122         }
2123
2124         if (!restart) {
2125                 ast_sd_notify("STOPPING=1");
2126         }
2127         if (ast_opt_console || (ast_opt_remote && !ast_opt_exec)) {
2128                 ast_el_write_default_histfile();
2129                 if (consolethread == AST_PTHREADT_NULL || consolethread == pthread_self()) {
2130                         /* Only end if we are the consolethread, otherwise there's a race with that thread. */
2131                         if (el != NULL) {
2132                                 el_end(el);
2133                         }
2134                         if (el_hist != NULL) {
2135                                 history_end(el_hist);
2136                         }
2137                 } else if (mon_sig_flags == pthread_self()) {
2138                         if (consolethread != AST_PTHREADT_NULL) {
2139                                 pthread_kill(consolethread, SIGURG);
2140                         }
2141                 }
2142         }
2143         active_channels = ast_active_channels();
2144         /* Don't publish messages if we're a remote console - we won't have all of the Stasis
2145          * topics or message types
2146          */
2147         if (!ast_opt_remote) {
2148                 json_object = ast_json_pack("{s: s, s: s}",
2149                                 "Shutdown", active_channels ? "Uncleanly" : "Cleanly",
2150                                 "Restart", restart ? "True" : "False");
2151                 ast_manager_publish_event("Shutdown", EVENT_FLAG_SYSTEM, json_object);
2152                 ast_json_unref(json_object);
2153                 json_object = NULL;
2154         }
2155         ast_verb(0, "Asterisk %s ending (%d).\n",
2156                 active_channels ? "uncleanly" : "cleanly", num);
2157
2158         ast_verb(0, "Executing last minute cleanups\n");
2159         ast_run_atexits(run_cleanups);
2160
2161         ast_debug(1, "Asterisk ending (%d).\n", num);
2162         if (ast_socket > -1) {
2163                 pthread_cancel(lthread);
2164                 close(ast_socket);
2165                 ast_socket = -1;
2166                 if (!ast_socket_is_sd) {
2167                         unlink(ast_config_AST_SOCKET);
2168                 }
2169                 pthread_kill(lthread, SIGURG);
2170                 pthread_join(lthread, NULL);
2171         }
2172         if (ast_consock > -1)
2173                 close(ast_consock);
2174         if (!ast_opt_remote)
2175                 unlink(ast_config_AST_PID);
2176         ast_alertpipe_close(sig_alert_pipe);
2177         printf("%s", term_quit());
2178         if (restart) {
2179                 int i;
2180                 ast_verb(0, "Preparing for Asterisk restart...\n");
2181                 /* Mark all FD's for closing on exec */
2182                 for (i = 3; i < 32768; i++) {
2183                         fcntl(i, F_SETFD, FD_CLOEXEC);
2184                 }
2185                 ast_verb(0, "Asterisk is now restarting...\n");
2186                 restartnow = 1;
2187
2188                 /* close logger */
2189                 close_logger();
2190                 clean_time_zones();
2191
2192                 /* If there is a consolethread running send it a SIGHUP
2193                    so it can execvp, otherwise we can do it ourselves */
2194                 if ((consolethread != AST_PTHREADT_NULL) && (consolethread != pthread_self())) {
2195                         pthread_kill(consolethread, SIGHUP);
2196                         /* Give the signal handler some time to complete */
2197                         sleep(2);
2198                 } else
2199                         execvp(_argv[0], _argv);
2200
2201         } else {
2202                 /* close logger */
2203                 close_logger();
2204                 clean_time_zones();
2205         }
2206
2207         exit(0);
2208 }
2209
2210 static void __quit_handler(int num)
2211 {
2212         sig_flags.need_quit = 1;
2213         if (ast_alertpipe_write(sig_alert_pipe)) {
2214                 fprintf(stderr, "quit_handler: write() failed: %s\n", strerror(errno));
2215         }
2216         /* There is no need to restore the signal handler here, since the app
2217          * is going to exit */
2218 }
2219
2220 static void __remote_quit_handler(int num)
2221 {
2222         sig_flags.need_quit = 1;
2223 }
2224
2225 static void set_header(char *outbuf, int maxout, char level)
2226 {
2227         const char *cmp;
2228         char date[40];
2229
2230         switch (level) {
2231         case 0: cmp = NULL;
2232                 break;
2233         case 1: cmp = VERBOSE_PREFIX_1;
2234                 break;
2235         case 2: cmp = VERBOSE_PREFIX_2;
2236                 break;
2237         case 3: cmp = VERBOSE_PREFIX_3;
2238                 break;
2239         default: cmp = VERBOSE_PREFIX_4;
2240                 break;
2241         }
2242
2243         if (ast_opt_timestamp) {
2244                 struct ast_tm tm;
2245                 struct timeval now = ast_tvnow();
2246                 ast_localtime(&now, &tm, NULL);
2247                 ast_strftime(date, sizeof(date), ast_logger_get_dateformat(), &tm);
2248         }
2249
2250         snprintf(outbuf, maxout, "%s%s%s%s%s%s",
2251                 ast_opt_timestamp ? "[" : "",
2252                 ast_opt_timestamp ? date : "",
2253                 ast_opt_timestamp ? "] " : "",
2254                 cmp ? ast_term_color(COLOR_GRAY, 0) : "",
2255                 cmp ? cmp : "",
2256                 cmp ? ast_term_reset() : "");
2257 }
2258
2259 struct console_state_data {
2260         char verbose_line_level;
2261 };
2262
2263 static int console_state_init(void *ptr)
2264 {
2265         struct console_state_data *state = ptr;
2266         state->verbose_line_level = 0;
2267         return 0;
2268 }
2269
2270 AST_THREADSTORAGE_CUSTOM(console_state, console_state_init, ast_free_ptr);
2271
2272 static int console_print(const char *s)
2273 {
2274         struct console_state_data *state =
2275                 ast_threadstorage_get(&console_state, sizeof(*state));
2276
2277         char prefix[80];
2278         const char *c;
2279         int num, res = 0;
2280         unsigned int newline;
2281
2282         do {
2283                 if (VERBOSE_HASMAGIC(s)) {
2284
2285                         /* always use the given line's level, otherwise
2286                            we'll use the last line's level */
2287                         state->verbose_line_level = VERBOSE_MAGIC2LEVEL(s);
2288
2289                         /* move past magic */
2290                         s++;
2291
2292                         set_header(prefix, sizeof(prefix), state->verbose_line_level);
2293                 } else {
2294                         *prefix = '\0';
2295                 }
2296                 c = s;
2297
2298                 /* for a given line separate on verbose magic, newline, and eol */
2299                 if ((s = strchr(c, '\n'))) {
2300                         ++s;
2301                         newline = 1;
2302                 } else {
2303                         s = strchr(c, '\0');
2304                         newline = 0;
2305                 }
2306
2307                 /* check if we should write this line after calculating begin/end
2308                    so we process the case of a higher level line embedded within
2309                    two lower level lines */
2310                 if (state->verbose_line_level > option_verbose) {
2311                         continue;
2312                 }
2313
2314                 if (!ast_strlen_zero(prefix)) {
2315                         fputs(prefix, stdout);
2316                 }
2317
2318                 num = s - c;
2319                 if (fwrite(c, sizeof(char), num, stdout) < num) {
2320                         break;
2321                 }
2322
2323                 if (!res) {
2324                         /* if at least some info has been written
2325                            we'll want to return true */
2326                         res = 1;
2327                 }
2328         } while (*s);
2329
2330         if (newline) {
2331                 /* if ending on a newline then reset last level to zero
2332                     since what follows may be not be logging output */
2333                 state->verbose_line_level = 0;
2334         }
2335
2336         if (res) {
2337                 fflush(stdout);
2338         }
2339
2340         return res;
2341 }
2342
2343 static int ast_all_zeros(const char *s)
2344 {
2345         while (*s) {
2346                 if (*s > 32)
2347                         return 0;
2348                 s++;
2349         }
2350         return 1;
2351 }
2352
2353 /* This is the main console CLI command handler.  Run by the main() thread. */
2354 static void consolehandler(const char *s)
2355 {
2356         printf("%s", term_end());
2357         fflush(stdout);
2358
2359         /* Called when readline data is available */
2360         if (!ast_all_zeros(s))
2361                 ast_el_add_history(s);
2362         /* The real handler for bang */
2363         if (s[0] == '!') {
2364                 if (s[1])
2365                         ast_safe_system(s+1);
2366                 else
2367                         ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
2368         } else
2369                 ast_cli_command(STDOUT_FILENO, s);
2370 }
2371
2372 static int remoteconsolehandler(const char *s)
2373 {
2374         int ret = 0;
2375
2376         /* Called when readline data is available */
2377         if (!ast_all_zeros(s))
2378                 ast_el_add_history(s);
2379
2380         while (isspace(*s)) {
2381                 s++;
2382         }
2383
2384         /* The real handler for bang */
2385         if (s[0] == '!') {
2386                 if (s[1])
2387                         ast_safe_system(s+1);
2388                 else
2389                         ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
2390                 ret = 1;
2391         } else if ((strncasecmp(s, "quit", 4) == 0 || strncasecmp(s, "exit", 4) == 0) &&
2392             (s[4] == '\0' || isspace(s[4]))) {
2393                 quit_handler(0, SHUTDOWN_FAST, 0);
2394                 ret = 1;
2395         }
2396
2397         return ret;
2398 }
2399
2400 static char *handle_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2401 {
2402         switch (cmd) {
2403         case CLI_INIT:
2404                 e->command = "core show version";
2405                 e->usage =
2406                         "Usage: core show version\n"
2407                         "       Shows Asterisk version information.\n";
2408                 return NULL;
2409         case CLI_GENERATE:
2410                 return NULL;
2411         }
2412
2413         if (a->argc != 3)
2414                 return CLI_SHOWUSAGE;
2415         ast_cli(a->fd, "Asterisk %s built by %s @ %s on a %s running %s on %s\n",
2416                 ast_get_version(), ast_build_user, ast_build_hostname,
2417                 ast_build_machine, ast_build_os, ast_build_date);
2418         return CLI_SUCCESS;
2419 }
2420
2421 static char *handle_stop_now(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2422 {
2423         switch (cmd) {
2424         case CLI_INIT:
2425                 e->command = "core stop now";
2426                 e->usage =
2427                         "Usage: core stop now\n"
2428                         "       Shuts down a running Asterisk immediately, hanging up all active calls .\n";
2429                 ast_cli_allow_at_shutdown(e);
2430                 return NULL;
2431         case CLI_GENERATE:
2432                 return NULL;
2433         }
2434
2435         if (a->argc != e->args)
2436                 return CLI_SHOWUSAGE;
2437         quit_handler(0, SHUTDOWN_NORMAL, 0 /* not restart */);
2438         return CLI_SUCCESS;
2439 }
2440
2441 static char *handle_stop_gracefully(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2442 {
2443         switch (cmd) {
2444         case CLI_INIT:
2445                 e->command = "core stop gracefully";
2446                 e->usage =
2447                         "Usage: core stop gracefully\n"
2448                         "       Causes Asterisk to not accept new calls, and exit when all\n"
2449                         "       active calls have terminated normally.\n";
2450                 ast_cli_allow_at_shutdown(e);
2451                 return NULL;
2452         case CLI_GENERATE:
2453                 return NULL;
2454         }
2455
2456         if (a->argc != e->args)
2457                 return CLI_SHOWUSAGE;
2458         quit_handler(0, SHUTDOWN_NICE, 0 /* no restart */);
2459         return CLI_SUCCESS;
2460 }
2461
2462 static char *handle_stop_when_convenient(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2463 {
2464         switch (cmd) {
2465         case CLI_INIT:
2466                 e->command = "core stop when convenient";
2467                 e->usage =
2468                         "Usage: core stop when convenient\n"
2469                         "       Causes Asterisk to perform a shutdown when all active calls have ended.\n";
2470                 ast_cli_allow_at_shutdown(e);
2471                 return NULL;
2472         case CLI_GENERATE:
2473                 return NULL;
2474         }
2475
2476         if (a->argc != e->args)
2477                 return CLI_SHOWUSAGE;
2478         ast_cli(a->fd, "Waiting for inactivity to perform halt\n");
2479         quit_handler(0, SHUTDOWN_REALLY_NICE, 0 /* don't restart */);
2480         return CLI_SUCCESS;
2481 }
2482
2483 static char *handle_restart_now(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2484 {
2485         switch (cmd) {
2486         case CLI_INIT:
2487                 e->command = "core restart now";
2488                 e->usage =
2489                         "Usage: core restart now\n"
2490                         "       Causes Asterisk to hangup all calls and exec() itself performing a cold\n"
2491                         "       restart.\n";
2492                 ast_cli_allow_at_shutdown(e);
2493                 return NULL;
2494         case CLI_GENERATE:
2495                 return NULL;
2496         }
2497
2498         if (a->argc != e->args)
2499                 return CLI_SHOWUSAGE;
2500         quit_handler(0, SHUTDOWN_NORMAL, 1 /* restart */);
2501         return CLI_SUCCESS;
2502 }
2503
2504 static char *handle_restart_gracefully(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2505 {
2506         switch (cmd) {
2507         case CLI_INIT:
2508                 e->command = "core restart gracefully";
2509                 e->usage =
2510                         "Usage: core restart gracefully\n"
2511                         "       Causes Asterisk to stop accepting new calls and exec() itself performing a cold\n"
2512                         "       restart when all active calls have ended.\n";
2513                 ast_cli_allow_at_shutdown(e);
2514                 return NULL;
2515         case CLI_GENERATE:
2516                 return NULL;
2517         }
2518
2519         if (a->argc != e->args)
2520                 return CLI_SHOWUSAGE;
2521         quit_handler(0, SHUTDOWN_NICE, 1 /* restart */);
2522         return CLI_SUCCESS;
2523 }
2524
2525 static char *handle_restart_when_convenient(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2526 {
2527         switch (cmd) {
2528         case CLI_INIT:
2529                 e->command = "core restart when convenient";
2530                 e->usage =
2531                         "Usage: core restart when convenient\n"
2532                         "       Causes Asterisk to perform a cold restart when all active calls have ended.\n";
2533                 ast_cli_allow_at_shutdown(e);
2534                 return NULL;
2535         case CLI_GENERATE:
2536                 return NULL;
2537         }
2538
2539         if (a->argc != e->args)
2540                 return CLI_SHOWUSAGE;
2541         ast_cli(a->fd, "Waiting for inactivity to perform restart\n");
2542         quit_handler(0, SHUTDOWN_REALLY_NICE, 1 /* restart */);
2543         return CLI_SUCCESS;
2544 }
2545
2546 static char *handle_abort_shutdown(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2547 {
2548         switch (cmd) {
2549         case CLI_INIT:
2550                 e->command = "core abort shutdown";
2551                 e->usage =
2552                         "Usage: core abort shutdown\n"
2553                         "       Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
2554                         "       call operations.\n";
2555                 ast_cli_allow_at_shutdown(e);
2556                 return NULL;
2557         case CLI_GENERATE:
2558                 return NULL;
2559         }
2560
2561         if (a->argc != e->args)
2562                 return CLI_SHOWUSAGE;
2563
2564         ast_cancel_shutdown();
2565
2566         return CLI_SUCCESS;
2567 }
2568
2569 static char *handle_bang(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2570 {
2571         switch (cmd) {
2572         case CLI_INIT:
2573                 e->command = "!";
2574                 e->usage =
2575                         "Usage: !<command>\n"
2576                         "       Executes a given shell command\n";
2577                 return NULL;
2578         case CLI_GENERATE:
2579                 return NULL;
2580         }
2581
2582         return CLI_SUCCESS;
2583 }
2584 static const char warranty_lines[] = {
2585         "\n"
2586         "                           NO WARRANTY\n"
2587         "\n"
2588         "BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\n"
2589         "FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\n"
2590         "OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\n"
2591         "PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\n"
2592         "OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n"
2593         "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\n"
2594         "TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\n"
2595         "PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\n"
2596         "REPAIR OR CORRECTION.\n"
2597         "\n"
2598         "IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\n"
2599         "WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\n"
2600         "REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\n"
2601         "INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\n"
2602         "OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\n"
2603         "TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\n"
2604         "YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\n"
2605         "PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\n"
2606         "POSSIBILITY OF SUCH DAMAGES.\n"
2607 };
2608
2609 static char *show_warranty(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2610 {
2611         switch (cmd) {
2612         case CLI_INIT:
2613                 e->command = "core show warranty";
2614                 e->usage =
2615                         "Usage: core show warranty\n"
2616                         "       Shows the warranty (if any) for this copy of Asterisk.\n";
2617                 return NULL;
2618         case CLI_GENERATE:
2619                 return NULL;
2620         }
2621
2622         ast_cli(a->fd, "%s", warranty_lines);
2623
2624         return CLI_SUCCESS;
2625 }
2626
2627 static const char license_lines[] = {
2628         "\n"
2629         "This program is free software; you can redistribute it and/or modify\n"
2630         "it under the terms of the GNU General Public License version 2 as\n"
2631         "published by the Free Software Foundation.\n"
2632         "\n"
2633         "This program also contains components licensed under other licenses.\n"
2634         "They include:\n"
2635         "\n"
2636         "This program is distributed in the hope that it will be useful,\n"
2637         "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
2638         "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
2639         "GNU General Public License for more details.\n"
2640         "\n"
2641         "You should have received a copy of the GNU General Public License\n"
2642         "along with this program; if not, write to the Free Software\n"
2643         "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
2644 };
2645
2646 static char *show_license(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2647 {
2648         switch (cmd) {
2649         case CLI_INIT:
2650                 e->command = "core show license";
2651                 e->usage =
2652                         "Usage: core show license\n"
2653                         "       Shows the license(s) for this copy of Asterisk.\n";
2654                 return NULL;
2655         case CLI_GENERATE:
2656                 return NULL;
2657         }
2658
2659         ast_cli(a->fd, "%s", license_lines);
2660
2661         return CLI_SUCCESS;
2662 }
2663
2664 #define ASTERISK_PROMPT "*CLI> "
2665
2666 /*!
2667  * \brief Shutdown Asterisk CLI commands.
2668  *
2669  * \note These CLI commands cannot be unregistered at shutdown
2670  * because one of them is likely the reason for the shutdown.
2671  * The CLI generates a warning if a command is in-use when it is
2672  * unregistered.
2673  */
2674 static struct ast_cli_entry cli_asterisk_shutdown[] = {
2675         AST_CLI_DEFINE(handle_stop_now, "Shut down Asterisk immediately"),
2676         AST_CLI_DEFINE(handle_stop_gracefully, "Gracefully shut down Asterisk"),
2677         AST_CLI_DEFINE(handle_stop_when_convenient, "Shut down Asterisk at empty call volume"),
2678         AST_CLI_DEFINE(handle_restart_now, "Restart Asterisk immediately"),
2679         AST_CLI_DEFINE(handle_restart_gracefully, "Restart Asterisk gracefully"),
2680         AST_CLI_DEFINE(handle_restart_when_convenient, "Restart Asterisk at empty call volume"),
2681 };
2682
2683 static struct ast_cli_entry cli_asterisk[] = {
2684         AST_CLI_DEFINE(handle_abort_shutdown, "Cancel a running shutdown"),
2685         AST_CLI_DEFINE(show_warranty, "Show the warranty (if any) for this copy of Asterisk"),
2686         AST_CLI_DEFINE(show_license, "Show the license(s) for this copy of Asterisk"),
2687         AST_CLI_DEFINE(handle_version, "Display version info"),
2688         AST_CLI_DEFINE(handle_bang, "Execute a shell command"),
2689 #if !defined(LOW_MEMORY)
2690         AST_CLI_DEFINE(handle_show_threads, "Show running threads"),
2691 #if defined(HAVE_SYSINFO) || defined(HAVE_SYSCTL)
2692         AST_CLI_DEFINE(handle_show_sysinfo, "Show System Information"),
2693 #endif
2694         AST_CLI_DEFINE(handle_show_profile, "Display profiling info"),
2695         AST_CLI_DEFINE(handle_show_settings, "Show some core settings"),
2696         AST_CLI_DEFINE(handle_clear_profile, "Clear profiling info"),
2697 #endif /* ! LOW_MEMORY */
2698 };
2699
2700 static void send_rasterisk_connect_commands(void)
2701 {
2702         char buf[80];
2703
2704         /*
2705          * Tell the server asterisk instance about the verbose level
2706          * initially desired.
2707          */
2708         if (option_verbose) {
2709                 snprintf(buf, sizeof(buf), "core set verbose atleast %d silent", option_verbose);
2710                 fdsend(ast_consock, buf);
2711         }
2712
2713         if (option_debug) {
2714                 snprintf(buf, sizeof(buf), "core set debug atleast %d", option_debug);
2715                 fdsend(ast_consock, buf);
2716         }
2717
2718         /* Leave verbose filtering to the server. */
2719         option_verbose = INT_MAX;
2720
2721         if (!ast_opt_mute) {
2722                 fdsend(ast_consock, "logger mute silent");
2723         } else {
2724                 printf("log and verbose output currently muted ('logger mute' to unmute)\n");
2725         }
2726 }
2727
2728 #ifdef HAVE_LIBEDIT_IS_UNICODE
2729 #define CHAR_T_LIBEDIT wchar_t
2730 #define CHAR_TO_LIBEDIT(c) btowc(c)
2731 #else
2732 #define CHAR_T_LIBEDIT char
2733 #define CHAR_TO_LIBEDIT(c) c
2734 #endif
2735
2736 static int ast_el_read_char(EditLine *editline, CHAR_T_LIBEDIT *cp)
2737 {
2738         int num_read = 0;
2739         int lastpos = 0;
2740         struct pollfd fds[2];
2741         int res;
2742         int max;
2743 #define EL_BUF_SIZE 512
2744         char buf[EL_BUF_SIZE];
2745
2746         for (;;) {
2747                 max = 1;
2748                 fds[0].fd = ast_consock;
2749                 fds[0].events = POLLIN;
2750                 if (!ast_opt_exec) {
2751                         fds[1].fd = STDIN_FILENO;
2752                         fds[1].events = POLLIN;
2753                         max++;
2754                 }
2755                 res = ast_poll(fds, max, -1);
2756                 if (res < 0) {
2757                         if (sig_flags.need_quit || sig_flags.need_quit_handler) {
2758                                 break;
2759                         }
2760                         if (errno == EINTR) {
2761                                 continue;
2762                         }
2763                         fprintf(stderr, "poll failed: %s\n", strerror(errno));
2764                         break;
2765                 }
2766
2767                 if (!ast_opt_exec && fds[1].revents) {
2768                         char c = '\0';
2769
2770                         num_read = read(STDIN_FILENO, &c, 1);
2771                         if (num_read < 1) {
2772                                 break;
2773                         }
2774
2775                         *cp = CHAR_TO_LIBEDIT(c);
2776
2777                         return num_read;
2778                 }
2779
2780                 if (fds[0].revents) {
2781                         res = read(ast_consock, buf, sizeof(buf) - 1);
2782                         /* if the remote side disappears exit */
2783                         if (res < 1) {
2784                                 fprintf(stderr, "\nDisconnected from Asterisk server\n");
2785                                 if (!ast_opt_reconnect) {
2786                                         quit_handler(0, SHUTDOWN_FAST, 0);
2787                                 } else {
2788                                         int tries;
2789                                         int reconnects_per_second = 20;
2790
2791                                         fprintf(stderr, "Attempting to reconnect for 30 seconds\n");
2792                                         for (tries = 0; tries < 30 * reconnects_per_second; tries++) {
2793                                                 if (ast_tryconnect()) {
2794                                                         fprintf(stderr, "Reconnect succeeded after %.3f seconds\n", 1.0 / reconnects_per_second * tries);
2795                                                         printf("%s", term_quit());
2796                                                         WELCOME_MESSAGE;
2797                                                         send_rasterisk_connect_commands();
2798                                                         break;
2799                                                 }
2800
2801                                                 usleep(1000000 / reconnects_per_second);
2802                                         }
2803                                         if (tries >= 30 * reconnects_per_second) {
2804                                                 fprintf(stderr, "Failed to reconnect for 30 seconds.  Quitting.\n");
2805                                                 quit_handler(0, SHUTDOWN_FAST, 0);
2806                                         }
2807                                 }
2808                                 continue;
2809                         }
2810
2811                         buf[res] = '\0';
2812
2813                         /* Write over the CLI prompt */
2814                         if (!ast_opt_exec && !lastpos) {
2815                                 if (write(STDOUT_FILENO, "\r\e[0K", 5) < 0) {
2816                                 }
2817                         }
2818
2819                         console_print(buf);
2820
2821                         if ((res < EL_BUF_SIZE - 1) && ((buf[res-1] == '\n') || (res >= 2 && buf[res-2] == '\n'))) {
2822                                 *cp = CHAR_TO_LIBEDIT(CC_REFRESH);
2823
2824                                 return 1;
2825                         }
2826                         lastpos = 1;
2827                 }
2828         }
2829
2830         *cp = CHAR_TO_LIBEDIT('\0');
2831
2832         return 0;
2833 }
2834
2835 static struct ast_str *prompt = NULL;
2836
2837 static char *cli_prompt(EditLine *editline)
2838 {
2839         char tmp[100];
2840         char *pfmt;
2841         int color_used = 0;
2842         static int cli_prompt_changes = 0;
2843         struct passwd *pw;
2844         struct group *gr;
2845
2846         if (prompt == NULL) {
2847                 prompt = ast_str_create(100);
2848         } else if (!cli_prompt_changes) {
2849                 return ast_str_buffer(prompt);
2850         } else {
2851                 ast_str_reset(prompt);
2852         }
2853
2854         if ((pfmt = getenv("ASTERISK_PROMPT"))) {
2855                 char *t = pfmt;
2856                 struct timeval ts = ast_tvnow();
2857                 while (*t != '\0') {
2858                         if (*t == '%') {
2859                                 char hostname[MAXHOSTNAMELEN] = "";
2860                                 int i, which;
2861                                 struct ast_tm tm = { 0, };
2862                                 int fgcolor = COLOR_WHITE, bgcolor = COLOR_BLACK;
2863
2864                                 t++;
2865                                 switch (*t) {
2866                                 case 'C': /* color */
2867                                         t++;
2868                                         if (sscanf(t, "%30d;%30d%n", &fgcolor, &bgcolor, &i) == 2) {
2869                                                 ast_term_color_code(&prompt, fgcolor, bgcolor);
2870                                                 t += i - 1;
2871                                         } else if (sscanf(t, "%30d%n", &fgcolor, &i) == 1) {
2872                                                 ast_term_color_code(&prompt, fgcolor, 0);
2873                                                 t += i - 1;
2874                                         }
2875
2876                                         /* If the color has been reset correctly, then there's no need to reset it later */
2877                                         color_used = ((fgcolor == COLOR_WHITE) && (bgcolor == COLOR_BLACK)) ? 0 : 1;
2878                                         break;
2879                                 case 'd': /* date */
2880                                         if (ast_localtime(&ts, &tm, NULL)) {
2881                                                 ast_strftime(tmp, sizeof(tmp), "%Y-%m-%d", &tm);
2882                                                 ast_str_append(&prompt, 0, "%s", tmp);
2883                                                 cli_prompt_changes++;
2884                                         }
2885                                         break;
2886                                 case 'g': /* group */
2887                                         if ((gr = getgrgid(getgid()))) {
2888                                                 ast_str_append(&prompt, 0, "%s", gr->gr_name);
2889                                         }
2890                                         break;
2891                                 case 'h': /* hostname */
2892                                         if (!gethostname(hostname, sizeof(hostname) - 1)) {
2893                                                 ast_str_append(&prompt, 0, "%s", hostname);
2894                                         } else {
2895                                                 ast_str_append(&prompt, 0, "%s", "localhost");
2896                                         }
2897                                         break;
2898                                 case 'H': /* short hostname */
2899                                         if (!gethostname(hostname, sizeof(hostname) - 1)) {
2900                                                 char *dotptr;
2901                                                 if ((dotptr = strchr(hostname, '.'))) {
2902                                                         *dotptr = '\0';
2903                                                 }
2904                                                 ast_str_append(&prompt, 0, "%s", hostname);
2905                                         } else {
2906                                                 ast_str_append(&prompt, 0, "%s", "localhost");
2907                                         }
2908                                         break;
2909 #ifdef HAVE_GETLOADAVG
2910                                 case 'l': /* load avg */
2911                                         t++;
2912                                         if (sscanf(t, "%30d", &which) == 1 && which > 0 && which <= 3) {
2913                                                 double list[3];
2914                                                 getloadavg(list, 3);
2915                                                 ast_str_append(&prompt, 0, "%.2f", list[which - 1]);
2916                                                 cli_prompt_changes++;
2917                                         }
2918                                         break;
2919 #endif
2920                                 case 's': /* Asterisk system name (from asterisk.conf) */
2921                                         ast_str_append(&prompt, 0, "%s", ast_config_AST_SYSTEM_NAME);
2922                                         break;
2923                                 case 't': /* time */
2924                                         if (ast_localtime(&ts, &tm, NULL)) {
2925                                                 ast_strftime(tmp, sizeof(tmp), "%H:%M:%S", &tm);
2926                                                 ast_str_append(&prompt, 0, "%s", tmp);
2927                                                 cli_prompt_changes++;
2928                                         }
2929                                         break;
2930                                 case 'u': /* username */
2931                                         if ((pw = getpwuid(getuid()))) {
2932                                                 ast_str_append(&prompt, 0, "%s", pw->pw_name);
2933                                         }
2934                                         break;
2935                                 case '#': /* process console or remote? */
2936                                         ast_str_append(&prompt, 0, "%c", ast_opt_remote ? '>' : '#');
2937                                         break;
2938                                 case '%': /* literal % */
2939                                         ast_str_append(&prompt, 0, "%c", '%');
2940                                         break;
2941                                 case '\0': /* % is last character - prevent bug */
2942                                         t--;
2943                                         break;
2944                                 }
2945                         } else {
2946                                 ast_str_append(&prompt, 0, "%c", *t);
2947                         }
2948                         t++;
2949                 }
2950                 if (color_used) {
2951                         /* Force colors back to normal at end */
2952                         ast_term_color_code(&prompt, 0, 0);
2953                 }
2954         } else {
2955                 ast_str_set(&prompt, 0, "%s%s",
2956                         remotehostname ? remotehostname : "",
2957                         ASTERISK_PROMPT);
2958         }
2959
2960         return ast_str_buffer(prompt);
2961 }
2962
2963 static struct ast_vector_string *ast_el_strtoarr(char *buf)
2964 {
2965         char *retstr;
2966         struct ast_vector_string *vec = ast_calloc(1, sizeof(*vec));
2967
2968         if (!vec) {
2969                 return NULL;
2970         }
2971
2972         while ((retstr = strsep(&buf, " "))) {
2973                 if (!strcmp(retstr, AST_CLI_COMPLETE_EOF)) {
2974                         break;
2975                 }
2976
2977                 retstr = ast_strdup(retstr);
2978                 if (!retstr || AST_VECTOR_APPEND(vec, retstr)) {
2979                         ast_free(retstr);
2980                         goto vector_cleanup;
2981                 }
2982         }
2983
2984         if (!AST_VECTOR_SIZE(vec)) {
2985                 goto vector_cleanup;
2986         }
2987
2988         return vec;
2989
2990 vector_cleanup:
2991         AST_VECTOR_CALLBACK_VOID(vec, ast_free);
2992         AST_VECTOR_PTR_FREE(vec);
2993
2994         return NULL;
2995 }
2996
2997 static void ast_cli_display_match_list(struct ast_vector_string *matches, int max)
2998 {
2999         int idx = 1;
3000         /* find out how many entries can be put on one line, with two spaces between strings */
3001         int limit = ast_get_termcols(STDOUT_FILENO) / (max + 2);
3002
3003         if (limit == 0) {
3004                 limit = 1;
3005         }
3006
3007         for (;;) {
3008                 int numoutputline;
3009
3010                 for (numoutputline = 0; numoutputline < limit && idx < AST_VECTOR_SIZE(matches); idx++) {
3011                         numoutputline++;
3012                         fprintf(stdout, "%-*s  ", max, AST_VECTOR_GET(matches, idx));
3013                 }
3014
3015                 if (!numoutputline) {
3016                         break;
3017                 }
3018
3019                 fprintf(stdout, "\n");
3020         }
3021 }
3022
3023
3024 static char *cli_complete(EditLine *editline, int ch)
3025 {
3026         int len = 0;
3027         char *ptr;
3028         struct ast_vector_string *matches;
3029         int retval = CC_ERROR;
3030         char savechr;
3031         int res;
3032
3033         LineInfo *lf = (LineInfo *)el_line(editline);
3034
3035         savechr = *(char *)lf->cursor;
3036         *(char *)lf->cursor = '\0';
3037         ptr = (char *)lf->cursor;
3038         if (ptr) {
3039                 while (ptr > lf->buffer) {
3040                         if (isspace(*ptr)) {
3041                                 ptr++;
3042                                 break;
3043                         }
3044                         ptr--;
3045                 }
3046         }
3047
3048         len = lf->cursor - ptr;
3049
3050         if (ast_opt_remote) {
3051 #define CMD_MATCHESARRAY "_COMMAND MATCHESARRAY \"%s\" \"%s\""
3052                 char *mbuf;
3053                 char *new_mbuf;
3054                 int mlen = 0;
3055                 int maxmbuf = ast_asprintf(&mbuf, CMD_MATCHESARRAY, lf->buffer, ptr);
3056
3057                 if (maxmbuf == -1) {
3058                         *((char *) lf->cursor) = savechr;
3059
3060                         return (char *)(CC_ERROR);
3061                 }
3062
3063                 fdsend(ast_consock, mbuf);
3064                 res = 0;
3065                 mlen = 0;
3066                 mbuf[0] = '\0';
3067
3068                 while (!strstr(mbuf, AST_CLI_COMPLETE_EOF) && res != -1) {
3069                         if (mlen + 1024 > maxmbuf) {
3070                                 /* Expand buffer to the next 1024 byte increment plus a NULL terminator. */
3071                                 maxmbuf = mlen + 1024;
3072                                 new_mbuf = ast_realloc(mbuf, maxmbuf + 1);
3073                                 if (!new_mbuf) {
3074                                         ast_free(mbuf);
3075                                         *((char *) lf->cursor) = savechr;
3076
3077                                         return (char *)(CC_ERROR);
3078                                 }
3079                                 mbuf = new_mbuf;
3080                         }
3081                         /* Only read 1024 bytes at a time */
3082                         res = read(ast_consock, mbuf + mlen, 1024);
3083                         if (res > 0) {
3084                                 mlen += res;
3085                                 mbuf[mlen] = '\0';
3086                         }
3087                 }
3088                 mbuf[mlen] = '\0';
3089
3090                 matches = ast_el_strtoarr(mbuf);
3091                 ast_free(mbuf);
3092         } else {
3093                 matches = ast_cli_completion_vector((char *)lf->buffer, ptr);
3094         }
3095
3096         if (matches) {
3097                 int i;
3098                 int maxlen, match_len;
3099                 const char *best_match = AST_VECTOR_GET(matches, 0);
3100
3101                 if (!ast_strlen_zero(best_match)) {
3102                         el_deletestr(editline, (int) len);
3103                         el_insertstr(editline, best_match);
3104                         retval = CC_REFRESH;
3105                 }
3106
3107                 if (AST_VECTOR_SIZE(matches) == 2) {
3108                         /* Found an exact match */
3109                         el_insertstr(editline, " ");
3110                         retval = CC_REFRESH;
3111                 } else {
3112                         /* Must be more than one match */
3113                         for (i = 1, maxlen = 0; i < AST_VECTOR_SIZE(matches); i++) {
3114                                 match_len = strlen(AST_VECTOR_GET(matches, i));
3115                                 if (match_len > maxlen) {
3116                                         maxlen = match_len;
3117                                 }
3118                         }
3119
3120                         fprintf(stdout, "\n");
3121                         ast_cli_display_match_list(matches, maxlen);
3122                         retval = CC_REDISPLAY;
3123                 }
3124                 AST_VECTOR_CALLBACK_VOID(matches, ast_free);
3125                 AST_VECTOR_PTR_FREE(matches);
3126         }
3127
3128         *((char *) lf->cursor) = savechr;
3129
3130         return (char *)(long)retval;
3131 }
3132
3133 static int ast_el_initialize(void)
3134 {
3135         HistEvent ev;
3136         char *editor, *editrc = getenv("EDITRC");
3137
3138         if (!(editor = getenv("AST_EDITMODE"))) {
3139                 if (!(editor = getenv("AST_EDITOR"))) {
3140                         editor = "emacs";
3141                 }
3142         }
3143
3144         if (el != NULL)
3145                 el_end(el);
3146         if (el_hist != NULL)
3147                 history_end(el_hist);
3148
3149         el = el_init("asterisk", stdin, stdout, stderr);
3150         el_set(el, EL_PROMPT, cli_prompt);
3151
3152         el_set(el, EL_EDITMODE, 1);
3153         el_set(el, EL_EDITOR, editor);
3154         el_hist = history_init();
3155         if (!el || !el_hist)
3156                 return -1;
3157
3158         /* setup history with 100 entries */
3159         history(el_hist, &ev, H_SETSIZE, 100);
3160
3161         el_set(el, EL_HIST, history, el_hist);
3162
3163         el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
3164         /* Bind <tab> to command completion */
3165         el_set(el, EL_BIND, "^I", "ed-complete", NULL);
3166         /* Bind ? to command completion */
3167         el_set(el, EL_BIND, "?", "ed-complete", NULL);
3168         /* Bind ^D to redisplay */
3169         el_set(el, EL_BIND, "^D", "ed-redisplay", NULL);
3170         /* Bind Delete to delete char left */
3171         el_set(el, EL_BIND, "\\e[3~", "ed-delete-next-char", NULL);
3172         /* Bind Home and End to move to line start and end */
3173         el_set(el, EL_BIND, "\\e[1~", "ed-move-to-beg", NULL);
3174         el_set(el, EL_BIND, "\\e[4~", "ed-move-to-end", NULL);
3175         /* Bind C-left and C-right to move by word (not all terminals) */
3176         el_set(el, EL_BIND, "\\eOC", "vi-next-word", NULL);
3177         el_set(el, EL_BIND, "\\eOD", "vi-prev-word", NULL);
3178
3179         if (editrc) {
3180                 el_source(el, editrc);
3181         }
3182
3183         return 0;
3184 }
3185
3186 #define MAX_HISTORY_COMMAND_LENGTH 256
3187
3188 static int ast_el_add_history(const char *buf)
3189 {
3190         HistEvent ev;
3191         char *stripped_buf;
3192
3193         if (el_hist == NULL || el == NULL) {
3194                 ast_el_initialize();
3195         }
3196         if (strlen(buf) > (MAX_HISTORY_COMMAND_LENGTH - 1)) {
3197                 return 0;
3198         }
3199
3200         stripped_buf = ast_strip(ast_strdupa(buf));
3201
3202         /* HISTCONTROL=ignoredups */
3203         if (!history(el_hist, &ev, H_FIRST) && strcmp(ev.str, stripped_buf) == 0) {
3204                 return 0;
3205         }
3206
3207         return history(el_hist, &ev, H_ENTER, stripped_buf);
3208 }
3209
3210 static int ast_el_write_history(const char *filename)
3211 {
3212         HistEvent ev;
3213
3214         if (el_hist == NULL || el == NULL)
3215                 ast_el_initialize();
3216
3217         return (history(el_hist, &ev, H_SAVE, filename));
3218 }
3219
3220 static int ast_el_read_history(const char *filename)
3221 {
3222         HistEvent ev;
3223
3224         if (el_hist == NULL || el == NULL) {
3225                 ast_el_initialize();
3226         }
3227
3228         return history(el_hist, &ev, H_LOAD, filename);
3229 }
3230
3231 static void ast_el_read_default_histfile(void)
3232 {
3233         char histfile[80] = "";
3234         const char *home = getenv("HOME");
3235
3236         if (!ast_strlen_zero(home)) {
3237                 snprintf(histfile, sizeof(histfile), "%s/.asterisk_history", home);
3238                 ast_el_read_history(histfile);
3239         }
3240 }
3241
3242 static void ast_el_write_default_histfile(void)
3243 {
3244         char histfile[80] = "";
3245         const char *home = getenv("HOME");
3246
3247         if (!ast_strlen_zero(home)) {
3248                 snprintf(histfile, sizeof(histfile), "%s/.asterisk_history", home);
3249                 ast_el_write_history(histfile);
3250         }
3251 }
3252
3253 static void ast_remotecontrol(char *data)
3254 {
3255         char buf[256] = "";
3256         int res;
3257         char *hostname;
3258         char *cpid;
3259         char *version;
3260         int pid;