Merge "res_rtp_asterisk: Always return provided DTLS packet length."
[asterisk/asterisk.git] / main / asterisk.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2018, 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 - 2018, 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__) || defined(__DragonFly__)
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/mwi.h"
214 #include "asterisk/lock.h"
215 #include "asterisk/utils.h"
216 #include "asterisk/file.h"
217 #include "asterisk/io.h"
218 #include "asterisk/config.h"
219 #include "asterisk/ast_version.h"
220 #include "asterisk/linkedlists.h"
221 #include "asterisk/devicestate.h"
222 #include "asterisk/presencestate.h"
223 #include "asterisk/module.h"
224 #include "asterisk/buildinfo.h"
225 #include "asterisk/xmldoc.h"
226 #include "asterisk/poll-compat.h"
227 #include "asterisk/test.h"
228 #include "asterisk/rtp_engine.h"
229 #include "asterisk/format.h"
230 #include "asterisk/aoc.h"
231 #include "asterisk/uuid.h"
232 #include "asterisk/sorcery.h"
233 #include "asterisk/bucket.h"
234 #include "asterisk/stasis.h"
235 #include "asterisk/json.h"
236 #include "asterisk/stasis_endpoints.h"
237 #include "asterisk/stasis_system.h"
238 #include "asterisk/security_events.h"
239 #include "asterisk/endpoints.h"
240 #include "asterisk/codec.h"
241 #include "asterisk/format_cache.h"
242 #include "asterisk/media_cache.h"
243 #include "asterisk/astdb.h"
244 #include "asterisk/options.h"
245
246 #include "../defaults.h"
247
248 /*** DOCUMENTATION
249         <managerEvent language="en_US" name="FullyBooted">
250                 <managerEventInstance class="EVENT_FLAG_SYSTEM">
251                         <synopsis>Raised when all Asterisk initialization procedures have finished.</synopsis>
252                         <syntax>
253                                 <parameter name="Status">
254                                         <para>Informational message</para>
255                                 </parameter>
256                                 <parameter name="Uptime">
257                                         <para>Seconds since start</para>
258                                 </parameter>
259                                 <parameter name="LastReload">
260                                         <para>Seconds since last reload</para>
261                                 </parameter>
262                         </syntax>
263                 </managerEventInstance>
264         </managerEvent>
265         <managerEvent language="en_US" name="Shutdown">
266                 <managerEventInstance class="EVENT_FLAG_SYSTEM">
267                         <synopsis>Raised when Asterisk is shutdown or restarted.</synopsis>
268                         <syntax>
269                                 <parameter name="Shutdown">
270                                         <para>Whether the shutdown is proceeding cleanly (all channels
271                                         were hungup successfully) or uncleanly (channels will be
272                                         terminated)</para>
273                                         <enumlist>
274                                                 <enum name="Uncleanly"/>
275                                                 <enum name="Cleanly"/>
276                                         </enumlist>
277                                 </parameter>
278                                 <parameter name="Restart">
279                                         <para>Whether or not a restart will occur.</para>
280                                         <enumlist>
281                                                 <enum name="True"/>
282                                                 <enum name="False"/>
283                                         </enumlist>
284                                 </parameter>
285                         </syntax>
286                 </managerEventInstance>
287         </managerEvent>
288  ***/
289
290 #ifndef AF_LOCAL
291 #define AF_LOCAL AF_UNIX
292 #define PF_LOCAL PF_UNIX
293 #endif
294
295 #define AST_MAX_CONNECTS 128
296 #define NUM_MSGS 64
297
298 /*! Displayed copyright tag */
299 #define COPYRIGHT_TAG "Copyright (C) 1999 - 2018, Digium, Inc. and others."
300
301 /*! \brief Welcome message when starting a CLI interface */
302 #define WELCOME_MESSAGE \
303     ast_verbose("Asterisk %s, " COPYRIGHT_TAG "\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 static int ast_socket = -1;             /*!< UNIX Socket for allowing remote control */
312 static int ast_socket_is_sd = 0; /*!< Is socket activation responsible for ast_socket? */
313 static int ast_consock = -1;            /*!< UNIX Socket for controlling another asterisk */
314 pid_t ast_mainpid;
315 struct console {
316         int fd;                         /*!< File descriptor */
317         int p[2];                       /*!< Pipe */
318         pthread_t t;                    /*!< Thread of handler */
319         int mute;                       /*!< Is the console muted for logs */
320         int uid;                        /*!< Remote user ID. */
321         int gid;                        /*!< Remote group ID. */
322         int levels[NUMLOGLEVELS];       /*!< Which log levels are enabled for the console */
323         /*! Verbosity level of this console. */
324         int option_verbose;
325 };
326
327 struct ast_atexit {
328         void (*func)(void);
329         int is_cleanup;
330         AST_LIST_ENTRY(ast_atexit) list;
331 };
332
333 static AST_LIST_HEAD_STATIC(atexits, ast_atexit);
334
335 struct timeval ast_startuptime;
336 struct timeval ast_lastreloadtime;
337
338 static History *el_hist;
339 static EditLine *el;
340 static char *remotehostname;
341
342 struct console consoles[AST_MAX_CONNECTS];
343
344 static int ast_el_add_history(const char *);
345 static int ast_el_read_history(const char *);
346 static int ast_el_write_history(const char *);
347
348 static void ast_el_read_default_histfile(void);
349 static void ast_el_write_default_histfile(void);
350
351 static void asterisk_daemon(int isroot, const char *runuser, const char *rungroup);
352
353 static char *_argv[256];
354
355 typedef enum {
356         /*! Normal operation */
357         NOT_SHUTTING_DOWN,
358         /*! Committed to shutting down.  Final phase */
359         SHUTTING_DOWN_FINAL,
360         /*! Committed to shutting down.  Initial phase */
361         SHUTTING_DOWN,
362         /*!
363          * Valid values for quit_handler() niceness below.
364          * These shutdown/restart levels can be cancelled.
365          *
366          * Remote console exit right now
367          */
368         SHUTDOWN_FAST,
369         /*! core stop/restart now */
370         SHUTDOWN_NORMAL,
371         /*! core stop/restart gracefully */
372         SHUTDOWN_NICE,
373         /*! core stop/restart when convenient */
374         SHUTDOWN_REALLY_NICE
375 } shutdown_nice_t;
376
377 static shutdown_nice_t shuttingdown = NOT_SHUTTING_DOWN;
378
379 /*! Prevent new channel allocation for shutdown. */
380 static int shutdown_pending;
381
382 static int restartnow;
383 static pthread_t consolethread = AST_PTHREADT_NULL;
384 static pthread_t mon_sig_flags;
385 static int canary_pid = 0;
386 static char canary_filename[128];
387 static int multi_thread_safe;
388
389 static char randompool[256];
390
391 static int sig_alert_pipe[2] = { -1, -1 };
392 static struct {
393          unsigned int need_reload:1;
394          unsigned int need_quit:1;
395          unsigned int need_quit_handler:1;
396          unsigned int need_el_end:1;
397 } sig_flags;
398
399 #if !defined(LOW_MEMORY)
400 struct thread_list_t {
401         AST_RWLIST_ENTRY(thread_list_t) list;
402         char *name;
403         pthread_t id;
404         int lwp;
405 };
406
407 static AST_RWLIST_HEAD_STATIC(thread_list, thread_list_t);
408
409 void ast_register_thread(char *name)
410 {
411         struct thread_list_t *new = ast_calloc(1, sizeof(*new));
412
413         if (!new)
414                 return;
415
416         ast_assert(multi_thread_safe);
417         new->id = pthread_self();
418         new->lwp = ast_get_tid();
419         new->name = name; /* steal the allocated memory for the thread name */
420         AST_RWLIST_WRLOCK(&thread_list);
421         AST_RWLIST_INSERT_HEAD(&thread_list, new, list);
422         AST_RWLIST_UNLOCK(&thread_list);
423 }
424
425 void ast_unregister_thread(void *id)
426 {
427         struct thread_list_t *x;
428
429         AST_RWLIST_WRLOCK(&thread_list);
430         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&thread_list, x, list) {
431                 if ((void *) x->id == id) {
432                         AST_RWLIST_REMOVE_CURRENT(list);
433                         break;
434                 }
435         }
436         AST_RWLIST_TRAVERSE_SAFE_END;
437         AST_RWLIST_UNLOCK(&thread_list);
438         if (x) {
439                 ast_free(x->name);
440                 ast_free(x);
441         }
442 }
443
444 /*! \brief Give an overview of core settings */
445 static char *handle_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
446 {
447         char buf[BUFSIZ];
448         struct ast_tm tm;
449         char eid_str[128];
450         struct rlimit limits;
451         char pbx_uuid[AST_UUID_STR_LEN];
452
453         switch (cmd) {
454         case CLI_INIT:
455                 e->command = "core show settings";
456                 e->usage = "Usage: core show settings\n"
457                            "       Show core misc settings";
458                 return NULL;
459         case CLI_GENERATE:
460                 return NULL;
461         }
462
463         ast_eid_to_str(eid_str, sizeof(eid_str), &ast_eid_default);
464         ast_pbx_uuid_get(pbx_uuid, sizeof(pbx_uuid));
465
466         ast_cli(a->fd, "\nPBX Core settings\n");
467         ast_cli(a->fd, "-----------------\n");
468         ast_cli(a->fd, "  Version:                     %s\n", ast_get_version());
469         ast_cli(a->fd, "  Build Options:               %s\n", S_OR(ast_get_build_opts(), "(none)"));
470         if (ast_option_maxcalls)
471                 ast_cli(a->fd, "  Maximum calls:               %d (Current %d)\n", ast_option_maxcalls, ast_active_channels());
472         else
473                 ast_cli(a->fd, "  Maximum calls:               Not set\n");
474
475         if (getrlimit(RLIMIT_NOFILE, &limits)) {
476                 ast_cli(a->fd, "  Maximum open file handles:   Error because of %s\n", strerror(errno));
477         } else if (limits.rlim_cur == RLIM_INFINITY) {
478                 ast_cli(a->fd, "  Maximum open file handles:   Unlimited\n");
479         } else if (limits.rlim_cur < ast_option_maxfiles) {
480                 ast_cli(a->fd, "  Maximum open file handles:   %d (is) %d (requested)\n", (int) limits.rlim_cur, ast_option_maxfiles);
481         } else {
482                 ast_cli(a->fd, "  Maximum open file handles:   %d\n", (int) limits.rlim_cur);
483         }
484
485         ast_cli(a->fd, "  Root console verbosity:      %d\n", option_verbose);
486         ast_cli(a->fd, "  Current console verbosity:   %d\n", ast_verb_console_get());
487         ast_cli(a->fd, "  Debug level:                 %d\n", option_debug);
488         ast_cli(a->fd, "  Maximum load average:        %lf\n", ast_option_maxload);
489 #if defined(HAVE_SYSINFO)
490         ast_cli(a->fd, "  Minimum free memory:         %ld MB\n", option_minmemfree);
491 #endif
492         if (ast_localtime(&ast_startuptime, &tm, NULL)) {
493                 ast_strftime(buf, sizeof(buf), "%H:%M:%S", &tm);
494                 ast_cli(a->fd, "  Startup time:                %s\n", buf);
495         }
496         if (ast_localtime(&ast_lastreloadtime, &tm, NULL)) {
497                 ast_strftime(buf, sizeof(buf), "%H:%M:%S", &tm);
498                 ast_cli(a->fd, "  Last reload time:            %s\n", buf);
499         }
500         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);
501         ast_cli(a->fd, "  System name:                 %s\n", ast_config_AST_SYSTEM_NAME);
502         ast_cli(a->fd, "  Entity ID:                   %s\n", eid_str);
503         ast_cli(a->fd, "  PBX UUID:                    %s\n", pbx_uuid);
504         ast_cli(a->fd, "  Default language:            %s\n", ast_defaultlanguage);
505         ast_cli(a->fd, "  Language prefix:             %s\n", ast_language_is_prefix ? "Enabled" : "Disabled");
506         ast_cli(a->fd, "  User name and group:         %s/%s\n", ast_config_AST_RUN_USER, ast_config_AST_RUN_GROUP);
507         ast_cli(a->fd, "  Executable includes:         %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_EXEC_INCLUDES) ? "Enabled" : "Disabled");
508         ast_cli(a->fd, "  Transcode via SLIN:          %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_TRANSCODE_VIA_SLIN) ? "Enabled" : "Disabled");
509         ast_cli(a->fd, "  Transmit silence during rec: %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_TRANSMIT_SILENCE) ? "Enabled" : "Disabled");
510         ast_cli(a->fd, "  Generic PLC:                 %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_GENERIC_PLC) ? "Enabled" : "Disabled");
511         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");
512         ast_cli(a->fd, "  Min DTMF duration::          %u\n", option_dtmfminduration);
513 #if !defined(LOW_MEMORY)
514         ast_cli(a->fd, "  Cache media frames:          %s\n", ast_opt_cache_media_frames ? "Enabled" : "Disabled");
515 #endif
516         ast_cli(a->fd, "  RTP use dynamic payloads:    %u\n", ast_option_rtpusedynamic);
517
518         if (ast_option_rtpptdynamic == AST_RTP_PT_LAST_REASSIGN) {
519                 ast_cli(a->fd, "  RTP dynamic payload types:   %u,%u-%u\n",
520                         ast_option_rtpptdynamic,
521                         AST_RTP_PT_FIRST_DYNAMIC, AST_RTP_MAX_PT - 1);
522         } else if (ast_option_rtpptdynamic < AST_RTP_PT_LAST_REASSIGN) {
523                 ast_cli(a->fd, "  RTP dynamic payload types:   %u-%u,%u-%u\n",
524                         ast_option_rtpptdynamic, AST_RTP_PT_LAST_REASSIGN,
525                         AST_RTP_PT_FIRST_DYNAMIC, AST_RTP_MAX_PT - 1);
526         } else {
527                 ast_cli(a->fd, "  RTP dynamic payload types:   %u-%u\n",
528                         AST_RTP_PT_FIRST_DYNAMIC, AST_RTP_MAX_PT - 1);
529         }
530
531         ast_cli(a->fd, "\n* Subsystems\n");
532         ast_cli(a->fd, "  -------------\n");
533         ast_cli(a->fd, "  Manager (AMI):               %s\n", check_manager_enabled() ? "Enabled" : "Disabled");
534         ast_cli(a->fd, "  Web Manager (AMI/HTTP):      %s\n", check_webmanager_enabled() ? "Enabled" : "Disabled");
535         ast_cli(a->fd, "  Call data records:           %s\n", ast_cdr_is_enabled() ? "Enabled" : "Disabled");
536         ast_cli(a->fd, "  Realtime Architecture (ARA): %s\n", ast_realtime_enabled() ? "Enabled" : "Disabled");
537
538         /*! \todo we could check musiconhold, voicemail, smdi, adsi, queues  */
539
540         ast_cli(a->fd, "\n* Directories\n");
541         ast_cli(a->fd, "  -------------\n");
542         ast_cli(a->fd, "  Configuration file:          %s\n", ast_config_AST_CONFIG_FILE);
543         ast_cli(a->fd, "  Configuration directory:     %s\n", ast_config_AST_CONFIG_DIR);
544         ast_cli(a->fd, "  Module directory:            %s\n", ast_config_AST_MODULE_DIR);
545         ast_cli(a->fd, "  Spool directory:             %s\n", ast_config_AST_SPOOL_DIR);
546         ast_cli(a->fd, "  Log directory:               %s\n", ast_config_AST_LOG_DIR);
547         ast_cli(a->fd, "  Run/Sockets directory:       %s\n", ast_config_AST_RUN_DIR);
548         ast_cli(a->fd, "  PID file:                    %s\n", ast_config_AST_PID);
549         ast_cli(a->fd, "  VarLib directory:            %s\n", ast_config_AST_VAR_DIR);
550         ast_cli(a->fd, "  Data directory:              %s\n", ast_config_AST_DATA_DIR);
551         ast_cli(a->fd, "  ASTDB:                       %s\n", ast_config_AST_DB);
552         ast_cli(a->fd, "  IAX2 Keys directory:         %s\n", ast_config_AST_KEY_DIR);
553         ast_cli(a->fd, "  AGI Scripts directory:       %s\n", ast_config_AST_AGI_DIR);
554         ast_cli(a->fd, "\n\n");
555         return CLI_SUCCESS;
556 }
557
558 static char *handle_show_threads(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
559 {
560         int count = 0;
561         struct thread_list_t *cur;
562         switch (cmd) {
563         case CLI_INIT:
564                 e->command = "core show threads";
565                 e->usage =
566                         "Usage: core show threads\n"
567                         "       List threads currently active in the system.\n";
568                 return NULL;
569         case CLI_GENERATE:
570                 return NULL;
571         }
572
573         AST_RWLIST_RDLOCK(&thread_list);
574         AST_RWLIST_TRAVERSE(&thread_list, cur, list) {
575                 ast_cli(a->fd, "%p %d %s\n", (void *)cur->id, cur->lwp, cur->name);
576                 count++;
577         }
578         AST_RWLIST_UNLOCK(&thread_list);
579         ast_cli(a->fd, "%d threads listed.\n", count);
580         return CLI_SUCCESS;
581 }
582
583 #if defined (HAVE_SYSCTL) && defined(HAVE_SWAPCTL)
584 /*
585  * swapmode is rewritten by Tobias Weingartner <weingart@openbsd.org>
586  * to be based on the new swapctl(2) system call.
587  */
588 static int swapmode(int *used, int *total)
589 {
590         struct swapent *swdev;
591         int nswap, rnswap, i;
592
593         nswap = swapctl(SWAP_NSWAP, 0, 0);
594         if (nswap == 0)
595                 return 0;
596
597         swdev = ast_calloc(nswap, sizeof(*swdev));
598         if (swdev == NULL)
599                 return 0;
600
601         rnswap = swapctl(SWAP_STATS, swdev, nswap);
602         if (rnswap == -1) {
603                 ast_free(swdev);
604                 return 0;
605         }
606
607         /* if rnswap != nswap, then what? */
608
609         /* Total things up */
610         *total = *used = 0;
611         for (i = 0; i < nswap; i++) {
612                 if (swdev[i].se_flags & SWF_ENABLE) {
613                         *used += (swdev[i].se_inuse / (1024 / DEV_BSIZE));
614                         *total += (swdev[i].se_nblks / (1024 / DEV_BSIZE));
615                 }
616         }
617         ast_free(swdev);
618         return 1;
619 }
620 #endif
621
622 #if defined(HAVE_SYSINFO) || defined(HAVE_SYSCTL)
623 /*! \brief Give an overview of system statistics */
624 static char *handle_show_sysinfo(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
625 {
626         uint64_t physmem, freeram;
627 #if defined(HAVE_SYSINFO) || defined(HAVE_SWAPCTL)
628         int totalswap = 0;
629         uint64_t freeswap = 0;
630 #endif
631         int nprocs = 0;
632         long uptime = 0;
633 #if defined(HAVE_SYSINFO)
634         struct sysinfo sys_info;
635 #elif defined(HAVE_SYSCTL)
636         static int pageshift;
637         struct vmtotal vmtotal;
638         struct timeval  boottime;
639         time_t  now;
640         int mib[2], pagesize;
641 #if defined(HAVE_SWAPCTL)
642         int usedswap = 0;
643 #endif
644         size_t len;
645 #endif
646
647         switch (cmd) {
648         case CLI_INIT:
649                 e->command = "core show sysinfo";
650                 e->usage =
651                         "Usage: core show sysinfo\n"
652                         "       List current system information.\n";
653                 return NULL;
654         case CLI_GENERATE:
655                 return NULL;
656         }
657
658 #if defined(HAVE_SYSINFO)
659         sysinfo(&sys_info);
660         uptime = sys_info.uptime / 3600;
661         physmem = sys_info.totalram * sys_info.mem_unit;
662         freeram = (sys_info.freeram * sys_info.mem_unit) / 1024;
663         totalswap = (sys_info.totalswap * sys_info.mem_unit) / 1024;
664         freeswap = (sys_info.freeswap * sys_info.mem_unit) / 1024;
665         nprocs = sys_info.procs;
666 #elif defined(HAVE_SYSCTL)
667         /* calculate the uptime by looking at boottime */
668         time(&now);
669         mib[0] = CTL_KERN;
670         mib[1] = KERN_BOOTTIME;
671         len = sizeof(boottime);
672         if (sysctl(mib, 2, &boottime, &len, NULL, 0) != -1) {
673                 uptime = now - boottime.tv_sec;
674         }
675         uptime = uptime/3600;
676         /* grab total physical memory  */
677         mib[0] = CTL_HW;
678 #if defined(HW_PHYSMEM64)
679         mib[1] = HW_PHYSMEM64;
680 #else
681         mib[1] = HW_PHYSMEM;
682 #endif
683         len = sizeof(physmem);
684         sysctl(mib, 2, &physmem, &len, NULL, 0);
685
686         pagesize = getpagesize();
687         pageshift = 0;
688         while (pagesize > 1) {
689                 pageshift++;
690                 pagesize >>= 1;
691         }
692
693         /* we only need the amount of log(2)1024 for our conversion */
694         pageshift -= 10;
695
696         /* grab vm totals */
697         mib[0] = CTL_VM;
698         mib[1] = VM_METER;
699         len = sizeof(vmtotal);
700         sysctl(mib, 2, &vmtotal, &len, NULL, 0);
701         freeram = (vmtotal.t_free << pageshift);
702         /* generate swap usage and totals */
703 #if defined(HAVE_SWAPCTL)
704         swapmode(&usedswap, &totalswap);
705         freeswap = (totalswap - usedswap);
706 #endif
707         /* grab number of processes */
708 #if defined(__OpenBSD__)
709         mib[0] = CTL_KERN;
710         mib[1] = KERN_NPROCS;
711         len = sizeof(nprocs);
712         sysctl(mib, 2, &nprocs, &len, NULL, 0);
713 #endif
714 #endif
715
716         ast_cli(a->fd, "\nSystem Statistics\n");
717         ast_cli(a->fd, "-----------------\n");
718         ast_cli(a->fd, "  System Uptime:             %ld hours\n", uptime);
719         ast_cli(a->fd, "  Total RAM:                 %" PRIu64 " KiB\n", physmem / 1024);
720         ast_cli(a->fd, "  Free RAM:                  %" PRIu64 " KiB\n", freeram);
721 #if defined(HAVE_SYSINFO)
722         ast_cli(a->fd, "  Buffer RAM:                %" PRIu64 " KiB\n", ((uint64_t) sys_info.bufferram * sys_info.mem_unit) / 1024);
723 #endif
724 #if defined(HAVE_SYSINFO) || defined(HAVE_SWAPCTL)
725         ast_cli(a->fd, "  Total Swap Space:          %d KiB\n", totalswap);
726         ast_cli(a->fd, "  Free Swap Space:           %" PRIu64 " KiB\n\n", freeswap);
727 #endif
728         ast_cli(a->fd, "  Number of Processes:       %d \n\n", nprocs);
729         return CLI_SUCCESS;
730 }
731 #endif
732
733 struct profile_entry {
734         const char *name;
735         uint64_t        scale;  /* if non-zero, values are scaled by this */
736         int64_t mark;
737         int64_t value;
738         int64_t events;
739 };
740
741 struct profile_data {
742         int entries;
743         int max_size;
744         struct profile_entry e[0];
745 };
746
747 static struct profile_data *prof_data;
748 #endif /* ! LOW_MEMORY */
749
750 /*! \brief allocates a counter with a given name and scale.
751  * \return Returns the identifier of the counter.
752  */
753 int ast_add_profile(const char *name, uint64_t scale)
754 {
755 #if !defined(LOW_MEMORY)
756         int l = sizeof(struct profile_data);
757         int n = 10;     /* default entries */
758
759         if (prof_data == NULL) {
760                 prof_data = ast_calloc(1, l + n*sizeof(struct profile_entry));
761                 if (prof_data == NULL)
762                         return -1;
763                 prof_data->entries = 0;
764                 prof_data->max_size = n;
765         }
766         if (prof_data->entries >= prof_data->max_size) {
767                 void *p;
768                 n = prof_data->max_size + 20;
769                 p = ast_realloc(prof_data, l + n*sizeof(struct profile_entry));
770                 if (p == NULL)
771                         return -1;
772                 prof_data = p;
773                 prof_data->max_size = n;
774         }
775         n = prof_data->entries++;
776         prof_data->e[n].name = ast_strdup(name);
777         prof_data->e[n].value = 0;
778         prof_data->e[n].events = 0;
779         prof_data->e[n].mark = 0;
780         prof_data->e[n].scale = scale;
781         return n;
782 #else /* if defined(LOW_MEMORY) */
783         return 0;
784 #endif
785 }
786
787 int64_t ast_profile(int i, int64_t delta)
788 {
789 #if !defined(LOW_MEMORY)
790         if (!prof_data || i < 0 || i > prof_data->entries)      /* invalid index */
791                 return 0;
792         if (prof_data->e[i].scale > 1)
793                 delta /= prof_data->e[i].scale;
794         prof_data->e[i].value += delta;
795         prof_data->e[i].events++;
796         return prof_data->e[i].value;
797 #else /* if defined(LOW_MEMORY) */
798         return 0;
799 #endif
800 }
801
802 #if !defined(LOW_MEMORY)
803 /* The RDTSC instruction was introduced on the Pentium processor and is not
804  * implemented on certain clones, like the Cyrix 586. Hence, the previous
805  * expectation of __i386__ was in error. */
806 #if defined ( __i686__) && (defined(__FreeBSD__) || defined(linux))
807 #if defined(__FreeBSD__)
808 #include <machine/cpufunc.h>
809 #elif defined(linux)
810 static __inline uint64_t
811 rdtsc(void)
812 {
813         uint64_t rv;
814
815         __asm __volatile(".byte 0x0f, 0x31" : "=A" (rv));
816         return (rv);
817 }
818 #endif
819 #else   /* supply a dummy function on other platforms */
820 static __inline uint64_t
821 rdtsc(void)
822 {
823         return 0;
824 }
825 #endif
826 #endif /* ! LOW_MEMORY */
827
828 int64_t ast_mark(int i, int startstop)
829 {
830 #if !defined(LOW_MEMORY)
831         if (!prof_data || i < 0 || i > prof_data->entries) /* invalid index */
832                 return 0;
833         if (startstop == 1)
834                 prof_data->e[i].mark = rdtsc();
835         else {
836                 prof_data->e[i].mark = (rdtsc() - prof_data->e[i].mark);
837                 if (prof_data->e[i].scale > 1)
838                         prof_data->e[i].mark /= prof_data->e[i].scale;
839                 prof_data->e[i].value += prof_data->e[i].mark;
840                 prof_data->e[i].events++;
841         }
842         return prof_data->e[i].mark;
843 #else /* if defined(LOW_MEMORY) */
844         return 0;
845 #endif
846 }
847
848 #if !defined(LOW_MEMORY)
849 #define DEFINE_PROFILE_MIN_MAX_VALUES min = 0; \
850         max = prof_data->entries;\
851         if  (a->argc > 3) { /* specific entries */ \
852                 if (isdigit(a->argv[3][0])) { \
853                         min = atoi(a->argv[3]); \
854                         if (a->argc == 5 && strcmp(a->argv[4], "-")) \
855                                 max = atoi(a->argv[4]); \
856                 } else \
857                         search = a->argv[3]; \
858         } \
859         if (max > prof_data->entries) \
860                 max = prof_data->entries;
861
862 static char *handle_show_profile(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
863 {
864         int i, min, max;
865         const char *search = NULL;
866         switch (cmd) {
867         case CLI_INIT:
868                 e->command = "core show profile";
869                 e->usage = "Usage: core show profile\n"
870                            "       show profile information";
871                 return NULL;
872         case CLI_GENERATE:
873                 return NULL;
874         }
875
876         if (prof_data == NULL)
877                 return 0;
878
879         DEFINE_PROFILE_MIN_MAX_VALUES;
880         ast_cli(a->fd, "profile values (%d, allocated %d)\n-------------------\n",
881                 prof_data->entries, prof_data->max_size);
882         ast_cli(a->fd, "%6s   %8s  %10s %12s %12s  %s\n", "ID", "Scale", "Events",
883                         "Value", "Average", "Name");
884         for (i = min; i < max; i++) {
885                 struct profile_entry *entry = &prof_data->e[i];
886                 if (!search || strstr(entry->name, search))
887                     ast_cli(a->fd, "%6d: [%8ld] %10ld %12lld %12lld  %s\n",
888                         i,
889                         (long)entry->scale,
890                         (long)entry->events, (long long)entry->value,
891                         (long long)(entry->events ? entry->value / entry->events : entry->value),
892                         entry->name);
893         }
894         return CLI_SUCCESS;
895 }
896
897 static char *handle_clear_profile(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
898 {
899         int i, min, max;
900         const char *search = NULL;
901         switch (cmd) {
902         case CLI_INIT:
903                 e->command = "core clear profile";
904                 e->usage = "Usage: core clear profile\n"
905                            "       clear profile information";
906                 return NULL;
907         case CLI_GENERATE:
908                 return NULL;
909         }
910
911         if (prof_data == NULL)
912                 return 0;
913
914         DEFINE_PROFILE_MIN_MAX_VALUES;
915         for (i= min; i < max; i++) {
916                 if (!search || strstr(prof_data->e[i].name, search)) {
917                         prof_data->e[i].value = 0;
918                         prof_data->e[i].events = 0;
919                 }
920         }
921         return CLI_SUCCESS;
922 }
923 #undef DEFINE_PROFILE_MIN_MAX_VALUES
924
925 #endif /* ! LOW_MEMORY */
926
927 int ast_pbx_uuid_get(char *pbx_uuid, int length)
928 {
929         return ast_db_get("pbx", "UUID", pbx_uuid, length);
930 }
931
932 static void publish_fully_booted(void)
933 {
934         struct ast_json *json_object;
935         int uptime = 0;
936         int lastreloaded = 0;
937         struct timeval tmp;
938         struct timeval curtime = ast_tvnow();
939
940         if (ast_startuptime.tv_sec) {
941                 tmp = ast_tvsub(curtime, ast_startuptime);
942                 uptime = (int) tmp.tv_sec;
943         }
944
945         if (ast_lastreloadtime.tv_sec) {
946                 tmp = ast_tvsub(curtime, ast_lastreloadtime);
947                 lastreloaded = (int) tmp.tv_sec;
948         }
949
950         json_object = ast_json_pack("{s: s, s: i, s: i}",
951                         "Status", "Fully Booted",
952                         "Uptime", uptime,
953                         "LastReload", lastreloaded);
954         ast_manager_publish_event("FullyBooted", EVENT_FLAG_SYSTEM, json_object);
955         ast_json_unref(json_object);
956 }
957
958 static void ast_run_atexits(int run_cleanups)
959 {
960         struct ast_atexit *ae;
961
962         AST_LIST_LOCK(&atexits);
963         while ((ae = AST_LIST_REMOVE_HEAD(&atexits, list))) {
964                 if (ae->func && (!ae->is_cleanup || run_cleanups)) {
965                         ae->func();
966                 }
967                 ast_free(ae);
968         }
969         AST_LIST_UNLOCK(&atexits);
970 }
971
972 static void __ast_unregister_atexit(void (*func)(void))
973 {
974         struct ast_atexit *ae;
975
976         AST_LIST_TRAVERSE_SAFE_BEGIN(&atexits, ae, list) {
977                 if (ae->func == func) {
978                         AST_LIST_REMOVE_CURRENT(list);
979                         ast_free(ae);
980                         break;
981                 }
982         }
983         AST_LIST_TRAVERSE_SAFE_END;
984 }
985
986 static int register_atexit(void (*func)(void), int is_cleanup)
987 {
988         struct ast_atexit *ae;
989
990         ae = ast_calloc(1, sizeof(*ae));
991         if (!ae) {
992                 return -1;
993         }
994         ae->func = func;
995         ae->is_cleanup = is_cleanup;
996
997         AST_LIST_LOCK(&atexits);
998         __ast_unregister_atexit(func);
999         AST_LIST_INSERT_HEAD(&atexits, ae, list);
1000         AST_LIST_UNLOCK(&atexits);
1001
1002         return 0;
1003 }
1004
1005 int ast_register_atexit(void (*func)(void))
1006 {
1007         return register_atexit(func, 0);
1008 }
1009
1010 int ast_register_cleanup(void (*func)(void))
1011 {
1012         return register_atexit(func, 1);
1013 }
1014
1015 void ast_unregister_atexit(void (*func)(void))
1016 {
1017         AST_LIST_LOCK(&atexits);
1018         __ast_unregister_atexit(func);
1019         AST_LIST_UNLOCK(&atexits);
1020 }
1021
1022 /* Sending commands from consoles back to the daemon requires a terminating NULL */
1023 static int fdsend(int fd, const char *s)
1024 {
1025         return write(fd, s, strlen(s) + 1);
1026 }
1027
1028 /* Sending messages from the daemon back to the display requires _excluding_ the terminating NULL */
1029 static int fdprint(int fd, const char *s)
1030 {
1031         return write(fd, s, strlen(s));
1032 }
1033
1034 /*! \brief NULL handler so we can collect the child exit status */
1035 static void _null_sig_handler(int sig)
1036 {
1037 }
1038
1039 static struct sigaction null_sig_handler = {
1040         .sa_handler = _null_sig_handler,
1041         .sa_flags = SA_RESTART,
1042 };
1043
1044 static struct sigaction ignore_sig_handler = {
1045         .sa_handler = SIG_IGN,
1046 };
1047
1048 AST_MUTEX_DEFINE_STATIC(safe_system_lock);
1049 /*! \brief Keep track of how many threads are currently trying to wait*() on
1050  *  a child process
1051  */
1052 static unsigned int safe_system_level = 0;
1053 static struct sigaction safe_system_prev_handler;
1054
1055 void ast_replace_sigchld(void)
1056 {
1057         unsigned int level;
1058
1059         ast_mutex_lock(&safe_system_lock);
1060         level = safe_system_level++;
1061
1062         /* only replace the handler if it has not already been done */
1063         if (level == 0) {
1064                 sigaction(SIGCHLD, &null_sig_handler, &safe_system_prev_handler);
1065         }
1066
1067         ast_mutex_unlock(&safe_system_lock);
1068 }
1069
1070 void ast_unreplace_sigchld(void)
1071 {
1072         unsigned int level;
1073
1074         ast_mutex_lock(&safe_system_lock);
1075         level = --safe_system_level;
1076
1077         /* only restore the handler if we are the last one */
1078         if (level == 0) {
1079                 sigaction(SIGCHLD, &safe_system_prev_handler, NULL);
1080         }
1081
1082         ast_mutex_unlock(&safe_system_lock);
1083 }
1084
1085 /*! \brief fork and perform other preparations for spawning applications */
1086 static pid_t safe_exec_prep(int dualfork)
1087 {
1088         pid_t pid;
1089
1090 #if defined(HAVE_WORKING_FORK) || defined(HAVE_WORKING_VFORK)
1091         ast_replace_sigchld();
1092
1093 #ifdef HAVE_WORKING_FORK
1094         pid = fork();
1095 #else
1096         pid = vfork();
1097 #endif
1098
1099         if (pid == 0) {
1100 #ifdef HAVE_CAP
1101                 cap_t cap = cap_from_text("cap_net_admin-eip");
1102
1103                 if (cap_set_proc(cap)) {
1104                         /* Careful with order! Logging cannot happen after we close FDs */
1105                         ast_log(LOG_WARNING, "Unable to remove capabilities.\n");
1106                 }
1107                 cap_free(cap);
1108 #endif
1109 #ifdef HAVE_WORKING_FORK
1110                 if (ast_opt_high_priority) {
1111                         ast_set_priority(0);
1112                 }
1113                 /* Close file descriptors and launch system command */
1114                 ast_close_fds_above_n(STDERR_FILENO);
1115 #endif
1116                 if (dualfork) {
1117 #ifdef HAVE_WORKING_FORK
1118                         pid = fork();
1119 #else
1120                         pid = vfork();
1121 #endif
1122                         if (pid < 0) {
1123                                 /* Second fork failed. */
1124                                 /* No logger available. */
1125                                 _exit(1);
1126                         }
1127
1128                         if (pid > 0) {
1129                                 /* This is the first fork, exit so the reaper finishes right away. */
1130                                 _exit(0);
1131                         }
1132
1133                         /* This is the second fork.  The first fork will exit immediately so
1134                          * Asterisk doesn't have to wait for completion.
1135                          * ast_safe_system("cmd &") would run in the background, but the '&'
1136                          * cannot be added with ast_safe_execvp, so we have to double fork.
1137                          */
1138                 }
1139         }
1140
1141         if (pid < 0) {
1142                 ast_log(LOG_WARNING, "Fork failed: %s\n", strerror(errno));
1143         }
1144 #else
1145         ast_log(LOG_WARNING, "Fork failed: %s\n", strerror(ENOTSUP));
1146         pid = -1;
1147 #endif
1148
1149         return pid;
1150 }
1151
1152 /*! \brief wait for spawned application to complete and unreplace sigchld */
1153 static int safe_exec_wait(pid_t pid)
1154 {
1155         int res = -1;
1156
1157 #if defined(HAVE_WORKING_FORK) || defined(HAVE_WORKING_VFORK)
1158         if (pid > 0) {
1159                 for (;;) {
1160                         int status;
1161
1162                         res = waitpid(pid, &status, 0);
1163                         if (res > -1) {
1164                                 res = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
1165                                 break;
1166                         }
1167                         if (errno != EINTR) {
1168                                 break;
1169                         }
1170                 }
1171         }
1172
1173         ast_unreplace_sigchld();
1174 #endif
1175
1176         return res;
1177 }
1178
1179 int ast_safe_execvp(int dualfork, const char *file, char *const argv[])
1180 {
1181         pid_t pid = safe_exec_prep(dualfork);
1182
1183         if (pid == 0) {
1184                 execvp(file, argv);
1185                 _exit(1);
1186                 /* noreturn from _exit */
1187         }
1188
1189         return safe_exec_wait(pid);
1190 }
1191
1192 int ast_safe_system(const char *s)
1193 {
1194         pid_t pid = safe_exec_prep(0);
1195
1196         if (pid == 0) {
1197                 execl("/bin/sh", "/bin/sh", "-c", s, (char *) NULL);
1198                 _exit(1);
1199                 /* noreturn from _exit */
1200         }
1201
1202         return safe_exec_wait(pid);
1203 }
1204
1205 /*!
1206  * \brief enable or disable a logging level to a specified console
1207  */
1208 void ast_console_toggle_loglevel(int fd, int level, int state)
1209 {
1210         int x;
1211
1212         if (level >= NUMLOGLEVELS) {
1213                 level = NUMLOGLEVELS - 1;
1214         }
1215
1216         for (x = 0;x < AST_MAX_CONNECTS; x++) {
1217                 if (fd == consoles[x].fd) {
1218                         /*
1219                          * Since the logging occurs when levels are false, set to
1220                          * flipped iinput because this function accepts 0 as off and 1 as on
1221                          */
1222                         consoles[x].levels[level] = state ? 0 : 1;
1223                         return;
1224                 }
1225         }
1226 }
1227
1228 /*!
1229  * \brief mute or unmute a console from logging
1230  */
1231 void ast_console_toggle_mute(int fd, int silent)
1232 {
1233         int x;
1234         for (x = 0;x < AST_MAX_CONNECTS; x++) {
1235                 if (fd == consoles[x].fd) {
1236                         if (consoles[x].mute) {
1237                                 consoles[x].mute = 0;
1238                                 if (!silent)
1239                                         ast_cli(fd, "Console is not muted anymore.\n");
1240                         } else {
1241                                 consoles[x].mute = 1;
1242                                 if (!silent)
1243                                         ast_cli(fd, "Console is muted.\n");
1244                         }
1245                         return;
1246                 }
1247         }
1248         ast_cli(fd, "Couldn't find remote console.\n");
1249 }
1250
1251 /*!
1252  * \brief log the string to all attached network console clients
1253  */
1254 static void ast_network_puts_mutable(const char *string, int level, int sublevel)
1255 {
1256         int x;
1257
1258         for (x = 0; x < AST_MAX_CONNECTS; ++x) {
1259                 if (consoles[x].fd < 0
1260                         || consoles[x].mute
1261                         || consoles[x].levels[level]
1262                         || (level == __LOG_VERBOSE && consoles[x].option_verbose < sublevel)) {
1263                         continue;
1264                 }
1265                 fdprint(consoles[x].p[1], string);
1266         }
1267 }
1268
1269 /*!
1270  * \brief log the string to the root console, and all attached
1271  * network console clients
1272  */
1273 void ast_console_puts_mutable(const char *string, int level)
1274 {
1275         ast_console_puts_mutable_full(string, level, 0);
1276 }
1277
1278 static int console_print(const char *s);
1279
1280 void ast_console_puts_mutable_full(const char *message, int level, int sublevel)
1281 {
1282         /* Send to the root console */
1283         console_print(message);
1284
1285         /* Wake up a poll()ing console */
1286         if (ast_opt_console && consolethread != AST_PTHREADT_NULL) {
1287                 pthread_kill(consolethread, SIGURG);
1288         }
1289
1290         /* Send to any network console clients */
1291         ast_network_puts_mutable(message, level, sublevel);
1292 }
1293
1294 /*!
1295  * \brief write the string to all attached console clients
1296  */
1297 static void ast_network_puts(const char *string)
1298 {
1299         int x;
1300
1301         for (x = 0; x < AST_MAX_CONNECTS; ++x) {
1302                 if (consoles[x].fd < 0) {
1303                         continue;
1304                 }
1305                 fdprint(consoles[x].p[1], string);
1306         }
1307 }
1308
1309 /*!
1310  * \brief write the string to the root console, and all attached
1311  * network console clients
1312  */
1313 void ast_console_puts(const char *string)
1314 {
1315         /* Send to the root console */
1316         fputs(string, stdout);
1317         fflush(stdout);
1318
1319         /* Send to any network console clients */
1320         ast_network_puts(string);
1321 }
1322
1323 static pthread_t lthread;
1324
1325 /*!
1326  * \brief read() function supporting the reception of user credentials.
1327  *
1328  * \param fd Socket file descriptor.
1329  * \param buffer Receive buffer.
1330  * \param size 'buffer' size.
1331  * \param con Console structure to set received credentials
1332  * \retval -1 on error
1333  * \retval the number of bytes received on success.
1334  */
1335 static int read_credentials(int fd, char *buffer, size_t size, struct console *con)
1336 {
1337 #if defined(SO_PEERCRED)
1338 #ifdef HAVE_STRUCT_SOCKPEERCRED_UID
1339 #define HAVE_STRUCT_UCRED_UID
1340         struct sockpeercred cred;
1341 #else
1342         struct ucred cred;
1343 #endif
1344         socklen_t len = sizeof(cred);
1345 #endif
1346 #if defined(HAVE_GETPEEREID)
1347         uid_t uid;
1348         gid_t gid;
1349 #else
1350         int uid, gid;
1351 #endif
1352         int result;
1353
1354         result = read(fd, buffer, size);
1355         if (result < 0) {
1356                 return result;
1357         }
1358
1359 #if defined(SO_PEERCRED) && (defined(HAVE_STRUCT_UCRED_UID) || defined(HAVE_STRUCT_UCRED_CR_UID))
1360         if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &len)) {
1361                 return result;
1362         }
1363 #if defined(HAVE_STRUCT_UCRED_UID)
1364         uid = cred.uid;
1365         gid = cred.gid;
1366 #else /* defined(HAVE_STRUCT_UCRED_CR_UID) */
1367         uid = cred.cr_uid;
1368         gid = cred.cr_gid;
1369 #endif /* defined(HAVE_STRUCT_UCRED_UID) */
1370
1371 #elif defined(HAVE_GETPEEREID)
1372         if (getpeereid(fd, &uid, &gid)) {
1373                 return result;
1374         }
1375 #else
1376         return result;
1377 #endif
1378         con->uid = uid;
1379         con->gid = gid;
1380
1381         return result;
1382 }
1383
1384 /* This is the thread running the remote console on the main process. */
1385 static void *netconsole(void *vconsole)
1386 {
1387         struct console *con = vconsole;
1388         char hostname[MAXHOSTNAMELEN] = "";
1389         char inbuf[512];
1390         char outbuf[512];
1391         const char * const end_buf = inbuf + sizeof(inbuf);
1392         char *start_read = inbuf;
1393         int res;
1394         struct pollfd fds[2];
1395
1396         if (gethostname(hostname, sizeof(hostname)-1))
1397                 ast_copy_string(hostname, "<Unknown>", sizeof(hostname));
1398         snprintf(outbuf, sizeof(outbuf), "%s/%ld/%s\n", hostname, (long)ast_mainpid, ast_get_version());
1399         fdprint(con->fd, outbuf);
1400         ast_verb_console_register(&con->option_verbose);
1401         for (;;) {
1402                 fds[0].fd = con->fd;
1403                 fds[0].events = POLLIN;
1404                 fds[0].revents = 0;
1405                 fds[1].fd = con->p[0];
1406                 fds[1].events = POLLIN;
1407                 fds[1].revents = 0;
1408
1409                 res = ast_poll(fds, 2, -1);
1410                 if (res < 0) {
1411                         if (errno != EINTR)
1412                                 ast_log(LOG_WARNING, "poll returned < 0: %s\n", strerror(errno));
1413                         continue;
1414                 }
1415                 if (fds[0].revents) {
1416                         int cmds_read, bytes_read;
1417                         if ((bytes_read = read_credentials(con->fd, start_read, end_buf - start_read, con)) < 1) {
1418                                 break;
1419                         }
1420                         /* XXX This will only work if it is the first command, and I'm not sure fixing it is worth the effort. */
1421                         if (strncmp(inbuf, "cli quit after ", 15) == 0) {
1422                                 ast_cli_command_multiple_full(con->uid, con->gid, con->fd, bytes_read - 15, inbuf + 15);
1423                                 break;
1424                         }
1425                         /* ast_cli_command_multiple_full will only process individual commands terminated by a
1426                          * NULL and not trailing partial commands. */
1427                         if (!(cmds_read = ast_cli_command_multiple_full(con->uid, con->gid, con->fd, bytes_read + start_read - inbuf, inbuf))) {
1428                                 /* No commands were read. We either have a short read on the first command
1429                                  * with space left, or a command that is too long */
1430                                 if (start_read + bytes_read < end_buf) {
1431                                         start_read += bytes_read;
1432                                 } else {
1433                                         ast_log(LOG_ERROR, "Command too long! Skipping\n");
1434                                         start_read = inbuf;
1435                                 }
1436                                 continue;
1437                         }
1438                         if (start_read[bytes_read - 1] == '\0') {
1439                                 /* The read ended on a command boundary, start reading again at the head of inbuf */
1440                                 start_read = inbuf;
1441                                 continue;
1442                         }
1443                         /* If we get this far, we have left over characters that have not been processed.
1444                          * Advance to the character after the last command read by ast_cli_command_multiple_full.
1445                          * We are guaranteed to have at least cmds_read NULLs */
1446                         while (cmds_read-- && (start_read = strchr(start_read, '\0'))) {
1447                                 start_read++;
1448                         }
1449                         memmove(inbuf, start_read, end_buf - start_read);
1450                         start_read = end_buf - start_read + inbuf;
1451                 }
1452                 if (fds[1].revents) {
1453                         res = read_credentials(con->p[0], outbuf, sizeof(outbuf), con);
1454                         if (res < 1) {
1455                                 ast_log(LOG_ERROR, "read returned %d\n", res);
1456                                 break;
1457                         }
1458                         res = write(con->fd, outbuf, res);
1459                         if (res < 1)
1460                                 break;
1461                 }
1462         }
1463         ast_verb_console_unregister();
1464         if (!ast_opt_hide_connect) {
1465                 ast_verb(3, "Remote UNIX connection disconnected\n");
1466         }
1467         close(con->fd);
1468         close(con->p[0]);
1469         close(con->p[1]);
1470         con->fd = -1;
1471
1472         return NULL;
1473 }
1474
1475 static void *listener(void *unused)
1476 {
1477         struct sockaddr_un sunaddr;
1478         int s;
1479         socklen_t len;
1480         int x;
1481         int poll_result;
1482         struct pollfd fds[1];
1483
1484         for (;;) {
1485                 if (ast_socket < 0) {
1486                         return NULL;
1487                 }
1488                 fds[0].fd = ast_socket;
1489                 fds[0].events = POLLIN;
1490                 poll_result = ast_poll(fds, 1, -1);
1491                 pthread_testcancel();
1492                 if (poll_result < 0) {
1493                         if (errno != EINTR) {
1494                                 ast_log(LOG_WARNING, "poll returned error: %s\n", strerror(errno));
1495                         }
1496                         continue;
1497                 }
1498                 len = sizeof(sunaddr);
1499                 s = accept(ast_socket, (struct sockaddr *)&sunaddr, &len);
1500                 if (s < 0) {
1501                         if (errno != EINTR)
1502                                 ast_log(LOG_WARNING, "Accept returned %d: %s\n", s, strerror(errno));
1503                 } else {
1504 #if defined(SO_PASSCRED)
1505                         int sckopt = 1;
1506                         /* turn on socket credentials passing. */
1507                         if (setsockopt(s, SOL_SOCKET, SO_PASSCRED, &sckopt, sizeof(sckopt)) < 0) {
1508                                 ast_log(LOG_WARNING, "Unable to turn on socket credentials passing\n");
1509                                 close(s);
1510                         } else
1511 #endif
1512                         {
1513                                 for (x = 0; x < AST_MAX_CONNECTS; x++) {
1514                                         if (consoles[x].fd >= 0) {
1515                                                 continue;
1516                                         }
1517                                         if (socketpair(AF_LOCAL, SOCK_STREAM, 0, consoles[x].p)) {
1518                                                 ast_log(LOG_ERROR, "Unable to create pipe: %s\n", strerror(errno));
1519                                                 fdprint(s, "Server failed to create pipe\n");
1520                                                 close(s);
1521                                                 break;
1522                                         }
1523                                         ast_fd_set_flags(consoles[x].p[1], O_NONBLOCK);
1524                                         consoles[x].mute = 1; /* Default is muted, we will un-mute if necessary */
1525                                         /* Default uid and gid to -2, so then in cli.c/cli_has_permissions() we will be able
1526                                            to know if the user didn't send the credentials. */
1527                                         consoles[x].uid = -2;
1528                                         consoles[x].gid = -2;
1529                                         /* Server default of remote console verbosity level is OFF. */
1530                                         consoles[x].option_verbose = 0;
1531                                         consoles[x].fd = s;
1532                                         if (ast_pthread_create_detached_background(&consoles[x].t, NULL, netconsole, &consoles[x])) {
1533                                                 consoles[x].fd = -1;
1534                                                 ast_log(LOG_ERROR, "Unable to spawn thread to handle connection: %s\n", strerror(errno));
1535                                                 close(consoles[x].p[0]);
1536                                                 close(consoles[x].p[1]);
1537                                                 fdprint(s, "Server failed to spawn thread\n");
1538                                                 close(s);
1539                                         }
1540                                         break;
1541                                 }
1542                                 if (x >= AST_MAX_CONNECTS) {
1543                                         fdprint(s, "No more connections allowed\n");
1544                                         ast_log(LOG_WARNING, "No more connections allowed\n");
1545                                         close(s);
1546                                 } else if ((consoles[x].fd > -1) && (!ast_opt_hide_connect)) {
1547                                         ast_verb(3, "Remote UNIX connection\n");
1548                                 }
1549                         }
1550                 }
1551         }
1552         return NULL;
1553 }
1554
1555 static int ast_makesocket(void)
1556 {
1557         struct sockaddr_un sunaddr;
1558         int res;
1559         int x;
1560         uid_t uid = -1;
1561         gid_t gid = -1;
1562
1563         for (x = 0; x < AST_MAX_CONNECTS; x++) {
1564                 consoles[x].fd = -1;
1565         }
1566
1567         if (ast_socket_is_sd) {
1568                 ast_socket = ast_sd_get_fd_un(SOCK_STREAM, ast_config_AST_SOCKET);
1569
1570                 goto start_lthread;
1571         }
1572
1573         unlink(ast_config_AST_SOCKET);
1574         ast_socket = socket(PF_LOCAL, SOCK_STREAM, 0);
1575         if (ast_socket < 0) {
1576                 ast_log(LOG_WARNING, "Unable to create control socket: %s\n", strerror(errno));
1577                 return -1;
1578         }
1579         memset(&sunaddr, 0, sizeof(sunaddr));
1580         sunaddr.sun_family = AF_LOCAL;
1581         ast_copy_string(sunaddr.sun_path, ast_config_AST_SOCKET, sizeof(sunaddr.sun_path));
1582         res = bind(ast_socket, (struct sockaddr *)&sunaddr, sizeof(sunaddr));
1583         if (res) {
1584                 ast_log(LOG_WARNING, "Unable to bind socket to %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
1585                 close(ast_socket);
1586                 ast_socket = -1;
1587                 return -1;
1588         }
1589         res = listen(ast_socket, 2);
1590         if (res < 0) {
1591                 ast_log(LOG_WARNING, "Unable to listen on socket %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
1592                 close(ast_socket);
1593                 ast_socket = -1;
1594                 return -1;
1595         }
1596
1597 start_lthread:
1598         if (ast_pthread_create_background(&lthread, NULL, listener, NULL)) {
1599                 ast_log(LOG_WARNING, "Unable to create listener thread.\n");
1600                 close(ast_socket);
1601                 return -1;
1602         }
1603
1604         if (ast_socket_is_sd) {
1605                 /* owner/group/permissions are set by systemd, we might not even have access
1606                  * to socket file so leave it alone */
1607                 return 0;
1608         }
1609
1610         if (!ast_strlen_zero(ast_config_AST_CTL_OWNER)) {
1611                 struct passwd *pw;
1612                 if ((pw = getpwnam(ast_config_AST_CTL_OWNER)) == NULL)
1613                         ast_log(LOG_WARNING, "Unable to find uid of user %s\n", ast_config_AST_CTL_OWNER);
1614                 else
1615                         uid = pw->pw_uid;
1616         }
1617
1618         if (!ast_strlen_zero(ast_config_AST_CTL_GROUP)) {
1619                 struct group *grp;
1620                 if ((grp = getgrnam(ast_config_AST_CTL_GROUP)) == NULL)
1621                         ast_log(LOG_WARNING, "Unable to find gid of group %s\n", ast_config_AST_CTL_GROUP);
1622                 else
1623                         gid = grp->gr_gid;
1624         }
1625
1626         if (chown(ast_config_AST_SOCKET, uid, gid) < 0)
1627                 ast_log(LOG_WARNING, "Unable to change ownership of %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
1628
1629         if (!ast_strlen_zero(ast_config_AST_CTL_PERMISSIONS)) {
1630                 unsigned int p1;
1631                 mode_t p;
1632                 sscanf(ast_config_AST_CTL_PERMISSIONS, "%30o", &p1);
1633                 p = p1;
1634                 if ((chmod(ast_config_AST_SOCKET, p)) < 0)
1635                         ast_log(LOG_WARNING, "Unable to change file permissions of %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
1636         }
1637
1638         return 0;
1639 }
1640
1641 static int ast_tryconnect(void)
1642 {
1643         struct sockaddr_un sunaddr;
1644         int res;
1645         ast_consock = socket(PF_LOCAL, SOCK_STREAM, 0);
1646         if (ast_consock < 0) {
1647                 fprintf(stderr, "Unable to create socket: %s\n", strerror(errno));
1648                 return 0;
1649         }
1650         memset(&sunaddr, 0, sizeof(sunaddr));
1651         sunaddr.sun_family = AF_LOCAL;
1652         ast_copy_string(sunaddr.sun_path, ast_config_AST_SOCKET, sizeof(sunaddr.sun_path));
1653         res = connect(ast_consock, (struct sockaddr *)&sunaddr, sizeof(sunaddr));
1654         if (res) {
1655                 close(ast_consock);
1656                 ast_consock = -1;
1657                 return 0;
1658         } else
1659                 return 1;
1660 }
1661
1662 /*! \brief Urgent handler
1663  *
1664  * Called by soft_hangup to interrupt the poll, read, or other
1665  * system call.  We don't actually need to do anything though.
1666  * Remember: Cannot EVER ast_log from within a signal handler
1667  */
1668 static void _urg_handler(int num)
1669 {
1670         return;
1671 }
1672
1673 static struct sigaction urg_handler = {
1674         .sa_handler = _urg_handler,
1675 };
1676
1677 static void _hup_handler(int num)
1678 {
1679         int save_errno = errno;
1680
1681         if (restartnow) {
1682                 if (el) {
1683                         el_end(el);
1684                 }
1685                 execvp(_argv[0], _argv);
1686         }
1687
1688         printf("Received HUP signal -- Reloading configs\n");
1689         sig_flags.need_reload = 1;
1690         if (ast_alertpipe_write(sig_alert_pipe)) {
1691                 fprintf(stderr, "hup_handler: write() failed: %s\n", strerror(errno));
1692         }
1693         errno = save_errno;
1694 }
1695
1696 static struct sigaction hup_handler = {
1697         .sa_handler = _hup_handler,
1698         .sa_flags = SA_RESTART,
1699 };
1700
1701 static void _child_handler(int sig)
1702 {
1703         /* Must not ever ast_log or ast_verbose within signal handler */
1704         int n, status, save_errno = errno;
1705
1706         /*
1707          * Reap all dead children -- not just one
1708          */
1709         for (n = 0; waitpid(-1, &status, WNOHANG) > 0; n++)
1710                 ;
1711         if (n == 0 && option_debug)
1712                 printf("Huh?  Child handler, but nobody there?\n");
1713         errno = save_errno;
1714 }
1715
1716 static struct sigaction child_handler = {
1717         .sa_handler = _child_handler,
1718         .sa_flags = SA_RESTART,
1719 };
1720
1721 /*! \brief Set an X-term or screen title */
1722 static void set_title(char *text)
1723 {
1724         if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
1725                 fprintf(stdout, "\033]2;%s\007", text);
1726 }
1727
1728 static void set_icon(char *text)
1729 {
1730         if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
1731                 fprintf(stdout, "\033]1;%s\007", text);
1732 }
1733
1734 /*! \brief Check whether we were set to high(er) priority. */
1735 static int has_priority(void)
1736 {
1737         /* Neither of these calls should fail with these arguments. */
1738 #ifdef __linux__
1739         /* For SCHED_OTHER, SCHED_BATCH and SCHED_IDLE, this will return
1740          * 0. For the realtime priorities SCHED_RR and SCHED_FIFO, it
1741          * will return something >= 1. */
1742         return sched_getscheduler(0);
1743 #else
1744         /* getpriority() can return a value in -20..19 (or even -INF..20)
1745          * where negative numbers are high priority. We don't bother
1746          * checking errno. If the query fails and it returns -1, we'll
1747          * assume that we're running at high prio; a safe assumption
1748          * that will enable the resource starvation monitor (canary)
1749          * just in case. */
1750         return (getpriority(PRIO_PROCESS, 0) < 0);
1751 #endif
1752 }
1753
1754 /*! \brief Set priority on all known threads. */
1755 static int set_priority_all(int pri)
1756 {
1757 #if !defined(__linux__)
1758         /* The non-linux version updates the entire process prio. */
1759         return ast_set_priority(pri);
1760 #elif defined(LOW_MEMORY)
1761         ast_log(LOG_WARNING, "Unable to enumerate all threads to update priority\n");
1762         return ast_set_priority(pri);
1763 #else
1764         struct thread_list_t *cur;
1765         struct sched_param sched;
1766         char const *policy_str;
1767         int policy;
1768
1769         memset(&sched, 0, sizeof(sched));
1770         if (pri) {
1771                 policy = SCHED_RR;
1772                 policy_str = "realtime";
1773                 sched.sched_priority = 10;
1774         } else {
1775                 policy = SCHED_OTHER;
1776                 policy_str = "regular";
1777                 sched.sched_priority = 0;
1778         }
1779         if (sched_setscheduler(getpid(), policy, &sched)) {
1780                 ast_log(LOG_WARNING, "Unable to set %s thread priority on main thread\n", policy_str);
1781                 return -1;
1782         }
1783         ast_verb(1, "Setting %s thread priority on all threads\n", policy_str);
1784         AST_RWLIST_RDLOCK(&thread_list);
1785         AST_RWLIST_TRAVERSE(&thread_list, cur, list) {
1786                 /* Don't care about the return value. It should work. */
1787                 sched_setscheduler(cur->lwp, policy, &sched);
1788         }
1789         AST_RWLIST_UNLOCK(&thread_list);
1790         return 0;
1791 #endif
1792 }
1793
1794 /*! \brief We set ourselves to a high priority, that we might pre-empt
1795  * everything else.  If your PBX has heavy activity on it, this is a
1796  * good thing.
1797  */
1798 int ast_set_priority(int pri)
1799 {
1800         struct sched_param sched;
1801         memset(&sched, 0, sizeof(sched));
1802 #ifdef __linux__
1803         if (pri) {
1804                 sched.sched_priority = 10;
1805                 if (sched_setscheduler(0, SCHED_RR, &sched)) {
1806                         ast_log(LOG_WARNING, "Unable to set high priority\n");
1807                         return -1;
1808                 } else
1809                         ast_verb(1, "Set to realtime thread\n");
1810         } else {
1811                 sched.sched_priority = 0;
1812                 /* According to the manpage, these parameters can never fail. */
1813                 sched_setscheduler(0, SCHED_OTHER, &sched);
1814         }
1815 #else
1816         if (pri) {
1817                 if (setpriority(PRIO_PROCESS, 0, -10) == -1) {
1818                         ast_log(LOG_WARNING, "Unable to set high priority\n");
1819                         return -1;
1820                 } else
1821                         ast_verb(1, "Set to high priority\n");
1822         } else {
1823                 /* According to the manpage, these parameters can never fail. */
1824                 setpriority(PRIO_PROCESS, 0, 0);
1825         }
1826 #endif
1827         return 0;
1828 }
1829
1830 int ast_shutdown_final(void)
1831 {
1832         return shuttingdown == SHUTTING_DOWN_FINAL;
1833 }
1834
1835 int ast_shutting_down(void)
1836 {
1837         return shutdown_pending;
1838 }
1839
1840 int ast_cancel_shutdown(void)
1841 {
1842         int shutdown_aborted = 0;
1843
1844         ast_mutex_lock(&safe_system_lock);
1845         if (shuttingdown >= SHUTDOWN_FAST) {
1846                 shuttingdown = NOT_SHUTTING_DOWN;
1847                 shutdown_pending = 0;
1848                 shutdown_aborted = 1;
1849         }
1850         ast_mutex_unlock(&safe_system_lock);
1851         return shutdown_aborted;
1852 }
1853
1854 /*!
1855  * \internal
1856  * \brief Initiate system shutdown -- prevents new channels from being allocated.
1857  */
1858 static void ast_begin_shutdown(void)
1859 {
1860         ast_mutex_lock(&safe_system_lock);
1861         if (shuttingdown != NOT_SHUTTING_DOWN) {
1862                 shutdown_pending = 1;
1863         }
1864         ast_mutex_unlock(&safe_system_lock);
1865 }
1866
1867 static int can_safely_quit(shutdown_nice_t niceness, int restart);
1868 static void really_quit(int num, shutdown_nice_t niceness, int restart);
1869
1870 static void quit_handler(int num, shutdown_nice_t niceness, int restart)
1871 {
1872         if (can_safely_quit(niceness, restart)) {
1873                 really_quit(num, niceness, restart);
1874                 /* No one gets here. */
1875         }
1876         /* It wasn't our time. */
1877 }
1878
1879 #define SHUTDOWN_TIMEOUT        15      /* Seconds */
1880
1881 /*!
1882  * \internal
1883  * \brief Wait for all channels to die, a timeout, or shutdown cancelled.
1884  * \since 13.3.0
1885  *
1886  * \param niceness Shutdown niceness in effect
1887  * \param seconds Number of seconds to wait or less than zero if indefinitely.
1888  *
1889  * \retval zero if waiting wasn't necessary.  We were idle.
1890  * \retval non-zero if we had to wait.
1891  */
1892 static int wait_for_channels_to_die(shutdown_nice_t niceness, int seconds)
1893 {
1894         time_t start;
1895         time_t now;
1896         int waited = 0;
1897
1898         time(&start);
1899         for (;;) {
1900                 if (!ast_undestroyed_channels() || shuttingdown != niceness) {
1901                         break;
1902                 }
1903                 if (seconds < 0) {
1904                         /* No timeout so just poll every second */
1905                         sleep(1);
1906                 } else {
1907                         time(&now);
1908
1909                         /* Wait up to the given seconds for all channels to go away */
1910                         if (seconds < (now - start)) {
1911                                 break;
1912                         }
1913
1914                         /* Sleep 1/10 of a second */
1915                         usleep(100000);
1916                 }
1917                 waited = 1;
1918         }
1919         return waited;
1920 }
1921
1922 static int can_safely_quit(shutdown_nice_t niceness, int restart)
1923 {
1924         int waited = 0;
1925
1926         /* Check if someone else isn't already doing this. */
1927         ast_mutex_lock(&safe_system_lock);
1928         if (shuttingdown != NOT_SHUTTING_DOWN && niceness >= shuttingdown) {
1929                 /* Already in progress and other request was less nice. */
1930                 ast_mutex_unlock(&safe_system_lock);
1931                 ast_verbose("Ignoring asterisk %s request, already in progress.\n", restart ? "restart" : "shutdown");
1932                 return 0;
1933         }
1934         shuttingdown = niceness;
1935         ast_mutex_unlock(&safe_system_lock);
1936
1937         /* Try to get as many CDRs as possible submitted to the backend engines
1938          * (if in batch mode). really_quit happens to call it again when running
1939          * the atexit handlers, otherwise this would be a bit early. */
1940         ast_cdr_engine_term();
1941
1942         /*
1943          * Shutdown the message queue for the technology agnostic message channel.
1944          * This has to occur before we pause shutdown pending ast_undestroyed_channels.
1945          *
1946          * XXX This is not reversed on shutdown cancel.
1947          */
1948         ast_msg_shutdown();
1949
1950         if (niceness == SHUTDOWN_NORMAL) {
1951                 /* Begin shutdown routine, hanging up active channels */
1952                 ast_begin_shutdown();
1953                 if (ast_opt_console) {
1954                         ast_verb(0, "Beginning asterisk %s....\n", restart ? "restart" : "shutdown");
1955                 }
1956                 ast_softhangup_all();
1957                 waited |= wait_for_channels_to_die(niceness, SHUTDOWN_TIMEOUT);
1958         } else if (niceness >= SHUTDOWN_NICE) {
1959                 if (niceness != SHUTDOWN_REALLY_NICE) {
1960                         ast_begin_shutdown();
1961                 }
1962                 if (ast_opt_console) {
1963                         ast_verb(0, "Waiting for inactivity to perform %s...\n", restart ? "restart" : "halt");
1964                 }
1965                 waited |= wait_for_channels_to_die(niceness, -1);
1966         }
1967
1968         /* Re-acquire lock and check if someone changed the niceness, in which
1969          * case someone else has taken over the shutdown.
1970          */
1971         ast_mutex_lock(&safe_system_lock);
1972         if (shuttingdown != niceness) {
1973                 if (shuttingdown == NOT_SHUTTING_DOWN && ast_opt_console) {
1974                         ast_verb(0, "Asterisk %s cancelled.\n", restart ? "restart" : "shutdown");
1975                 }
1976                 ast_mutex_unlock(&safe_system_lock);
1977                 return 0;
1978         }
1979
1980         if (niceness >= SHUTDOWN_REALLY_NICE) {
1981                 shuttingdown = SHUTTING_DOWN;
1982                 ast_mutex_unlock(&safe_system_lock);
1983
1984                 /* No more Mr. Nice guy.  We are committed to shutting down now. */
1985                 ast_begin_shutdown();
1986                 ast_softhangup_all();
1987                 waited |= wait_for_channels_to_die(SHUTTING_DOWN, SHUTDOWN_TIMEOUT);
1988
1989                 ast_mutex_lock(&safe_system_lock);
1990         }
1991         shuttingdown = SHUTTING_DOWN_FINAL;
1992         ast_mutex_unlock(&safe_system_lock);
1993
1994         if (niceness >= SHUTDOWN_NORMAL && waited) {
1995                 /*
1996                  * We were not idle.  Give things in progress a chance to
1997                  * recognize the final shutdown phase.
1998                  */
1999                 sleep(1);
2000         }
2001         return 1;
2002 }
2003
2004 /*! Called when exiting is certain. */
2005 static void really_quit(int num, shutdown_nice_t niceness, int restart)
2006 {
2007         int active_channels;
2008         struct ast_json *json_object = NULL;
2009         int run_cleanups = niceness >= SHUTDOWN_NICE;
2010
2011         if (run_cleanups && modules_shutdown()) {
2012                 ast_verb(0, "Some modules could not be unloaded, switching to fast shutdown\n");
2013                 run_cleanups = 0;
2014         }
2015
2016         if (!restart) {
2017                 ast_sd_notify("STOPPING=1");
2018         }
2019         if (ast_opt_console || (ast_opt_remote && !ast_opt_exec)) {
2020                 ast_el_write_default_histfile();
2021                 if (consolethread == AST_PTHREADT_NULL || consolethread == pthread_self()) {
2022                         /* Only end if we are the consolethread, otherwise there's a race with that thread. */
2023                         if (el != NULL) {
2024                                 el_end(el);
2025                         }
2026                         if (el_hist != NULL) {
2027                                 history_end(el_hist);
2028                         }
2029                 } else if (!restart) {
2030                         sig_flags.need_el_end = 1;
2031                         pthread_kill(consolethread, SIGURG);
2032                 }
2033         }
2034         active_channels = ast_active_channels();
2035         /* Don't publish messages if we're a remote console - we won't have all of the Stasis
2036          * topics or message types
2037          */
2038         if (!ast_opt_remote) {
2039                 json_object = ast_json_pack("{s: s, s: s}",
2040                                 "Shutdown", active_channels ? "Uncleanly" : "Cleanly",
2041                                 "Restart", restart ? "True" : "False");
2042                 ast_manager_publish_event("Shutdown", EVENT_FLAG_SYSTEM, json_object);
2043                 ast_json_unref(json_object);
2044                 json_object = NULL;
2045         }
2046         ast_verb(0, "Asterisk %s ending (%d).\n",
2047                 active_channels ? "uncleanly" : "cleanly", num);
2048
2049         ast_verb(0, "Executing last minute cleanups\n");
2050         ast_run_atexits(run_cleanups);
2051
2052         ast_debug(1, "Asterisk ending (%d).\n", num);
2053         if (ast_socket > -1) {
2054                 pthread_cancel(lthread);
2055                 close(ast_socket);
2056                 ast_socket = -1;
2057                 if (!ast_socket_is_sd) {
2058                         unlink(ast_config_AST_SOCKET);
2059                 }
2060                 pthread_kill(lthread, SIGURG);
2061                 pthread_join(lthread, NULL);
2062         }
2063         if (ast_consock > -1)
2064                 close(ast_consock);
2065         if (!ast_opt_remote)
2066                 unlink(ast_config_AST_PID);
2067         ast_alertpipe_close(sig_alert_pipe);
2068         printf("%s", term_quit());
2069         if (restart) {
2070                 int i;
2071                 ast_verb(0, "Preparing for Asterisk restart...\n");
2072                 /* Mark all FD's for closing on exec */
2073                 for (i = 3; i < 32768; i++) {
2074                         fcntl(i, F_SETFD, FD_CLOEXEC);
2075                 }
2076                 ast_verb(0, "Asterisk is now restarting...\n");
2077                 restartnow = 1;
2078
2079                 /* close logger */
2080                 close_logger();
2081                 clean_time_zones();
2082
2083                 /* If there is a consolethread running send it a SIGHUP
2084                    so it can execvp, otherwise we can do it ourselves */
2085                 if ((consolethread != AST_PTHREADT_NULL) && (consolethread != pthread_self())) {
2086                         pthread_kill(consolethread, SIGHUP);
2087                         /* Give the signal handler some time to complete */
2088                         sleep(2);
2089                 } else
2090                         execvp(_argv[0], _argv);
2091
2092         } else {
2093                 /* close logger */
2094                 close_logger();
2095                 clean_time_zones();
2096         }
2097
2098         exit(0);
2099 }
2100
2101 static void __quit_handler(int num)
2102 {
2103         sig_flags.need_quit = 1;
2104         if (ast_alertpipe_write(sig_alert_pipe)) {
2105                 fprintf(stderr, "quit_handler: write() failed: %s\n", strerror(errno));
2106         }
2107         /* There is no need to restore the signal handler here, since the app
2108          * is going to exit */
2109 }
2110
2111 static void __remote_quit_handler(int num)
2112 {
2113         sig_flags.need_quit = 1;
2114 }
2115
2116 static void set_header(char *outbuf, int maxout, char level)
2117 {
2118         const char *cmp;
2119         char date[40];
2120
2121         switch (level) {
2122         case 0: cmp = NULL;
2123                 break;
2124         case 1: cmp = VERBOSE_PREFIX_1;
2125                 break;
2126         case 2: cmp = VERBOSE_PREFIX_2;
2127                 break;
2128         case 3: cmp = VERBOSE_PREFIX_3;
2129                 break;
2130         default: cmp = VERBOSE_PREFIX_4;
2131                 break;
2132         }
2133
2134         if (ast_opt_timestamp) {
2135                 struct ast_tm tm;
2136                 struct timeval now = ast_tvnow();
2137                 ast_localtime(&now, &tm, NULL);
2138                 ast_strftime(date, sizeof(date), ast_logger_get_dateformat(), &tm);
2139         }
2140
2141         snprintf(outbuf, maxout, "%s%s%s%s%s%s",
2142                 ast_opt_timestamp ? "[" : "",
2143                 ast_opt_timestamp ? date : "",
2144                 ast_opt_timestamp ? "] " : "",
2145                 cmp ? ast_term_color(COLOR_GRAY, 0) : "",
2146                 cmp ? cmp : "",
2147                 cmp ? ast_term_reset() : "");
2148 }
2149
2150 struct console_state_data {
2151         char verbose_line_level;
2152 };
2153
2154 static int console_state_init(void *ptr)
2155 {
2156         struct console_state_data *state = ptr;
2157         state->verbose_line_level = 0;
2158         return 0;
2159 }
2160
2161 AST_THREADSTORAGE_CUSTOM(console_state, console_state_init, ast_free_ptr);
2162
2163 static int console_print(const char *s)
2164 {
2165         struct console_state_data *state =
2166                 ast_threadstorage_get(&console_state, sizeof(*state));
2167
2168         char prefix[80];
2169         const char *c;
2170         int num, res = 0;
2171         unsigned int newline;
2172
2173         do {
2174                 if (VERBOSE_HASMAGIC(s)) {
2175
2176                         /* always use the given line's level, otherwise
2177                            we'll use the last line's level */
2178                         state->verbose_line_level = VERBOSE_MAGIC2LEVEL(s);
2179
2180                         /* move past magic */
2181                         s++;
2182
2183                         set_header(prefix, sizeof(prefix), state->verbose_line_level);
2184                 } else {
2185                         *prefix = '\0';
2186                 }
2187                 c = s;
2188
2189                 /* for a given line separate on verbose magic, newline, and eol */
2190                 if ((s = strchr(c, '\n'))) {
2191                         ++s;
2192                         newline = 1;
2193                 } else {
2194                         s = strchr(c, '\0');
2195                         newline = 0;
2196                 }
2197
2198                 /* check if we should write this line after calculating begin/end
2199                    so we process the case of a higher level line embedded within
2200                    two lower level lines */
2201                 if (state->verbose_line_level > option_verbose) {
2202                         continue;
2203                 }
2204
2205                 if (!ast_strlen_zero(prefix)) {
2206                         fputs(prefix, stdout);
2207                 }
2208
2209                 num = s - c;
2210                 if (fwrite(c, sizeof(char), num, stdout) < num) {
2211                         break;
2212                 }
2213
2214                 if (!res) {
2215                         /* if at least some info has been written
2216                            we'll want to return true */
2217                         res = 1;
2218                 }
2219         } while (*s);
2220
2221         if (newline) {
2222                 /* if ending on a newline then reset last level to zero
2223                     since what follows may be not be logging output */
2224                 state->verbose_line_level = 0;
2225         }
2226
2227         if (res) {
2228                 fflush(stdout);
2229         }
2230
2231         return res;
2232 }
2233
2234 static int ast_all_zeros(const char *s)
2235 {
2236         while (*s) {
2237                 if (*s > 32)
2238                         return 0;
2239                 s++;
2240         }
2241         return 1;
2242 }
2243
2244 /* This is the main console CLI command handler.  Run by the main() thread. */
2245 static void consolehandler(const char *s)
2246 {
2247         printf("%s", term_end());
2248         fflush(stdout);
2249
2250         /* Called when readline data is available */
2251         if (!ast_all_zeros(s))
2252                 ast_el_add_history(s);
2253         /* The real handler for bang */
2254         if (s[0] == '!') {
2255                 if (s[1])
2256                         ast_safe_system(s+1);
2257                 else
2258                         ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
2259         } else
2260                 ast_cli_command(STDOUT_FILENO, s);
2261 }
2262
2263 static int remoteconsolehandler(const char *s)
2264 {
2265         int ret = 0;
2266
2267         /* Called when readline data is available */
2268         if (!ast_all_zeros(s))
2269                 ast_el_add_history(s);
2270
2271         while (isspace(*s)) {
2272                 s++;
2273         }
2274
2275         /* The real handler for bang */
2276         if (s[0] == '!') {
2277                 if (s[1])
2278                         ast_safe_system(s+1);
2279                 else
2280                         ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
2281                 ret = 1;
2282         } else if ((strncasecmp(s, "quit", 4) == 0 || strncasecmp(s, "exit", 4) == 0) &&
2283             (s[4] == '\0' || isspace(s[4]))) {
2284                 quit_handler(0, SHUTDOWN_FAST, 0);
2285                 ret = 1;
2286         }
2287
2288         return ret;
2289 }
2290
2291 static char *handle_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2292 {
2293         switch (cmd) {
2294         case CLI_INIT:
2295                 e->command = "core show version";
2296                 e->usage =
2297                         "Usage: core show version\n"
2298                         "       Shows Asterisk version information.\n";
2299                 return NULL;
2300         case CLI_GENERATE:
2301                 return NULL;
2302         }
2303
2304         if (a->argc != 3)
2305                 return CLI_SHOWUSAGE;
2306         ast_cli(a->fd, "Asterisk %s built by %s @ %s on a %s running %s on %s\n",
2307                 ast_get_version(), ast_build_user, ast_build_hostname,
2308                 ast_build_machine, ast_build_os, ast_build_date);
2309         return CLI_SUCCESS;
2310 }
2311
2312 static char *handle_stop_now(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2313 {
2314         switch (cmd) {
2315         case CLI_INIT:
2316                 e->command = "core stop now";
2317                 e->usage =
2318                         "Usage: core stop now\n"
2319                         "       Shuts down a running Asterisk immediately, hanging up all active calls .\n";
2320                 ast_cli_allow_at_shutdown(e);
2321                 return NULL;
2322         case CLI_GENERATE:
2323                 return NULL;
2324         }
2325
2326         if (a->argc != e->args)
2327                 return CLI_SHOWUSAGE;
2328         quit_handler(0, SHUTDOWN_NORMAL, 0 /* not restart */);
2329         return CLI_SUCCESS;
2330 }
2331
2332 static char *handle_stop_gracefully(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2333 {
2334         switch (cmd) {
2335         case CLI_INIT:
2336                 e->command = "core stop gracefully";
2337                 e->usage =
2338                         "Usage: core stop gracefully\n"
2339                         "       Causes Asterisk to not accept new calls, and exit when all\n"
2340                         "       active calls have terminated normally.\n";
2341                 ast_cli_allow_at_shutdown(e);
2342                 return NULL;
2343         case CLI_GENERATE:
2344                 return NULL;
2345         }
2346
2347         if (a->argc != e->args)
2348                 return CLI_SHOWUSAGE;
2349         quit_handler(0, SHUTDOWN_NICE, 0 /* no restart */);
2350         return CLI_SUCCESS;
2351 }
2352
2353 static char *handle_stop_when_convenient(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2354 {
2355         switch (cmd) {
2356         case CLI_INIT:
2357                 e->command = "core stop when convenient";
2358                 e->usage =
2359                         "Usage: core stop when convenient\n"
2360                         "       Causes Asterisk to perform a shutdown when all active calls have ended.\n";
2361                 ast_cli_allow_at_shutdown(e);
2362                 return NULL;
2363         case CLI_GENERATE:
2364                 return NULL;
2365         }
2366
2367         if (a->argc != e->args)
2368                 return CLI_SHOWUSAGE;
2369         ast_cli(a->fd, "Waiting for inactivity to perform halt\n");
2370         quit_handler(0, SHUTDOWN_REALLY_NICE, 0 /* don't restart */);
2371         return CLI_SUCCESS;
2372 }
2373
2374 static char *handle_restart_now(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2375 {
2376         switch (cmd) {
2377         case CLI_INIT:
2378                 e->command = "core restart now";
2379                 e->usage =
2380                         "Usage: core restart now\n"
2381                         "       Causes Asterisk to hangup all calls and exec() itself performing a cold\n"
2382                         "       restart.\n";
2383                 ast_cli_allow_at_shutdown(e);
2384                 return NULL;
2385         case CLI_GENERATE:
2386                 return NULL;
2387         }
2388
2389         if (a->argc != e->args)
2390                 return CLI_SHOWUSAGE;
2391         quit_handler(0, SHUTDOWN_NORMAL, 1 /* restart */);
2392         return CLI_SUCCESS;
2393 }
2394
2395 static char *handle_restart_gracefully(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2396 {
2397         switch (cmd) {
2398         case CLI_INIT:
2399                 e->command = "core restart gracefully";
2400                 e->usage =
2401                         "Usage: core restart gracefully\n"
2402                         "       Causes Asterisk to stop accepting new calls and exec() itself performing a cold\n"
2403                         "       restart when all active calls have ended.\n";
2404                 ast_cli_allow_at_shutdown(e);
2405                 return NULL;
2406         case CLI_GENERATE:
2407                 return NULL;
2408         }
2409
2410         if (a->argc != e->args)
2411                 return CLI_SHOWUSAGE;
2412         quit_handler(0, SHUTDOWN_NICE, 1 /* restart */);
2413         return CLI_SUCCESS;
2414 }
2415
2416 static char *handle_restart_when_convenient(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2417 {
2418         switch (cmd) {
2419         case CLI_INIT:
2420                 e->command = "core restart when convenient";
2421                 e->usage =
2422                         "Usage: core restart when convenient\n"
2423                         "       Causes Asterisk to perform a cold restart when all active calls have ended.\n";
2424                 ast_cli_allow_at_shutdown(e);
2425                 return NULL;
2426         case CLI_GENERATE:
2427                 return NULL;
2428         }
2429
2430         if (a->argc != e->args)
2431                 return CLI_SHOWUSAGE;
2432         ast_cli(a->fd, "Waiting for inactivity to perform restart\n");
2433         quit_handler(0, SHUTDOWN_REALLY_NICE, 1 /* restart */);
2434         return CLI_SUCCESS;
2435 }
2436
2437 static char *handle_abort_shutdown(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2438 {
2439         switch (cmd) {
2440         case CLI_INIT:
2441                 e->command = "core abort shutdown";
2442                 e->usage =
2443                         "Usage: core abort shutdown\n"
2444                         "       Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
2445                         "       call operations.\n";
2446                 ast_cli_allow_at_shutdown(e);
2447                 return NULL;
2448         case CLI_GENERATE:
2449                 return NULL;
2450         }
2451
2452         if (a->argc != e->args)
2453                 return CLI_SHOWUSAGE;
2454
2455         ast_cancel_shutdown();
2456
2457         return CLI_SUCCESS;
2458 }
2459
2460 static char *handle_bang(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2461 {
2462         switch (cmd) {
2463         case CLI_INIT:
2464                 e->command = "!";
2465                 e->usage =
2466                         "Usage: !<command>\n"
2467                         "       Executes a given shell command\n";
2468                 return NULL;
2469         case CLI_GENERATE:
2470                 return NULL;
2471         }
2472
2473         return CLI_SUCCESS;
2474 }
2475 static const char warranty_lines[] = {
2476         "\n"
2477         "                           NO WARRANTY\n"
2478         "\n"
2479         "BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\n"
2480         "FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\n"
2481         "OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\n"
2482         "PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\n"
2483         "OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n"
2484         "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\n"
2485         "TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\n"
2486         "PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\n"
2487         "REPAIR OR CORRECTION.\n"
2488         "\n"
2489         "IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\n"
2490         "WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\n"
2491         "REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\n"
2492         "INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\n"
2493         "OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\n"
2494         "TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\n"
2495         "YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\n"
2496         "PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\n"
2497         "POSSIBILITY OF SUCH DAMAGES.\n"
2498 };
2499
2500 static char *show_warranty(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2501 {
2502         switch (cmd) {
2503         case CLI_INIT:
2504                 e->command = "core show warranty";
2505                 e->usage =
2506                         "Usage: core show warranty\n"
2507                         "       Shows the warranty (if any) for this copy of Asterisk.\n";
2508                 return NULL;
2509         case CLI_GENERATE:
2510                 return NULL;
2511         }
2512
2513         ast_cli(a->fd, "%s", warranty_lines);
2514
2515         return CLI_SUCCESS;
2516 }
2517
2518 static const char license_lines[] = {
2519         "\n"
2520         "This program is free software; you can redistribute it and/or modify\n"
2521         "it under the terms of the GNU General Public License version 2 as\n"
2522         "published by the Free Software Foundation.\n"
2523         "\n"
2524         "This program also contains components licensed under other licenses.\n"
2525         "They include:\n"
2526         "\n"
2527         "This program is distributed in the hope that it will be useful,\n"
2528         "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
2529         "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
2530         "GNU General Public License for more details.\n"
2531         "\n"
2532         "You should have received a copy of the GNU General Public License\n"
2533         "along with this program; if not, write to the Free Software\n"
2534         "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
2535 };
2536
2537 static char *show_license(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2538 {
2539         switch (cmd) {
2540         case CLI_INIT:
2541                 e->command = "core show license";
2542                 e->usage =
2543                         "Usage: core show license\n"
2544                         "       Shows the license(s) for this copy of Asterisk.\n";
2545                 return NULL;
2546         case CLI_GENERATE:
2547                 return NULL;
2548         }
2549
2550         ast_cli(a->fd, "%s", license_lines);
2551
2552         return CLI_SUCCESS;
2553 }
2554
2555 #define ASTERISK_PROMPT "*CLI> "
2556
2557 /*!
2558  * \brief Shutdown Asterisk CLI commands.
2559  *
2560  * \note These CLI commands cannot be unregistered at shutdown
2561  * because one of them is likely the reason for the shutdown.
2562  * The CLI generates a warning if a command is in-use when it is
2563  * unregistered.
2564  */
2565 static struct ast_cli_entry cli_asterisk_shutdown[] = {
2566         AST_CLI_DEFINE(handle_stop_now, "Shut down Asterisk immediately"),
2567         AST_CLI_DEFINE(handle_stop_gracefully, "Gracefully shut down Asterisk"),
2568         AST_CLI_DEFINE(handle_stop_when_convenient, "Shut down Asterisk at empty call volume"),
2569         AST_CLI_DEFINE(handle_restart_now, "Restart Asterisk immediately"),
2570         AST_CLI_DEFINE(handle_restart_gracefully, "Restart Asterisk gracefully"),
2571         AST_CLI_DEFINE(handle_restart_when_convenient, "Restart Asterisk at empty call volume"),
2572 };
2573
2574 static struct ast_cli_entry cli_asterisk[] = {
2575         AST_CLI_DEFINE(handle_abort_shutdown, "Cancel a running shutdown"),
2576         AST_CLI_DEFINE(show_warranty, "Show the warranty (if any) for this copy of Asterisk"),
2577         AST_CLI_DEFINE(show_license, "Show the license(s) for this copy of Asterisk"),
2578         AST_CLI_DEFINE(handle_version, "Display version info"),
2579         AST_CLI_DEFINE(handle_bang, "Execute a shell command"),
2580 #if !defined(LOW_MEMORY)
2581         AST_CLI_DEFINE(handle_show_threads, "Show running threads"),
2582 #if defined(HAVE_SYSINFO) || defined(HAVE_SYSCTL)
2583         AST_CLI_DEFINE(handle_show_sysinfo, "Show System Information"),
2584 #endif
2585         AST_CLI_DEFINE(handle_show_profile, "Display profiling info"),
2586         AST_CLI_DEFINE(handle_show_settings, "Show some core settings"),
2587         AST_CLI_DEFINE(handle_clear_profile, "Clear profiling info"),
2588 #endif /* ! LOW_MEMORY */
2589 };
2590
2591 static void send_rasterisk_connect_commands(void)
2592 {
2593         char buf[80];
2594
2595         /*
2596          * Tell the server asterisk instance about the verbose level
2597          * initially desired.
2598          */
2599         if (option_verbose) {
2600                 snprintf(buf, sizeof(buf), "core set verbose atleast %d silent", option_verbose);
2601                 fdsend(ast_consock, buf);
2602         }
2603
2604         if (option_debug) {
2605                 snprintf(buf, sizeof(buf), "core set debug atleast %d", option_debug);
2606                 fdsend(ast_consock, buf);
2607         }
2608
2609         /* Leave verbose filtering to the server. */
2610         option_verbose = INT_MAX;
2611
2612         if (!ast_opt_mute) {
2613                 fdsend(ast_consock, "logger mute silent");
2614         } else {
2615                 printf("log and verbose output currently muted ('logger mute' to unmute)\n");
2616         }
2617 }
2618
2619 #ifdef HAVE_LIBEDIT_IS_UNICODE
2620 #define CHAR_T_LIBEDIT wchar_t
2621 #define CHAR_TO_LIBEDIT(c) btowc(c)
2622 #else
2623 #define CHAR_T_LIBEDIT char
2624 #define CHAR_TO_LIBEDIT(c) c
2625 #endif
2626
2627 static int ast_el_read_char(EditLine *editline, CHAR_T_LIBEDIT *cp)
2628 {
2629         int num_read = 0;
2630         int lastpos = 0;
2631         struct pollfd fds[2];
2632         int res;
2633         int max;
2634 #define EL_BUF_SIZE 512
2635         char buf[EL_BUF_SIZE];
2636
2637         for (;;) {
2638                 max = 1;
2639                 fds[0].fd = ast_consock;
2640                 fds[0].events = POLLIN;
2641                 if (!ast_opt_exec) {
2642                         fds[1].fd = STDIN_FILENO;
2643                         fds[1].events = POLLIN;
2644                         max++;
2645                 }
2646                 res = ast_poll(fds, max, -1);
2647                 if (res < 0) {
2648                         if (sig_flags.need_quit || sig_flags.need_quit_handler || sig_flags.need_el_end) {
2649                                 break;
2650                         }
2651                         if (errno == EINTR) {
2652                                 continue;
2653                         }
2654                         fprintf(stderr, "poll failed: %s\n", strerror(errno));
2655                         break;
2656                 }
2657
2658                 if (!ast_opt_exec && fds[1].revents) {
2659                         char c = '\0';
2660
2661                         num_read = read(STDIN_FILENO, &c, 1);
2662                         if (num_read < 1) {
2663                                 break;
2664                         }
2665
2666                         *cp = CHAR_TO_LIBEDIT(c);
2667
2668                         return num_read;
2669                 }
2670
2671                 if (fds[0].revents) {
2672                         res = read(ast_consock, buf, sizeof(buf) - 1);
2673                         /* if the remote side disappears exit */
2674                         if (res < 1) {
2675                                 fprintf(stderr, "\nDisconnected from Asterisk server\n");
2676                                 if (!ast_opt_reconnect) {
2677                                         quit_handler(0, SHUTDOWN_FAST, 0);
2678                                 } else {
2679                                         int tries;
2680                                         int reconnects_per_second = 20;
2681
2682                                         fprintf(stderr, "Attempting to reconnect for 30 seconds\n");
2683                                         for (tries = 0; tries < 30 * reconnects_per_second; tries++) {
2684                                                 if (ast_tryconnect()) {
2685                                                         fprintf(stderr, "Reconnect succeeded after %.3f seconds\n", 1.0 / reconnects_per_second * tries);
2686                                                         printf("%s", term_quit());
2687                                                         WELCOME_MESSAGE;
2688                                                         send_rasterisk_connect_commands();
2689                                                         break;
2690                                                 }
2691
2692                                                 usleep(1000000 / reconnects_per_second);
2693                                         }
2694                                         if (tries >= 30 * reconnects_per_second) {
2695                                                 fprintf(stderr, "Failed to reconnect for 30 seconds.  Quitting.\n");
2696                                                 quit_handler(0, SHUTDOWN_FAST, 0);
2697                                         }
2698                                 }
2699                                 continue;
2700                         }
2701
2702                         buf[res] = '\0';
2703
2704                         /* Write over the CLI prompt */
2705                         if (!ast_opt_exec && !lastpos) {
2706                                 if (write(STDOUT_FILENO, "\r\e[0K", 5) < 0) {
2707                                 }
2708                         }
2709
2710                         console_print(buf);
2711
2712                         if ((res < EL_BUF_SIZE - 1) && ((buf[res-1] == '\n') || (res >= 2 && buf[res-2] == '\n'))) {
2713                                 *cp = CHAR_TO_LIBEDIT(CC_REFRESH);
2714
2715                                 return 1;
2716                         }
2717                         lastpos = 1;
2718                 }
2719         }
2720
2721         *cp = CHAR_TO_LIBEDIT('\0');
2722
2723         return 0;
2724 }
2725
2726 static struct ast_str *prompt = NULL;
2727
2728 static char *cli_prompt(EditLine *editline)
2729 {
2730         char tmp[100];
2731         char *pfmt;
2732         int color_used = 0;
2733         static int cli_prompt_changes = 0;
2734         struct passwd *pw;
2735         struct group *gr;
2736
2737         if (prompt == NULL) {
2738                 prompt = ast_str_create(100);
2739         } else if (!cli_prompt_changes) {
2740                 return ast_str_buffer(prompt);
2741         } else {
2742                 ast_str_reset(prompt);
2743         }
2744
2745         if ((pfmt = getenv("ASTERISK_PROMPT"))) {
2746                 char *t = pfmt;
2747                 struct timeval ts = ast_tvnow();
2748                 while (*t != '\0') {
2749                         if (*t == '%') {
2750                                 char hostname[MAXHOSTNAMELEN] = "";
2751                                 int i, which;
2752                                 struct ast_tm tm = { 0, };
2753                                 int fgcolor = COLOR_WHITE, bgcolor = COLOR_BLACK;
2754
2755                                 t++;
2756                                 switch (*t) {
2757                                 case 'C': /* color */
2758                                         t++;
2759                                         if (sscanf(t, "%30d;%30d%n", &fgcolor, &bgcolor, &i) == 2) {
2760                                                 ast_term_color_code(&prompt, fgcolor, bgcolor);
2761                                                 t += i - 1;
2762                                         } else if (sscanf(t, "%30d%n", &fgcolor, &i) == 1) {
2763                                                 ast_term_color_code(&prompt, fgcolor, 0);
2764                                                 t += i - 1;
2765                                         }
2766
2767                                         /* If the color has been reset correctly, then there's no need to reset it later */
2768                                         color_used = ((fgcolor == COLOR_WHITE) && (bgcolor == COLOR_BLACK)) ? 0 : 1;
2769                                         break;
2770                                 case 'd': /* date */
2771                                         if (ast_localtime(&ts, &tm, NULL)) {
2772                                                 ast_strftime(tmp, sizeof(tmp), "%Y-%m-%d", &tm);
2773                                                 ast_str_append(&prompt, 0, "%s", tmp);
2774                                                 cli_prompt_changes++;
2775                                         }
2776                                         break;
2777                                 case 'g': /* group */
2778                                         if ((gr = getgrgid(getgid()))) {
2779                                                 ast_str_append(&prompt, 0, "%s", gr->gr_name);
2780                                         }
2781                                         break;
2782                                 case 'h': /* hostname */
2783                                         if (!gethostname(hostname, sizeof(hostname) - 1)) {
2784                                                 ast_str_append(&prompt, 0, "%s", hostname);
2785                                         } else {
2786                                                 ast_str_append(&prompt, 0, "%s", "localhost");
2787                                         }
2788                                         break;
2789                                 case 'H': /* short hostname */
2790                                         if (!gethostname(hostname, sizeof(hostname) - 1)) {
2791                                                 char *dotptr;
2792                                                 if ((dotptr = strchr(hostname, '.'))) {
2793                                                         *dotptr = '\0';
2794                                                 }
2795                                                 ast_str_append(&prompt, 0, "%s", hostname);
2796                                         } else {
2797                                                 ast_str_append(&prompt, 0, "%s", "localhost");
2798                                         }
2799                                         break;
2800 #ifdef HAVE_GETLOADAVG
2801                                 case 'l': /* load avg */
2802                                         t++;
2803                                         if (sscanf(t, "%30d", &which) == 1 && which > 0 && which <= 3) {
2804                                                 double list[3];
2805                                                 getloadavg(list, 3);
2806                                                 ast_str_append(&prompt, 0, "%.2f", list[which - 1]);
2807                                                 cli_prompt_changes++;
2808                                         }
2809                                         break;
2810 #endif
2811                                 case 's': /* Asterisk system name (from asterisk.conf) */
2812                                         ast_str_append(&prompt, 0, "%s", ast_config_AST_SYSTEM_NAME);
2813                                         break;
2814                                 case 't': /* time */
2815                                         if (ast_localtime(&ts, &tm, NULL)) {
2816                                                 ast_strftime(tmp, sizeof(tmp), "%H:%M:%S", &tm);
2817                                                 ast_str_append(&prompt, 0, "%s", tmp);
2818                                                 cli_prompt_changes++;
2819                                         }
2820                                         break;
2821                                 case 'u': /* username */
2822                                         if ((pw = getpwuid(getuid()))) {
2823                                                 ast_str_append(&prompt, 0, "%s", pw->pw_name);
2824                                         }
2825                                         break;
2826                                 case '#': /* process console or remote? */
2827                                         ast_str_append(&prompt, 0, "%c", ast_opt_remote ? '>' : '#');
2828                                         break;
2829                                 case '%': /* literal % */
2830                                         ast_str_append(&prompt, 0, "%c", '%');
2831                                         break;
2832                                 case '\0': /* % is last character - prevent bug */
2833                                         t--;
2834                                         break;
2835                                 }
2836                         } else {
2837                                 ast_str_append(&prompt, 0, "%c", *t);
2838                         }
2839                         t++;
2840                 }
2841                 if (color_used) {
2842                         /* Force colors back to normal at end */
2843                         ast_term_color_code(&prompt, 0, 0);
2844                 }
2845         } else {
2846                 ast_str_set(&prompt, 0, "%s%s",
2847                         remotehostname ? remotehostname : "",
2848                         ASTERISK_PROMPT);
2849         }
2850
2851         return ast_str_buffer(prompt);
2852 }
2853
2854 static struct ast_vector_string *ast_el_strtoarr(char *buf)
2855 {
2856         char *retstr;
2857         struct ast_vector_string *vec = ast_calloc(1, sizeof(*vec));
2858
2859         if (!vec) {
2860                 return NULL;
2861         }
2862
2863         while ((retstr = strsep(&buf, " "))) {
2864                 if (!strcmp(retstr, AST_CLI_COMPLETE_EOF)) {
2865                         break;
2866                 }
2867
2868                 retstr = ast_strdup(retstr);
2869                 if (!retstr || AST_VECTOR_APPEND(vec, retstr)) {
2870                         ast_free(retstr);
2871                         goto vector_cleanup;
2872                 }
2873         }
2874
2875         if (!AST_VECTOR_SIZE(vec)) {
2876                 goto vector_cleanup;
2877         }
2878
2879         return vec;
2880
2881 vector_cleanup:
2882         AST_VECTOR_CALLBACK_VOID(vec, ast_free);
2883         AST_VECTOR_PTR_FREE(vec);
2884
2885         return NULL;
2886 }
2887
2888 static void ast_cli_display_match_list(struct ast_vector_string *matches, int max)
2889 {
2890         int idx = 1;
2891         /* find out how many entries can be put on one line, with two spaces between strings */
2892         int limit = ast_get_termcols(STDOUT_FILENO) / (max + 2);
2893
2894         if (limit == 0) {
2895                 limit = 1;
2896         }
2897
2898         for (;;) {
2899                 int numoutputline;
2900
2901                 for (numoutputline = 0; numoutputline < limit && idx < AST_VECTOR_SIZE(matches); idx++) {
2902                         numoutputline++;
2903                         fprintf(stdout, "%-*s  ", max, AST_VECTOR_GET(matches, idx));
2904                 }
2905
2906                 if (!numoutputline) {
2907                         break;
2908                 }
2909
2910                 fprintf(stdout, "\n");
2911         }
2912 }
2913
2914
2915 static char *cli_complete(EditLine *editline, int ch)
2916 {
2917         int len = 0;
2918         char *ptr;
2919         struct ast_vector_string *matches;
2920         int retval = CC_ERROR;
2921         char savechr;
2922         int res;
2923
2924         LineInfo *lf = (LineInfo *)el_line(editline);
2925
2926         savechr = *(char *)lf->cursor;
2927         *(char *)lf->cursor = '\0';
2928         ptr = (char *)lf->cursor;
2929         if (ptr) {
2930                 while (ptr > lf->buffer) {
2931                         if (isspace(*ptr)) {
2932                                 ptr++;
2933                                 break;
2934                         }
2935                         ptr--;
2936                 }
2937         }
2938
2939         len = lf->cursor - ptr;
2940
2941         if (ast_opt_remote) {
2942 #define CMD_MATCHESARRAY "_COMMAND MATCHESARRAY \"%s\" \"%s\""
2943                 char *mbuf;
2944                 char *new_mbuf;
2945                 int mlen = 0;
2946                 int maxmbuf = ast_asprintf(&mbuf, CMD_MATCHESARRAY, lf->buffer, ptr);
2947
2948                 if (maxmbuf == -1) {
2949                         *((char *) lf->cursor) = savechr;
2950
2951                         return (char *)(CC_ERROR);
2952                 }
2953
2954                 fdsend(ast_consock, mbuf);
2955                 res = 0;
2956                 mlen = 0;
2957                 mbuf[0] = '\0';
2958
2959                 while (!strstr(mbuf, AST_CLI_COMPLETE_EOF) && res != -1) {
2960                         if (mlen + 1024 > maxmbuf) {
2961                                 /* Expand buffer to the next 1024 byte increment plus a NULL terminator. */
2962                                 maxmbuf = mlen + 1024;
2963                                 new_mbuf = ast_realloc(mbuf, maxmbuf + 1);
2964                                 if (!new_mbuf) {
2965                                         ast_free(mbuf);
2966                                         *((char *) lf->cursor) = savechr;
2967
2968                                         return (char *)(CC_ERROR);
2969                                 }
2970                                 mbuf = new_mbuf;
2971                         }
2972                         /* Only read 1024 bytes at a time */
2973                         res = read(ast_consock, mbuf + mlen, 1024);
2974                         if (res > 0) {
2975                                 mlen += res;
2976                                 mbuf[mlen] = '\0';
2977                         }
2978                 }
2979                 mbuf[mlen] = '\0';
2980
2981                 matches = ast_el_strtoarr(mbuf);
2982                 ast_free(mbuf);
2983         } else {
2984                 matches = ast_cli_completion_vector((char *)lf->buffer, ptr);
2985         }
2986
2987         if (matches) {
2988                 int i;
2989                 int maxlen, match_len;
2990                 const char *best_match = AST_VECTOR_GET(matches, 0);
2991
2992                 if (!ast_strlen_zero(best_match)) {
2993                         el_deletestr(editline, (int) len);
2994                         el_insertstr(editline, best_match);
2995                         retval = CC_REFRESH;
2996                 }
2997
2998                 if (AST_VECTOR_SIZE(matches) == 2) {
2999                         /* Found an exact match */
3000                         el_insertstr(editline, " ");
3001                         retval = CC_REFRESH;
3002                 } else {
3003                         /* Must be more than one match */
3004                         for (i = 1, maxlen = 0; i < AST_VECTOR_SIZE(matches); i++) {
3005                                 match_len = strlen(AST_VECTOR_GET(matches, i));
3006                                 if (match_len > maxlen) {
3007                                         maxlen = match_len;
3008                                 }
3009                         }
3010
3011                         fprintf(stdout, "\n");
3012                         ast_cli_display_match_list(matches, maxlen);
3013                         retval = CC_REDISPLAY;
3014                 }
3015                 AST_VECTOR_CALLBACK_VOID(matches, ast_free);
3016                 AST_VECTOR_PTR_FREE(matches);
3017         }
3018
3019         *((char *) lf->cursor) = savechr;
3020
3021         return (char *)(long)retval;
3022 }
3023
3024 static int ast_el_initialize(void)
3025 {
3026         HistEvent ev;
3027         char *editor, *editrc = getenv("EDITRC");
3028
3029         if (!(editor = getenv("AST_EDITMODE"))) {
3030                 if (!(editor = getenv("AST_EDITOR"))) {
3031                         editor = "emacs";
3032                 }
3033         }
3034
3035         if (el != NULL)
3036                 el_end(el);
3037         if (el_hist != NULL)
3038                 history_end(el_hist);
3039
3040         el = el_init("asterisk", stdin, stdout, stderr);
3041         el_set(el, EL_PROMPT, cli_prompt);
3042
3043         el_set(el, EL_EDITMODE, 1);
3044         el_set(el, EL_EDITOR, editor);
3045         el_hist = history_init();
3046         if (!el || !el_hist)
3047                 return -1;
3048
3049         /* setup history with 100 entries */
3050         history(el_hist, &ev, H_SETSIZE, 100);
3051
3052         el_set(el, EL_HIST, history, el_hist);
3053
3054         el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
3055         /* Bind <tab> to command completion */
3056         el_set(el, EL_BIND, "^I", "ed-complete", NULL);
3057         /* Bind ? to command completion */
3058         el_set(el, EL_BIND, "?", "ed-complete", NULL);
3059         /* Bind ^D to redisplay */
3060         el_set(el, EL_BIND, "^D", "ed-redisplay", NULL);
3061         /* Bind Delete to delete char left */
3062         el_set(el, EL_BIND, "\\e[3~", "ed-delete-next-char", NULL);
3063         /* Bind Home and End to move to line start and end */
3064         el_set(el, EL_BIND, "\\e[1~", "ed-move-to-beg", NULL);
3065         el_set(el, EL_BIND, "\\e[4~", "ed-move-to-end", NULL);
3066         /* Bind C-left and C-right to move by word (not all terminals) */
3067         el_set(el, EL_BIND, "\\eOC", "vi-next-word", NULL);
3068         el_set(el, EL_BIND, "\\eOD", "vi-prev-word", NULL);
3069
3070         if (editrc) {
3071                 el_source(el, editrc);
3072         }
3073
3074         return 0;
3075 }
3076
3077 #define MAX_HISTORY_COMMAND_LENGTH 256
3078
3079 static int ast_el_add_history(const char *buf)
3080 {
3081         HistEvent ev;
3082         char *stripped_buf;
3083
3084         if (el_hist == NULL || el == NULL) {
3085                 ast_el_initialize();
3086         }
3087         if (strlen(buf) > (MAX_HISTORY_COMMAND_LENGTH - 1)) {
3088                 return 0;
3089         }
3090
3091         stripped_buf = ast_strip(ast_strdupa(buf));
3092
3093         /* HISTCONTROL=ignoredups */
3094         if (!history(el_hist, &ev, H_FIRST) && strcmp(ev.str, stripped_buf) == 0) {
3095                 return 0;
3096         }
3097
3098         return history(el_hist, &ev, H_ENTER, stripped_buf);
3099 }
3100
3101 static int ast_el_write_history(const char *filename)
3102 {
3103         HistEvent ev;
3104
3105         if (el_hist == NULL || el == NULL)
3106                 ast_el_initialize();
3107
3108         return (history(el_hist, &ev, H_SAVE, filename));
3109 }
3110
3111 static int ast_el_read_history(const char *filename)
3112 {
3113         HistEvent ev;
3114
3115         if (el_hist == NULL || el == NULL) {
3116                 ast_el_initialize();
3117         }
3118
3119         return history(el_hist, &ev, H_LOAD, filename);
3120 }
3121
3122 static void ast_el_read_default_histfile(void)
3123 {
3124         char histfile[80] = "";
3125         const char *home = getenv("HOME");
3126
3127         if (!ast_strlen_zero(home)) {
3128                 snprintf(histfile, sizeof(histfile), "%s/.asterisk_history", home);
3129                 ast_el_read_history(histfile);
3130         }
3131 }
3132
3133 static void ast_el_write_default_histfile(void)
3134 {
3135         char histfile[80] = "";
3136         const char *home = getenv("HOME");
3137
3138         if (!ast_strlen_zero(home)) {
3139                 snprintf(histfile, sizeof(histfile), "%s/.asterisk_history", home);
3140                 ast_el_write_history(histfile);
3141         }
3142 }
3143
3144 static void ast_remotecontrol(char *data)
3145 {
3146         char buf[256] = "";
3147         int res;
3148         char *hostname;
3149         char *cpid;
3150         char *version;
3151         int pid;
3152         char *stringp = NULL;
3153
3154         char *ebuf;
3155         int num = 0;
3156
3157         ast_term_init();
3158         printf("%s", term_end());
3159         fflush(stdout);
3160
3161         memset(&sig_flags, 0, sizeof(sig_flags));
3162         signal(SIGINT, __remote_quit_handler);
3163         signal(SIGTERM, __remote_quit_handler);
3164         signal(SIGHUP, __remote_quit_handler);
3165
3166         if (read(ast_consock, buf, sizeof(buf) - 1) < 0) {
3167                 ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
3168                 return;
3169         }
3170         if (data) {
3171                 char prefix[] = "cli quit after ";
3172                 char *tmp = ast_alloca(strlen(data) + strlen(prefix) + 1);
3173                 sprintf(tmp, "%s%s", prefix, data);
3174                 if (write(ast_consock, tmp, strlen(tmp) + 1) < 0) {
3175                         ast_log(LOG_ERROR, "write() failed: %s\n", strerror(errno));
3176                         if (sig_flags.need_quit || sig_flags.need_quit_handler || sig_flags.need_el_end) {
3177                                 return;
3178                         }
3179                 }
3180         }
3181         stringp = buf;
3182         hostname = strsep(&stringp, "/");
3183         cpid = strsep(&stringp, "/");
3184         version = strsep(&stringp, "\n");
3185         if (!version)
3186                 version = "<Version Unknown>";
3187         stringp = hostname;
3188         strsep(&stringp, ".");
3189         if (cpid)
3190                 pid = atoi(cpid);
3191         else
3192                 pid = -1;
3193         if (!data) {
3194                 send_rasterisk_connect_commands();
3195         }
3196
3197         if (ast_opt_exec && data) {  /* hack to print output then exit if asterisk -rx is used */
3198                 int linefull = 1, prev_linefull = 1, prev_line_verbose = 0;
3199                 struct pollfd fds;
3200                 fds.fd = ast_consock;
3201                 fds.events = POLLIN;
3202                 fds.revents = 0;
3203
3204                 while (ast_poll(&fds, 1, 60000) > 0) {
3205                         char buffer[512] = "", *curline = buffer, *nextline;
3206                         int not_written = 1;
3207
3208                         if (sig_flags.need_quit || sig_flags.need_quit_handler || sig_flags.need_el_end) {
3209                                 break;
3210                         }
3211
3212                         if (read(ast_consock, buffer, sizeof(buffer) - 1) <= 0) {
3213                                 break;
3214                         }
3215
3216                         do {
3217                                 prev_linefull = linefull;
3218                                 if ((nextline = strchr(curline, '\n'))) {
3219                                         linefull = 1;
3220                                         nextline++;
3221                                 } else {
3222                                         linefull = 0;
3223                                         nextline = strchr(curline, '\0');
3224                                 }
3225
3226                                 /* Skip verbose lines */
3227                                 /* Prev line full? | Line is verbose | Last line verbose? | Print
3228                                  * TRUE            | TRUE*           | TRUE               | FALSE
3229                                  * TRUE            | TRUE*           | FALSE              | FALSE
3230                                  * TRUE            | FALSE*          | TRUE               | TRUE
3231                                  * TRUE            | FALSE*          | FALSE              | TRUE
3232                                  * FALSE           | TRUE            | TRUE*              | FALSE
3233                                  * FALSE           | TRUE            | FALSE*             | TRUE
3234                                  * FALSE           | FALSE           | TRUE*              | FALSE
3235                                  * FALSE           | FALSE           | FALSE*             | TRUE
3236                                  */
3237                                 if ((!prev_linefull && !prev_line_verbose) || (prev_linefull && *curline > 0)) {
3238                                         prev_line_verbose = 0;
3239                                         not_written = 0;
3240                                         if (write(STDOUT_FILENO, curline, nextline - curline) < 0) {
3241                                                 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
3242                                         }
3243                                 } else {
3244                                         prev_line_verbose = 1;
3245                                 }
3246                                 curline = nextline;
3247                         } while (!ast_strlen_zero(curline));
3248
3249                         /* No non-verbose output in 60 seconds. */
3250                         if (not_written) {
3251                                 break;
3252                         }
3253                 }
3254                 return;
3255         }
3256
3257         ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
3258         remotehostname = hostname;
3259         if (el_hist == NULL || el == NULL)
3260                 ast_el_initialize();
3261         ast_el_read_default_histfile();
3262
3263         el_set(el, EL_GETCFN, ast_el_read_char);
3264
3265         for (;;) {
3266                 ebuf = (char *)el_gets(el, &num);
3267
3268                 if (sig_flags.need_quit || sig_flags.need_quit_handler || sig_flags.need_el_end) {
3269                         break;
3270                 }
3271
3272                 if (!ebuf && write(1, "", 1) < 0)
3273                         break;
3274
3275                 if (!ast_strlen_zero(ebuf)) {
3276                         if (ebuf[strlen(ebuf)-1] == '\n')
3277                                 ebuf[strlen(ebuf)-1] = '\0';
3278                         if (!remoteconsolehandler(ebuf)) {
3279                                 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
3280                                 if (res < 1) {
3281                                         ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
3282                                         break;
3283                                 }
3284                         }
3285                 }
3286         }
3287         printf("\nDisconnected from Asterisk server\n");
3288 }
3289
3290 static int show_version(void)
3291 {
3292         printf("Asterisk %s\n", ast_get_version());
3293         return 0;
3294 }
3295
3296 static int show_cli_help(void)
3297 {
3298         printf("Asterisk %s, " COPYRIGHT_TAG "\n", ast_get_version());
3299         printf("Usage: asterisk [OPTIONS]\n");
3300         printf("Valid Options:\n");
3301         printf("   -V              Display version number and exit\n");
3302         printf("   -C <configfile> Use an alternate configuration file\n");
3303         printf("   -G <group>      Run as a group other than the caller\n");
3304         printf("   -U <user>       Run as a user other than the caller\n");
3305         printf("   -c              Provide console CLI\n");
3306         printf("   -d              Increase debugging (multiple d's = more debugging)\n");
3307 #if HAVE_WORKING_FORK
3308         printf("   -f              Do not fork\n");
3309         printf("   -F              Always fork\n");
3310 #endif
3311         printf("   -g              Dump core in case of a crash\n");
3312         printf("   -h              This help screen\n");
3313         printf("   -i              Initialize crypto keys at startup\n");
3314         printf("   -L <load>       Limit the maximum load average before rejecting new calls\n");
3315         printf("   -M <value>      Limit the maximum number of calls to the specified value\n");
3316         printf("   -m              Mute debugging and console output on the console\n");
3317         printf("   -n              Disable console colorization\n");
3318         printf("   -p              Run as pseudo-realtime thread\n");
3319         printf("   -q              Quiet mode (suppress output)\n");
3320         printf("   -r              Connect to Asterisk on this machine\n");
3321         printf("   -R              Same as -r, except attempt to reconnect if disconnected\n");
3322         printf("   -s <socket>     Connect to Asterisk via socket <socket> (only valid with -r)\n");
3323         printf("   -t              Record soundfiles in /var/tmp and move them where they\n");
3324         printf("                   belong after they are done\n");
3325         printf("   -T              Display the time in [Mmm dd hh:mm:ss] format for each line\n");
3326         printf("                   of output to the CLI\n");
3327         printf("   -v              Increase verbosity (multiple v's = more verbose)\n");
3328         printf("   -x <cmd>        Execute command <cmd> (implies -r)\n");
3329         printf("   -X              Enable use of #exec in asterisk.conf\n");
3330         printf("   -W              Adjust terminal colors to compensate for a light background\n");
3331         printf("\n");
3332         return 0;
3333 }
3334
3335 static void read_pjproject_startup_options(void)
3336 {
3337         struct ast_config *cfg;
3338         struct ast_variable *v;
3339         struct ast_flags config_flags = { CONFIG_FLAG_NOCACHE | CONFIG_FLAG_NOREALTIME };
3340
3341         ast_option_pjproject_log_level = DEFAULT_PJ_LOG_MAX_LEVEL;
3342         ast_option_pjproject_cache_pools = DEFAULT_PJPROJECT_CACHE_POOLS;
3343
3344         cfg = ast_config_load2("pjproject.conf", "" /* core, can't reload */, config_flags);
3345         if (!cfg
3346                 || cfg == CONFIG_STATUS_FILEUNCHANGED
3347                 || cfg == CONFIG_STATUS_FILEINVALID) {
3348                 /* We'll have to use defaults */
3349                 return;
3350         }
3351
3352         for (v = ast_variable_browse(cfg, "startup"); v; v = v->next) {
3353                 if (!strcasecmp(v->name, "log_level")) {
3354                         if (sscanf(v->value, "%30d", &ast_option_pjproject_log_level) != 1) {
3355                                 ast_option_pjproject_log_level = DEFAULT_PJ_LOG_MAX_LEVEL;
3356                         } else if (ast_option_pjproject_log_level < 0) {
3357                                 ast_option_pjproject_log_level = 0;
3358                         } else if (MAX_PJ_LOG_MAX_LEVEL < ast_option_pjproject_log_level) {
3359                                 ast_option_pjproject_log_level = MAX_PJ_LOG_MAX_LEVEL;
3360                         }
3361                 } else if (!strcasecmp(v->name, "cache_pools")) {
3362                         ast_option_pjproject_cache_pools = !ast_false(v->value);
3363                 }
3364         }
3365
3366         ast_config_destroy(cfg);
3367 }
3368
3369 static void *monitor_sig_flags(void *unused)
3370 {
3371         for (;;) {
3372                 struct pollfd p = { sig_alert_pipe[0], POLLIN, 0 };
3373
3374                 ast_poll(&p, 1, -1);
3375                 if (sig_flags.need_reload) {
3376                         sig_flags.need_reload = 0;
3377                         ast_module_reload(NULL);
3378                 }
3379                 if (sig_flags.need_quit) {
3380                         sig_flags.need_quit = 0;
3381                         if ((consolethread != AST_PTHREADT_NULL) && (consolethread != pthread_self())) {
3382                                 sig_flags.need_quit_handler = 1;
3383                                 pthread_kill(consolethread, SIGURG);
3384                         } else {
3385                                 quit_handler(0, SHUTDOWN_NORMAL, 0);
3386                         }
3387                 }
3388                 ast_alertpipe_read(sig_alert_pipe);
3389         }
3390
3391         return NULL;
3392 }
3393
3394 static void *canary_thread(void *unused)
3395 {
3396         struct stat canary_stat;
3397         struct timeval now;
3398
3399         /* Give the canary time to sing */
3400         sleep(120);
3401
3402         for (;;) {
3403                 now = ast_tvnow();
3404                 if (stat(canary_filename, &canary_stat) || now.tv_sec > canary_stat.st_mtime + 60) {
3405                         ast_log(LOG_WARNING,
3406                                 "The canary is no more.  He has ceased to be!  "
3407                                 "He's expired and gone to meet his maker!  "
3408                                 "He's a stiff!  Bereft of life, he rests in peace.  "
3409                                 "His metabolic processes are now history!  He's off the twig!  "
3410                                 "He's kicked the bucket.  He's shuffled off his mortal coil, "
3411                                 "run down the curtain, and joined the bleeding choir invisible!!  "
3412                                 "THIS is an EX-CANARY.  (Reducing priority)\n");
3413                         set_priority_all(0);
3414                         pthread_exit(NULL);
3415                 }
3416
3417                 /* Check the canary once a minute */
3418                 sleep(60);
3419         }
3420 }
3421
3422 /* Used by libc's atexit(3) function */
3423 static void canary_exit(void)
3424 {
3425         if (canary_pid > 0) {
3426                 int status;
3427                 kill(canary_pid, SIGKILL);
3428                 waitpid(canary_pid, &status, 0);
3429         }
3430 }
3431
3432 /* Execute CLI commands on startup.  Run by main() thread. */
3433 static void run_startup_commands(void)
3434 {
3435         int fd;
3436         struct ast_config *cfg;
3437         struct ast_flags cfg_flags = { 0 };
3438         struct ast_variable *v;
3439
3440         if (!(cfg = ast_config_load2("cli.conf", "" /* core, can't reload */, cfg_flags)))
3441                 return;
3442         if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
3443                 return;
3444         }
3445
3446         fd = open("/dev/null", O_RDWR);
3447         if (fd < 0) {
3448                 ast_config_destroy(cfg);
3449                 return;
3450         }
3451
3452         for (v = ast_variable_browse(cfg, "startup_commands"); v; v = v->next) {
3453                 if (ast_true(v->value))
3454                         ast_cli_command(fd, v->name);
3455         }
3456
3457         close(fd);
3458         ast_config_destroy(cfg);
3459 }
3460
3461 static void env_init(void)
3462 {
3463         setenv("AST_SYSTEMNAME", ast_config_AST_SYSTEM_NAME, 1);
3464         setenv("AST_BUILD_HOST", ast_build_hostname, 1);
3465         setenv("AST_BUILD_DATE", ast_build_date, 1);
3466         setenv("AST_BUILD_KERNEL", ast_build_kernel, 1);
3467         setenv("AST_BUILD_MACHINE", ast_build_machine, 1);
3468         setenv("AST_BUILD_OS", ast_build_os, 1);
3469         setenv("AST_BUILD_USER", ast_build_user, 1);
3470         setenv("AST_VERSION", ast_get_version(), 1);
3471 }
3472
3473 static void print_intro_message(const char *runuser, const char *rungroup)
3474 {
3475         if (ast_opt_console || option_verbose || (ast_opt_remote && !ast_opt_exec)) {
3476                 WELCOME_MESSAGE;
3477                 if (runuser) {
3478                         ast_verbose("Running as user '%s'\n", runuser);
3479                 }
3480                 if (rungroup) {
3481                         ast_verbose("Running under group '%s'\n", rungroup);
3482                 }
3483         }
3484 }
3485
3486 static void main_atexit(void)
3487 {
3488         ast_cli_unregister_multiple(cli_asterisk, ARRAY_LEN(cli_asterisk));
3489 }
3490
3491 int main(int argc, char *argv[])
3492 {
3493         int c;
3494         int x;
3495         int isroot = 1, rundir_exists = 0;
3496         RAII_VAR(char *, runuser, NULL, ast_free);
3497         RAII_VAR(char *, rungroup, NULL, ast_free);
3498         RAII_VAR(char *, xarg, NULL, ast_free);
3499         struct rlimit l;
3500         static const char *getopt_settings = "BC:cde:FfG:ghIiL:M:mnpqRrs:TtU:VvWXx:";
3501
3502         /* Remember original args for restart */
3503         if (argc > ARRAY_LEN(_argv) - 1) {
3504                 fprintf(stderr, "Truncating argument size to %d\n", (int)ARRAY_LEN(_argv) - 1);
3505                 argc = ARRAY_LEN(_argv) - 1;
3506         }
3507         for (x = 0; x < argc; x++)
3508                 _argv[x] = argv[x];
3509         _argv[x] = NULL;
3510
3511         if (geteuid() != 0)
3512                 isroot = 0;
3513
3514         /* if the progname is rasterisk consider it a remote console */
3515         if (argv[0] && (strstr(argv[0], "rasterisk")) != NULL) {
3516                 ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK | AST_OPT_FLAG_REMOTE);
3517         }
3518         ast_mainpid = getpid();
3519
3520         /* Process command-line options that effect asterisk.conf load. */
3521         while ((c = getopt(argc, argv, getopt_settings)) != -1) {
3522                 switch (c) {
3523                 case 'X':
3524                         ast_set_flag(&ast_options, AST_OPT_FLAG_EXEC_INCLUDES);
3525                         break;
3526                 case 'C':
3527                         set_asterisk_conf_path(optarg);
3528                         break;
3529                 case 'd':
3530                         option_debug++;
3531                         break;
3532                 case 'h':
3533                         show_cli_help();
3534                         exit(0);
3535                 case 'R':
3536                 case 'r':
3537                 case 'x':
3538                         /* ast_opt_remote is checked during config load.  This is only part of what
3539                          * these options do, see the second loop for the rest of the actions. */
3540                         ast_set_flag(&ast_options, AST_OPT_FLAG_REMOTE);
3541                         break;
3542                 case 'V':
3543                         show_version();
3544                         exit(0);
3545                 case 'v':
3546                         option_verbose++;
3547                         break;
3548                 case '?':
3549                         exit(1);
3550                 }
3551         }
3552
3553         /* Initialize env so it is available if #exec is used in asterisk.conf. */
3554         env_init();
3555
3556         load_asterisk_conf();
3557
3558         /* Update env to include any systemname that was set. */
3559         env_init();
3560
3561         /*! \brief Check for options
3562          *
3563          * \todo Document these options
3564          */
3565         optind = 1;
3566         while ((c = getopt(argc, argv, getopt_settings)) != -1) {
3567                 /*!\note Please keep the ordering here to alphabetical, capital letters
3568                  * first.  This will make it easier in the future to select unused
3569                  * option flags for new features. */
3570                 switch (c) {
3571                 case 'B': /* Force black background */
3572                         ast_set_flag(&ast_options, AST_OPT_FLAG_FORCE_BLACK_BACKGROUND);
3573                         ast_clear_flag(&ast_options, AST_OPT_FLAG_LIGHT_BACKGROUND);
3574                         break;
3575                 case 'X':
3576                         /* The command-line -X option enables #exec for asterisk.conf only. */
3577                         break;
3578                 case 'C':
3579                         /* already processed. */
3580                         break;
3581                 case 'c':
3582                         ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK | AST_OPT_FLAG_CONSOLE);
3583                         break;
3584                 case 'd':
3585                         /* already processed. */
3586                         break;
3587 #if defined(HAVE_SYSINFO)
3588                 case 'e':
3589                         if ((sscanf(&optarg[1], "%30ld", &option_minmemfree) != 1) || (option_minmemfree < 0)) {
3590                                 option_minmemfree = 0;
3591                         }
3592                         break;
3593 #endif
3594 #if HAVE_WORKING_FORK
3595                 case 'F':
3596                         ast_set_flag(&ast_options, AST_OPT_FLAG_ALWAYS_FORK);
3597                         break;
3598                 case 'f':
3599                         ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK);
3600                         break;
3601 #endif
3602                 case 'G':
3603                         rungroup = ast_strdup(optarg);
3604                         break;
3605                 case 'g':
3606                         ast_set_flag(&ast_options, AST_OPT_FLAG_DUMP_CORE);
3607                         break;
3608                 case 'h':
3609                         /* already processed. */
3610                         break;
3611                 case 'I':
3612                         fprintf(stderr,
3613                                 "NOTICE: The -I option is no longer needed.\n"
3614                                 "  It will always be enabled if you have a timing module loaded.\n");
3615                         break;
3616                 case 'i':
3617                         ast_set_flag(&ast_options, AST_OPT_FLAG_INIT_KEYS);
3618                         break;
3619                 case 'L':
3620                         if ((sscanf(optarg, "%30lf", &ast_option_maxload) != 1) || (ast_option_maxload < 0.0)) {
3621                                 ast_option_maxload = 0.0;
3622                         }
3623                         break;
3624                 case 'M':
3625                         if ((sscanf(optarg, "%30d", &ast_option_maxcalls) != 1) || (ast_option_maxcalls < 0)) {
3626                                 ast_option_maxcalls = 0;
3627                         }
3628                         break;
3629                 case 'm':
3630                         ast_set_flag(&ast_options, AST_OPT_FLAG_MUTE);
3631                         break;
3632                 case 'n':
3633                         ast_set_flag(&ast_options, AST_OPT_FLAG_NO_COLOR);
3634                         break;
3635                 case 'p':
3636                         ast_set_flag(&ast_options, AST_OPT_FLAG_HIGH_PRIORITY);
3637                         break;
3638                 case 'q':
3639                         ast_set_flag(&ast_options, AST_OPT_FLAG_QUIET);
3640                         break;
3641                 case 'R':
3642                         ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK | AST_OPT_FLAG_REMOTE | AST_OPT_FLAG_RECONNECT);
3643                         break;
3644                 case 'r':
3645                         ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK | AST_OPT_FLAG_REMOTE);
3646                         break;
3647                 case 's':
3648                         if (ast_opt_remote) {
3649                                 set_socket_path(optarg);
3650                         }
3651                         break;
3652                 case 'T':
3653                         ast_set_flag(&ast_options, AST_OPT_FLAG_TIMESTAMP);
3654                         break;
3655                 case 't':
3656                         ast_set_flag(&ast_options, AST_OPT_FLAG_CACHE_RECORD_FILES);
3657                         break;
3658                 case 'U':
3659                         runuser = ast_strdup(optarg);
3660                         break;
3661                 case 'V':
3662                 case 'v':
3663                         /* already processed. */
3664                         break;
3665                 case 'W': /* White background */
3666                         ast_set_flag(&ast_options, AST_OPT_FLAG_LIGHT_BACKGROUND);
3667                         ast_clear_flag(&ast_options, AST_OPT_FLAG_FORCE_BLACK_BACKGROUND);
3668                         break;
3669                 case 'x':
3670                         /* -r is implied by -x so set the flags -r sets as well. */
3671                         ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK | AST_OPT_FLAG_REMOTE);
3672
3673                         ast_set_flag(&ast_options, AST_OPT_FLAG_EXEC | AST_OPT_FLAG_NO_COLOR);
3674                         xarg = ast_strdup(optarg);
3675                         break;
3676                 case '?':
3677                         /* already processed. */
3678                         break;
3679                 }
3680         }
3681
3682         /* For remote connections, change the name of the remote connection.
3683          * We do this for the benefit of init scripts (which need to know if/when
3684          * the main asterisk process has died yet). */
3685         if (ast_opt_remote) {
3686                 strcpy(argv[0], "rasterisk");
3687                 for (x = 1; x < argc; x++) {
3688                         argv[x] = argv[0] + 10;
3689                 }
3690         }
3691
3692         if (!ast_language_is_prefix && !ast_opt_remote) {
3693                 fprintf(stderr, "The 'languageprefix' option in asterisk.conf is deprecated; in a future release it will be removed, and your sound files will need to be organized in the 'new style' language layout.\n");
3694         }
3695
3696         if (ast_opt_always_fork && (ast_opt_remote || ast_opt_console)) {
3697                 fprintf(stderr, "'alwaysfork' is not compatible with console or remote console mode; ignored\n");
3698                 ast_clear_flag(&ast_options, AST_OPT_FLAG_ALWAYS_FORK);
3699         }
3700
3701         if (ast_opt_dump_core) {
3702                 memset(&l, 0, sizeof(l));
3703                 l.rlim_cur = RLIM_INFINITY;
3704                 l.rlim_max = RLIM_INFINITY;
3705                 if (setrlimit(RLIMIT_CORE, &l)) {
3706                         fprintf(stderr, "Unable to disable core size resource limit: %s\n", strerror(errno));
3707                 }
3708         }
3709
3710         if (getrlimit(RLIMIT_NOFILE, &l)) {
3711                 fprintf(stderr, "Unable to check file descriptor limit: %s\n", strerror(errno));
3712         }
3713
3714 #if !defined(CONFIGURE_RAN_AS_ROOT)
3715         /* Check if select(2) will run with more file descriptors */
3716         do {
3717                 int fd, fd2;
3718                 ast_fdset readers;
3719                 struct timeval tv = { 0, };
3720
3721                 if (l.rlim_cur <= FD_SETSIZE) {
3722                         /* The limit of select()able FDs is irrelevant, because we'll never
3723                          * open one that high. */
3724                         break;
3725                 }
3726
3727                 if (!(fd = open("/dev/null", O_RDONLY))) {
3728                         fprintf(stderr, "Cannot open a file descriptor at boot? %s\n", strerror(errno));
3729                         break; /* XXX Should we exit() here? XXX */
3730                 }
3731
3732                 fd2 = ((l.rlim_cur > sizeof(readers) * 8) ? sizeof(readers) * 8 : l.rlim_cur) - 1;
3733                 if (dup2(fd, fd2) < 0) {
3734                         fprintf(stderr, "Cannot open maximum file descriptor %d at boot? %s\n", fd2, strerror(errno));
3735                         close(fd);
3736                         break;
3737                 }
3738
3739                 FD_ZERO(&readers);
3740                 FD_SET(fd2, &readers);
3741                 if (ast_select(fd2 + 1, &readers, NULL, NULL, &tv) < 0) {
3742                         fprintf(stderr, "Maximum select()able file descriptor is %d\n", FD_SETSIZE);
3743                 }
3744                 ast_FD_SETSIZE = l.rlim_cur > ast_FDMAX ? ast_FDMAX : l.rlim_cur;
3745                 close(fd);
3746                 close(fd2);
3747         } while (0);
3748 #elif defined(HAVE_VARIABLE_FDSET)
3749         ast_FD_SETSIZE = l.rlim_cur > ast_FDMAX ? ast_FDMAX : l.rlim_cur;
3750 #endif /* !defined(CONFIGURE_RAN_AS_ROOT) */
3751
3752         if ((!rungroup) && !ast_strlen_zero(ast_config_AST_RUN_GROUP))
3753                 rungroup = ast_strdup(ast_config_AST_RUN_GROUP);
3754         if ((!runuser) && !ast_strlen_zero(ast_config_AST_RUN_USER))
3755                 runuser = ast_strdup(ast_config_AST_RUN_USER);
3756
3757         /* Must install this signal handler up here to ensure that if the canary
3758          * fails to execute that it doesn't kill the Asterisk process.
3759          */
3760         sigaction(SIGCHLD, &child_handler, NULL);
3761
3762         /* It's common on some platforms to clear /var/run at boot.  Create the
3763          * socket file directory before we drop privileges. */
3764         if (mkdir(ast_config_AST_RUN_DIR, 0755)) {
3765                 if (errno == EEXIST) {
3766                         rundir_exists = 1;
3767                 } else {
3768                         fprintf(stderr, "Unable to create socket file directory.  Remote consoles will not be able to connect! (%s)\n", strerror(x));
3769                 }
3770         }
3771
3772 #ifndef __CYGWIN__
3773
3774         if (isroot) {
3775                 ast_set_priority(ast_opt_high_priority);
3776         }
3777
3778         if (isroot && rungroup) {
3779                 struct group *gr;
3780                 gr = getgrnam(rungroup);
3781                 if (!gr) {
3782                         fprintf(stderr, "No such group '%s'!\n", rungroup);
3783                         exit(1);
3784                 }
3785                 if (!rundir_exists && chown(ast_config_AST_RUN_DIR, -1, gr->gr_gid)) {
3786                         fprintf(stderr, "Unable to chgrp run directory to %d (%s)\n", (int) gr->gr_gid, rungroup);
3787                 }
3788                 if (setgid(gr->gr_gid)) {
3789                         fprintf(stderr, "Unable to setgid to %d (%s)\n", (int)gr->gr_gid, rungroup);
3790                         exit(1);
3791                 }
3792                 if (setgroups(0, NULL)) {
3793                         fprintf(stderr, "Unable to drop unneeded groups\n");
3794                         exit(1);
3795                 }
3796         }
3797
3798         if (runuser && !ast_test_flag(&ast_options, AST_OPT_FLAG_REMOTE)) {
3799 #ifdef HAVE_CAP
3800                 int has_cap = 1;
3801 #endif /* HAVE_CAP */
3802                 struct passwd *pw;
3803                 pw = getpwnam(runuser);
3804                 if (!pw) {
3805                         fprintf(stderr, "No such user '%s'!\n", runuser);
3806                         exit(1);
3807                 }
3808                 if (chown(ast_config_AST_RUN_DIR, pw->pw_uid, -1)) {
3809                         fprintf(stderr, "Unable to chown run directory to %d (%s)\n", (int) pw->pw_uid, runuser);
3810                 }
3811 #ifdef HAVE_CAP
3812                 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0)) {
3813                         ast_log(LOG_WARNING, "Unable to keep capabilities.\n");
3814                         has_cap = 0;
3815                 }
3816 #endif /* HAVE_CAP */
3817                 if (!isroot && pw->pw_uid != geteuid()) {
3818                         fprintf(stderr, "Asterisk started as nonroot, but runuser '%s' requested.\n", runuser);
3819                         exit(1);
3820                 }
3821                 if (!rungroup) {
3822                         if (setgid(pw->pw_gid)) {
3823                                 fprintf(stderr, "Unable to setgid to %d!\n", (int)pw->pw_gid);
3824                                 exit(1);
3825                         }
3826                         if (isroot && initgroups(pw->pw_name, pw->pw_gid)) {
3827                                 fprintf(stderr, "Unable to init groups for '%s'\n", runuser);
3828                                 exit(1);
3829                         }
3830                 }
3831                 if (setuid(pw->pw_uid)) {
3832                         fprintf(stderr, "Unable to setuid to %d (%s)\n", (int)pw->pw_uid, runuser);
3833                         exit(1);
3834                 }
3835 #ifdef HAVE_CAP
3836                 if (has_cap) {
3837                         cap_t cap;
3838
3839                         cap = cap_from_text("cap_net_admin=eip");
3840
3841                         if (cap_set_proc(cap)) {
3842                                 fprintf(stderr, "Unable to install capabilities.\n");
3843                         }
3844                         if (cap_free(cap)) {
3845                                 fprintf(stderr, "Unable to drop capabilities.\n");
3846                         }
3847                 }
3848 #endif /* HAVE_CAP */
3849         }
3850
3851 #endif /* __CYGWIN__ */
3852
3853 #ifdef linux
3854         if (geteuid() && ast_opt_dump_core) {
3855                 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) < 0) {
3856                         fprintf(stderr, "Unable to set the process for core dumps after changing to a non-root user. %s\n", strerror(errno));
3857                 }
3858         }
3859 #endif
3860
3861         {
3862 #if defined(HAVE_EACCESS) || defined(HAVE_EUIDACCESS)
3863 #if defined(HAVE_EUIDACCESS) && !defined(HAVE_EACCESS)
3864 #define eaccess euidaccess
3865 #endif
3866                 char dir[PATH_MAX];
3867                 if (!getcwd(dir, sizeof(dir)) || eaccess(dir, R_OK | X_OK | F_OK)) {
3868                         fprintf(stderr, "Unable to access the running directory (%s).  Changing to '/' for compatibility.\n", strerror(errno));
3869                         /* If we cannot access the CWD, then we couldn't dump core anyway,
3870                          * so chdir("/") won't break anything. */
3871                         if (chdir("/")) {
3872                                 /* chdir(/) should never fail, so this ends up being a no-op */
3873                                 fprintf(stderr, "chdir(\"/\") failed?!! %s\n", strerror(errno));
3874                         }
3875                 } else
3876 #endif /* defined(HAVE_EACCESS) || defined(HAVE_EUIDACCESS) */
3877                 if (!ast_opt_no_fork && !ast_opt_dump_core) {
3878                         /* Backgrounding, but no cores, so chdir won't break anything. */
3879                         if (chdir("/")) {
3880                                 fprintf(stderr, "Unable to chdir(\"/\") ?!! %s\n", strerror(errno));
3881                         }
3882                 }
3883         }
3884
3885         /* Initial value of the maximum active system verbosity level. */
3886         ast_verb_sys_level = option_verbose;
3887
3888         if (ast_sd_get_fd_un(SOCK_STREAM, ast_config_AST_SOCKET) > 0) {
3889                 ast_socket_is_sd = 1;
3890         }
3891
3892         /* DO NOT perform check for existing daemon if systemd has CLI socket activation */
3893         if (!ast_socket_is_sd && ast_tryconnect()) {
3894                 /* One is already running */
3895                 if (ast_opt_remote) {
3896                         multi_thread_safe = 1;
3897                         if (ast_opt_exec) {
3898                                 ast_remotecontrol(xarg);
3899                                 quit_handler(0, SHUTDOWN_FAST, 0);
3900                                 exit(0);
3901                         }
3902                         ast_term_init();
3903                         printf("%s", term_end());
3904                         fflush(stdout);
3905
3906                         print_intro_message(runuser, rungroup);
3907                         printf("%s", term_quit());
3908                         ast_remotecontrol(NULL);
3909                         quit_handler(0, SHUTDOWN_FAST, 0);
3910                         exit(0);
3911                 } else {
3912                         fprintf(stderr, "Asterisk already running on %s.  Use 'asterisk -r' to connect.\n", ast_config_AST_SOCKET);
3913                         printf("%s", term_quit());
3914                         exit(1);
3915                 }
3916         } else if (ast_opt_remote || ast_opt_exec) {
3917                 fprintf(stderr, "Unable to connect to remote asterisk (does %s exist?)\n", ast_config_AST_SOCKET);
3918                 printf("%s", term_quit());
3919                 exit(1);
3920         }
3921
3922         /* Not a remote console? Start the daemon. */
3923         asterisk_daemon(isroot, runuser, rungroup);
3924         return 0;
3925 }
3926
3927 static inline void check_init(int init_result, const char *name)
3928 {
3929         if (init_result) {
3930                 if (ast_is_logger_initialized()) {
3931                         ast_log(LOG_ERROR, "%s initialization failed.  ASTERISK EXITING!\n%s", name, term_quit());
3932                 } else {
3933                         fprintf(stderr, "%s initialization failed.  ASTERISK EXITING!\n%s", name, term_quit());
3934                 }
3935                 ast_run_atexits(0);
3936                 exit(init_result == -2 ? 2 : 1);
3937         }
3938 }
3939
3940 static void asterisk_daemon(int isroot, const char *runuser, const char *rungroup)
3941 {
3942         FILE *f;
3943         sigset_t sigs;
3944         int num;
3945         char *buf;
3946         char pbx_uuid[AST_UUID_STR_LEN];
3947
3948         /* Set time as soon as possible */
3949         ast_lastreloadtime = ast_startuptime = ast_tvnow();
3950
3951         /* This needs to remain as high up in the initial start up as possible.
3952          * daemon causes a fork to occur, which has all sorts of unintended
3953          * consequences for things that interact with threads.  This call *must*
3954          * occur before anything in Asterisk spawns or manipulates thread related
3955          * primitives. */
3956 #if HAVE_WORKING_FORK
3957         if (ast_opt_always_fork || !ast_opt_no_fork) {
3958 #ifndef HAVE_SBIN_LAUNCHD
3959                 if (daemon(1, 0) < 0) {
3960                         fprintf(stderr, "daemon() failed: %s\n", strerror(errno));
3961                 } else {
3962                         ast_mainpid = getpid();
3963                 }
3964 #else
3965                 fprintf(stderr, "Mac OS X detected.  Use 'launchctl load /Library/LaunchDaemon/org.asterisk.asterisk.plist'.\n");
3966 #endif
3967         }
3968 #endif
3969
3970         /* At this point everything has been forked successfully,
3971          * we have determined that we aren't attempting to connect to
3972          * an Asterisk instance, and that there isn't one already running. */
3973         multi_thread_safe = 1;
3974
3975         load_astmm_phase_1();
3976
3977         /* Check whether high prio was succesfully set by us or some
3978          * other incantation. */
3979         if (has_priority()) {
3980                 ast_set_flag(&ast_options, AST_OPT_FLAG_HIGH_PRIORITY);
3981         } else {
3982                 ast_clear_flag(&ast_options, AST_OPT_FLAG_HIGH_PRIORITY);
3983         }
3984
3985         /* Spawning of astcanary must happen AFTER the call to daemon(3) */
3986         if (ast_opt_high_priority) {
3987                 snprintf(canary_filename, sizeof(canary_filename), "%s/alt.asterisk.canary.tweet.tweet.tweet", ast_config_AST_RUN_DIR);
3988
3989                 /* Don't let the canary child kill Asterisk, if it dies immediately */
3990                 sigaction(SIGPIPE, &ignore_sig_handler, NULL);
3991
3992                 canary_pid = fork();
3993                 if (canary_pid == 0) {
3994                         char canary_binary[PATH_MAX], ppid[12];
3995
3996                         /* Reset signal handler */
3997                         signal(SIGCHLD, SIG_DFL);
3998                         signal(SIGPIPE, SIG_DFL);
3999
4000                         ast_close_fds_above_n(0);
4001                         ast_set_priority(0);
4002                         snprintf(ppid, sizeof(ppid), "%d", (int) ast_mainpid);
4003
4004                         /* Use the astcanary binary that we installed */
4005                         snprintf(canary_binary, sizeof(canary_binary), "%s/astcanary", ast_config_AST_SBIN_DIR);
4006                         execl(canary_binary, "astcanary", canary_filename, ppid, (char *)NULL);
4007
4008                         /* Should never happen */
4009                         _exit(1);
4010                 } else if (canary_pid > 0) {
4011                         pthread_t dont_care;
4012                         ast_pthread_create_detached(&dont_care, NULL, canary_thread, NULL);
4013                 }
4014
4015                 /* Kill the canary when we exit */
4016                 ast_register_atexit(canary_exit);
4017         }
4018
4019         /* Blindly write the PID file. */
4020         unlink(ast_config_AST_PID);
4021         f = fopen(ast_config_AST_PID, "w");
4022         if (f) {
4023                 fprintf(f, "%ld\n", (long)ast_mainpid);
4024                 fclose(f);
4025         } else {
4026                 fprintf(stderr, "Unable to open pid file '%s': %s\n", ast_config_AST_PID, strerror(errno));
4027         }
4028
4029         /* Initialize the terminal.  Since all processes have been forked,
4030          * we can now start using the standard log messages.
4031          */
4032         ast_term_init();
4033         printf("%s", term_end());
4034         fflush(stdout);
4035
4036         print_intro_message(runuser, rungroup);
4037
4038         register_config_cli();
4039
4040         check_init(astobj2_init(), "AO2");
4041         check_init(ast_named_locks_init(), "Named Locks");
4042
4043         if (ast_opt_console) {
4044                 if (el_hist == NULL || el == NULL)
4045                         ast_el_initialize();
4046                 ast_el_read_default_histfile();
4047         }
4048
4049 #ifdef AST_XML_DOCS
4050         /* Load XML documentation. */
4051         ast_xmldoc_load_documentation();
4052 #endif
4053
4054         check_init(astdb_init(), "ASTdb");
4055
4056         ast_uuid_init();
4057
4058         if (ast_pbx_uuid_get(pbx_uuid, sizeof(pbx_uuid))) {
4059                 ast_uuid_generate_str(pbx_uuid, sizeof(pbx_uuid));
4060                 ast_db_put("pbx", "UUID", pbx_uuid);
4061         }
4062         ast_verb(0, "PBX UUID: %s\n", pbx_uuid);
4063
4064         check_init(ast_json_init(), "libjansson");
4065         ast_ulaw_init();
4066         ast_alaw_init();
4067         tdd_init();
4068         callerid_init();
4069         ast_builtins_init();
4070
4071         check_init(ast_utils_init(), "Utilities");
4072         check_init(ast_tps_init(), "Task Processor Core");
4073         check_init(ast_fd_init(), "File Descriptor Debugging");
4074         check_init(ast_pbx_init(), "ast_pbx_init");
4075         check_init(aco_init(), "Configuration Option Framework");
4076         check_init(stasis_init(), "Stasis");
4077 #ifdef TEST_FRAMEWORK
4078         check_init(ast_test_init(), "Test Framework");
4079 #endif
4080         check_init(ast_translate_init(), "Translator Core");
4081
4082         ast_aoc_cli_init();
4083
4084         check_init(ast_sorcery_init(), "Sorcery");
4085         check_init(ast_codec_init(), "Codecs");
4086         check_init(ast_format_init(), "Formats");
4087         check_init(ast_format_cache_init(), "Format Cache");
4088         check_init(ast_codec_builtin_init(), "Built-in Codecs");
4089         check_init(ast_bucket_init(), "Bucket API");
4090         check_init(ast_stasis_system_init(), "Stasis system-level information");
4091         check_init(ast_endpoint_stasis_init(), "Stasis Endpoint");
4092
4093         ast_makesocket();
4094         /* GCC 4.9 gives a bogus "right-hand operand of comma expression has
4095          * no effect" warning */
4096         (void) sigemptyset(&sigs);
4097         (void) sigaddset(&sigs, SIGHUP);
4098         (void) sigaddset(&sigs, SIGTERM);
4099         (void) sigaddset(&sigs, SIGINT);
4100         (void) sigaddset(&sigs, SIGPIPE);
4101         (void) sigaddset(&sigs, SIGWINCH);
4102         pthread_sigmask(SIG_BLOCK, &sigs, NULL);
4103         sigaction(SIGURG, &urg_handler, NULL);
4104         signal(SIGINT, __quit_handler);
4105         signal(SIGTERM, __quit_handler);
4106         sigaction(SIGHUP, &hup_handler, NULL);
4107         sigaction(SIGPIPE, &ignore_sig_handler, NULL);
4108
4109         /* ensure that the random number generators are seeded with a different value every time
4110            Asterisk is started
4111         */
4112         srand((unsigned int) getpid() + (unsigned int) time(NULL));
4113         initstate((unsigned int) getpid() * 65536 + (unsigned int) time(NULL), randompool, sizeof(randompool));
4114
4115         threadstorage_init();
4116
4117         check_init(init_logger(), "Logger");
4118         check_init(ast_rtp_engine_init(), "RTP Engine");
4119
4120         ast_autoservice_init();
4121
4122         check_init(ast_timing_init(), "Timing");
4123         check_init(ast_ssl_init(), "SSL");
4124         read_pjproject_startup_options();
4125         check_init(ast_pj_init(), "Embedded PJProject");
4126         check_init(app_init(), "App Core");
4127         check_init(mwi_init(), "MWI Core");
4128         check_init(devstate_init(), "Device State Core");
4129         check_init(ast_msg_init(), "Messaging API");
4130         check_init(ast_channels_init(), "Channel");
4131         check_init(ast_endpoint_init(), "Endpoints");
4132         check_init(ast_pickup_init(), "Call Pickup");
4133         check_init(ast_bridging_init(), "Bridging");
4134         check_init(ast_parking_stasis_init(), "Parking Core");
4135         check_init(ast_device_state_engine_init(), "Device State Engine");
4136         check_init(ast_presence_state_engine_init(), "Presence State Engine");
4137         check_init(dns_core_init(), "DNS Resolver Core");
4138         check_init(ast_dns_system_resolver_init(), "Default DNS resolver");
4139         check_init(ast_security_stasis_init(), "Security Stasis Topic and Events");
4140         check_init(ast_image_init(), "Image");
4141         check_init(ast_file_init(), "Generic File Format Support");
4142         check_init(load_pbx(), "load_pbx");
4143         check_init(load_pbx_builtins(), "Builtin PBX Applications");
4144         check_init(load_pbx_functions_cli(), "PBX Functions Support");
4145         check_init(load_pbx_variables(), "PBX Variables Support");
4146         check_init(load_pbx_switch(), "PBX Switch Support");
4147         check_init(load_pbx_app(), "PBX Application Support");
4148         check_init(load_pbx_hangup_handler(), "PBX Hangup Handler Support");
4149         check_init(ast_local_init(), "Local Proxy Channel Driver");
4150
4151         /* We should avoid most config loads before this point as they can't use realtime. */
4152         check_init(load_modules(), "Module");
4153
4154         /*
4155          * This has to load after the dynamic modules load, as items in the media
4156          * cache can't be constructed from items in the AstDB without their
4157          * bucket backends.
4158          */
4159         check_init(ast_media_cache_init(), "Media Cache");
4160
4161         /* loads the cli_permissoins.conf file needed to implement cli restrictions. */
4162         ast_cli_perms_init(0);
4163
4164         ast_stun_init();
4165
4166         dnsmgr_start_refresh();
4167
4168         if (ast_opt_no_fork) {
4169                 consolethread = pthread_self();
4170         }
4171
4172         ast_alertpipe_init(sig_alert_pipe);
4173
4174         ast_process_pending_reloads();
4175
4176         ast_set_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED);
4177         publish_fully_booted();
4178
4179         pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
4180
4181         load_astmm_phase_2();
4182
4183         ast_cli_register_multiple(cli_asterisk_shutdown, ARRAY_LEN(cli_asterisk_shutdown));
4184         ast_cli_register_multiple(cli_asterisk, ARRAY_LEN(cli_asterisk));
4185         ast_register_cleanup(main_atexit);
4186
4187         run_startup_commands();
4188         ast_sd_notify("READY=1");
4189
4190         ast_verb(0, COLORIZE_FMT "\n", COLORIZE(COLOR_BRGREEN, 0, "Asterisk Ready."));
4191
4192         logger_queue_start();
4193
4194         if (ast_opt_console) {
4195                 /* Console stuff now... */
4196                 /* Register our quit function */
4197                 char title[256];
4198                 char hostname[MAXHOSTNAMELEN] = "";
4199
4200                 if (gethostname(hostname, sizeof(hostname) - 1)) {
4201                         ast_copy_string(hostname, "<Unknown>", sizeof(hostname));
4202                 }
4203
4204                 ast_pthread_create_detached(&mon_sig_flags, NULL, monitor_sig_flags, NULL);
4205
4206                 set_icon("Asterisk");
4207                 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %ld)", hostname, (long)ast_mainpid);
4208                 set_title(title);
4209
4210                 el_set(el, EL_GETCFN, ast_el_read_char);
4211
4212                 for (;;) {
4213                         if (sig_flags.need_el_end) {
4214                                 el_end(el);
4215
4216                                 return;
4217