Sat Mar 26 11:07:37 2011

Asterisk developer's documentation


asterisk.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2010, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 
00020 /* Doxygenified Copyright Header */
00021 /*!
00022  * \mainpage Asterisk -- An Open Source Telephony Toolkit
00023  *
00024  * \par Developer Documentation for Asterisk
00025  *
00026  * This is the main developer documentation for Asterisk. It is 
00027  * generated by running "make progdocs" from the Asterisk source tree.  
00028  *
00029  * In addition to the information available on the Asterisk source code, 
00030  * please see the appendices for information on coding guidelines, 
00031  * release management, commit policies, and more.
00032  *
00033  * \par Additional documentation
00034  * \arg \ref Licensing
00035  * \arg \ref DevDoc 
00036  * \arg \ref ConfigFiles
00037  *
00038  * \section copyright Copyright and Author
00039  *
00040  * Copyright (C) 1999 - 2009, Digium, Inc.
00041  * Asterisk is a <a href="http://www.digium.com/en/company/view-policy.php?id=Trademark-Policy">registered trademark</a>
00042  * of <a href="http://www.digium.com">Digium, Inc</a>.
00043  *
00044  * \author Mark Spencer <markster@digium.com>
00045  * Also see \ref AstCREDITS
00046  *
00047  * See http://www.asterisk.org for more information about
00048  * the Asterisk project. Please do not directly contact
00049  * any of the maintainers of this project for assistance;
00050  * the project provides a web site, mailing lists, and IRC
00051  * channels for your use.
00052  */
00053 
00054 /*! \file
00055   \brief Top level source file for Asterisk  - the Open Source PBX. Implementation
00056   of PBX core functions and CLI interface.
00057   
00058  */
00059 
00060 #include "asterisk.h"
00061 
00062 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 294639 $")
00063 
00064 #include "asterisk/_private.h"
00065 
00066 #undef sched_setscheduler
00067 #undef setpriority
00068 #include <sys/time.h>
00069 #include <fcntl.h>
00070 #include <signal.h>
00071 #include <sched.h>
00072 #include <sys/un.h>
00073 #include <sys/wait.h>
00074 #include <ctype.h>
00075 #include <sys/resource.h>
00076 #include <grp.h>
00077 #include <pwd.h>
00078 #include <sys/stat.h>
00079 #if defined(HAVE_SYSINFO)
00080 #include <sys/sysinfo.h>
00081 #elif defined(HAVE_SYSCTL)
00082 #include <sys/param.h>
00083 #include <sys/sysctl.h>
00084 #if !defined(__OpenBSD__)
00085 #include <sys/vmmeter.h>
00086 #if defined(__FreeBSD__)
00087 #include <vm/vm_param.h>
00088 #endif
00089 #endif
00090 #if defined(HAVE_SWAPCTL)
00091 #include <sys/swap.h>
00092 #endif
00093 #endif
00094 #include <regex.h>
00095 
00096 #if defined(SOLARIS)
00097 int daemon(int, int);  /* defined in libresolv of all places */
00098 #include <sys/loadavg.h>
00099 #endif
00100 
00101 #ifdef linux
00102 #include <sys/prctl.h>
00103 #ifdef HAVE_CAP
00104 #include <sys/capability.h>
00105 #endif /* HAVE_CAP */
00106 #endif /* linux */
00107 
00108 #include "asterisk/paths.h"   /* we define here the variables so better agree on the prototype */
00109 #include "asterisk/network.h"
00110 #include "asterisk/cli.h"
00111 #include "asterisk/channel.h"
00112 #include "asterisk/features.h"
00113 #include "asterisk/ulaw.h"
00114 #include "asterisk/alaw.h"
00115 #include "asterisk/callerid.h"
00116 #include "asterisk/image.h"
00117 #include "asterisk/tdd.h"
00118 #include "asterisk/term.h"
00119 #include "asterisk/manager.h"
00120 #include "asterisk/cdr.h"
00121 #include "asterisk/pbx.h"
00122 #include "asterisk/enum.h"
00123 #include "asterisk/rtp.h"
00124 #include "asterisk/http.h"
00125 #include "asterisk/udptl.h"
00126 #include "asterisk/app.h"
00127 #include "asterisk/lock.h"
00128 #include "asterisk/utils.h"
00129 #include "asterisk/file.h"
00130 #include "asterisk/io.h"
00131 #include "editline/histedit.h"
00132 #include "asterisk/config.h"
00133 #include "asterisk/ast_version.h"
00134 #include "asterisk/linkedlists.h"
00135 #include "asterisk/devicestate.h"
00136 #include "asterisk/module.h"
00137 #include "asterisk/dsp.h"
00138 #include "asterisk/buildinfo.h"
00139 #include "asterisk/xmldoc.h"
00140 #include "asterisk/poll-compat.h"
00141 
00142 #include "asterisk/doxyref.h"    /* Doxygen documentation */
00143 
00144 #include "../defaults.h"
00145 
00146 #ifndef AF_LOCAL
00147 #define AF_LOCAL AF_UNIX
00148 #define PF_LOCAL PF_UNIX
00149 #endif
00150 
00151 #define AST_MAX_CONNECTS 128
00152 #define NUM_MSGS 64
00153 
00154 /*! \brief Welcome message when starting a CLI interface */
00155 #define WELCOME_MESSAGE \
00156     ast_verbose("Asterisk %s, Copyright (C) 1999 - 2010 Digium, Inc. and others.\n" \
00157                 "Created by Mark Spencer <markster@digium.com>\n" \
00158                 "Asterisk comes with ABSOLUTELY NO WARRANTY; type 'core show warranty' for details.\n" \
00159                 "This is free software, with components licensed under the GNU General Public\n" \
00160                 "License version 2 and other licenses; you are welcome to redistribute it under\n" \
00161                 "certain conditions. Type 'core show license' for details.\n" \
00162                 "=========================================================================\n", ast_get_version()) \
00163 
00164 /*! \defgroup main_options Main Configuration Options
00165  * \brief Main configuration options from asterisk.conf or OS command line on starting Asterisk.
00166  * \arg \ref Config_ast "asterisk.conf"
00167  * \note Some of them can be changed in the CLI 
00168  */
00169 /*! @{ */
00170 
00171 struct ast_flags ast_options = { AST_DEFAULT_OPTIONS };
00172 struct ast_flags ast_compat = { 7 };
00173 
00174 int option_verbose;           /*!< Verbosity level */
00175 int option_debug;          /*!< Debug level */
00176 double option_maxload;           /*!< Max load avg on system */
00177 int option_maxcalls;          /*!< Max number of active calls */
00178 int option_maxfiles;          /*!< Max number of open file handles (files, sockets) */
00179 #if defined(HAVE_SYSINFO)
00180 long option_minmemfree;          /*!< Minimum amount of free system memory - stop accepting calls if free memory falls below this watermark */
00181 #endif
00182 
00183 /*! @} */
00184 
00185 struct ast_eid ast_eid_default;
00186 
00187 /* XXX tmpdir is a subdir of the spool directory, and no way to remap it */
00188 char record_cache_dir[AST_CACHE_DIR_LEN] = DEFAULT_TMP_DIR;
00189 
00190 static int ast_socket = -1;      /*!< UNIX Socket for allowing remote control */
00191 static int ast_consock = -1;     /*!< UNIX Socket for controlling another asterisk */
00192 pid_t ast_mainpid;
00193 struct console {
00194    int fd;           /*!< File descriptor */
00195    int p[2];         /*!< Pipe */
00196    pthread_t t;         /*!< Thread of handler */
00197    int mute;         /*!< Is the console muted for logs */
00198    int uid;       /*!< Remote user ID. */
00199    int gid;       /*!< Remote group ID. */
00200    int levels[NUMLOGLEVELS];  /*!< Which log levels are enabled for the console */
00201 };
00202 
00203 struct ast_atexit {
00204    void (*func)(void);
00205    AST_RWLIST_ENTRY(ast_atexit) list;
00206 };
00207 
00208 static AST_RWLIST_HEAD_STATIC(atexits, ast_atexit);
00209 
00210 struct timeval ast_startuptime;
00211 struct timeval ast_lastreloadtime;
00212 
00213 static History *el_hist;
00214 static EditLine *el;
00215 static char *remotehostname;
00216 
00217 struct console consoles[AST_MAX_CONNECTS];
00218 
00219 char defaultlanguage[MAX_LANGUAGE] = DEFAULT_LANGUAGE;
00220 
00221 static int ast_el_add_history(char *);
00222 static int ast_el_read_history(char *);
00223 static int ast_el_write_history(char *);
00224 
00225 struct _cfg_paths {
00226    char config_dir[PATH_MAX];
00227    char module_dir[PATH_MAX];
00228    char spool_dir[PATH_MAX];
00229    char monitor_dir[PATH_MAX];
00230    char var_dir[PATH_MAX];
00231    char data_dir[PATH_MAX];
00232    char log_dir[PATH_MAX];
00233    char agi_dir[PATH_MAX];
00234    char run_dir[PATH_MAX];
00235    char key_dir[PATH_MAX];
00236 
00237    char config_file[PATH_MAX];
00238    char db_path[PATH_MAX];
00239    char pid_path[PATH_MAX];
00240    char socket_path[PATH_MAX];
00241    char run_user[PATH_MAX];
00242    char run_group[PATH_MAX];
00243    char system_name[128];
00244 };
00245 
00246 static struct _cfg_paths cfg_paths;
00247 
00248 const char *ast_config_AST_CONFIG_DIR  = cfg_paths.config_dir;
00249 const char *ast_config_AST_CONFIG_FILE = cfg_paths.config_file;
00250 const char *ast_config_AST_MODULE_DIR  = cfg_paths.module_dir;
00251 const char *ast_config_AST_SPOOL_DIR   = cfg_paths.spool_dir;
00252 const char *ast_config_AST_MONITOR_DIR = cfg_paths.monitor_dir;
00253 const char *ast_config_AST_VAR_DIR  = cfg_paths.var_dir;
00254 const char *ast_config_AST_DATA_DIR = cfg_paths.data_dir;
00255 const char *ast_config_AST_LOG_DIR  = cfg_paths.log_dir;
00256 const char *ast_config_AST_AGI_DIR  = cfg_paths.agi_dir;
00257 const char *ast_config_AST_KEY_DIR  = cfg_paths.key_dir;
00258 const char *ast_config_AST_RUN_DIR  = cfg_paths.run_dir;
00259 
00260 const char *ast_config_AST_DB    = cfg_paths.db_path;
00261 const char *ast_config_AST_PID      = cfg_paths.pid_path;
00262 const char *ast_config_AST_SOCKET   = cfg_paths.socket_path;
00263 const char *ast_config_AST_RUN_USER = cfg_paths.run_user;
00264 const char *ast_config_AST_RUN_GROUP   = cfg_paths.run_group;
00265 const char *ast_config_AST_SYSTEM_NAME = cfg_paths.system_name;
00266 
00267 static char ast_config_AST_CTL_PERMISSIONS[PATH_MAX];
00268 static char ast_config_AST_CTL_OWNER[PATH_MAX] = "\0";
00269 static char ast_config_AST_CTL_GROUP[PATH_MAX] = "\0";
00270 static char ast_config_AST_CTL[PATH_MAX] = "asterisk.ctl";
00271 
00272 extern unsigned int ast_FD_SETSIZE;
00273 
00274 static char *_argv[256];
00275 static int shuttingdown;
00276 static int restartnow;
00277 static pthread_t consolethread = AST_PTHREADT_NULL;
00278 static pthread_t mon_sig_flags;
00279 static int canary_pid = 0;
00280 static char canary_filename[128];
00281 
00282 static char randompool[256];
00283 
00284 static int sig_alert_pipe[2] = { -1, -1 };
00285 static struct {
00286     unsigned int need_reload:1;
00287     unsigned int need_quit:1;
00288 } sig_flags;
00289 
00290 #if !defined(LOW_MEMORY)
00291 struct file_version {
00292    AST_RWLIST_ENTRY(file_version) list;
00293    const char *file;
00294    char *version;
00295 };
00296 
00297 static AST_RWLIST_HEAD_STATIC(file_versions, file_version);
00298 
00299 void ast_register_file_version(const char *file, const char *version)
00300 {
00301    struct file_version *new;
00302    char *work;
00303    size_t version_length;
00304 
00305    work = ast_strdupa(version);
00306    work = ast_strip(ast_strip_quoted(work, "$", "$"));
00307    version_length = strlen(work) + 1;
00308    
00309    if (!(new = ast_calloc(1, sizeof(*new) + version_length)))
00310       return;
00311 
00312    new->file = file;
00313    new->version = (char *) new + sizeof(*new);
00314    memcpy(new->version, work, version_length);
00315    AST_RWLIST_WRLOCK(&file_versions);
00316    AST_RWLIST_INSERT_HEAD(&file_versions, new, list);
00317    AST_RWLIST_UNLOCK(&file_versions);
00318 }
00319 
00320 void ast_unregister_file_version(const char *file)
00321 {
00322    struct file_version *find;
00323 
00324    AST_RWLIST_WRLOCK(&file_versions);
00325    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&file_versions, find, list) {
00326       if (!strcasecmp(find->file, file)) {
00327          AST_RWLIST_REMOVE_CURRENT(list);
00328          break;
00329       }
00330    }
00331    AST_RWLIST_TRAVERSE_SAFE_END;
00332    AST_RWLIST_UNLOCK(&file_versions);
00333 
00334    if (find)
00335       ast_free(find);
00336 }
00337 
00338 char *ast_complete_source_filename(const char *partial, int n)
00339 {
00340    struct file_version *find;
00341    size_t len = strlen(partial);
00342    int count = 0;
00343    char *res = NULL;
00344 
00345    AST_RWLIST_RDLOCK(&file_versions);
00346    AST_RWLIST_TRAVERSE(&file_versions, find, list) {
00347       if (!strncasecmp(find->file, partial, len) && ++count > n) {
00348          res = ast_strdup(find->file);
00349          break;
00350       }
00351    }
00352    AST_RWLIST_UNLOCK(&file_versions);
00353    return res;
00354 }
00355 
00356 /*! \brief Find version for given module name */
00357 const char *ast_file_version_find(const char *file)
00358 {
00359    struct file_version *iterator;
00360 
00361    AST_RWLIST_WRLOCK(&file_versions);
00362    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&file_versions, iterator, list) {
00363       if (!strcasecmp(iterator->file, file))
00364          break;
00365    }
00366    AST_RWLIST_TRAVERSE_SAFE_END;
00367    AST_RWLIST_UNLOCK(&file_versions);
00368    if (iterator)
00369       return iterator->version;
00370    return NULL;
00371 }      
00372        
00373 
00374 
00375 struct thread_list_t {
00376    AST_RWLIST_ENTRY(thread_list_t) list;
00377    char *name;
00378    pthread_t id;
00379 };
00380 
00381 static AST_RWLIST_HEAD_STATIC(thread_list, thread_list_t);
00382 
00383 void ast_register_thread(char *name)
00384 { 
00385    struct thread_list_t *new = ast_calloc(1, sizeof(*new));
00386 
00387    if (!new)
00388       return;
00389    new->id = pthread_self();
00390    new->name = name; /* steal the allocated memory for the thread name */
00391    AST_RWLIST_WRLOCK(&thread_list);
00392    AST_RWLIST_INSERT_HEAD(&thread_list, new, list);
00393    AST_RWLIST_UNLOCK(&thread_list);
00394 }
00395 
00396 void ast_unregister_thread(void *id)
00397 {
00398    struct thread_list_t *x;
00399 
00400    AST_RWLIST_WRLOCK(&thread_list);
00401    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&thread_list, x, list) {
00402       if ((void *) x->id == id) {
00403          AST_RWLIST_REMOVE_CURRENT(list);
00404          break;
00405       }
00406    }
00407    AST_RWLIST_TRAVERSE_SAFE_END;
00408    AST_RWLIST_UNLOCK(&thread_list);
00409    if (x) {
00410       ast_free(x->name);
00411       ast_free(x);
00412    }
00413 }
00414 
00415 /*! \brief Give an overview of core settings */
00416 static char *handle_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00417 {
00418    char buf[BUFSIZ];
00419    struct ast_tm tm;
00420    char eid_str[128];
00421 
00422    switch (cmd) {
00423    case CLI_INIT:
00424       e->command = "core show settings";
00425       e->usage = "Usage: core show settings\n"
00426             "       Show core misc settings";
00427       return NULL;
00428    case CLI_GENERATE:
00429       return NULL;
00430    }
00431 
00432    ast_eid_to_str(eid_str, sizeof(eid_str), &ast_eid_default);
00433 
00434    ast_cli(a->fd, "\nPBX Core settings\n");
00435    ast_cli(a->fd, "-----------------\n");
00436    ast_cli(a->fd, "  Version:                     %s\n", ast_get_version());
00437    ast_cli(a->fd, "  Build Options:               %s\n", S_OR(AST_BUILDOPTS, "(none)"));
00438    if (option_maxcalls)
00439       ast_cli(a->fd, "  Maximum calls:               %d (Current %d)\n", option_maxcalls, ast_active_channels());
00440    else
00441       ast_cli(a->fd, "  Maximum calls:               Not set\n");
00442    if (option_maxfiles)
00443       ast_cli(a->fd, "  Maximum open file handles:   %d\n", option_maxfiles); 
00444    else
00445       ast_cli(a->fd, "  Maximum open file handles:   Not set\n");
00446    ast_cli(a->fd, "  Verbosity:                   %d\n", option_verbose);
00447    ast_cli(a->fd, "  Debug level:                 %d\n", option_debug);
00448    ast_cli(a->fd, "  Maximum load average:        %lf\n", option_maxload);
00449 #if defined(HAVE_SYSINFO)
00450    ast_cli(a->fd, "  Minimum free memory:         %ld MB\n", option_minmemfree);
00451 #endif
00452    if (ast_localtime(&ast_startuptime, &tm, NULL)) {
00453       ast_strftime(buf, sizeof(buf), "%H:%M:%S", &tm);
00454       ast_cli(a->fd, "  Startup time:                %s\n", buf);
00455    }
00456    if (ast_localtime(&ast_lastreloadtime, &tm, NULL)) {
00457       ast_strftime(buf, sizeof(buf), "%H:%M:%S", &tm);
00458       ast_cli(a->fd, "  Last reload time:            %s\n", buf);
00459    }
00460    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);
00461    ast_cli(a->fd, "  System name:                 %s\n", ast_config_AST_SYSTEM_NAME);
00462    ast_cli(a->fd, "  Entity ID:                   %s\n", eid_str);
00463    ast_cli(a->fd, "  Default language:            %s\n", defaultlanguage);
00464    ast_cli(a->fd, "  Language prefix:             %s\n", ast_language_is_prefix ? "Enabled" : "Disabled");
00465    ast_cli(a->fd, "  User name and group:         %s/%s\n", ast_config_AST_RUN_USER, ast_config_AST_RUN_GROUP);
00466    ast_cli(a->fd, "  Executable includes:         %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_EXEC_INCLUDES) ? "Enabled" : "Disabled");
00467    ast_cli(a->fd, "  Transcode via SLIN:          %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_TRANSCODE_VIA_SLIN) ? "Enabled" : "Disabled");
00468    ast_cli(a->fd, "  Internal timing:             %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_INTERNAL_TIMING) ? "Enabled" : "Disabled");
00469    ast_cli(a->fd, "  Transmit silence during rec: %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_TRANSMIT_SILENCE) ? "Enabled" : "Disabled");
00470    ast_cli(a->fd, "  Generic PLC:                 %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_GENERIC_PLC) ? "Enabled" : "Disabled");
00471 
00472    ast_cli(a->fd, "\n* Subsystems\n");
00473    ast_cli(a->fd, "  -------------\n");
00474    ast_cli(a->fd, "  Manager (AMI):               %s\n", check_manager_enabled() ? "Enabled" : "Disabled");
00475    ast_cli(a->fd, "  Web Manager (AMI/HTTP):      %s\n", check_webmanager_enabled() ? "Enabled" : "Disabled");
00476    ast_cli(a->fd, "  Send Manager FullyBooted:    %s\n", ast_opt_send_fullybooted ? "Enabled" : "Disabled");
00477    ast_cli(a->fd, "  Call data records:           %s\n", check_cdr_enabled() ? "Enabled" : "Disabled");
00478    ast_cli(a->fd, "  Realtime Architecture (ARA): %s\n", ast_realtime_enabled() ? "Enabled" : "Disabled");
00479 
00480    /*! \todo we could check musiconhold, voicemail, smdi, adsi, queues  */
00481 
00482    ast_cli(a->fd, "\n* Directories\n");
00483    ast_cli(a->fd, "  -------------\n");
00484    ast_cli(a->fd, "  Configuration file:          %s\n", ast_config_AST_CONFIG_FILE);
00485    ast_cli(a->fd, "  Configuration directory:     %s\n", ast_config_AST_CONFIG_DIR);
00486    ast_cli(a->fd, "  Module directory:            %s\n", ast_config_AST_MODULE_DIR);
00487    ast_cli(a->fd, "  Spool directory:             %s\n", ast_config_AST_SPOOL_DIR);
00488    ast_cli(a->fd, "  Log directory:               %s\n", ast_config_AST_LOG_DIR);
00489    ast_cli(a->fd, "\n\n");
00490    return CLI_SUCCESS;
00491 }
00492 
00493 static char *handle_show_threads(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00494 {
00495    int count = 0;
00496    struct thread_list_t *cur;
00497    switch (cmd) {
00498    case CLI_INIT:
00499       e->command = "core show threads";
00500       e->usage = 
00501          "Usage: core show threads\n"
00502          "       List threads currently active in the system.\n";
00503       return NULL;
00504    case CLI_GENERATE:
00505       return NULL;
00506    }
00507 
00508    AST_RWLIST_RDLOCK(&thread_list);
00509    AST_RWLIST_TRAVERSE(&thread_list, cur, list) {
00510       ast_cli(a->fd, "%p %s\n", (void *)cur->id, cur->name);
00511       count++;
00512    }
00513         AST_RWLIST_UNLOCK(&thread_list);
00514    ast_cli(a->fd, "%d threads listed.\n", count);
00515    return CLI_SUCCESS;
00516 }
00517 
00518 #if defined (HAVE_SYSCTL) && defined(HAVE_SWAPCTL)
00519 /*
00520  * swapmode is rewritten by Tobias Weingartner <weingart@openbsd.org>
00521  * to be based on the new swapctl(2) system call.
00522  */
00523 static int swapmode(int *used, int *total)
00524 {
00525    struct swapent *swdev;
00526    int nswap, rnswap, i;
00527 
00528    nswap = swapctl(SWAP_NSWAP, 0, 0);
00529    if (nswap == 0)
00530       return 0;
00531 
00532    swdev = ast_calloc(nswap, sizeof(*swdev));
00533    if (swdev == NULL)
00534       return 0;
00535 
00536    rnswap = swapctl(SWAP_STATS, swdev, nswap);
00537    if (rnswap == -1) {
00538       ast_free(swdev);
00539       return 0;
00540    }
00541 
00542    /* if rnswap != nswap, then what? */
00543 
00544    /* Total things up */
00545    *total = *used = 0;
00546    for (i = 0; i < nswap; i++) {
00547       if (swdev[i].se_flags & SWF_ENABLE) {
00548          *used += (swdev[i].se_inuse / (1024 / DEV_BSIZE));
00549          *total += (swdev[i].se_nblks / (1024 / DEV_BSIZE));
00550       }
00551    }
00552    ast_free(swdev);
00553    return 1;
00554 }
00555 #elif defined(HAVE_SYSCTL) && !defined(HAVE_SYSINFO)
00556 static int swapmode(int *used, int *total)
00557 {
00558    *used = *total = 0;
00559    return 1;
00560 }
00561 #endif
00562 
00563 #if defined(HAVE_SYSINFO) || defined(HAVE_SYSCTL)
00564 /*! \brief Give an overview of system statistics */
00565 static char *handle_show_sysinfo(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00566 {
00567    uint64_t physmem, freeram;
00568    uint64_t freeswap = 0;
00569    int totalswap = 0;
00570    int nprocs = 0;
00571    long uptime = 0;
00572 #if defined(HAVE_SYSINFO)
00573    struct sysinfo sys_info;
00574    sysinfo(&sys_info);
00575    uptime = sys_info.uptime / 3600;
00576    physmem = sys_info.totalram * sys_info.mem_unit;
00577    freeram = (sys_info.freeram * sys_info.mem_unit) / 1024;
00578    totalswap = (sys_info.totalswap * sys_info.mem_unit) / 1024;
00579    freeswap = (sys_info.freeswap * sys_info.mem_unit) / 1024;
00580    nprocs = sys_info.procs;
00581 #elif defined(HAVE_SYSCTL)
00582    static int pageshift;
00583    struct vmtotal vmtotal;
00584    struct timeval boottime;
00585    time_t   now;
00586    int mib[2], pagesize, usedswap = 0;
00587    size_t len;
00588    /* calculate the uptime by looking at boottime */
00589    time(&now);
00590    mib[0] = CTL_KERN;
00591    mib[1] = KERN_BOOTTIME;
00592    len = sizeof(boottime);
00593    if (sysctl(mib, 2, &boottime, &len, NULL, 0) != -1) {
00594       uptime = now - boottime.tv_sec;
00595    }
00596    uptime = uptime/3600;
00597    /* grab total physical memory  */
00598    mib[0] = CTL_HW;
00599 #if defined(HW_PHYSMEM64)
00600    mib[1] = HW_PHYSMEM64;
00601 #else
00602    mib[1] = HW_PHYSMEM;
00603 #endif
00604    len = sizeof(physmem);
00605    sysctl(mib, 2, &physmem, &len, NULL, 0);
00606 
00607    pagesize = getpagesize();
00608    pageshift = 0;
00609    while (pagesize > 1) {
00610       pageshift++;
00611       pagesize >>= 1;
00612    }
00613 
00614    /* we only need the amount of log(2)1024 for our conversion */
00615    pageshift -= 10;
00616 
00617    /* grab vm totals */
00618    mib[0] = CTL_VM;
00619    mib[1] = VM_METER;
00620    len = sizeof(vmtotal);
00621    sysctl(mib, 2, &vmtotal, &len, NULL, 0);
00622    freeram = (vmtotal.t_free << pageshift);
00623    /* generate swap usage and totals */
00624    swapmode(&usedswap, &totalswap);
00625    freeswap = (totalswap - usedswap);
00626    /* grab number of processes */
00627 #if defined(__OpenBSD__)
00628    mib[0] = CTL_KERN;
00629    mib[1] = KERN_NPROCS;
00630    len = sizeof(nprocs);
00631    sysctl(mib, 2, &nprocs, &len, NULL, 0);
00632 #endif
00633 #endif
00634 
00635    switch (cmd) {
00636    case CLI_INIT:
00637       e->command = "core show sysinfo";
00638       e->usage =
00639          "Usage: core show sysinfo\n"
00640          "       List current system information.\n";
00641       return NULL;
00642    case CLI_GENERATE:
00643       return NULL;
00644    }
00645 
00646    ast_cli(a->fd, "\nSystem Statistics\n");
00647    ast_cli(a->fd, "-----------------\n");
00648    ast_cli(a->fd, "  System Uptime:             %lu hours\n", uptime);
00649    ast_cli(a->fd, "  Total RAM:                 %" PRIu64 " KiB\n", physmem / 1024);
00650    ast_cli(a->fd, "  Free RAM:                  %" PRIu64 " KiB\n", freeram);
00651 #if defined(HAVE_SYSINFO)
00652    ast_cli(a->fd, "  Buffer RAM:                %" PRIu64 " KiB\n", ((uint64_t) sys_info.bufferram * sys_info.mem_unit) / 1024);
00653 #endif
00654 #if defined (HAVE_SYSCTL) && defined(HAVE_SWAPCTL)
00655    ast_cli(a->fd, "  Total Swap Space:          %u KiB\n", totalswap);
00656    ast_cli(a->fd, "  Free Swap Space:           %" PRIu64 " KiB\n\n", freeswap);
00657 #endif
00658    ast_cli(a->fd, "  Number of Processes:       %d \n\n", nprocs);
00659    return CLI_SUCCESS;
00660 }
00661 #endif
00662 
00663 struct profile_entry {
00664    const char *name;
00665    uint64_t scale;   /* if non-zero, values are scaled by this */
00666    int64_t  mark;
00667    int64_t  value;
00668    int64_t  events;
00669 };
00670 
00671 struct profile_data {
00672    int entries;
00673    int max_size;
00674    struct profile_entry e[0];
00675 };
00676 
00677 static struct profile_data *prof_data;
00678 
00679 /*! \brief allocates a counter with a given name and scale.
00680  * \return Returns the identifier of the counter.
00681  */
00682 int ast_add_profile(const char *name, uint64_t scale)
00683 {
00684    int l = sizeof(struct profile_data);
00685    int n = 10; /* default entries */
00686 
00687    if (prof_data == NULL) {
00688       prof_data = ast_calloc(1, l + n*sizeof(struct profile_entry));
00689       if (prof_data == NULL)
00690          return -1;
00691       prof_data->entries = 0;
00692       prof_data->max_size = n;
00693    }
00694    if (prof_data->entries >= prof_data->max_size) {
00695       void *p;
00696       n = prof_data->max_size + 20;
00697       p = ast_realloc(prof_data, l + n*sizeof(struct profile_entry));
00698       if (p == NULL)
00699          return -1;
00700       prof_data = p;
00701       prof_data->max_size = n;
00702    }
00703    n = prof_data->entries++;
00704    prof_data->e[n].name = ast_strdup(name);
00705    prof_data->e[n].value = 0;
00706    prof_data->e[n].events = 0;
00707    prof_data->e[n].mark = 0;
00708    prof_data->e[n].scale = scale;
00709    return n;
00710 }
00711 
00712 int64_t ast_profile(int i, int64_t delta)
00713 {
00714    if (!prof_data || i < 0 || i > prof_data->entries) /* invalid index */
00715       return 0;
00716    if (prof_data->e[i].scale > 1)
00717       delta /= prof_data->e[i].scale;
00718    prof_data->e[i].value += delta;
00719    prof_data->e[i].events++;
00720    return prof_data->e[i].value;
00721 }
00722 
00723 /* The RDTSC instruction was introduced on the Pentium processor and is not
00724  * implemented on certain clones, like the Cyrix 586. Hence, the previous
00725  * expectation of __i386__ was in error. */
00726 #if defined ( __i686__) && (defined(__FreeBSD__) || defined(linux))
00727 #if defined(__FreeBSD__)
00728 #include <machine/cpufunc.h>
00729 #elif defined(linux)
00730 static __inline uint64_t
00731 rdtsc(void)
00732 { 
00733    uint64_t rv;
00734 
00735    __asm __volatile(".byte 0x0f, 0x31" : "=A" (rv));
00736    return (rv);
00737 }
00738 #endif
00739 #else /* supply a dummy function on other platforms */
00740 static __inline uint64_t
00741 rdtsc(void)
00742 {
00743    return 0;
00744 }
00745 #endif
00746 
00747 int64_t ast_mark(int i, int startstop)
00748 {
00749    if (!prof_data || i < 0 || i > prof_data->entries) /* invalid index */
00750       return 0;
00751    if (startstop == 1)
00752       prof_data->e[i].mark = rdtsc();
00753    else {
00754       prof_data->e[i].mark = (rdtsc() - prof_data->e[i].mark);
00755       if (prof_data->e[i].scale > 1)
00756          prof_data->e[i].mark /= prof_data->e[i].scale;
00757       prof_data->e[i].value += prof_data->e[i].mark;
00758       prof_data->e[i].events++;
00759    }
00760    return prof_data->e[i].mark;
00761 }
00762 
00763 #define DEFINE_PROFILE_MIN_MAX_VALUES min = 0; \
00764    max = prof_data->entries;\
00765    if  (a->argc > 3) { /* specific entries */ \
00766       if (isdigit(a->argv[3][0])) { \
00767          min = atoi(a->argv[3]); \
00768          if (a->argc == 5 && strcmp(a->argv[4], "-")) \
00769             max = atoi(a->argv[4]); \
00770       } else \
00771          search = a->argv[3]; \
00772    } \
00773    if (max > prof_data->entries) \
00774       max = prof_data->entries;
00775 
00776 static char *handle_show_profile(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00777 {
00778    int i, min, max;
00779    char *search = NULL;
00780    switch (cmd) {
00781    case CLI_INIT:
00782       e->command = "core show profile";
00783       e->usage = "Usage: core show profile\n"
00784             "       show profile information";
00785       return NULL;
00786    case CLI_GENERATE:
00787       return NULL;
00788    }
00789 
00790    if (prof_data == NULL)
00791       return 0;
00792 
00793    DEFINE_PROFILE_MIN_MAX_VALUES;
00794    ast_cli(a->fd, "profile values (%d, allocated %d)\n-------------------\n",
00795       prof_data->entries, prof_data->max_size);
00796    ast_cli(a->fd, "%6s   %8s  %10s %12s %12s  %s\n", "ID", "Scale", "Events",
00797          "Value", "Average", "Name");
00798    for (i = min; i < max; i++) {
00799       struct profile_entry *entry = &prof_data->e[i];
00800       if (!search || strstr(entry->name, search))
00801           ast_cli(a->fd, "%6d: [%8ld] %10ld %12lld %12lld  %s\n",
00802          i,
00803          (long)entry->scale,
00804          (long)entry->events, (long long)entry->value,
00805          (long long)(entry->events ? entry->value / entry->events : entry->value),
00806          entry->name);
00807    }
00808    return CLI_SUCCESS;
00809 }
00810 
00811 static char *handle_clear_profile(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00812 {
00813    int i, min, max;
00814    char *search = NULL;
00815    switch (cmd) {
00816    case CLI_INIT:
00817       e->command = "core clear profile";
00818       e->usage = "Usage: core clear profile\n"
00819             "       clear profile information";
00820       return NULL;
00821    case CLI_GENERATE:
00822       return NULL;
00823    }
00824 
00825    if (prof_data == NULL)
00826       return 0;
00827 
00828    DEFINE_PROFILE_MIN_MAX_VALUES;
00829    for (i= min; i < max; i++) {
00830       if (!search || strstr(prof_data->e[i].name, search)) {
00831          prof_data->e[i].value = 0;
00832          prof_data->e[i].events = 0;
00833       }
00834    }
00835    return CLI_SUCCESS;
00836 }
00837 #undef DEFINE_PROFILE_MIN_MAX_VALUES
00838 
00839 /*! \brief CLI command to list module versions */
00840 static char *handle_show_version_files(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00841 {
00842 #define FORMAT "%-25.25s %-40.40s\n"
00843    struct file_version *iterator;
00844    regex_t regexbuf;
00845    int havepattern = 0;
00846    int havename = 0;
00847    int count_files = 0;
00848    char *ret = NULL;
00849    int matchlen, which = 0;
00850    struct file_version *find;
00851 
00852    switch (cmd) {
00853    case CLI_INIT:
00854       e->command = "core show file version [like]";
00855       e->usage = 
00856          "Usage: core show file version [like <pattern>]\n"
00857          "       Lists the revision numbers of the files used to build this copy of Asterisk.\n"
00858          "       Optional regular expression pattern is used to filter the file list.\n";
00859       return NULL;
00860    case CLI_GENERATE:
00861       matchlen = strlen(a->word);
00862       if (a->pos != 3)
00863          return NULL;
00864       AST_RWLIST_RDLOCK(&file_versions);
00865       AST_RWLIST_TRAVERSE(&file_versions, find, list) {
00866          if (!strncasecmp(a->word, find->file, matchlen) && ++which > a->n) {
00867             ret = ast_strdup(find->file);
00868             break;
00869          }
00870       }
00871       AST_RWLIST_UNLOCK(&file_versions);
00872       return ret;
00873    }
00874 
00875 
00876    switch (a->argc) {
00877    case 6:
00878       if (!strcasecmp(a->argv[4], "like")) {
00879          if (regcomp(&regexbuf, a->argv[5], REG_EXTENDED | REG_NOSUB))
00880             return CLI_SHOWUSAGE;
00881          havepattern = 1;
00882       } else
00883          return CLI_SHOWUSAGE;
00884       break;
00885    case 5:
00886       havename = 1;
00887       break;
00888    case 4:
00889       break;
00890    default:
00891       return CLI_SHOWUSAGE;
00892    }
00893 
00894    ast_cli(a->fd, FORMAT, "File", "Revision");
00895    ast_cli(a->fd, FORMAT, "----", "--------");
00896    AST_RWLIST_RDLOCK(&file_versions);
00897    AST_RWLIST_TRAVERSE(&file_versions, iterator, list) {
00898       if (havename && strcasecmp(iterator->file, a->argv[4]))
00899          continue;
00900 
00901       if (havepattern && regexec(&regexbuf, iterator->file, 0, NULL, 0))
00902          continue;
00903 
00904       ast_cli(a->fd, FORMAT, iterator->file, iterator->version);
00905       count_files++;
00906       if (havename)
00907          break;
00908    }
00909    AST_RWLIST_UNLOCK(&file_versions);
00910    if (!havename) {
00911       ast_cli(a->fd, "%d files listed.\n", count_files);
00912    }
00913 
00914    if (havepattern)
00915       regfree(&regexbuf);
00916 
00917    return CLI_SUCCESS;
00918 #undef FORMAT
00919 }
00920 
00921 #endif /* ! LOW_MEMORY */
00922 
00923 int ast_register_atexit(void (*func)(void))
00924 {
00925    struct ast_atexit *ae;
00926 
00927    if (!(ae = ast_calloc(1, sizeof(*ae))))
00928       return -1;
00929 
00930    ae->func = func;
00931 
00932    ast_unregister_atexit(func);  
00933 
00934    AST_RWLIST_WRLOCK(&atexits);
00935    AST_RWLIST_INSERT_HEAD(&atexits, ae, list);
00936    AST_RWLIST_UNLOCK(&atexits);
00937 
00938    return 0;
00939 }
00940 
00941 void ast_unregister_atexit(void (*func)(void))
00942 {
00943    struct ast_atexit *ae = NULL;
00944 
00945    AST_RWLIST_WRLOCK(&atexits);
00946    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&atexits, ae, list) {
00947       if (ae->func == func) {
00948          AST_RWLIST_REMOVE_CURRENT(list);
00949          break;
00950       }
00951    }
00952    AST_RWLIST_TRAVERSE_SAFE_END;
00953    AST_RWLIST_UNLOCK(&atexits);
00954 
00955    free(ae);
00956 }
00957 
00958 /* Sending commands from consoles back to the daemon requires a terminating NULL */
00959 static int fdsend(int fd, const char *s)
00960 {
00961    return write(fd, s, strlen(s) + 1);
00962 }
00963 
00964 /* Sending messages from the daemon back to the display requires _excluding_ the terminating NULL */
00965 static int fdprint(int fd, const char *s)
00966 {
00967    return write(fd, s, strlen(s));
00968 }
00969 
00970 /*! \brief NULL handler so we can collect the child exit status */
00971 static void _null_sig_handler(int sig)
00972 {
00973 
00974 }
00975 
00976 static struct sigaction null_sig_handler = {
00977    .sa_handler = _null_sig_handler,
00978    .sa_flags = SA_RESTART,
00979 };
00980 
00981 static struct sigaction ignore_sig_handler = {
00982    .sa_handler = SIG_IGN,
00983 };
00984 
00985 AST_MUTEX_DEFINE_STATIC(safe_system_lock);
00986 /*! \brief Keep track of how many threads are currently trying to wait*() on
00987  *  a child process */
00988 static unsigned int safe_system_level = 0;
00989 static struct sigaction safe_system_prev_handler;
00990 
00991 void ast_replace_sigchld(void)
00992 {
00993    unsigned int level;
00994 
00995    ast_mutex_lock(&safe_system_lock);
00996    level = safe_system_level++;
00997 
00998    /* only replace the handler if it has not already been done */
00999    if (level == 0) {
01000       sigaction(SIGCHLD, &null_sig_handler, &safe_system_prev_handler);
01001    }
01002 
01003    ast_mutex_unlock(&safe_system_lock);
01004 }
01005 
01006 void ast_unreplace_sigchld(void)
01007 {
01008    unsigned int level;
01009 
01010    ast_mutex_lock(&safe_system_lock);
01011    level = --safe_system_level;
01012 
01013    /* only restore the handler if we are the last one */
01014    if (level == 0) {
01015       sigaction(SIGCHLD, &safe_system_prev_handler, NULL);
01016    }
01017 
01018    ast_mutex_unlock(&safe_system_lock);
01019 }
01020 
01021 int ast_safe_system(const char *s)
01022 {
01023    pid_t pid;
01024    int res;
01025    struct rusage rusage;
01026    int status;
01027 
01028 #if defined(HAVE_WORKING_FORK) || defined(HAVE_WORKING_VFORK)
01029    ast_replace_sigchld();
01030 
01031 #ifdef HAVE_WORKING_FORK
01032    pid = fork();
01033 #else
01034    pid = vfork();
01035 #endif   
01036 
01037    if (pid == 0) {
01038 #ifdef HAVE_CAP
01039       cap_t cap = cap_from_text("cap_net_admin-eip");
01040 
01041       if (cap_set_proc(cap)) {
01042          /* Careful with order! Logging cannot happen after we close FDs */
01043          ast_log(LOG_WARNING, "Unable to remove capabilities.\n");
01044       }
01045       cap_free(cap);
01046 #endif
01047 #ifdef HAVE_WORKING_FORK
01048       if (ast_opt_high_priority)
01049          ast_set_priority(0);
01050       /* Close file descriptors and launch system command */
01051       ast_close_fds_above_n(STDERR_FILENO);
01052 #endif
01053       execl("/bin/sh", "/bin/sh", "-c", s, (char *) NULL);
01054       _exit(1);
01055    } else if (pid > 0) {
01056       for (;;) {
01057          res = wait4(pid, &status, 0, &rusage);
01058          if (res > -1) {
01059             res = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
01060             break;
01061          } else if (errno != EINTR) 
01062             break;
01063       }
01064    } else {
01065       ast_log(LOG_WARNING, "Fork failed: %s\n", strerror(errno));
01066       res = -1;
01067    }
01068 
01069    ast_unreplace_sigchld();
01070 #else /* !defined(HAVE_WORKING_FORK) && !defined(HAVE_WORKING_VFORK) */
01071    res = -1;
01072 #endif
01073 
01074    return res;
01075 }
01076 
01077 void ast_console_toggle_loglevel(int fd, int level, int state)
01078 {
01079    int x;
01080    for (x = 0;x < AST_MAX_CONNECTS; x++) {
01081       if (fd == consoles[x].fd) {
01082          consoles[x].levels[level] = state;
01083          return;
01084       }
01085    }
01086 }
01087 
01088 /*!
01089  * \brief mute or unmute a console from logging
01090  */
01091 void ast_console_toggle_mute(int fd, int silent) {
01092    int x;
01093    for (x = 0;x < AST_MAX_CONNECTS; x++) {
01094       if (fd == consoles[x].fd) {
01095          if (consoles[x].mute) {
01096             consoles[x].mute = 0;
01097             if (!silent)
01098                ast_cli(fd, "Console is not muted anymore.\n");
01099          } else {
01100             consoles[x].mute = 1;
01101             if (!silent)
01102                ast_cli(fd, "Console is muted.\n");
01103          }
01104          return;
01105       }
01106    }
01107    ast_cli(fd, "Couldn't find remote console.\n");
01108 }
01109 
01110 /*!
01111  * \brief log the string to all attached console clients
01112  */
01113 static void ast_network_puts_mutable(const char *string, int level)
01114 {
01115    int x;
01116    for (x = 0;x < AST_MAX_CONNECTS; x++) {
01117       if (consoles[x].mute)
01118          continue;
01119       if (consoles[x].fd > -1) {
01120          if (!consoles[x].levels[level]) 
01121             fdprint(consoles[x].p[1], string);
01122       }
01123    }
01124 }
01125 
01126 /*!
01127  * \brief log the string to the console, and all attached
01128  * console clients
01129  */
01130 void ast_console_puts_mutable(const char *string, int level)
01131 {
01132    fputs(string, stdout);
01133    fflush(stdout);
01134    ast_network_puts_mutable(string, level);
01135 }
01136 
01137 /*!
01138  * \brief write the string to all attached console clients
01139  */
01140 static void ast_network_puts(const char *string)
01141 {
01142    int x;
01143    for (x = 0; x < AST_MAX_CONNECTS; x++) {
01144       if (consoles[x].fd > -1) 
01145          fdprint(consoles[x].p[1], string);
01146    }
01147 }
01148 
01149 /*!
01150  * write the string to the console, and all attached
01151  * console clients
01152  */
01153 void ast_console_puts(const char *string)
01154 {
01155    fputs(string, stdout);
01156    fflush(stdout);
01157    ast_network_puts(string);
01158 }
01159 
01160 static void network_verboser(const char *s)
01161 {
01162    ast_network_puts_mutable(s, __LOG_VERBOSE);
01163 }
01164 
01165 static pthread_t lthread;
01166 
01167 /*!
01168  * \brief read() function supporting the reception of user credentials.
01169  *
01170  * \param fd Socket file descriptor.
01171  * \param buffer Receive buffer.
01172  * \param size 'buffer' size.
01173  * \param con Console structure to set received credentials
01174  * \retval -1 on error
01175  * \retval the number of bytes received on success.
01176  */
01177 static int read_credentials(int fd, char *buffer, size_t size, struct console *con)
01178 {
01179 #if defined(SO_PEERCRED)
01180    struct ucred cred;
01181    socklen_t len = sizeof(cred);
01182 #endif
01183 #if defined(HAVE_GETPEEREID)
01184    uid_t uid;
01185    gid_t gid;
01186 #else
01187    int uid, gid;
01188 #endif
01189    int result;
01190 
01191    result = read(fd, buffer, size);
01192    if (result < 0) {
01193       return result;
01194    }
01195 
01196 #if defined(SO_PEERCRED)
01197    if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &len)) {
01198       return result;
01199    }
01200    uid = cred.uid;
01201    gid = cred.gid;
01202 #elif defined(HAVE_GETPEEREID)
01203    if (getpeereid(fd, &uid, &gid)) {
01204       return result;
01205    }
01206 #else
01207    return result;
01208 #endif
01209    con->uid = uid;
01210    con->gid = gid;
01211 
01212    return result;
01213 }
01214 
01215 static void *netconsole(void *vconsole)
01216 {
01217    struct console *con = vconsole;
01218    char hostname[MAXHOSTNAMELEN] = "";
01219    char tmp[512];
01220    int res;
01221    struct pollfd fds[2];
01222    
01223    if (gethostname(hostname, sizeof(hostname)-1))
01224       ast_copy_string(hostname, "<Unknown>", sizeof(hostname));
01225    snprintf(tmp, sizeof(tmp), "%s/%ld/%s\n", hostname, (long)ast_mainpid, ast_get_version());
01226    fdprint(con->fd, tmp);
01227    for (;;) {
01228       fds[0].fd = con->fd;
01229       fds[0].events = POLLIN;
01230       fds[0].revents = 0;
01231       fds[1].fd = con->p[0];
01232       fds[1].events = POLLIN;
01233       fds[1].revents = 0;
01234 
01235       res = ast_poll(fds, 2, -1);
01236       if (res < 0) {
01237          if (errno != EINTR)
01238             ast_log(LOG_WARNING, "poll returned < 0: %s\n", strerror(errno));
01239          continue;
01240       }
01241       if (fds[0].revents) {
01242          res = read_credentials(con->fd, tmp, sizeof(tmp) - 1, con);
01243          if (res < 1) {
01244             break;
01245          }
01246          tmp[res] = 0;
01247          if (strncmp(tmp, "cli quit after ", 15) == 0) {
01248             ast_cli_command_multiple_full(con->uid, con->gid, con->fd, res - 15, tmp + 15);
01249             break;
01250          }
01251          ast_cli_command_multiple_full(con->uid, con->gid, con->fd, res, tmp);
01252       }
01253       if (fds[1].revents) {
01254          res = read_credentials(con->p[0], tmp, sizeof(tmp), con);
01255          if (res < 1) {
01256             ast_log(LOG_ERROR, "read returned %d\n", res);
01257             break;
01258          }
01259          res = write(con->fd, tmp, res);
01260          if (res < 1)
01261             break;
01262       }
01263    }
01264    if (!ast_opt_hide_connect) {
01265       ast_verb(3, "Remote UNIX connection disconnected\n");
01266    }
01267    close(con->fd);
01268    close(con->p[0]);
01269    close(con->p[1]);
01270    con->fd = -1;
01271    
01272    return NULL;
01273 }
01274 
01275 static void *listener(void *unused)
01276 {
01277    struct sockaddr_un sunaddr;
01278    int s;
01279    socklen_t len;
01280    int x;
01281    int flags;
01282    struct pollfd fds[1];
01283    for (;;) {
01284       if (ast_socket < 0)
01285          return NULL;
01286       fds[0].fd = ast_socket;
01287       fds[0].events = POLLIN;
01288       s = ast_poll(fds, 1, -1);
01289       pthread_testcancel();
01290       if (s < 0) {
01291          if (errno != EINTR)
01292             ast_log(LOG_WARNING, "poll returned error: %s\n", strerror(errno));
01293          continue;
01294       }
01295       len = sizeof(sunaddr);
01296       s = accept(ast_socket, (struct sockaddr *)&sunaddr, &len);
01297       if (s < 0) {
01298          if (errno != EINTR)
01299             ast_log(LOG_WARNING, "Accept returned %d: %s\n", s, strerror(errno));
01300       } else {
01301 #if !defined(SO_PASSCRED)
01302          {
01303 #else
01304          int sckopt = 1;
01305          /* turn on socket credentials passing. */
01306          if (setsockopt(s, SOL_SOCKET, SO_PASSCRED, &sckopt, sizeof(sckopt)) < 0) {
01307             ast_log(LOG_WARNING, "Unable to turn on socket credentials passing\n");
01308          } else {
01309 #endif
01310             for (x = 0; x < AST_MAX_CONNECTS; x++) {
01311                if (consoles[x].fd >= 0) {
01312                   continue;
01313                }
01314                if (socketpair(AF_LOCAL, SOCK_STREAM, 0, consoles[x].p)) {
01315                   ast_log(LOG_ERROR, "Unable to create pipe: %s\n", strerror(errno));
01316                   consoles[x].fd = -1;
01317                   fdprint(s, "Server failed to create pipe\n");
01318                   close(s);
01319                   break;
01320                }
01321                flags = fcntl(consoles[x].p[1], F_GETFL);
01322                fcntl(consoles[x].p[1], F_SETFL, flags | O_NONBLOCK);
01323                consoles[x].fd = s;
01324                consoles[x].mute = 1; /* Default is muted, we will un-mute if necessary */
01325                /* Default uid and gid to -2, so then in cli.c/cli_has_permissions() we will be able
01326                   to know if the user didn't send the credentials. */
01327                consoles[x].uid = -2;
01328                consoles[x].gid = -2;
01329                if (ast_pthread_create_detached_background(&consoles[x].t, NULL, netconsole, &consoles[x])) {
01330                   ast_log(LOG_ERROR, "Unable to spawn thread to handle connection: %s\n", strerror(errno));
01331                   close(consoles[x].p[0]);
01332                   close(consoles[x].p[1]);
01333                   consoles[x].fd = -1;
01334                   fdprint(s, "Server failed to spawn thread\n");
01335                   close(s);
01336                }
01337                break;
01338             }
01339             if (x >= AST_MAX_CONNECTS) {
01340                fdprint(s, "No more connections allowed\n");
01341                ast_log(LOG_WARNING, "No more connections allowed\n");
01342                close(s);
01343             } else if ((consoles[x].fd > -1) && (!ast_opt_hide_connect)) {
01344                ast_verb(3, "Remote UNIX connection\n");
01345             }
01346          }
01347       }
01348    }
01349    return NULL;
01350 }
01351 
01352 static int ast_makesocket(void)
01353 {
01354    struct sockaddr_un sunaddr;
01355    int res;
01356    int x;
01357    uid_t uid = -1;
01358    gid_t gid = -1;
01359 
01360    for (x = 0; x < AST_MAX_CONNECTS; x++) 
01361       consoles[x].fd = -1;
01362    unlink(ast_config_AST_SOCKET);
01363    ast_socket = socket(PF_LOCAL, SOCK_STREAM, 0);
01364    if (ast_socket < 0) {
01365       ast_log(LOG_WARNING, "Unable to create control socket: %s\n", strerror(errno));
01366       return -1;
01367    }     
01368    memset(&sunaddr, 0, sizeof(sunaddr));
01369    sunaddr.sun_family = AF_LOCAL;
01370    ast_copy_string(sunaddr.sun_path, ast_config_AST_SOCKET, sizeof(sunaddr.sun_path));
01371    res = bind(ast_socket, (struct sockaddr *)&sunaddr, sizeof(sunaddr));
01372    if (res) {
01373       ast_log(LOG_WARNING, "Unable to bind socket to %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
01374       close(ast_socket);
01375       ast_socket = -1;
01376       return -1;
01377    }
01378    res = listen(ast_socket, 2);
01379    if (res < 0) {
01380       ast_log(LOG_WARNING, "Unable to listen on socket %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
01381       close(ast_socket);
01382       ast_socket = -1;
01383       return -1;
01384    }
01385    if (ast_register_verbose(network_verboser)) {
01386       ast_log(LOG_WARNING, "Unable to register network verboser?\n");
01387    }
01388 
01389    ast_pthread_create_background(&lthread, NULL, listener, NULL);
01390 
01391    if (!ast_strlen_zero(ast_config_AST_CTL_OWNER)) {
01392       struct passwd *pw;
01393       if ((pw = getpwnam(ast_config_AST_CTL_OWNER)) == NULL)
01394          ast_log(LOG_WARNING, "Unable to find uid of user %s\n", ast_config_AST_CTL_OWNER);
01395       else
01396          uid = pw->pw_uid;
01397    }
01398       
01399    if (!ast_strlen_zero(ast_config_AST_CTL_GROUP)) {
01400       struct group *grp;
01401       if ((grp = getgrnam(ast_config_AST_CTL_GROUP)) == NULL)
01402          ast_log(LOG_WARNING, "Unable to find gid of group %s\n", ast_config_AST_CTL_GROUP);
01403       else
01404          gid = grp->gr_gid;
01405    }
01406 
01407    if (chown(ast_config_AST_SOCKET, uid, gid) < 0)
01408       ast_log(LOG_WARNING, "Unable to change ownership of %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
01409 
01410    if (!ast_strlen_zero(ast_config_AST_CTL_PERMISSIONS)) {
01411       int p1;
01412       mode_t p;
01413       sscanf(ast_config_AST_CTL_PERMISSIONS, "%30o", &p1);
01414       p = p1;
01415       if ((chmod(ast_config_AST_SOCKET, p)) < 0)
01416          ast_log(LOG_WARNING, "Unable to change file permissions of %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
01417    }
01418 
01419    return 0;
01420 }
01421 
01422 static int ast_tryconnect(void)
01423 {
01424    struct sockaddr_un sunaddr;
01425    int res;
01426    ast_consock = socket(PF_LOCAL, SOCK_STREAM, 0);
01427    if (ast_consock < 0) {
01428       ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
01429       return 0;
01430    }
01431    memset(&sunaddr, 0, sizeof(sunaddr));
01432    sunaddr.sun_family = AF_LOCAL;
01433    ast_copy_string(sunaddr.sun_path, ast_config_AST_SOCKET, sizeof(sunaddr.sun_path));
01434    res = connect(ast_consock, (struct sockaddr *)&sunaddr, sizeof(sunaddr));
01435    if (res) {
01436       close(ast_consock);
01437       ast_consock = -1;
01438       return 0;
01439    } else
01440       return 1;
01441 }
01442 
01443 /*! \brief Urgent handler
01444 
01445  Called by soft_hangup to interrupt the poll, read, or other
01446  system call.  We don't actually need to do anything though.  
01447  Remember: Cannot EVER ast_log from within a signal handler 
01448  */
01449 static void _urg_handler(int num)
01450 {
01451    return;
01452 }
01453 
01454 static struct sigaction urg_handler = {
01455    .sa_handler = _urg_handler,
01456    .sa_flags = SA_RESTART,
01457 };
01458 
01459 static void _hup_handler(int num)
01460 {
01461    int a = 0;
01462    if (option_verbose > 1) 
01463       printf("Received HUP signal -- Reloading configs\n");
01464    if (restartnow)
01465       execvp(_argv[0], _argv);
01466    sig_flags.need_reload = 1;
01467    if (sig_alert_pipe[1] != -1) {
01468       if (write(sig_alert_pipe[1], &a, sizeof(a)) < 0) {
01469          fprintf(stderr, "hup_handler: write() failed: %s\n", strerror(errno));
01470       }
01471    }
01472 }
01473 
01474 static struct sigaction hup_handler = {
01475    .sa_handler = _hup_handler,
01476    .sa_flags = SA_RESTART,
01477 };
01478 
01479 static void _child_handler(int sig)
01480 {
01481    /* Must not ever ast_log or ast_verbose within signal handler */
01482    int n, status;
01483 
01484    /*
01485     * Reap all dead children -- not just one
01486     */
01487    for (n = 0; wait4(-1, &status, WNOHANG, NULL) > 0; n++)
01488       ;
01489    if (n == 0 && option_debug)   
01490       printf("Huh?  Child handler, but nobody there?\n");
01491 }
01492 
01493 static struct sigaction child_handler = {
01494    .sa_handler = _child_handler,
01495    .sa_flags = SA_RESTART,
01496 };
01497 
01498 /*! \brief Set maximum open files */
01499 static void set_ulimit(int value)
01500 {
01501    struct rlimit l = {0, 0};
01502    
01503    if (value <= 0) {
01504       ast_log(LOG_WARNING, "Unable to change max files open to invalid value %i\n",value);
01505       return;
01506    }
01507    
01508    l.rlim_cur = value;
01509    l.rlim_max = value;
01510    
01511    if (setrlimit(RLIMIT_NOFILE, &l)) {
01512       ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n",strerror(errno));
01513       return;
01514    }
01515    
01516    ast_log(LOG_NOTICE, "Setting max files open to %d\n",value);
01517    
01518    return;
01519 }
01520 
01521 /*! \brief Set an X-term or screen title */
01522 static void set_title(char *text)
01523 {
01524    if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
01525       fprintf(stdout, "\033]2;%s\007", text);
01526 }
01527 
01528 static void set_icon(char *text)
01529 {
01530    if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
01531       fprintf(stdout, "\033]1;%s\007", text);
01532 }
01533 
01534 /*! \brief We set ourselves to a high priority, that we might pre-empt everything
01535    else.  If your PBX has heavy activity on it, this is a good thing.  */
01536 int ast_set_priority(int pri)
01537 {
01538    struct sched_param sched;
01539    memset(&sched, 0, sizeof(sched));
01540 #ifdef __linux__
01541    if (pri) {  
01542       sched.sched_priority = 10;
01543       if (sched_setscheduler(0, SCHED_RR, &sched)) {
01544          ast_log(LOG_WARNING, "Unable to set high priority\n");
01545          return -1;
01546       } else
01547          if (option_verbose)
01548             ast_verbose("Set to realtime thread\n");
01549    } else {
01550       sched.sched_priority = 0;
01551       /* According to the manpage, these parameters can never fail. */
01552       sched_setscheduler(0, SCHED_OTHER, &sched);
01553    }
01554 #else
01555    if (pri) {
01556       if (setpriority(PRIO_PROCESS, 0, -10) == -1) {
01557          ast_log(LOG_WARNING, "Unable to set high priority\n");
01558          return -1;
01559       } else
01560          if (option_verbose)
01561             ast_verbose("Set to high priority\n");
01562    } else {
01563       /* According to the manpage, these parameters can never fail. */
01564       setpriority(PRIO_PROCESS, 0, 0);
01565    }
01566 #endif
01567    return 0;
01568 }
01569 
01570 static void ast_run_atexits(void)
01571 {
01572    struct ast_atexit *ae;
01573    AST_RWLIST_RDLOCK(&atexits);
01574    AST_RWLIST_TRAVERSE(&atexits, ae, list) {
01575       if (ae->func) 
01576          ae->func();
01577    }
01578    AST_RWLIST_UNLOCK(&atexits);
01579 }
01580 
01581 static void quit_handler(int num, int niceness, int safeshutdown, int restart)
01582 {
01583    char filename[80] = "";
01584    time_t s,e;
01585    int x;
01586    /* Try to get as many CDRs as possible submitted to the backend engines (if in batch mode) */
01587    ast_cdr_engine_term();
01588    if (safeshutdown) {
01589       shuttingdown = 1;
01590       if (!niceness) {
01591          /* Begin shutdown routine, hanging up active channels */
01592          ast_begin_shutdown(1);
01593          if (option_verbose && ast_opt_console)
01594             ast_verbose("Beginning asterisk %s....\n", restart ? "restart" : "shutdown");
01595          time(&s);
01596          for (;;) {
01597             time(&e);
01598             /* Wait up to 15 seconds for all channels to go away */
01599             if ((e - s) > 15)
01600                break;
01601             if (!ast_active_channels())
01602                break;
01603             if (!shuttingdown)
01604                break;
01605             /* Sleep 1/10 of a second */
01606             usleep(100000);
01607          }
01608       } else {
01609          if (niceness < 2)
01610             ast_begin_shutdown(0);
01611          if (option_verbose && ast_opt_console)
01612             ast_verbose("Waiting for inactivity to perform %s...\n", restart ? "restart" : "halt");
01613          for (;;) {
01614             if (!ast_active_channels())
01615                break;
01616             if (!shuttingdown)
01617                break;
01618             sleep(1);
01619          }
01620       }
01621 
01622       if (!shuttingdown) {
01623          if (option_verbose && ast_opt_console)
01624             ast_verbose("Asterisk %s cancelled.\n", restart ? "restart" : "shutdown");
01625          return;
01626       }
01627 
01628       if (niceness)
01629          ast_module_shutdown();
01630    }
01631    if (ast_opt_console || (ast_opt_remote && !ast_opt_exec)) {
01632       pthread_t thisthread = pthread_self();
01633       if (getenv("HOME")) {
01634          snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
01635       }
01636       if (!ast_strlen_zero(filename)) {
01637          ast_el_write_history(filename);
01638       }
01639       if (consolethread == AST_PTHREADT_NULL || consolethread == thisthread || mon_sig_flags == thisthread) {
01640          /* Only end if we are the consolethread or signal handler, otherwise there's a race with that thread. */
01641          if (el != NULL) {
01642             el_end(el);
01643          }
01644          if (el_hist != NULL) {
01645             history_end(el_hist);
01646          }
01647       }
01648    }
01649    if (option_verbose)
01650       ast_verbose("Executing last minute cleanups\n");
01651    ast_run_atexits();
01652    /* Called on exit */
01653    if (option_verbose && ast_opt_console)
01654       ast_verbose("Asterisk %s ending (%d).\n", ast_active_channels() ? "uncleanly" : "cleanly", num);
01655    ast_debug(1, "Asterisk ending (%d).\n", num);
01656    manager_event(EVENT_FLAG_SYSTEM, "Shutdown", "Shutdown: %s\r\nRestart: %s\r\n", ast_active_channels() ? "Uncleanly" : "Cleanly", restart ? "True" : "False");
01657    if (ast_socket > -1) {
01658       pthread_cancel(lthread);
01659       close(ast_socket);
01660       ast_socket = -1;
01661       unlink(ast_config_AST_SOCKET);
01662    }
01663    if (ast_consock > -1)
01664       close(ast_consock);
01665    if (!ast_opt_remote)
01666       unlink(ast_config_AST_PID);
01667    printf("%s", term_quit());
01668    if (restart) {
01669       if (option_verbose || ast_opt_console)
01670          ast_verbose("Preparing for Asterisk restart...\n");
01671       /* Mark all FD's for closing on exec */
01672       for (x=3; x < 32768; x++) {
01673          fcntl(x, F_SETFD, FD_CLOEXEC);
01674       }
01675       if (option_verbose || ast_opt_console)
01676          ast_verbose("Asterisk is now restarting...\n");
01677       restartnow = 1;
01678 
01679       /* close logger */
01680       close_logger();
01681 
01682       /* If there is a consolethread running send it a SIGHUP 
01683          so it can execvp, otherwise we can do it ourselves */
01684       if ((consolethread != AST_PTHREADT_NULL) && (consolethread != pthread_self())) {
01685          pthread_kill(consolethread, SIGHUP);
01686          /* Give the signal handler some time to complete */
01687          sleep(2);
01688       } else
01689          execvp(_argv[0], _argv);
01690    
01691    } else {
01692       /* close logger */
01693       close_logger();
01694    }
01695    exit(0);
01696 }
01697 
01698 static void __quit_handler(int num)
01699 {
01700    int a = 0;
01701    sig_flags.need_quit = 1;
01702    if (sig_alert_pipe[1] != -1) {
01703       if (write(sig_alert_pipe[1], &a, sizeof(a)) < 0) {
01704          fprintf(stderr, "quit_handler: write() failed: %s\n", strerror(errno));
01705       }
01706    }
01707    /* There is no need to restore the signal handler here, since the app
01708     * is going to exit */
01709 }
01710 
01711 static void __remote_quit_handler(int num)
01712 {
01713    sig_flags.need_quit = 1;
01714 }
01715 
01716 static const char *fix_header(char *outbuf, int maxout, const char *s, char *cmp)
01717 {
01718    const char *c;
01719 
01720    /* Check for verboser preamble */
01721    if (*s == 127) {
01722       s++;
01723    }
01724 
01725    if (!strncmp(s, cmp, strlen(cmp))) {
01726       c = s + strlen(cmp);
01727       term_color(outbuf, cmp, COLOR_GRAY, 0, maxout);
01728       return c;
01729    }
01730    return NULL;
01731 }
01732 
01733 static void console_verboser(const char *s)
01734 {
01735    char tmp[80];
01736    const char *c = NULL;
01737 
01738    if ((c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_4)) ||
01739        (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_3)) ||
01740        (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_2)) ||
01741        (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_1))) {
01742       fputs(tmp, stdout);
01743       fputs(c, stdout);
01744    } else {
01745       if (*s == 127) {
01746          s++;
01747       }
01748       fputs(s, stdout);
01749    }
01750 
01751    fflush(stdout);
01752    
01753    /* Wake up a poll()ing console */
01754    if (ast_opt_console && consolethread != AST_PTHREADT_NULL)
01755       pthread_kill(consolethread, SIGURG);
01756 }
01757 
01758 static int ast_all_zeros(char *s)
01759 {
01760    while (*s) {
01761       if (*s > 32)
01762          return 0;
01763       s++;  
01764    }
01765    return 1;
01766 }
01767 
01768 static void consolehandler(char *s)
01769 {
01770    printf("%s", term_end());
01771    fflush(stdout);
01772 
01773    /* Called when readline data is available */
01774    if (!ast_all_zeros(s))
01775       ast_el_add_history(s);
01776    /* The real handler for bang */
01777    if (s[0] == '!') {
01778       if (s[1])
01779          ast_safe_system(s+1);
01780       else
01781          ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
01782    } else 
01783       ast_cli_command(STDOUT_FILENO, s);
01784 }
01785 
01786 static int remoteconsolehandler(char *s)
01787 {
01788    int ret = 0;
01789 
01790    /* Called when readline data is available */
01791    if (!ast_all_zeros(s))
01792       ast_el_add_history(s);
01793    /* The real handler for bang */
01794    if (s[0] == '!') {
01795       if (s[1])
01796          ast_safe_system(s+1);
01797       else
01798          ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
01799       ret = 1;
01800    }
01801    if ((strncasecmp(s, "quit", 4) == 0 || strncasecmp(s, "exit", 4) == 0) &&
01802        (s[4] == '\0' || isspace(s[4]))) {
01803       quit_handler(0, 0, 0, 0);
01804       ret = 1;
01805    }
01806 
01807    return ret;
01808 }
01809 
01810 static char *handle_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01811 {
01812    switch (cmd) {
01813    case CLI_INIT:
01814       e->command = "core show version";
01815       e->usage = 
01816          "Usage: core show version\n"
01817          "       Shows Asterisk version information.\n";
01818       return NULL;
01819    case CLI_GENERATE:
01820       return NULL;
01821    }
01822 
01823    if (a->argc != 3)
01824       return CLI_SHOWUSAGE;
01825    ast_cli(a->fd, "Asterisk %s built by %s @ %s on a %s running %s on %s\n",
01826       ast_get_version(), ast_build_user, ast_build_hostname,
01827       ast_build_machine, ast_build_os, ast_build_date);
01828    return CLI_SUCCESS;
01829 }
01830 
01831 #if 0
01832 static int handle_quit(int fd, int argc, char *argv[])
01833 {
01834    if (argc != 1)
01835       return RESULT_SHOWUSAGE;
01836    quit_handler(0, 0, 1, 0);
01837    return RESULT_SUCCESS;
01838 }
01839 #endif
01840 
01841 static char *handle_stop_now(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01842 {
01843    switch (cmd) {
01844    case CLI_INIT:
01845       e->command = "core stop now";
01846       e->usage = 
01847          "Usage: core stop now\n"
01848          "       Shuts down a running Asterisk immediately, hanging up all active calls .\n";
01849       return NULL;
01850    case CLI_GENERATE:
01851       return NULL;
01852    }
01853 
01854    if (a->argc != e->args)
01855       return CLI_SHOWUSAGE;
01856    quit_handler(0, 0 /* Not nice */, 1 /* safely */, 0 /* not restart */);
01857    return CLI_SUCCESS;
01858 }
01859 
01860 static char *handle_stop_gracefully(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01861 {
01862    switch (cmd) {
01863    case CLI_INIT:
01864       e->command = "core stop gracefully";
01865       e->usage = 
01866          "Usage: core stop gracefully\n"
01867          "       Causes Asterisk to not accept new calls, and exit when all\n"
01868          "       active calls have terminated normally.\n";
01869       return NULL;
01870    case CLI_GENERATE:
01871       return NULL;
01872    }
01873 
01874    if (a->argc != e->args)
01875       return CLI_SHOWUSAGE;
01876    quit_handler(0, 1 /* nicely */, 1 /* safely */, 0 /* no restart */);
01877    return CLI_SUCCESS;
01878 }
01879 
01880 static char *handle_stop_when_convenient(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01881 {
01882    switch (cmd) {
01883    case CLI_INIT:
01884       e->command = "core stop when convenient";
01885       e->usage = 
01886          "Usage: core stop when convenient\n"
01887          "       Causes Asterisk to perform a shutdown when all active calls have ended.\n";
01888       return NULL;
01889    case CLI_GENERATE:
01890       return NULL;
01891    }
01892 
01893    if (a->argc != e->args)
01894       return CLI_SHOWUSAGE;
01895    ast_cli(a->fd, "Waiting for inactivity to perform halt\n");
01896    quit_handler(0, 2 /* really nicely */, 1 /* safely */, 0 /* don't restart */);
01897    return CLI_SUCCESS;
01898 }
01899 
01900 static char *handle_restart_now(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01901 {
01902    switch (cmd) {
01903    case CLI_INIT:
01904       e->command = "core restart now";
01905       e->usage = 
01906          "Usage: core restart now\n"
01907          "       Causes Asterisk to hangup all calls and exec() itself performing a cold\n"
01908          "       restart.\n";
01909       return NULL;
01910    case CLI_GENERATE:
01911       return NULL;
01912    }
01913 
01914    if (a->argc != e->args)
01915       return CLI_SHOWUSAGE;
01916    quit_handler(0, 0 /* not nicely */, 1 /* safely */, 1 /* restart */);
01917    return CLI_SUCCESS;
01918 }
01919 
01920 static char *handle_restart_gracefully(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01921 {
01922    switch (cmd) {
01923    case CLI_INIT:
01924       e->command = "core restart gracefully";
01925       e->usage = 
01926          "Usage: core restart gracefully\n"
01927          "       Causes Asterisk to stop accepting new calls and exec() itself performing a cold\n"
01928          "       restart when all active calls have ended.\n";
01929       return NULL;
01930    case CLI_GENERATE:
01931       return NULL;
01932    }
01933 
01934    if (a->argc != e->args)
01935       return CLI_SHOWUSAGE;
01936    quit_handler(0, 1 /* nicely */, 1 /* safely */, 1 /* restart */);
01937    return CLI_SUCCESS;
01938 }
01939 
01940 static char *handle_restart_when_convenient(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01941 {
01942    switch (cmd) {
01943    case CLI_INIT:
01944       e->command = "core restart when convenient";
01945       e->usage = 
01946          "Usage: core restart when convenient\n"
01947          "       Causes Asterisk to perform a cold restart when all active calls have ended.\n";
01948       return NULL;
01949    case CLI_GENERATE:
01950       return NULL;
01951    }
01952 
01953    if (a->argc != e->args)
01954       return CLI_SHOWUSAGE;
01955    ast_cli(a->fd, "Waiting for inactivity to perform restart\n");
01956    quit_handler(0, 2 /* really nicely */, 1 /* safely */, 1 /* restart */);
01957    return CLI_SUCCESS;
01958 }
01959 
01960 static char *handle_abort_shutdown(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01961 {
01962    switch (cmd) {
01963    case CLI_INIT:
01964       e->command = "core abort shutdown";
01965       e->usage = 
01966          "Usage: core abort shutdown\n"
01967          "       Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
01968          "       call operations.\n";
01969       return NULL;
01970    case CLI_GENERATE:
01971       return NULL;
01972    }
01973 
01974    if (a->argc != e->args)
01975       return CLI_SHOWUSAGE;
01976    ast_cancel_shutdown();
01977    shuttingdown = 0;
01978    return CLI_SUCCESS;
01979 }
01980 
01981 static char *handle_bang(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01982 {
01983    switch (cmd) {
01984    case CLI_INIT:
01985       e->command = "!";
01986       e->usage = 
01987          "Usage: !<command>\n"
01988          "       Executes a given shell command\n";
01989       return NULL;
01990    case CLI_GENERATE:
01991       return NULL;
01992    }
01993 
01994    return CLI_SUCCESS;
01995 }
01996 static const char warranty_lines[] = {
01997    "\n"
01998    "            NO WARRANTY\n"
01999    "\n"
02000    "BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\n"
02001    "FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\n"
02002    "OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\n"
02003    "PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\n"
02004    "OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n"
02005    "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\n"
02006    "TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\n"
02007    "PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\n"
02008    "REPAIR OR CORRECTION.\n"
02009    "\n"
02010    "IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\n"
02011    "WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\n"
02012    "REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\n"
02013    "INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\n"
02014    "OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\n"
02015    "TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\n"
02016    "YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\n"
02017    "PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\n"
02018    "POSSIBILITY OF SUCH DAMAGES.\n"
02019 };
02020 
02021 static char *show_warranty(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
02022 {
02023    switch (cmd) {
02024    case CLI_INIT:
02025       e->command = "core show warranty";
02026       e->usage = 
02027          "Usage: core show warranty\n"
02028          "       Shows the warranty (if any) for this copy of Asterisk.\n";
02029       return NULL;
02030    case CLI_GENERATE:
02031       return NULL;
02032    }
02033 
02034    ast_cli(a->fd, "%s", warranty_lines);
02035 
02036    return CLI_SUCCESS;
02037 }
02038 
02039 static const char license_lines[] = {
02040    "\n"
02041    "This program is free software; you can redistribute it and/or modify\n"
02042    "it under the terms of the GNU General Public License version 2 as\n"
02043    "published by the Free Software Foundation.\n"
02044    "\n"
02045    "This program also contains components licensed under other licenses.\n"
02046    "They include:\n"
02047    "\n"
02048    "This program is distributed in the hope that it will be useful,\n"
02049    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
02050    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
02051    "GNU General Public License for more details.\n"
02052    "\n"
02053    "You should have received a copy of the GNU General Public License\n"
02054    "along with this program; if not, write to the Free Software\n"
02055    "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
02056 };
02057 
02058 static char *show_license(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
02059 {
02060    switch (cmd) {
02061    case CLI_INIT:
02062       e->command = "core show license";
02063       e->usage = 
02064          "Usage: core show license\n"
02065          "       Shows the license(s) for this copy of Asterisk.\n";
02066       return NULL;
02067    case CLI_GENERATE:
02068       return NULL;
02069    }
02070 
02071    ast_cli(a->fd, "%s", license_lines);
02072 
02073    return CLI_SUCCESS;
02074 }
02075 
02076 #define ASTERISK_PROMPT "*CLI> "
02077 
02078 #define ASTERISK_PROMPT2 "%s*CLI> "
02079 
02080 static struct ast_cli_entry cli_asterisk[] = {
02081    AST_CLI_DEFINE(handle_abort_shutdown, "Cancel a running shutdown"),
02082    AST_CLI_DEFINE(handle_stop_now, "Shut down Asterisk immediately"),
02083    AST_CLI_DEFINE(handle_stop_gracefully, "Gracefully shut down Asterisk"),
02084    AST_CLI_DEFINE(handle_stop_when_convenient, "Shut down Asterisk at empty call volume"),
02085    AST_CLI_DEFINE(handle_restart_now, "Restart Asterisk immediately"), 
02086    AST_CLI_DEFINE(handle_restart_gracefully, "Restart Asterisk gracefully"),
02087    AST_CLI_DEFINE(handle_restart_when_convenient, "Restart Asterisk at empty call volume"),
02088    AST_CLI_DEFINE(show_warranty, "Show the warranty (if any) for this copy of Asterisk"),
02089    AST_CLI_DEFINE(show_license, "Show the license(s) for this copy of Asterisk"),
02090    AST_CLI_DEFINE(handle_version, "Display version info"),
02091    AST_CLI_DEFINE(handle_bang, "Execute a shell command"),
02092 #if !defined(LOW_MEMORY)
02093    AST_CLI_DEFINE(handle_show_version_files, "List versions of files used to build Asterisk"),
02094    AST_CLI_DEFINE(handle_show_threads, "Show running threads"),
02095 #if defined(HAVE_SYSINFO) || defined(HAVE_SYSCTL)
02096    AST_CLI_DEFINE(handle_show_sysinfo, "Show System Information"),
02097 #endif
02098    AST_CLI_DEFINE(handle_show_profile, "Display profiling info"),
02099    AST_CLI_DEFINE(handle_show_settings, "Show some core settings"),
02100    AST_CLI_DEFINE(handle_clear_profile, "Clear profiling info"),
02101 #endif /* ! LOW_MEMORY */
02102 };
02103 
02104 static int ast_el_read_char(EditLine *editline, char *cp)
02105 {
02106    int num_read = 0;
02107    int lastpos = 0;
02108    struct pollfd fds[2];
02109    int res;
02110    int max;
02111 #define EL_BUF_SIZE 512
02112    char buf[EL_BUF_SIZE];
02113 
02114    for (;;) {
02115       max = 1;
02116       fds[0].fd = ast_consock;
02117       fds[0].events = POLLIN;
02118       if (!ast_opt_exec) {
02119          fds[1].fd = STDIN_FILENO;
02120          fds[1].events = POLLIN;
02121          max++;
02122       }
02123       res = ast_poll(fds, max, -1);
02124       if (res < 0) {
02125          if (sig_flags.need_quit)
02126             break;
02127          if (errno == EINTR)
02128             continue;
02129          ast_log(LOG_ERROR, "poll failed: %s\n", strerror(errno));
02130          break;
02131       }
02132 
02133       if (!ast_opt_exec && fds[1].revents) {
02134          num_read = read(STDIN_FILENO, cp, 1);
02135          if (num_read < 1) {
02136             break;
02137          } else 
02138             return (num_read);
02139       }
02140       if (fds[0].revents) {
02141          char *tmp;
02142          res = read(ast_consock, buf, sizeof(buf) - 1);
02143          /* if the remote side disappears exit */
02144          if (res < 1) {
02145             fprintf(stderr, "\nDisconnected from Asterisk server\n");
02146             if (!ast_opt_reconnect) {
02147                quit_handler(0, 0, 0, 0);
02148             } else {
02149                int tries;
02150                int reconnects_per_second = 20;
02151                fprintf(stderr, "Attempting to reconnect for 30 seconds\n");
02152                for (tries = 0; tries < 30 * reconnects_per_second; tries++) {
02153                   if (ast_tryconnect()) {
02154                      fprintf(stderr, "Reconnect succeeded after %.3f seconds\n", 1.0 / reconnects_per_second * tries);
02155                      printf("%s", term_quit());
02156                      WELCOME_MESSAGE;
02157                      if (!ast_opt_mute)
02158                         fdsend(ast_consock, "logger mute silent");
02159                      else 
02160                         printf("log and verbose output currently muted ('logger mute' to unmute)\n");
02161                      break;
02162                   } else
02163                      usleep(1000000 / reconnects_per_second);
02164                }
02165                if (tries >= 30 * reconnects_per_second) {
02166                   fprintf(stderr, "Failed to reconnect for 30 seconds.  Quitting.\n");
02167                   quit_handler(0, 0, 0, 0);
02168                }
02169             }
02170          }
02171 
02172          buf[res] = '\0';
02173 
02174          /* Strip preamble from asynchronous events, too */
02175          for (tmp = buf; *tmp; tmp++) {
02176             if (*tmp == 127) {
02177                memmove(tmp, tmp + 1, strlen(tmp));
02178                tmp--;
02179                res--;
02180             }
02181          }
02182 
02183          /* Write over the CLI prompt */
02184          if (!ast_opt_exec && !lastpos) {
02185             if (write(STDOUT_FILENO, "\r", 5) < 0) {
02186             }
02187          }
02188          if (write(STDOUT_FILENO, buf, res) < 0) {
02189          }
02190          if ((res < EL_BUF_SIZE - 1) && ((buf[res-1] == '\n') || (buf[res-2] == '\n'))) {
02191             *cp = CC_REFRESH;
02192             return(1);
02193          } else
02194             lastpos = 1;
02195       }
02196    }
02197 
02198    *cp = '\0';
02199    return (0);
02200 }
02201 
02202 static struct ast_str *prompt = NULL;
02203 
02204 static char *cli_prompt(EditLine *editline)
02205 {
02206    char tmp[100];
02207    char *pfmt;
02208    int color_used = 0;
02209    static int cli_prompt_changes = 0;
02210    char term_code[20];
02211    struct passwd *pw;
02212    struct group *gr;
02213 
02214    if (prompt == NULL) {
02215       prompt = ast_str_create(100);
02216    } else if (!cli_prompt_changes) {
02217       return ast_str_buffer(prompt);
02218    } else {
02219       ast_str_reset(prompt);
02220    }
02221 
02222    if ((pfmt = getenv("ASTERISK_PROMPT"))) {
02223       char *t = pfmt;
02224       struct timeval ts = ast_tvnow();
02225       while (*t != '\0') {
02226          if (*t == '%') {
02227             char hostname[MAXHOSTNAMELEN] = "";
02228             int i, which;
02229             struct ast_tm tm = { 0, };
02230             int fgcolor = COLOR_WHITE, bgcolor = COLOR_BLACK;
02231 
02232             t++;
02233             switch (*t) {
02234             case 'C': /* color */
02235                t++;
02236                if (sscanf(t, "%30d;%30d%n", &fgcolor, &bgcolor, &i) == 2) {
02237                   ast_str_append(&prompt, 0, "%s", term_color_code(term_code, fgcolor, bgcolor, sizeof(term_code)));
02238                   t += i - 1;
02239                } else if (sscanf(t, "%30d%n", &fgcolor, &i) == 1) {
02240                   ast_str_append(&prompt, 0, "%s", term_color_code(term_code, fgcolor, 0, sizeof(term_code)));
02241                   t += i - 1;
02242                }
02243 
02244                /* If the color has been reset correctly, then there's no need to reset it later */
02245                color_used = ((fgcolor == COLOR_WHITE) && (bgcolor == COLOR_BLACK)) ? 0 : 1;
02246                break;
02247             case 'd': /* date */
02248                if (ast_localtime(&ts, &tm, NULL)) {
02249                   ast_strftime(tmp, sizeof(tmp), "%Y-%m-%d", &tm);
02250                   ast_str_append(&prompt, 0, "%s", tmp);
02251                   cli_prompt_changes++;
02252                }
02253                break;
02254             case 'g': /* group */
02255                if ((gr = getgrgid(getgid()))) {
02256                   ast_str_append(&prompt, 0, "%s", gr->gr_name);
02257                }
02258                break;
02259             case 'h': /* hostname */
02260                if (!gethostname(hostname, sizeof(hostname) - 1)) {
02261                   ast_str_append(&prompt, 0, "%s", hostname);
02262                } else {
02263                   ast_str_append(&prompt, 0, "%s", "localhost");
02264                }
02265                break;
02266             case 'H': /* short hostname */
02267                if (!gethostname(hostname, sizeof(hostname) - 1)) {
02268                   char *dotptr;
02269                   if ((dotptr = strchr(hostname, '.'))) {
02270                      *dotptr = '\0';
02271                   }
02272                   ast_str_append(&prompt, 0, "%s", hostname);
02273                } else {
02274                   ast_str_append(&prompt, 0, "%s", "localhost");
02275                }
02276                break;
02277 #ifdef HAVE_GETLOADAVG
02278             case 'l': /* load avg */
02279                t++;
02280                if (sscanf(t, "%30d", &which) == 1 && which > 0 && which <= 3) {
02281                   double list[3];
02282                   getloadavg(list, 3);
02283                   ast_str_append(&prompt, 0, "%.2f", list[which - 1]);
02284                   cli_prompt_changes++;
02285                }
02286                break;
02287 #endif
02288             case 's': /* Asterisk system name (from asterisk.conf) */
02289                ast_str_append(&prompt, 0, "%s", ast_config_AST_SYSTEM_NAME);
02290                break;
02291             case 't': /* time */
02292                if (ast_localtime(&ts, &tm, NULL)) {
02293                   ast_strftime(tmp, sizeof(tmp), "%H:%M:%S", &tm);
02294                   ast_str_append(&prompt, 0, "%s", tmp);
02295                   cli_prompt_changes++;
02296                }
02297                break;
02298             case 'u': /* username */
02299                if ((pw = getpwuid(getuid()))) {
02300                   ast_str_append(&prompt, 0, "%s", pw->pw_name);
02301                }
02302                break;
02303             case '#': /* process console or remote? */
02304                ast_str_append(&prompt, 0, "%c", ast_opt_remote ? '>' : '#');
02305                break;
02306             case '%': /* literal % */
02307                ast_str_append(&prompt, 0, "%c", '%');
02308                break;
02309             case '\0': /* % is last character - prevent bug */
02310                t--;
02311                break;
02312             }
02313          } else {
02314             ast_str_append(&prompt, 0, "%c", *t);
02315          }
02316          t++;
02317       }
02318       if (color_used) {
02319          /* Force colors back to normal at end */
02320          ast_str_append(&prompt, 0, "%s", term_color_code(term_code, 0, 0, sizeof(term_code)));
02321       }
02322    } else if (remotehostname) {
02323       ast_str_set(&prompt, 0, ASTERISK_PROMPT2, remotehostname);
02324    } else {
02325       ast_str_set(&prompt, 0, "%s", ASTERISK_PROMPT);
02326    }
02327 
02328    return ast_str_buffer(prompt);   
02329 }
02330 
02331 static char **ast_el_strtoarr(char *buf)
02332 {
02333    char **match_list = NULL, **match_list_tmp, *retstr;
02334    size_t match_list_len;
02335    int matches = 0;
02336 
02337    match_list_len = 1;
02338    while ( (retstr = strsep(&buf, " ")) != NULL) {
02339 
02340       if (!strcmp(retstr, AST_CLI_COMPLETE_EOF))
02341          break;
02342       if (matches + 1 >= match_list_len) {
02343          match_list_len <<= 1;
02344          if ((match_list_tmp = ast_realloc(match_list, match_list_len * sizeof(char *)))) {
02345             match_list = match_list_tmp;
02346          } else {
02347             if (match_list)
02348                ast_free(match_list);
02349             return (char **) NULL;
02350          }
02351       }
02352 
02353       match_list[matches++] = ast_strdup(retstr);
02354    }
02355 
02356    if (!match_list)
02357       return (char **) NULL;
02358 
02359    if (matches >= match_list_len) {
02360       if ((match_list_tmp = ast_realloc(match_list, (match_list_len + 1) * sizeof(char *)))) {
02361          match_list = match_list_tmp;
02362       } else {
02363          if (match_list)
02364             ast_free(match_list);
02365          return (char **) NULL;
02366       }
02367    }
02368 
02369    match_list[matches] = (char *) NULL;
02370 
02371    return match_list;
02372 }
02373 
02374 static int ast_el_sort_compare(const void *i1, const void *i2)
02375 {
02376    char *s1, *s2;
02377 
02378    s1 = ((char **)i1)[0];
02379    s2 = ((char **)i2)[0];
02380 
02381    return strcasecmp(s1, s2);
02382 }
02383 
02384 static int ast_cli_display_match_list(char **matches, int len, int max)
02385 {
02386    int i, idx, limit, count;
02387    int screenwidth = 0;
02388    int numoutput = 0, numoutputline = 0;
02389 
02390    screenwidth = ast_get_termcols(STDOUT_FILENO);
02391 
02392    /* find out how many entries can be put on one line, with two spaces between strings */
02393    limit = screenwidth / (max + 2);
02394    if (limit == 0)
02395       limit = 1;
02396 
02397    /* how many lines of output */
02398    count = len / limit;
02399    if (count * limit < len)
02400       count++;
02401 
02402    idx = 1;
02403 
02404    qsort(&matches[0], (size_t)(len), sizeof(char *), ast_el_sort_compare);
02405 
02406    for (; count > 0; count--) {
02407       numoutputline = 0;
02408       for (i = 0; i < limit && matches[idx]; i++, idx++) {
02409 
02410          /* Don't print dupes */
02411          if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
02412             i--;
02413             ast_free(matches[idx]);
02414             matches[idx] = NULL;
02415             continue;
02416          }
02417 
02418          numoutput++;
02419          numoutputline++;
02420          fprintf(stdout, "%-*s  ", max, matches[idx]);
02421          ast_free(matches[idx]);
02422          matches[idx] = NULL;
02423       }
02424       if (numoutputline > 0)
02425          fprintf(stdout, "\n");
02426    }
02427 
02428    return numoutput;
02429 }
02430 
02431 
02432 static char *cli_complete(EditLine *editline, int ch)
02433 {
02434    int len = 0;
02435    char *ptr;
02436    int nummatches = 0;
02437    char **matches;
02438    int retval = CC_ERROR;
02439    char buf[2048], savechr;
02440    int res;
02441 
02442    LineInfo *lf = (LineInfo *)el_line(editline);
02443 
02444    savechr = *(char *)lf->cursor;
02445    *(char *)lf->cursor = '\0';
02446    ptr = (char *)lf->cursor;
02447    if (ptr) {
02448       while (ptr > lf->buffer) {
02449          if (isspace(*ptr)) {
02450             ptr++;
02451             break;
02452          }
02453          ptr--;
02454       }
02455    }
02456 
02457    len = lf->cursor - ptr;
02458 
02459    if (ast_opt_remote) {
02460       snprintf(buf, sizeof(buf), "_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr); 
02461       fdsend(ast_consock, buf);
02462       res = read(ast_consock, buf, sizeof(buf) - 1);
02463       buf[res] = '\0';
02464       nummatches = atoi(buf);
02465 
02466       if (nummatches > 0) {
02467          char *mbuf;
02468          int mlen = 0, maxmbuf = 2048;
02469          /* Start with a 2048 byte buffer */       
02470          if (!(mbuf = ast_malloc(maxmbuf))) {
02471             lf->cursor[0] = savechr;
02472             return (char *)(CC_ERROR);
02473          }
02474          snprintf(buf, sizeof(buf), "_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr); 
02475          fdsend(ast_consock, buf);
02476          res = 0;
02477          mbuf[0] = '\0';
02478          while (!strstr(mbuf, AST_CLI_COMPLETE_EOF) && res != -1) {
02479             if (mlen + 1024 > maxmbuf) {
02480                /* Every step increment buffer 1024 bytes */
02481                maxmbuf += 1024;              
02482                if (!(mbuf = ast_realloc(mbuf, maxmbuf))) {
02483                   lf->cursor[0] = savechr;
02484                   return (char *)(CC_ERROR);
02485                }
02486             }
02487             /* Only read 1024 bytes at a time */
02488             res = read(ast_consock, mbuf + mlen, 1024);
02489             if (res > 0)
02490                mlen += res;
02491          }
02492          mbuf[mlen] = '\0';
02493 
02494          matches = ast_el_strtoarr(mbuf);
02495          ast_free(mbuf);
02496       } else
02497          matches = (char **) NULL;
02498    } else {
02499       char **p, *oldbuf=NULL;
02500       nummatches = 0;
02501       matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
02502       for (p = matches; p && *p; p++) {
02503          if (!oldbuf || strcmp(*p,oldbuf))
02504             nummatches++;
02505          oldbuf = *p;
02506       }
02507    }
02508 
02509    if (matches) {
02510       int i;
02511       int matches_num, maxlen, match_len;
02512 
02513       if (matches[0][0] != '\0') {
02514          el_deletestr(editline, (int) len);
02515          el_insertstr(editline, matches[0]);
02516          retval = CC_REFRESH;
02517       }
02518 
02519       if (nummatches == 1) {
02520          /* Found an exact match */
02521          el_insertstr(editline, " ");
02522          retval = CC_REFRESH;
02523       } else {
02524          /* Must be more than one match */
02525          for (i = 1, maxlen = 0; matches[i]; i++) {
02526             match_len = strlen(matches[i]);
02527             if (match_len > maxlen)
02528                maxlen = match_len;
02529          }
02530          matches_num = i - 1;
02531          if (matches_num >1) {
02532             fprintf(stdout, "\n");
02533             ast_cli_display_match_list(matches, nummatches, maxlen);
02534             retval = CC_REDISPLAY;
02535          } else { 
02536             el_insertstr(editline," ");
02537             retval = CC_REFRESH;
02538          }
02539       }
02540       for (i = 0; matches[i]; i++)
02541          ast_free(matches[i]);
02542       ast_free(matches);
02543    }
02544 
02545    lf->cursor[0] = savechr;
02546 
02547    return (char *)(long)retval;
02548 }
02549 
02550 static int ast_el_initialize(void)
02551 {
02552    HistEvent ev;
02553    char *editor = getenv("AST_EDITOR");
02554 
02555    if (el != NULL)
02556       el_end(el);
02557    if (el_hist != NULL)
02558       history_end(el_hist);
02559 
02560    el = el_init("asterisk", stdin, stdout, stderr);
02561    el_set(el, EL_PROMPT, cli_prompt);
02562 
02563    el_set(el, EL_EDITMODE, 1);      
02564    el_set(el, EL_EDITOR, editor ? editor : "emacs");     
02565    el_hist = history_init();
02566    if (!el || !el_hist)
02567       return -1;
02568 
02569    /* setup history with 100 entries */
02570    history(el_hist, &ev, H_SETSIZE, 100);
02571 
02572    el_set(el, EL_HIST, history, el_hist);
02573 
02574    el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
02575    /* Bind <tab> to command completion */
02576    el_set(el, EL_BIND, "^I", "ed-complete", NULL);
02577    /* Bind ? to command completion */
02578    el_set(el, EL_BIND, "?", "ed-complete", NULL);
02579    /* Bind ^D to redisplay */
02580    el_set(el, EL_BIND, "^D", "ed-redisplay", NULL);
02581 
02582    return 0;
02583 }
02584 
02585 #define MAX_HISTORY_COMMAND_LENGTH 256
02586 
02587 static int ast_el_add_history(char *buf)
02588 {
02589    HistEvent ev;
02590 
02591    if (el_hist == NULL || el == NULL)
02592       ast_el_initialize();
02593    if (strlen(buf) > (MAX_HISTORY_COMMAND_LENGTH - 1))
02594       return 0;
02595    return (history(el_hist, &ev, H_ENTER, ast_strip(ast_strdupa(buf))));
02596 }
02597 
02598 static int ast_el_write_history(char *filename)
02599 {
02600    HistEvent ev;
02601 
02602    if (el_hist == NULL || el == NULL)
02603       ast_el_initialize();
02604 
02605    return (history(el_hist, &ev, H_SAVE, filename));
02606 }
02607 
02608 static int ast_el_read_history(char *filename)
02609 {
02610    char buf[MAX_HISTORY_COMMAND_LENGTH];
02611    FILE *f;
02612    int ret = -1;
02613 
02614    if (el_hist == NULL || el == NULL)
02615       ast_el_initialize();
02616 
02617    if ((f = fopen(filename, "r")) == NULL)
02618       return ret;
02619 
02620    while (!feof(f)) {
02621       if (!fgets(buf, sizeof(buf), f))
02622          break;
02623       if (!strcmp(buf, "_HiStOrY_V2_\n"))
02624          continue;
02625       if (ast_all_zeros(buf))
02626          continue;
02627       if ((ret = ast_el_add_history(buf)) == -1)
02628          break;
02629    }
02630    fclose(f);
02631 
02632    return ret;
02633 }
02634 
02635 static void ast_remotecontrol(char *data)
02636 {
02637    char buf[80];
02638    int res;
02639    char filename[80] = "";
02640    char *hostname;
02641    char *cpid;
02642    char *version;
02643    int pid;
02644    char *stringp = NULL;
02645 
02646    char *ebuf;
02647    int num = 0;
02648 
02649    memset(&sig_flags, 0, sizeof(sig_flags));
02650    signal(SIGINT, __remote_quit_handler);
02651    signal(SIGTERM, __remote_quit_handler);
02652    signal(SIGHUP, __remote_quit_handler);
02653 
02654    if (read(ast_consock, buf, sizeof(buf)) < 0) {
02655       ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
02656       return;
02657    }
02658    if (data) {
02659       char prefix[] = "cli quit after ";
02660       char *tmp = alloca(strlen(data) + strlen(prefix) + 1);
02661       sprintf(tmp, "%s%s", prefix, data);
02662       if (write(ast_consock, tmp, strlen(tmp) + 1) < 0) {
02663          ast_log(LOG_ERROR, "write() failed: %s\n", strerror(errno));
02664          if (sig_flags.need_quit == 1) {
02665             return;
02666          }
02667       }
02668    }
02669    stringp = buf;
02670    hostname = strsep(&stringp, "/");
02671    cpid = strsep(&stringp, "/");
02672    version = strsep(&stringp, "\n");
02673    if (!version)
02674       version = "<Version Unknown>";
02675    stringp = hostname;
02676    strsep(&stringp, ".");
02677    if (cpid)
02678       pid = atoi(cpid);
02679    else
02680       pid = -1;
02681    if (!data) {
02682       char tmp[80];
02683       snprintf(tmp, sizeof(tmp), "core set verbose atleast %d", option_verbose);
02684       fdsend(ast_consock, tmp);
02685       snprintf(tmp, sizeof(tmp), "core set debug atleast %d", option_debug);
02686       fdsend(ast_consock, tmp);
02687       if (!ast_opt_mute)
02688          fdsend(ast_consock, "logger mute silent");
02689       else 
02690          printf("log and verbose output currently muted ('logger mute' to unmute)\n");
02691    }
02692 
02693    if (ast_opt_exec && data) {  /* hack to print output then exit if asterisk -rx is used */
02694       struct pollfd fds;
02695       fds.fd = ast_consock;
02696       fds.events = POLLIN;
02697       fds.revents = 0;
02698       while (ast_poll(&fds, 1, 60000) > 0) {
02699          char buffer[512] = "", *curline = buffer, *nextline;
02700          int not_written = 1;
02701 
02702          if (sig_flags.need_quit == 1) {
02703             break;
02704          }
02705 
02706          if (read(ast_consock, buffer, sizeof(buffer) - 1) <= 0) {
02707             break;
02708          }
02709 
02710          do {
02711             if ((nextline = strchr(curline, '\n'))) {
02712                nextline++;
02713             } else {
02714                nextline = strchr(curline, '\0');
02715             }
02716 
02717             /* Skip verbose lines */
02718             if (*curline != 127) {
02719                not_written = 0;
02720                if (write(STDOUT_FILENO, curline, nextline - curline) < 0) {
02721                   ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
02722                }
02723             }
02724             curline = nextline;
02725          } while (!ast_strlen_zero(curline));
02726 
02727          /* No non-verbose output in 60s */
02728          if (not_written) {
02729             break;
02730          }
02731       }
02732       return;
02733    }
02734 
02735    ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
02736    remotehostname = hostname;
02737    if (getenv("HOME")) 
02738       snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
02739    if (el_hist == NULL || el == NULL)
02740       ast_el_initialize();
02741 
02742    el_set(el, EL_GETCFN, ast_el_read_char);
02743 
02744    if (!ast_strlen_zero(filename))
02745       ast_el_read_history(filename);
02746 
02747    for (;;) {
02748       ebuf = (char *)el_gets(el, &num);
02749 
02750       if (sig_flags.need_quit == 1) {
02751          break;
02752       }
02753 
02754       if (!ebuf && write(1, "", 1) < 0)
02755          break;
02756 
02757       if (!ast_strlen_zero(ebuf)) {
02758          if (ebuf[strlen(ebuf)-1] == '\n')
02759             ebuf[strlen(ebuf)-1] = '\0';
02760          if (!remoteconsolehandler(ebuf)) {
02761             /* Strip preamble from output */
02762             char *temp;
02763             for (temp = ebuf; *temp; temp++) {
02764                if (*temp == 127) {
02765                   memmove(temp, temp + 1, strlen(temp));
02766                   temp--;
02767                }
02768             }
02769             res = write(ast_consock, ebuf, strlen(ebuf) + 1);
02770             if (res < 1) {
02771                ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
02772                break;
02773             }
02774          }
02775       }
02776    }
02777    printf("\nDisconnected from Asterisk server\n");
02778 }
02779 
02780 static int show_version(void)
02781 {
02782    printf("Asterisk %s\n", ast_get_version());
02783    return 0;
02784 }
02785 
02786 static int show_cli_help(void) {
02787    printf("Asterisk %s, Copyright (C) 1999 - 2010, Digium, Inc. and others.\n", ast_get_version());
02788    printf("Usage: asterisk [OPTIONS]\n");
02789    printf("Valid Options:\n");
02790    printf("   -V              Display version number and exit\n");
02791    printf("   -C <configfile> Use an alternate configuration file\n");
02792    printf("   -G <group>      Run as a group other than the caller\n");
02793    printf("   -U <user>       Run as a user other than the caller\n");
02794    printf("   -c              Provide console CLI\n");
02795    printf("   -d              Enable extra debugging\n");
02796 #if HAVE_WORKING_FORK
02797    printf("   -f              Do not fork\n");
02798    printf("   -F              Always fork\n");
02799 #endif
02800    printf("   -g              Dump core in case of a crash\n");
02801    printf("   -h              This help screen\n");
02802    printf("   -i              Initialize crypto keys at startup\n");
02803    printf("   -I              Enable internal timing if DAHDI timer is available\n");
02804    printf("   -L <load>       Limit the maximum load average before rejecting new calls\n");
02805    printf("   -M <value>      Limit the maximum number of calls to the specified value\n");
02806    printf("   -m              Mute debugging and console output on the console\n");
02807    printf("   -n              Disable console colorization\n");
02808    printf("   -p              Run as pseudo-realtime thread\n");
02809    printf("   -q              Quiet mode (suppress output)\n");
02810    printf("   -r              Connect to Asterisk on this machine\n");
02811    printf("   -R              Same as -r, except attempt to reconnect if disconnected\n");
02812    printf("   -s <socket>     Connect to Asterisk via socket <socket> (only valid with -r)\n");
02813    printf("   -t              Record soundfiles in /var/tmp and move them where they\n");
02814    printf("                   belong after they are done\n");
02815    printf("   -T              Display the time in [Mmm dd hh:mm:ss] format for each line\n");
02816    printf("                   of output to the CLI\n");
02817    printf("   -v              Increase verbosity (multiple v's = more verbose)\n");
02818    printf("   -x <cmd>        Execute command <cmd> (only valid with -r)\n");
02819    printf("   -W              Adjust terminal colors to compensate for a light background\n");
02820    printf("\n");
02821    return 0;
02822 }
02823 
02824 static void ast_readconfig(void) 
02825 {
02826    struct ast_config *cfg;
02827    struct ast_variable *v;
02828    char *config = DEFAULT_CONFIG_FILE;
02829    char hostname[MAXHOSTNAMELEN] = "";
02830    struct ast_flags config_flags = { 0 };
02831    struct {
02832       unsigned int dbdir:1;
02833       unsigned int keydir:1;
02834    } found = { 0, 0 };
02835 
02836    if (ast_opt_override_config) {
02837       cfg = ast_config_load2(ast_config_AST_CONFIG_FILE, "" /* core, can't reload */, config_flags);
02838       if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID)
02839          ast_log(LOG_WARNING, "Unable to open specified master config file '%s', using built-in defaults\n", ast_config_AST_CONFIG_FILE);
02840    } else 
02841       cfg = ast_config_load2(config, "" /* core, can't reload */, config_flags);
02842 
02843    /* init with buildtime config */
02844    ast_copy_string(cfg_paths.config_dir, DEFAULT_CONFIG_DIR, sizeof(cfg_paths.config_dir));
02845    ast_copy_string(cfg_paths.spool_dir, DEFAULT_SPOOL_DIR, sizeof(cfg_paths.spool_dir));
02846    ast_copy_string(cfg_paths.module_dir, DEFAULT_MODULE_DIR, sizeof(cfg_paths.module_dir));
02847    snprintf(cfg_paths.monitor_dir, sizeof(cfg_paths.monitor_dir), "%s/monitor", cfg_paths.spool_dir);
02848    ast_copy_string(cfg_paths.var_dir, DEFAULT_VAR_DIR, sizeof(cfg_paths.var_dir));
02849    ast_copy_string(cfg_paths.data_dir, DEFAULT_DATA_DIR, sizeof(cfg_paths.data_dir));
02850    ast_copy_string(cfg_paths.log_dir, DEFAULT_LOG_DIR, sizeof(cfg_paths.log_dir));
02851    ast_copy_string(cfg_paths.agi_dir, DEFAULT_AGI_DIR, sizeof(cfg_paths.agi_dir));
02852    ast_copy_string(cfg_paths.db_path, DEFAULT_DB, sizeof(cfg_paths.db_path));
02853    ast_copy_string(cfg_paths.key_dir, DEFAULT_KEY_DIR, sizeof(cfg_paths.key_dir));
02854    ast_copy_string(cfg_paths.pid_path, DEFAULT_PID, sizeof(cfg_paths.pid_path));
02855    ast_copy_string(cfg_paths.socket_path, DEFAULT_SOCKET, sizeof(cfg_paths.socket_path));
02856    ast_copy_string(cfg_paths.run_dir, DEFAULT_RUN_DIR, sizeof(cfg_paths.run_dir));
02857 
02858    ast_set_default_eid(&ast_eid_default);
02859 
02860    /* no asterisk.conf? no problem, use buildtime config! */
02861    if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
02862       return;
02863    }
02864 
02865    for (v = ast_variable_browse(cfg, "files"); v; v = v->next) {
02866       if (!strcasecmp(v->name, "astctlpermissions"))
02867          ast_copy_string(ast_config_AST_CTL_PERMISSIONS, v->value, sizeof(ast_config_AST_CTL_PERMISSIONS));
02868       else if (!strcasecmp(v->name, "astctlowner"))
02869          ast_copy_string(ast_config_AST_CTL_OWNER, v->value, sizeof(ast_config_AST_CTL_OWNER));
02870       else if (!strcasecmp(v->name, "astctlgroup"))
02871          ast_copy_string(ast_config_AST_CTL_GROUP, v->value, sizeof(ast_config_AST_CTL_GROUP));
02872       else if (!strcasecmp(v->name, "astctl"))
02873          ast_copy_string(ast_config_AST_CTL, v->value, sizeof(ast_config_AST_CTL));
02874    }
02875 
02876    for (v = ast_variable_browse(cfg, "directories"); v; v = v->next) {
02877       if (!strcasecmp(v->name, "astetcdir")) {
02878          ast_copy_string(cfg_paths.config_dir, v->value, sizeof(cfg_paths.config_dir));
02879       } else if (!strcasecmp(v->name, "astspooldir")) {
02880          ast_copy_string(cfg_paths.spool_dir, v->value, sizeof(cfg_paths.spool_dir));
02881          snprintf(cfg_paths.monitor_dir, sizeof(cfg_paths.monitor_dir), "%s/monitor", v->value);
02882       } else if (!strcasecmp(v->name, "astvarlibdir")) {
02883          ast_copy_string(cfg_paths.var_dir, v->value, sizeof(cfg_paths.var_dir));
02884          if (!found.dbdir)
02885             snprintf(cfg_paths.db_path, sizeof(cfg_paths.db_path), "%s/astdb", v->value);
02886       } else if (!strcasecmp(v->name, "astdbdir")) {
02887          snprintf(cfg_paths.db_path, sizeof(cfg_paths.db_path), "%s/astdb", v->value);
02888          found.dbdir = 1;
02889       } else if (!strcasecmp(v->name, "astdatadir")) {
02890          ast_copy_string(cfg_paths.data_dir, v->value, sizeof(cfg_paths.data_dir));
02891          if (!found.keydir)
02892             snprintf(cfg_paths.key_dir, sizeof(cfg_paths.key_dir), "%s/keys", v->value);
02893       } else if (!strcasecmp(v->name, "astkeydir")) {
02894          snprintf(cfg_paths.key_dir, sizeof(cfg_paths.key_dir), "%s/keys", v->value);
02895          found.keydir = 1;
02896       } else if (!strcasecmp(v->name, "astlogdir")) {
02897          ast_copy_string(cfg_paths.log_dir, v->value, sizeof(cfg_paths.log_dir));
02898       } else if (!strcasecmp(v->name, "astagidir")) {
02899          ast_copy_string(cfg_paths.agi_dir, v->value, sizeof(cfg_paths.agi_dir));
02900       } else if (!strcasecmp(v->name, "astrundir")) {
02901          snprintf(cfg_paths.pid_path, sizeof(cfg_paths.pid_path), "%s/%s", v->value, "asterisk.pid");
02902          snprintf(cfg_paths.socket_path, sizeof(cfg_paths.socket_path), "%s/%s", v->value, ast_config_AST_CTL);
02903          ast_copy_string(cfg_paths.run_dir, v->value, sizeof(cfg_paths.run_dir));
02904       } else if (!strcasecmp(v->name, "astmoddir")) {
02905          ast_copy_string(cfg_paths.module_dir, v->value, sizeof(cfg_paths.module_dir));
02906       }
02907    }
02908 
02909    for (v = ast_variable_browse(cfg, "options"); v; v = v->next) {
02910       /* verbose level (-v at startup) */
02911       if (!strcasecmp(v->name, "verbose")) {
02912          option_verbose = atoi(v->value);
02913       /* whether or not to force timestamping in CLI verbose output. (-T at startup) */
02914       } else if (!strcasecmp(v->name, "timestamp")) {
02915          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_TIMESTAMP);
02916       /* whether or not to support #exec in config files */
02917       } else if (!strcasecmp(v->name, "execincludes")) {
02918          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_EXEC_INCLUDES);
02919       /* debug level (-d at startup) */
02920       } else if (!strcasecmp(v->name, "debug")) {
02921          option_debug = 0;
02922          if (sscanf(v->value, "%30d", &option_debug) != 1) {
02923             option_debug = ast_true(v->value);
02924          }
02925 #if HAVE_WORKING_FORK
02926       /* Disable forking (-f at startup) */
02927       } else if (!strcasecmp(v->name, "nofork")) {
02928          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_NO_FORK);
02929       /* Always fork, even if verbose or debug are enabled (-F at startup) */
02930       } else if (!strcasecmp(v->name, "alwaysfork")) {
02931          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_ALWAYS_FORK);
02932 #endif
02933       /* Run quietly (-q at startup ) */
02934       } else if (!strcasecmp(v->name, "quiet")) {
02935          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_QUIET);
02936       /* Run as console (-c at startup, implies nofork) */
02937       } else if (!strcasecmp(v->name, "console")) {
02938          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_NO_FORK | AST_OPT_FLAG_CONSOLE);
02939       /* Run with high priority if the O/S permits (-p at startup) */
02940       } else if (!strcasecmp(v->name, "highpriority")) {
02941          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_HIGH_PRIORITY);
02942       /* Initialize RSA auth keys (IAX2) (-i at startup) */
02943       } else if (!strcasecmp(v->name, "initcrypto")) {
02944          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_INIT_KEYS);
02945       /* Disable ANSI colors for console (-c at startup) */
02946       } else if (!strcasecmp(v->name, "nocolor")) {
02947          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_NO_COLOR);
02948       /* Disable some usage warnings for picky people :p */
02949       } else if (!strcasecmp(v->name, "dontwarn")) {
02950          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_DONT_WARN);
02951       /* Dump core in case of crash (-g) */
02952       } else if (!strcasecmp(v->name, "dumpcore")) {
02953          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_DUMP_CORE);
02954       /* Cache recorded sound files to another directory during recording */
02955       } else if (!strcasecmp(v->name, "cache_record_files")) {
02956          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_CACHE_RECORD_FILES);
02957       /* Specify cache directory */
02958       }  else if (!strcasecmp(v->name, "record_cache_dir")) {
02959          ast_copy_string(record_cache_dir, v->value, AST_CACHE_DIR_LEN);
02960       /* Build transcode paths via SLINEAR, instead of directly */
02961       } else if (!strcasecmp(v->name, "transcode_via_sln")) {
02962          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_TRANSCODE_VIA_SLIN);
02963       /* Transmit SLINEAR silence while a channel is being recorded or DTMF is being generated on a channel */
02964       } else if (!strcasecmp(v->name, "transmit_silence_during_record") || !strcasecmp(v->name, "transmit_silence")) {
02965          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_TRANSMIT_SILENCE);
02966       /* Enable internal timing */
02967       } else if (!strcasecmp(v->name, "internal_timing")) {
02968          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_INTERNAL_TIMING);
02969       } else if (!strcasecmp(v->name, "maxcalls")) {
02970          if ((sscanf(v->value, "%30d", &option_maxcalls) != 1) || (option_maxcalls < 0)) {
02971             option_maxcalls = 0;
02972          }
02973       } else if (!strcasecmp(v->name, "maxload")) {
02974          double test[1];
02975 
02976          if (getloadavg(test, 1) == -1) {
02977             ast_log(LOG_ERROR, "Cannot obtain load average on this system. 'maxload' option disabled.\n");
02978             option_maxload = 0.0;
02979          } else if ((sscanf(v->value, "%30lf", &option_maxload) != 1) || (option_maxload < 0.0)) {
02980             option_maxload = 0.0;
02981          }
02982       /* Set the maximum amount of open files */
02983       } else if (!strcasecmp(v->name, "maxfiles")) {
02984          option_maxfiles = atoi(v->value);
02985          set_ulimit(option_maxfiles);
02986       /* What user to run as */
02987       } else if (!strcasecmp(v->name, "runuser")) {
02988          ast_copy_string(cfg_paths.run_user, v->value, sizeof(cfg_paths.run_user));
02989       /* What group to run as */
02990       } else if (!strcasecmp(v->name, "rungroup")) {
02991          ast_copy_string(cfg_paths.run_group, v->value, sizeof(cfg_paths.run_group));
02992       } else if (!strcasecmp(v->name, "systemname")) {
02993          ast_copy_string(cfg_paths.system_name, v->value, sizeof(cfg_paths.system_name));
02994       } else if (!strcasecmp(v->name, "autosystemname")) {
02995          if (ast_true(v->value)) {
02996             if (!gethostname(hostname, sizeof(hostname) - 1))
02997                ast_copy_string(cfg_paths.system_name, hostname, sizeof(cfg_paths.system_name));
02998             else {
02999                if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)){
03000                   ast_copy_string(cfg_paths.system_name, "localhost", sizeof(cfg_paths.system_name));
03001                }
03002                ast_log(LOG_ERROR, "Cannot obtain hostname for this system.  Using '%s' instead.\n", ast_config_AST_SYSTEM_NAME);
03003             }
03004          }
03005       } else if (!strcasecmp(v->name, "languageprefix")) {
03006          ast_language_is_prefix = ast_true(v->value);
03007       } else if (!strcasecmp(v->name, "lockmode")) {
03008          if (!strcasecmp(v->value, "lockfile")) {
03009             ast_set_lock_type(AST_LOCK_TYPE_LOCKFILE);
03010          } else if (!strcasecmp(v->value, "flock")) {
03011             ast_set_lock_type(AST_LOCK_TYPE_FLOCK);
03012          } else {
03013             ast_log(LOG_WARNING, "'%s' is not a valid setting for the lockmode option, "
03014                "defaulting to 'lockfile'\n", v->value);
03015             ast_set_lock_type(AST_LOCK_TYPE_LOCKFILE);
03016          }
03017 #if defined(HAVE_SYSINFO)
03018       } else if (!strcasecmp(v->name, "minmemfree")) {
03019          /* specify the minimum amount of free memory to retain.  Asterisk should stop accepting new calls
03020           * if the amount of free memory falls below this watermark */
03021          if ((sscanf(v->value, "%30ld", &option_minmemfree) != 1) || (option_minmemfree < 0)) {
03022             option_minmemfree = 0;
03023          }
03024 #endif
03025       } else if (!strcasecmp(v->name, "entityid")) {
03026          struct ast_eid tmp_eid;
03027          if (!ast_str_to_eid(&tmp_eid, v->value)) {
03028             ast_verbose("Successfully set global EID to '%s'\n", v->value);
03029             ast_eid_default = tmp_eid;
03030          } else
03031             ast_verbose("Invalid Entity ID '%s' provided\n", v->value);
03032       } else if (!strcasecmp(v->name, "lightbackground")) {
03033          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_LIGHT_BACKGROUND);
03034       } else if (!strcasecmp(v->name, "forceblackbackground")) {
03035          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_FORCE_BLACK_BACKGROUND);
03036       } else if (!strcasecmp(v->name, "hideconnect")) {
03037          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_HIDE_CONSOLE_CONNECT);
03038       } else if (!strcasecmp(v->name, "sendfullybooted")) {
03039          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_SEND_FULLYBOOTED);
03040       }
03041    }
03042    for (v = ast_variable_browse(cfg, "compat"); v; v = v->next) {
03043       float version;
03044       if (sscanf(v->value, "%30f", &version) != 1) {
03045          ast_log(LOG_WARNING, "Compatibility version for option '%s' is not a number: '%s'\n", v->name, v->value);
03046          continue;
03047       }
03048       if (!strcasecmp(v->name, "app_set")) {
03049          ast_set2_flag(&ast_compat, version < 1.5 ? 1 : 0, AST_COMPAT_APP_SET);
03050       } else if (!strcasecmp(v->name, "res_agi")) {
03051          ast_set2_flag(&ast_compat, version < 1.5 ? 1 : 0, AST_COMPAT_DELIM_RES_AGI);
03052       } else if (!strcasecmp(v->name, "pbx_realtime")) {
03053          ast_set2_flag(&ast_compat, version < 1.5 ? 1 : 0, AST_COMPAT_DELIM_PBX_REALTIME);
03054       }
03055    }
03056    ast_config_destroy(cfg);
03057 }
03058 
03059 static void *monitor_sig_flags(void *unused)
03060 {
03061    for (;;) {
03062       struct pollfd p = { sig_alert_pipe[0], POLLIN, 0 };
03063       int a;
03064       ast_poll(&p, 1, -1);
03065       if (sig_flags.need_reload) {
03066          sig_flags.need_reload = 0;
03067          ast_module_reload(NULL);
03068       }
03069       if (sig_flags.need_quit) {
03070          sig_flags.need_quit = 0;
03071          quit_handler(0, 0, 1, 0);
03072       }
03073       if (read(sig_alert_pipe[0], &a, sizeof(a)) != sizeof(a)) {
03074       }
03075    }
03076 
03077    return NULL;
03078 }
03079 
03080 static void *canary_thread(void *unused)
03081 {
03082    struct stat canary_stat;
03083    struct timeval now;
03084 
03085    /* Give the canary time to sing */
03086    sleep(120);
03087 
03088    for (;;) {
03089       stat(canary_filename, &canary_stat);
03090       now = ast_tvnow();
03091       if (now.tv_sec > canary_stat.st_mtime + 60) {
03092          ast_log(LOG_WARNING, "The canary is no more.  He has ceased to be!  He's expired and gone to meet his maker!  He's a stiff!  Bereft of life, he rests in peace.  His metabolic processes are now history!  He's off the twig!  He's kicked the bucket.  He's shuffled off his mortal coil, run down the curtain, and joined the bleeding choir invisible!!  THIS is an EX-CANARY.  (Reducing priority)\n");
03093          ast_set_priority(0);
03094          pthread_exit(NULL);
03095       }
03096 
03097       /* Check the canary once a minute */
03098       sleep(60);
03099    }
03100 }
03101 
03102 /* Used by libc's atexit(3) function */
03103 static void canary_exit(void)
03104 {
03105    if (canary_pid > 0)
03106       kill(canary_pid, SIGKILL);
03107 }
03108 
03109 static void run_startup_commands(void)
03110 {
03111    int fd;
03112    struct ast_config *cfg;
03113    struct ast_flags cfg_flags = { 0 };
03114    struct ast_variable *v;
03115 
03116    if (!(cfg = ast_config_load2("cli.conf", "" /* core, can't reload */, cfg_flags)))
03117       return;
03118    if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
03119       return;
03120    }
03121 
03122    fd = open("/dev/null", O_RDWR);
03123    if (fd < 0) {
03124       ast_config_destroy(cfg);
03125       return;
03126    }
03127 
03128    for (v = ast_variable_browse(cfg, "startup_commands"); v; v = v->next) {
03129       if (ast_true(v->value))
03130          ast_cli_command(fd, v->name);
03131    }
03132 
03133    close(fd);
03134    ast_config_destroy(cfg);
03135 }
03136 
03137 int main(int argc, char *argv[])
03138 {
03139    int c;
03140    char filename[80] = "";
03141    char hostname[MAXHOSTNAMELEN] = "";
03142    char tmp[80];
03143    char * xarg = NULL;
03144    int x;
03145    FILE *f;
03146    sigset_t sigs;
03147    int num;
03148    int isroot = 1, rundir_exists = 0;
03149    char *buf;
03150    const char *runuser = NULL, *rungroup = NULL;
03151    char *remotesock = NULL;
03152    struct rlimit l;
03153 
03154    /* Remember original args for restart */
03155    if (argc > ARRAY_LEN(_argv) - 1) {
03156       fprintf(stderr, "Truncating argument size to %d\n", (int)ARRAY_LEN(_argv) - 1);
03157       argc = ARRAY_LEN(_argv) - 1;
03158    }
03159    for (x = 0; x < argc; x++)
03160       _argv[x] = argv[x];
03161    _argv[x] = NULL;
03162 
03163    if (geteuid() != 0)
03164       isroot = 0;
03165 
03166    /* if the progname is rasterisk consider it a remote console */
03167    if (argv[0] && (strstr(argv[0], "rasterisk")) != NULL) {
03168       ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK | AST_OPT_FLAG_REMOTE);
03169    }
03170    if (gethostname(hostname, sizeof(hostname)-1))
03171       ast_copy_string(hostname, "<Unknown>", sizeof(hostname));
03172    ast_mainpid = getpid();
03173    ast_ulaw_init();
03174    ast_alaw_init();
03175    callerid_init();
03176    ast_builtins_init();
03177    ast_utils_init();
03178    tdd_init();
03179    ast_tps_init();
03180    ast_fd_init();
03181    ast_pbx_init();
03182 
03183    if (getenv("HOME")) 
03184       snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
03185    /* Check for options */
03186    while ((c = getopt(argc, argv, "mtThfFdvVqprRgciInx:U:G:C:L:M:e:s:WB")) != -1) {
03187       switch (c) {
03188 #if defined(HAVE_SYSINFO)
03189       case 'e':
03190          if ((sscanf(&optarg[1], "%30ld", &option_minmemfree) != 1) || (option_minmemfree < 0)) {
03191             option_minmemfree = 0;
03192          }
03193          break;
03194 #endif
03195 #if HAVE_WORKING_FORK
03196       case 'F':
03197          ast_set_flag(&ast_options, AST_OPT_FLAG_ALWAYS_FORK);
03198          break;
03199       case 'f':
03200          ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK);
03201          break;
03202 #endif
03203       case 'd':
03204          option_debug++;
03205          ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK);
03206          break;
03207       case 'c':
03208          ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK | AST_OPT_FLAG_CONSOLE);
03209          break;
03210       case 'n':
03211          ast_set_flag(&ast_options, AST_OPT_FLAG_NO_COLOR);
03212          break;
03213       case 'r':
03214          ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK | AST_OPT_FLAG_REMOTE);
03215          break;
03216       case 'R':
03217          ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK | AST_OPT_FLAG_REMOTE | AST_OPT_FLAG_RECONNECT);
03218          break;
03219       case 'p':
03220          ast_set_flag(&ast_options, AST_OPT_FLAG_HIGH_PRIORITY);
03221          break;
03222       case 'v':
03223          option_verbose++;
03224          ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK);
03225          break;
03226       case 'm':
03227          ast_set_flag(&ast_options, AST_OPT_FLAG_MUTE);
03228          break;
03229       case 'M':
03230          if ((sscanf(optarg, "%30d", &option_maxcalls) != 1) || (option_maxcalls < 0))
03231             option_maxcalls = 0;
03232          break;
03233       case 'L':
03234          if ((sscanf(optarg, "%30lf", &option_maxload) != 1) || (option_maxload < 0.0))
03235             option_maxload = 0.0;
03236          break;
03237       case 'q':
03238          ast_set_flag(&ast_options, AST_OPT_FLAG_QUIET);
03239          break;
03240       case 't':
03241          ast_set_flag(&ast_options, AST_OPT_FLAG_CACHE_RECORD_FILES);
03242          break;
03243       case 'T':
03244          ast_set_flag(&ast_options, AST_OPT_FLAG_TIMESTAMP);
03245          break;
03246       case 'x':
03247          ast_set_flag(&ast_options, AST_OPT_FLAG_EXEC);
03248          xarg = ast_strdupa(optarg);
03249          break;
03250       case 'C':
03251          ast_copy_string(cfg_paths.config_file, optarg, sizeof(cfg_paths.config_file));
03252          ast_set_flag(&ast_options, AST_OPT_FLAG_OVERRIDE_CONFIG);
03253          break;
03254       case 'I':
03255          ast_set_flag(&ast_options, AST_OPT_FLAG_INTERNAL_TIMING);
03256          break;
03257       case 'i':
03258          ast_set_flag(&ast_options, AST_OPT_FLAG_INIT_KEYS);
03259          break;
03260       case 'g':
03261          ast_set_flag(&ast_options, AST_OPT_FLAG_DUMP_CORE);
03262          break;
03263       case 'h':
03264          show_cli_help();
03265          exit(0);
03266       case 'V':
03267          show_version();
03268          exit(0);
03269       case 'U':
03270          runuser = ast_strdupa(optarg);
03271          break;
03272       case 'G':
03273          rungroup = ast_strdupa(optarg);
03274          break;
03275       case 's':
03276          remotesock = ast_strdupa(optarg);
03277          break;
03278       case 'W': /* White background */
03279          ast_set_flag(&ast_options, AST_OPT_FLAG_LIGHT_BACKGROUND);
03280          ast_clear_flag(&ast_options, AST_OPT_FLAG_FORCE_BLACK_BACKGROUND);
03281          break;
03282       case 'B': /* Force black background */
03283          ast_set_flag(&ast_options, AST_OPT_FLAG_FORCE_BLACK_BACKGROUND);
03284          ast_clear_flag(&ast_options, AST_OPT_FLAG_LIGHT_BACKGROUND);
03285          break;
03286       case '?':
03287          exit(1);
03288       }
03289    }
03290 
03291    if (ast_opt_console || option_verbose || (ast_opt_remote && !ast_opt_exec)) {
03292       if (ast_register_verbose(console_verboser)) {
03293          ast_log(LOG_WARNING, "Unable to register console verboser?\n");
03294       }
03295       WELCOME_MESSAGE;
03296    }
03297 
03298    if (ast_opt_console && !option_verbose) 
03299       ast_verbose("[ Booting...\n");
03300 
03301    /* For remote connections, change the name of the remote connection.
03302     * We do this for the benefit of init scripts (which need to know if/when
03303     * the main asterisk process has died yet). */
03304    if (ast_opt_remote) {
03305       strcpy(argv[0], "rasterisk");
03306       for (x = 1; x < argc; x++) {
03307          argv[x] = argv[0] + 10;
03308       }
03309    }
03310 
03311    if (ast_opt_console && !option_verbose) {
03312       ast_verbose("[ Reading Master Configuration ]\n");
03313    }
03314 
03315    ast_readconfig();
03316 
03317    if (ast_opt_remote && remotesock != NULL)
03318       ast_copy_string((char *) cfg_paths.socket_path, remotesock, sizeof(cfg_paths.socket_path));
03319 
03320    if (!ast_language_is_prefix && !ast_opt_remote)
03321       ast_log(LOG_WARNING, "The 'languageprefix' option in asterisk.conf is deprecated; in a future release it will be removed, and your sound files will need to be organized in the 'new style' language layout.\n");
03322 
03323    if (ast_opt_always_fork && (ast_opt_remote || ast_opt_console)) {
03324       ast_log(LOG_WARNING, "'alwaysfork' is not compatible with console or remote console mode; ignored\n");
03325       ast_clear_flag(&ast_options, AST_OPT_FLAG_ALWAYS_FORK);
03326    }
03327 
03328    if (ast_opt_dump_core) {
03329       memset(&l, 0, sizeof(l));
03330       l.rlim_cur = RLIM_INFINITY;
03331       l.rlim_max = RLIM_INFINITY;
03332       if (setrlimit(RLIMIT_CORE, &l)) {
03333          ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
03334       }
03335    }
03336 
03337    if (getrlimit(RLIMIT_NOFILE, &l)) {
03338       ast_log(LOG_WARNING, "Unable to check file descriptor limit: %s\n", strerror(errno));
03339    }
03340 
03341 #if !defined(CONFIGURE_RAN_AS_ROOT)
03342    /* Check if select(2) will run with more file descriptors */
03343    do {
03344       int fd, fd2;
03345       ast_fdset readers;
03346       struct timeval tv = { 0, };
03347 
03348       if (l.rlim_cur <= FD_SETSIZE) {
03349          /* The limit of select()able FDs is irrelevant, because we'll never
03350           * open one that high. */
03351          break;
03352       }
03353 
03354       if (!(fd = open("/dev/null", O_RDONLY))) {
03355          ast_log(LOG_ERROR, "Cannot open a file descriptor at boot? %s\n", strerror(errno));
03356          break; /* XXX Should we exit() here? XXX */
03357       }
03358 
03359       fd2 = (l.rlim_cur > sizeof(readers) * 8 ? sizeof(readers) * 8 : l.rlim_cur) - 1;
03360       if (dup2(fd, fd2) < 0) {
03361          ast_log(LOG_WARNING, "Cannot open maximum file descriptor %d at boot? %s\n", fd2, strerror(errno));
03362          break;
03363       }
03364 
03365       FD_ZERO(&readers);
03366       FD_SET(fd2, &readers);
03367       if (ast_select(fd2 + 1, &readers, NULL, NULL, &tv) < 0) {
03368          ast_log(LOG_WARNING, "Maximum select()able file descriptor is %d\n", FD_SETSIZE);
03369       }
03370    } while (0);
03371 #elif defined(HAVE_VARIABLE_FDSET)
03372    ast_FD_SETSIZE = l.rlim_cur;
03373 #endif /* !defined(CONFIGURE_RAN_AS_ROOT) */
03374 
03375    if ((!rungroup) && !ast_strlen_zero(ast_config_AST_RUN_GROUP))
03376       rungroup = ast_config_AST_RUN_GROUP;
03377    if ((!runuser) && !ast_strlen_zero(ast_config_AST_RUN_USER))
03378       runuser = ast_config_AST_RUN_USER;
03379 
03380    /* Must install this signal handler up here to ensure that if the canary
03381     * fails to execute that it doesn't kill the Asterisk process.
03382     */
03383    sigaction(SIGCHLD, &child_handler, NULL);
03384 
03385    /* It's common on some platforms to clear /var/run at boot.  Create the
03386     * socket file directory before we drop privileges. */
03387    if (mkdir(ast_config_AST_RUN_DIR, 0755)) {
03388       if (errno == EEXIST) {
03389          rundir_exists = 1;
03390       } else {
03391          ast_log(LOG_WARNING, "Unable to create socket file directory.  Remote consoles will not be able to connect! (%s)\n", strerror(x));
03392       }
03393    }
03394 
03395 #ifndef __CYGWIN__
03396 
03397    if (isroot) {
03398       ast_set_priority(ast_opt_high_priority);
03399    }
03400 
03401    if (isroot && rungroup) {
03402       struct group *gr;
03403       gr = getgrnam(rungroup);
03404       if (!gr) {
03405          ast_log(LOG_WARNING, "No such group '%s'!\n", rungroup);
03406          exit(1);
03407       }
03408       if (!rundir_exists && chown(ast_config_AST_RUN_DIR, -1, gr->gr_gid)) {
03409          ast_log(LOG_WARNING, "Unable to chgrp run directory to %d (%s)\n", (int) gr->gr_gid, rungroup);
03410       }
03411       if (setgid(gr->gr_gid)) {
03412          ast_log(LOG_WARNING, "Unable to setgid to %d (%s)\n", (int)gr->gr_gid, rungroup);
03413          exit(1);
03414       }
03415       if (setgroups(0, NULL)) {
03416          ast_log(LOG_WARNING, "Unable to drop unneeded groups\n");
03417          exit(1);
03418       }
03419       if (option_verbose)
03420          ast_verbose("Running as group '%s'\n", rungroup);
03421    }
03422 
03423    if (runuser && !ast_test_flag(&ast_options, AST_OPT_FLAG_REMOTE)) {
03424 #ifdef HAVE_CAP
03425       int has_cap = 1;
03426 #endif /* HAVE_CAP */
03427       struct passwd *pw;
03428       pw = getpwnam(runuser);
03429       if (!pw) {
03430          ast_log(LOG_WARNING, "No such user '%s'!\n", runuser);
03431          exit(1);
03432       }
03433       if (chown(ast_config_AST_RUN_DIR, pw->pw_uid, -1)) {
03434          ast_log(LOG_WARNING, "Unable to chown run directory to %d (%s)\n", (int) pw->pw_uid, runuser);
03435       }
03436 #ifdef HAVE_CAP
03437       if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0)) {
03438          ast_log(LOG_WARNING, "Unable to keep capabilities.\n");
03439          has_cap = 0;
03440       }
03441 #endif /* HAVE_CAP */
03442       if (!isroot && pw->pw_uid != geteuid()) {
03443          ast_log(LOG_ERROR, "Asterisk started as nonroot, but runuser '%s' requested.\n", runuser);
03444          exit(1);
03445       }
03446       if (!rungroup) {
03447          if (setgid(pw->pw_gid)) {
03448             ast_log(LOG_WARNING, "Unable to setgid to %d!\n", (int)pw->pw_gid);
03449             exit(1);
03450          }
03451          if (isroot && initgroups(pw->pw_name, pw->pw_gid)) {
03452             ast_log(LOG_WARNING, "Unable to init groups for '%s'\n", runuser);
03453             exit(1);
03454          }
03455       }
03456       if (setuid(pw->pw_uid)) {
03457          ast_log(LOG_WARNING, "Unable to setuid to %d (%s)\n", (int)pw->pw_uid, runuser);
03458          exit(1);
03459       }
03460       if (option_verbose)
03461          ast_verbose("Running as user '%s'\n", runuser);
03462 #ifdef HAVE_CAP
03463       if (has_cap) {
03464          cap_t cap;
03465 
03466          cap = cap_from_text("cap_net_admin=eip");
03467 
03468          if (cap_set_proc(cap))
03469             ast_log(LOG_WARNING, "Unable to install capabilities.\n");
03470 
03471          if (cap_free(cap))
03472             ast_log(LOG_WARNING, "Unable to drop capabilities.\n");
03473       }
03474 #endif /* HAVE_CAP */
03475    }
03476 
03477 #endif /* __CYGWIN__ */
03478 
03479 #ifdef linux
03480    if (geteuid() && ast_opt_dump_core) {
03481       if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) < 0) {
03482          ast_log(LOG_WARNING, "Unable to set the process for core dumps after changing to a non-root user. %s\n", strerror(errno));
03483       }
03484    }
03485 #endif
03486 
03487    {
03488 #if defined(HAVE_EACCESS) || defined(HAVE_EUIDACCESS)
03489 #if defined(HAVE_EUIDACCESS) && !defined(HAVE_EACCESS)
03490 #define eaccess euidaccess
03491 #endif
03492       char dir[PATH_MAX];
03493       if (!getcwd(dir, sizeof(dir)) || eaccess(dir, R_OK | X_OK | F_OK)) {
03494          ast_log(LOG_ERROR, "Unable to access the running directory (%s).  Changing to '/' for compatibility.\n", strerror(errno));
03495          /* If we cannot access the CWD, then we couldn't dump core anyway,
03496           * so chdir("/") won't break anything. */
03497          if (chdir("/")) {
03498             /* chdir(/) should never fail, so this ends up being a no-op */
03499             ast_log(LOG_ERROR, "chdir(\"/\") failed?!! %s\n", strerror(errno));
03500          }
03501       } else
03502 #endif /* defined(HAVE_EACCESS) || defined(HAVE_EUIDACCESS) */
03503       if (!ast_opt_no_fork && !ast_opt_dump_core) {
03504          /* Backgrounding, but no cores, so chdir won't break anything. */
03505          if (chdir("/")) {
03506             ast_log(LOG_ERROR, "Unable to chdir(\"/\") ?!! %s\n", strerror(errno));
03507          }
03508       }
03509    }
03510 
03511    ast_term_init();
03512    printf("%s", term_end());
03513    fflush(stdout);
03514 
03515    if (ast_opt_console && !option_verbose) 
03516       ast_verbose("[ Initializing Custom Configuration Options ]\n");
03517    /* custom config setup */
03518    register_config_cli();
03519    read_config_maps();
03520    
03521    if (ast_opt_console) {
03522       if (el_hist == NULL || el == NULL)
03523          ast_el_initialize();
03524 
03525       if (!ast_strlen_zero(filename))
03526          ast_el_read_history(filename);
03527    }
03528 
03529    if (ast_tryconnect()) {
03530       /* One is already running */
03531       if (ast_opt_remote) {
03532          if (ast_opt_exec) {
03533             ast_remotecontrol(xarg);
03534             quit_handler(0, 0, 0, 0);
03535             exit(0);
03536          }
03537          printf("%s", term_quit());
03538          ast_remotecontrol(NULL);
03539          quit_handler(0, 0, 0, 0);
03540          exit(0);
03541       } else {
03542          ast_log(LOG_ERROR, "Asterisk already running on %s.  Use 'asterisk -r' to connect.\n", ast_config_AST_SOCKET);
03543          printf("%s", term_quit());
03544          exit(1);
03545       }
03546    } else if (ast_opt_remote || ast_opt_exec) {
03547       ast_log(LOG_ERROR, "Unable to connect to remote asterisk (does %s exist?)\n", ast_config_AST_SOCKET);
03548       printf("%s", term_quit());
03549       exit(1);
03550    }
03551    /* Blindly write pid file since we couldn't connect */
03552    unlink(ast_config_AST_PID);
03553    f = fopen(ast_config_AST_PID, "w");
03554    if (f) {
03555       fprintf(f, "%ld\n", (long)getpid());
03556       fclose(f);
03557    } else
03558       ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", ast_config_AST_PID, strerror(errno));
03559 
03560 #if HAVE_WORKING_FORK
03561    if (ast_opt_always_fork || !ast_opt_no_fork) {
03562 #ifndef HAVE_SBIN_LAUNCHD
03563       if (daemon(1, 0) < 0) {
03564          ast_log(LOG_ERROR, "daemon() failed: %s\n", strerror(errno));
03565       }
03566       ast_mainpid = getpid();
03567       /* Blindly re-write pid file since we are forking */
03568       unlink(ast_config_AST_PID);
03569       f = fopen(ast_config_AST_PID, "w");
03570       if (f) {
03571          fprintf(f, "%ld\n", (long)ast_mainpid);
03572          fclose(f);
03573       } else
03574          ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", ast_config_AST_PID, strerror(errno));
03575 #else
03576       ast_log(LOG_WARNING, "Mac OS X detected.  Use 'launchctl load /Library/LaunchDaemon/org.asterisk.asterisk.plist'.\n");
03577 #endif
03578    }
03579 #endif
03580 
03581    /* Spawning of astcanary must happen AFTER the call to daemon(3) */
03582    if (isroot && ast_opt_high_priority) {
03583       snprintf(canary_filename, sizeof(canary_filename), "%s/alt.asterisk.canary.tweet.tweet.tweet", ast_config_AST_RUN_DIR);
03584 
03585       /* Don't let the canary child kill Asterisk, if it dies immediately */
03586       sigaction(SIGPIPE, &ignore_sig_handler, NULL);
03587 
03588       canary_pid = fork();
03589       if (canary_pid == 0) {
03590          char canary_binary[128], *lastslash, ppid[12];
03591 
03592          /* Reset signal handler */
03593          signal(SIGCHLD, SIG_DFL);
03594          signal(SIGPIPE, SIG_DFL);
03595 
03596          ast_close_fds_above_n(0);
03597          ast_set_priority(0);
03598          snprintf(ppid, sizeof(ppid), "%d", (int) ast_mainpid);
03599 
03600          execlp("astcanary", "astcanary", canary_filename, ppid, (char *)NULL);
03601 
03602          /* If not found, try the same path as used to execute asterisk */
03603          ast_copy_string(canary_binary, argv[0], sizeof(canary_binary));
03604          if ((lastslash = strrchr(canary_binary, '/'))) {
03605             ast_copy_string(lastslash + 1, "astcanary", sizeof(canary_binary) + canary_binary - (lastslash + 1));
03606             execl(canary_binary, "astcanary", canary_filename, (char *)NULL);
03607          }
03608 
03609          /* Should never happen */
03610          _exit(1);
03611       } else if (canary_pid > 0) {
03612          pthread_t dont_care;
03613          ast_pthread_create_detached(&dont_care, NULL, canary_thread, NULL);
03614       }
03615 
03616       /* Kill the canary when we exit */
03617       ast_register_atexit(canary_exit);
03618    }
03619 
03620    if (ast_event_init()) {
03621       printf("%s", term_quit());
03622       exit(1);
03623    }
03624 
03625 #ifdef TEST_FRAMEWORK
03626    if (ast_test_init()) {
03627       printf("%s", term_quit());
03628       exit(1);
03629    }
03630 #endif
03631 
03632    ast_makesocket();
03633    sigemptyset(&sigs);
03634    sigaddset(&sigs, SIGHUP);
03635    sigaddset(&sigs, SIGTERM);
03636    sigaddset(&sigs, SIGINT);
03637    sigaddset(&sigs, SIGPIPE);
03638    sigaddset(&sigs, SIGWINCH);
03639    pthread_sigmask(SIG_BLOCK, &sigs, NULL);
03640    sigaction(SIGURG, &urg_handler, NULL);
03641    signal(SIGINT, __quit_handler);
03642    signal(SIGTERM, __quit_handler);
03643    sigaction(SIGHUP, &hup_handler, NULL);
03644    sigaction(SIGPIPE, &ignore_sig_handler, NULL);
03645 
03646    /* ensure that the random number generators are seeded with a different value every time
03647       Asterisk is started
03648    */
03649    srand((unsigned int) getpid() + (unsigned int) time(NULL));
03650    initstate((unsigned int) getpid() * 65536 + (unsigned int) time(NULL), randompool, sizeof(randompool));
03651 
03652    if (init_logger()) {    /* Start logging subsystem */
03653       printf("%s", term_quit());
03654       exit(1);
03655    }
03656 
03657    threadstorage_init();
03658 
03659    astobj2_init();
03660 
03661    ast_autoservice_init();
03662 
03663    if (ast_timing_init()) {
03664       printf("%s", term_quit());
03665       exit(1);
03666    }
03667 
03668    if (ast_ssl_init()) {
03669       printf("%s", term_quit());
03670       exit(1);
03671    }
03672 
03673 #ifdef AST_XML_DOCS
03674    /* Load XML documentation. */
03675    ast_xmldoc_load_documentation();
03676 #endif
03677 
03678    if (load_modules(1)) {     /* Load modules, pre-load only */
03679       printf("%s", term_quit());
03680       exit(1);
03681    }
03682 
03683    if (dnsmgr_init()) {    /* Initialize the DNS manager */
03684       printf("%s", term_quit());
03685       exit(1);
03686    }
03687 
03688    ast_http_init();     /* Start the HTTP server, if needed */
03689 
03690    ast_channels_init();
03691 
03692    if (init_manager()) {
03693       printf("%s", term_quit());
03694       exit(1);
03695    }
03696 
03697    if (ast_cdr_engine_init()) {
03698       printf("%s", term_quit());
03699       exit(1);
03700    }
03701 
03702    if (ast_device_state_engine_init()) {
03703       printf("%s", term_quit());
03704       exit(1);
03705    }
03706 
03707    ast_rtp_init();
03708    ast_dsp_init();
03709    ast_udptl_init();
03710 
03711    if (ast_image_init()) {
03712       printf("%s", term_quit());
03713       exit(1);
03714    }
03715 
03716    if (ast_file_init()) {
03717       printf("%s", term_quit());
03718       exit(1);
03719    }
03720 
03721    if (load_pbx()) {
03722       printf("%s", term_quit());
03723       exit(1);
03724    }
03725 
03726    if (ast_indications_init()) {
03727       printf("%s", term_quit());
03728       exit(1);
03729    }
03730 
03731    ast_features_init();
03732 
03733    if (init_framer()) {
03734       printf("%s", term_quit());
03735       exit(1);
03736    }
03737 
03738    if (astdb_init()) {
03739       printf("%s", term_quit());
03740       exit(1);
03741    }
03742 
03743    if (ast_enum_init()) {
03744       printf("%s", term_quit());
03745       exit(1);
03746    }
03747 
03748    if (load_modules(0)) {
03749       printf("%s", term_quit());
03750       exit(1);
03751    }
03752 
03753    /* loads the cli_permissoins.conf file needed to implement cli restrictions. */
03754    ast_cli_perms_init(0);
03755 
03756    dnsmgr_start_refresh();
03757 
03758    /* We might have the option of showing a console, but for now just
03759       do nothing... */
03760    if (ast_opt_console && !option_verbose)
03761       ast_verbose(" ]\n");
03762    if (option_verbose || ast_opt_console)
03763       ast_verbose("%s", term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
03764    if (ast_opt_no_fork)
03765       consolethread = pthread_self();
03766 
03767    if (pipe(sig_alert_pipe))
03768       sig_alert_pipe[0] = sig_alert_pipe[1] = -1;
03769 
03770    ast_set_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED);
03771    if (ast_opt_send_fullybooted) {
03772       manager_event(EVENT_FLAG_SYSTEM, "FullyBooted", "Status: Fully Booted\r\n");
03773    }
03774 
03775    ast_process_pending_reloads();
03776 
03777    pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
03778 
03779 #ifdef __AST_DEBUG_MALLOC
03780    __ast_mm_init();
03781 #endif   
03782 
03783    ast_lastreloadtime = ast_startuptime = ast_tvnow();
03784    ast_cli_register_multiple(cli_asterisk, ARRAY_LEN(cli_asterisk));
03785 
03786    run_startup_commands();
03787 
03788    if (ast_opt_console) {
03789       /* Console stuff now... */
03790       /* Register our quit function */
03791       char title[256];
03792 
03793       ast_pthread_create_detached(&mon_sig_flags, NULL, monitor_sig_flags, NULL);
03794 
03795       set_icon("Asterisk");
03796       snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %ld)", hostname, (long)ast_mainpid);
03797       set_title(title);
03798 
03799       for (;;) {
03800          buf = (char *) el_gets(el, &num);
03801 
03802          if (!buf && write(1, "", 1) < 0)
03803             goto lostterm;
03804 
03805          if (buf) {
03806             if (buf[strlen(buf)-1] == '\n')
03807                buf[strlen(buf)-1] = '\0';
03808 
03809             consolehandler((char *)buf);
03810          } else if (ast_opt_remote && (write(STDOUT_FILENO, "\nUse EXIT or QUIT to exit the asterisk console\n",
03811                strlen("\nUse EXIT or QUIT to exit the asterisk console\n")) < 0)) {
03812             /* Whoa, stdout disappeared from under us... Make /dev/null's */
03813             int fd;
03814             fd = open("/dev/null", O_RDWR);
03815             if (fd > -1) {
03816                dup2(fd, STDOUT_FILENO);
03817                dup2(fd, STDIN_FILENO);
03818             } else
03819                ast_log(LOG_WARNING, "Failed to open /dev/null to recover from dead console. Bad things will happen!\n");
03820             break;
03821          }
03822       }
03823    }
03824 
03825    monitor_sig_flags(NULL);
03826 
03827 lostterm:
03828    return 0;
03829 }

Generated on Sat Mar 26 11:07:38 2011 for Asterisk - the Open Source PBX by  doxygen 1.5.9