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