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