Wed Aug 11 01:05:02 2010

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

Generated on Wed Aug 11 01:05:02 2010 for Asterisk - the Open Source PBX by  doxygen 1.5.9