Sat Mar 26 11:12:59 2011

Asterisk developer's documentation


asterisk.c File Reference

Top level source file for Asterisk - the Open Source PBX. Implementation of PBX core functions and CLI interface. More...

#include "asterisk.h"
#include "asterisk/_private.h"
#include <sys/time.h>
#include <fcntl.h>
#include <signal.h>
#include <sched.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <ctype.h>
#include <sys/resource.h>
#include <grp.h>
#include <pwd.h>
#include <sys/stat.h>
#include <sys/sysinfo.h>
#include <regex.h>
#include "asterisk/paths.h"
#include "asterisk/network.h"
#include "asterisk/cli.h"
#include "asterisk/channel.h"
#include "asterisk/features.h"
#include "asterisk/ulaw.h"
#include "asterisk/alaw.h"
#include "asterisk/callerid.h"
#include "asterisk/image.h"
#include "asterisk/tdd.h"
#include "asterisk/term.h"
#include "asterisk/manager.h"
#include "asterisk/cdr.h"
#include "asterisk/cel.h"
#include "asterisk/pbx.h"
#include "asterisk/enum.h"
#include "asterisk/http.h"
#include "asterisk/udptl.h"
#include "asterisk/app.h"
#include "asterisk/lock.h"
#include "asterisk/utils.h"
#include "asterisk/file.h"
#include "asterisk/io.h"
#include "editline/histedit.h"
#include "asterisk/config.h"
#include "asterisk/ast_version.h"
#include "asterisk/linkedlists.h"
#include "asterisk/devicestate.h"
#include "asterisk/module.h"
#include "asterisk/dsp.h"
#include "asterisk/buildinfo.h"
#include "asterisk/xmldoc.h"
#include "asterisk/poll-compat.h"
#include "asterisk/ccss.h"
#include "asterisk/test.h"
#include "asterisk/aoc.h"
#include "../defaults.h"

Go to the source code of this file.

Data Structures

struct  _cfg_paths
struct  ast_atexit
struct  atexits
struct  console
struct  file_version
struct  file_versions
struct  profile_data
struct  profile_entry
struct  thread_list
struct  thread_list_t

Defines

#define AF_LOCAL   AF_UNIX
#define AST_MAX_CONNECTS   128
#define ASTERISK_PROMPT   "*CLI> "
#define ASTERISK_PROMPT2   "%s*CLI> "
#define DEFINE_PROFILE_MIN_MAX_VALUES
#define EL_BUF_SIZE   512
#define FORMAT   "%-25.25s %-40.40s\n"
#define MAX_HISTORY_COMMAND_LENGTH   256
#define NUM_MSGS   64
#define PF_LOCAL   PF_UNIX
#define WELCOME_MESSAGE
 Welcome message when starting a CLI interface.

Functions

static void __quit_handler (int num)
static void __remote_quit_handler (int num)
static void _child_handler (int sig)
static void _hup_handler (int num)
static void _null_sig_handler (int sig)
 NULL handler so we can collect the child exit status.
static void _urg_handler (int num)
 Urgent handler.
int ast_add_profile (const char *name, uint64_t scale)
 allocates a counter with a given name and scale.
static int ast_all_zeros (char *s)
static int ast_cli_display_match_list (char **matches, int len, int max)
char * ast_complete_source_filename (const char *partial, int n)
void ast_console_puts (const char *string)
void ast_console_puts_mutable (const char *string, int level)
 log the string to the console, and all attached console clients
void ast_console_toggle_loglevel (int fd, int level, int state)
void ast_console_toggle_mute (int fd, int silent)
 mute or unmute a console from logging
static int ast_el_add_history (char *)
static int ast_el_initialize (void)
static int ast_el_read_char (EditLine *editline, char *cp)
static int ast_el_read_history (char *)
static int ast_el_sort_compare (const void *i1, const void *i2)
static char ** ast_el_strtoarr (char *buf)
static int ast_el_write_history (char *)
const char * ast_file_version_find (const char *file)
 Find version for given module name.
static int ast_makesocket (void)
int64_t ast_mark (int i, int startstop)
static void ast_network_puts (const char *string)
 write the string to all attached console clients
static void ast_network_puts_mutable (const char *string, int level)
 log the string to all attached console clients
int64_t ast_profile (int i, int64_t delta)
static void ast_readconfig (void)
int ast_register_atexit (void(*func)(void))
 Register a function to be executed before Asterisk exits.
void ast_register_file_version (const char *file, const char *version)
 Register the version of a source code file with the core.
void ast_register_thread (char *name)
static void ast_remotecontrol (char *data)
void ast_replace_sigchld (void)
 Replace the SIGCHLD handler.
static void ast_run_atexits (void)
int ast_safe_system (const char *s)
 Safely spawn an external program while closing file descriptors.
int ast_set_priority (int pri)
 We set ourselves to a high priority, that we might pre-empt everything else. If your PBX has heavy activity on it, this is a good thing.
static int ast_tryconnect (void)
void ast_unregister_atexit (void(*func)(void))
 Unregister a function registered with ast_register_atexit().
void ast_unregister_file_version (const char *file)
 Unregister a source code file from the core.
void ast_unregister_thread (void *id)
void ast_unreplace_sigchld (void)
 Restore the SIGCHLD handler.
static void canary_exit (void)
static void * canary_thread (void *unused)
static char * cli_complete (EditLine *editline, int ch)
static char * cli_prompt (EditLine *editline)
static void console_verboser (const char *s)
static void consolehandler (char *s)
static void env_init (void)
static int fdprint (int fd, const char *s)
static int fdsend (int fd, const char *s)
static const char * fix_header (char *outbuf, int maxout, const char *s, char *cmp)
static char * handle_abort_shutdown (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static char * handle_bang (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static char * handle_clear_profile (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static char * handle_restart_gracefully (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static char * handle_restart_now (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static char * handle_restart_when_convenient (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static char * handle_show_profile (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static char * handle_show_settings (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 Give an overview of core settings.
static char * handle_show_sysinfo (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 Give an overview of system statistics.
static char * handle_show_threads (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static char * handle_show_version_files (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 CLI command to list module versions.
static char * handle_stop_gracefully (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static char * handle_stop_now (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static char * handle_stop_when_convenient (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static char * handle_version (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static void * listener (void *unused)
int main (int argc, char *argv[])
static void * monitor_sig_flags (void *unused)
static void * netconsole (void *vconsole)
static void network_verboser (const char *s)
static void quit_handler (int num, int niceness, int safeshutdown, int restart)
static __inline uint64_t rdtsc (void)
static int read_credentials (int fd, char *buffer, size_t size, struct console *con)
 read() function supporting the reception of user credentials.
static int remoteconsolehandler (char *s)
static void run_startup_commands (void)
static void set_icon (char *text)
static void set_title (char *text)
 Set an X-term or screen title.
static void set_ulimit (int value)
 Set maximum open files.
static int show_cli_help (void)
static char * show_license (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static int show_version (void)
static char * show_warranty (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)

Variables

static char * _argv [256]
struct ast_flags ast_compat = { 0 }
const char * ast_config_AST_AGI_DIR = cfg_paths.agi_dir
const char * ast_config_AST_CONFIG_DIR = cfg_paths.config_dir
const char * ast_config_AST_CONFIG_FILE = cfg_paths.config_file
static char ast_config_AST_CTL [PATH_MAX] = "asterisk.ctl"
static char ast_config_AST_CTL_GROUP [PATH_MAX] = "\0"
static char ast_config_AST_CTL_OWNER [PATH_MAX] = "\0"
static char ast_config_AST_CTL_PERMISSIONS [PATH_MAX]
const char * ast_config_AST_DATA_DIR = cfg_paths.data_dir
const char * ast_config_AST_DB = cfg_paths.db_path
const char * ast_config_AST_KEY_DIR = cfg_paths.key_dir
const char * ast_config_AST_LOG_DIR = cfg_paths.log_dir
const char * ast_config_AST_MODULE_DIR = cfg_paths.module_dir
const char * ast_config_AST_MONITOR_DIR = cfg_paths.monitor_dir
const char * ast_config_AST_PID = cfg_paths.pid_path
const char * ast_config_AST_RUN_DIR = cfg_paths.run_dir
const char * ast_config_AST_RUN_GROUP = cfg_paths.run_group
const char * ast_config_AST_RUN_USER = cfg_paths.run_user
const char * ast_config_AST_SOCKET = cfg_paths.socket_path
const char * ast_config_AST_SPOOL_DIR = cfg_paths.spool_dir
const char * ast_config_AST_SYSTEM_NAME = cfg_paths.system_name
const char * ast_config_AST_VAR_DIR = cfg_paths.var_dir
static int ast_consock = -1
struct ast_eid ast_eid_default
 Global EID.
unsigned int ast_FD_SETSIZE
struct timeval ast_lastreloadtime
pid_t ast_mainpid
struct ast_flags ast_options = { AST_DEFAULT_OPTIONS }
static int ast_socket = -1
struct timeval ast_startuptime
static char canary_filename [128]
static int canary_pid = 0
static struct _cfg_paths cfg_paths
static struct sigaction child_handler
static struct ast_cli_entry cli_asterisk []
struct console consoles [AST_MAX_CONNECTS]
static pthread_t consolethread = AST_PTHREADT_NULL
char defaultlanguage [MAX_LANGUAGE] = DEFAULT_LANGUAGE
static EditLine * el
static History * el_hist
static struct sigaction hup_handler
static struct sigaction ignore_sig_handler
static const char license_lines []
static pthread_t lthread
static pthread_t mon_sig_flags
static struct sigaction null_sig_handler
int option_debug
int option_maxcalls
int option_maxfiles
double option_maxload
long option_minmemfree
int option_verbose
static struct profile_data * prof_data
static struct ast_str * prompt = NULL
static char randompool [256]
char record_cache_dir [AST_CACHE_DIR_LEN] = DEFAULT_TMP_DIR
static char * remotehostname
static int restartnow
static unsigned int safe_system_level = 0
 Keep track of how many threads are currently trying to wait*() on a child process.
static ast_mutex_t safe_system_lock = { { { NULL }, { 0 }, 0, { NULL }, { 0 }, {{{ 0 }}}, PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP } , 1, PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP }
static struct sigaction safe_system_prev_handler
static int shuttingdown
static int sig_alert_pipe [2] = { -1, -1 }
struct {
   unsigned int   need_quit:1
   unsigned int   need_reload:1
} sig_flags
static struct sigaction urg_handler
static const char warranty_lines []


Detailed Description

Top level source file for Asterisk - the Open Source PBX. Implementation of PBX core functions and CLI interface.

Definition in file asterisk.c.


Define Documentation

#define AF_LOCAL   AF_UNIX

Definition at line 150 of file asterisk.c.

#define AST_MAX_CONNECTS   128

#define ASTERISK_PROMPT   "*CLI> "

Definition at line 2085 of file asterisk.c.

Referenced by cli_prompt().

#define ASTERISK_PROMPT2   "%s*CLI> "

Definition at line 2087 of file asterisk.c.

Referenced by cli_prompt().

#define DEFINE_PROFILE_MIN_MAX_VALUES

Definition at line 772 of file asterisk.c.

Referenced by handle_clear_profile(), and handle_show_profile().

#define EL_BUF_SIZE   512

Referenced by ast_el_read_char().

#define FORMAT   "%-25.25s %-40.40s\n"

#define MAX_HISTORY_COMMAND_LENGTH   256

Definition at line 2594 of file asterisk.c.

Referenced by ast_el_add_history(), and ast_el_read_history().

#define NUM_MSGS   64

Definition at line 155 of file asterisk.c.

#define PF_LOCAL   PF_UNIX

Definition at line 151 of file asterisk.c.

Referenced by ast_makesocket(), and ast_tryconnect().

#define WELCOME_MESSAGE

Welcome message when starting a CLI interface.

Definition at line 158 of file asterisk.c.

Referenced by ast_el_read_char(), and main().


Function Documentation

static void __quit_handler ( int  num  )  [static]

Definition at line 1707 of file asterisk.c.

References errno, sig_alert_pipe, and sig_flags.

Referenced by main().

01708 {
01709    int a = 0;
01710    sig_flags.need_quit = 1;
01711    if (sig_alert_pipe[1] != -1) {
01712       if (write(sig_alert_pipe[1], &a, sizeof(a)) < 0) {
01713          fprintf(stderr, "quit_handler: write() failed: %s\n", strerror(errno));
01714       }
01715    }
01716    /* There is no need to restore the signal handler here, since the app
01717     * is going to exit */
01718 }

static void __remote_quit_handler ( int  num  )  [static]

Definition at line 1720 of file asterisk.c.

References sig_flags.

Referenced by ast_remotecontrol().

01721 {
01722    sig_flags.need_quit = 1;
01723 }

static void _child_handler ( int  sig  )  [static]

Definition at line 1488 of file asterisk.c.

References status.

01489 {
01490    /* Must not ever ast_log or ast_verbose within signal handler */
01491    int n, status;
01492 
01493    /*
01494     * Reap all dead children -- not just one
01495     */
01496    for (n = 0; wait4(-1, &status, WNOHANG, NULL) > 0; n++)
01497       ;
01498    if (n == 0 && option_debug)   
01499       printf("Huh?  Child handler, but nobody there?\n");
01500 }

static void _hup_handler ( int  num  )  [static]

Definition at line 1468 of file asterisk.c.

References _argv, errno, restartnow, sig_alert_pipe, and sig_flags.

01469 {
01470    int a = 0;
01471    if (option_verbose > 1) 
01472       printf("Received HUP signal -- Reloading configs\n");
01473    if (restartnow)
01474       execvp(_argv[0], _argv);
01475    sig_flags.need_reload = 1;
01476    if (sig_alert_pipe[1] != -1) {
01477       if (write(sig_alert_pipe[1], &a, sizeof(a)) < 0) {
01478          fprintf(stderr, "hup_handler: write() failed: %s\n", strerror(errno));
01479       }
01480    }
01481 }

static void _null_sig_handler ( int  sig  )  [static]

NULL handler so we can collect the child exit status.

Definition at line 980 of file asterisk.c.

00981 {
00982 
00983 }

static void _urg_handler ( int  num  )  [static]

Urgent handler.

Called by soft_hangup to interrupt the poll, read, or other system call. We don't actually need to do anything though. Remember: Cannot EVER ast_log from within a signal handler

Definition at line 1458 of file asterisk.c.

01459 {
01460    return;
01461 }

int ast_add_profile ( const char *  name,
uint64_t  scale 
)

allocates a counter with a given name and scale.

support for event profiling

Returns:
Returns the identifier of the counter.

Definition at line 691 of file asterisk.c.

References ast_calloc, ast_realloc, ast_strdup, profile_data::e, profile_data::entries, profile_entry::events, profile_entry::mark, profile_data::max_size, profile_entry::name, prof_data, profile_entry::scale, and profile_entry::value.

Referenced by extension_match_core().

00692 {
00693    int l = sizeof(struct profile_data);
00694    int n = 10; /* default entries */
00695 
00696    if (prof_data == NULL) {
00697       prof_data = ast_calloc(1, l + n*sizeof(struct profile_entry));
00698       if (prof_data == NULL)
00699          return -1;
00700       prof_data->entries = 0;
00701       prof_data->max_size = n;
00702    }
00703    if (prof_data->entries >= prof_data->max_size) {
00704       void *p;
00705       n = prof_data->max_size + 20;
00706       p = ast_realloc(prof_data, l + n*sizeof(struct profile_entry));
00707       if (p == NULL)
00708          return -1;
00709       prof_data = p;
00710       prof_data->max_size = n;
00711    }
00712    n = prof_data->entries++;
00713    prof_data->e[n].name = ast_strdup(name);
00714    prof_data->e[n].value = 0;
00715    prof_data->e[n].events = 0;
00716    prof_data->e[n].mark = 0;
00717    prof_data->e[n].scale = scale;
00718    return n;
00719 }

static int ast_all_zeros ( char *  s  )  [static]

Definition at line 1767 of file asterisk.c.

Referenced by ast_el_read_history(), consolehandler(), and remoteconsolehandler().

01768 {
01769    while (*s) {
01770       if (*s > 32)
01771          return 0;
01772       s++;  
01773    }
01774    return 1;
01775 }

static int ast_cli_display_match_list ( char **  matches,
int  len,
int  max 
) [static]

Definition at line 2393 of file asterisk.c.

References ast_el_sort_compare(), ast_free, and ast_get_termcols().

Referenced by cli_complete().

02394 {
02395    int i, idx, limit, count;
02396    int screenwidth = 0;
02397    int numoutput = 0, numoutputline = 0;
02398 
02399    screenwidth = ast_get_termcols(STDOUT_FILENO);
02400 
02401    /* find out how many entries can be put on one line, with two spaces between strings */
02402    limit = screenwidth / (max + 2);
02403    if (limit == 0)
02404       limit = 1;
02405 
02406    /* how many lines of output */
02407    count = len / limit;
02408    if (count * limit < len)
02409       count++;
02410 
02411    idx = 1;
02412 
02413    qsort(&matches[0], (size_t)(len), sizeof(char *), ast_el_sort_compare);
02414 
02415    for (; count > 0; count--) {
02416       numoutputline = 0;
02417       for (i = 0; i < limit && matches[idx]; i++, idx++) {
02418 
02419          /* Don't print dupes */
02420          if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
02421             i--;
02422             ast_free(matches[idx]);
02423             matches[idx] = NULL;
02424             continue;
02425          }
02426 
02427          numoutput++;
02428          numoutputline++;
02429          fprintf(stdout, "%-*s  ", max, matches[idx]);
02430          ast_free(matches[idx]);
02431          matches[idx] = NULL;
02432       }
02433       if (numoutputline > 0)
02434          fprintf(stdout, "\n");
02435    }
02436 
02437    return numoutput;
02438 }

char* ast_complete_source_filename ( const char *  partial,
int  n 
)

Definition at line 341 of file asterisk.c.

References AST_RWLIST_RDLOCK, AST_RWLIST_TRAVERSE, AST_RWLIST_UNLOCK, ast_strdup, file_version::file, len(), and ast_atexit::list.

Referenced by handle_verbose().

00342 {
00343    struct file_version *find;
00344    size_t len = strlen(partial);
00345    int count = 0;
00346    char *res = NULL;
00347 
00348    AST_RWLIST_RDLOCK(&file_versions);
00349    AST_RWLIST_TRAVERSE(&file_versions, find, list) {
00350       if (!strncasecmp(find->file, partial, len) && ++count > n) {
00351          res = ast_strdup(find->file);
00352          break;
00353       }
00354    }
00355    AST_RWLIST_UNLOCK(&file_versions);
00356    return res;
00357 }

void ast_console_puts ( const char *  string  ) 

write the string to the console, and all attached console clients

Definition at line 1162 of file asterisk.c.

References ast_network_puts().

Referenced by chan_misdn_log().

01163 {
01164    fputs(string, stdout);
01165    fflush(stdout);
01166    ast_network_puts(string);
01167 }

void ast_console_puts_mutable ( const char *  string,
int  level 
)

log the string to the console, and all attached console clients

Version:
1.6.1 added level parameter

Definition at line 1139 of file asterisk.c.

References ast_network_puts_mutable().

Referenced by logger_print_normal().

01140 {
01141    fputs(string, stdout);
01142    fflush(stdout);
01143    ast_network_puts_mutable(string, level);
01144 }

void ast_console_toggle_loglevel ( int  fd,
int  level,
int  state 
)

Since:
1.6.1

Definition at line 1086 of file asterisk.c.

References AST_MAX_CONNECTS, consoles, and console::levels.

Referenced by handle_logger_set_level().

01087 {
01088    int x;
01089    for (x = 0;x < AST_MAX_CONNECTS; x++) {
01090       if (fd == consoles[x].fd) {
01091          consoles[x].levels[level] = state;
01092          return;
01093       }
01094    }
01095 }

void ast_console_toggle_mute ( int  fd,
int  silent 
)

mute or unmute a console from logging

Definition at line 1100 of file asterisk.c.

References ast_cli(), AST_MAX_CONNECTS, consoles, console::mute, and mute.

Referenced by handle_logger_mute().

01100                                                  {
01101    int x;
01102    for (x = 0;x < AST_MAX_CONNECTS; x++) {
01103       if (fd == consoles[x].fd) {
01104          if (consoles[x].mute) {
01105             consoles[x].mute = 0;
01106             if (!silent)
01107                ast_cli(fd, "Console is not muted anymore.\n");
01108          } else {
01109             consoles[x].mute = 1;
01110             if (!silent)
01111                ast_cli(fd, "Console is muted.\n");
01112          }
01113          return;
01114       }
01115    }
01116    ast_cli(fd, "Couldn't find remote console.\n");
01117 }

static int ast_el_add_history ( char *  buf  )  [static]

Definition at line 2596 of file asterisk.c.

References ast_el_initialize(), ast_strdupa, ast_strip(), el, el_hist, and MAX_HISTORY_COMMAND_LENGTH.

Referenced by ast_el_read_history(), consolehandler(), and remoteconsolehandler().

02597 {
02598    HistEvent ev;
02599 
02600    if (el_hist == NULL || el == NULL)
02601       ast_el_initialize();
02602    if (strlen(buf) > (MAX_HISTORY_COMMAND_LENGTH - 1))
02603       return 0;
02604    return (history(el_hist, &ev, H_ENTER, ast_strip(ast_strdupa(buf))));
02605 }

static int ast_el_initialize ( void   )  [static]

Definition at line 2559 of file asterisk.c.

References cli_complete(), cli_prompt(), el, and el_hist.

Referenced by ast_el_add_history(), ast_el_read_history(), ast_el_write_history(), ast_remotecontrol(), and main().

02560 {
02561    HistEvent ev;
02562    char *editor = getenv("AST_EDITOR");
02563 
02564    if (el != NULL)
02565       el_end(el);
02566    if (el_hist != NULL)
02567       history_end(el_hist);
02568 
02569    el = el_init("asterisk", stdin, stdout, stderr);
02570    el_set(el, EL_PROMPT, cli_prompt);
02571 
02572    el_set(el, EL_EDITMODE, 1);      
02573    el_set(el, EL_EDITOR, editor ? editor : "emacs");     
02574    el_hist = history_init();
02575    if (!el || !el_hist)
02576       return -1;
02577 
02578    /* setup history with 100 entries */
02579    history(el_hist, &ev, H_SETSIZE, 100);
02580 
02581    el_set(el, EL_HIST, history, el_hist);
02582 
02583    el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
02584    /* Bind <tab> to command completion */
02585    el_set(el, EL_BIND, "^I", "ed-complete", NULL);
02586    /* Bind ? to command completion */
02587    el_set(el, EL_BIND, "?", "ed-complete", NULL);
02588    /* Bind ^D to redisplay */
02589    el_set(el, EL_BIND, "^D", "ed-redisplay", NULL);
02590 
02591    return 0;
02592 }

static int ast_el_read_char ( EditLine *  editline,
char *  cp 
) [static]

Definition at line 2113 of file asterisk.c.

References ast_log(), ast_opt_exec, ast_opt_mute, ast_opt_reconnect, ast_poll, ast_tryconnect(), EL_BUF_SIZE, errno, fdsend(), LOG_ERROR, quit_handler(), sig_flags, term_quit(), and WELCOME_MESSAGE.

Referenced by ast_remotecontrol().

02114 {
02115    int num_read = 0;
02116    int lastpos = 0;
02117    struct pollfd fds[2];
02118    int res;
02119    int max;
02120 #define EL_BUF_SIZE 512
02121    char buf[EL_BUF_SIZE];
02122 
02123    for (;;) {
02124       max = 1;
02125       fds[0].fd = ast_consock;
02126       fds[0].events = POLLIN;
02127       if (!ast_opt_exec) {
02128          fds[1].fd = STDIN_FILENO;
02129          fds[1].events = POLLIN;
02130          max++;
02131       }
02132       res = ast_poll(fds, max, -1);
02133       if (res < 0) {
02134          if (sig_flags.need_quit)
02135             break;
02136          if (errno == EINTR)
02137             continue;
02138          ast_log(LOG_ERROR, "poll failed: %s\n", strerror(errno));
02139          break;
02140       }
02141 
02142       if (!ast_opt_exec && fds[1].revents) {
02143          num_read = read(STDIN_FILENO, cp, 1);
02144          if (num_read < 1) {
02145             break;
02146          } else 
02147             return (num_read);
02148       }
02149       if (fds[0].revents) {
02150          char *tmp;
02151          res = read(ast_consock, buf, sizeof(buf) - 1);
02152          /* if the remote side disappears exit */
02153          if (res < 1) {
02154             fprintf(stderr, "\nDisconnected from Asterisk server\n");
02155             if (!ast_opt_reconnect) {
02156                quit_handler(0, 0, 0, 0);
02157             } else {
02158                int tries;
02159                int reconnects_per_second = 20;
02160                fprintf(stderr, "Attempting to reconnect for 30 seconds\n");
02161                for (tries = 0; tries < 30 * reconnects_per_second; tries++) {
02162                   if (ast_tryconnect()) {
02163                      fprintf(stderr, "Reconnect succeeded after %.3f seconds\n", 1.0 / reconnects_per_second * tries);
02164                      printf("%s", term_quit());
02165                      WELCOME_MESSAGE;
02166                      if (!ast_opt_mute)
02167                         fdsend(ast_consock, "logger mute silent");
02168                      else 
02169                         printf("log and verbose output currently muted ('logger mute' to unmute)\n");
02170                      break;
02171                   } else
02172                      usleep(1000000 / reconnects_per_second);
02173                }
02174                if (tries >= 30 * reconnects_per_second) {
02175                   fprintf(stderr, "Failed to reconnect for 30 seconds.  Quitting.\n");
02176                   quit_handler(0, 0, 0, 0);
02177                }
02178             }
02179          }
02180 
02181          buf[res] = '\0';
02182 
02183          /* Strip preamble from asynchronous events, too */
02184          for (tmp = buf; *tmp; tmp++) {
02185             if (*tmp == 127) {
02186                memmove(tmp, tmp + 1, strlen(tmp));
02187                tmp--;
02188                res--;
02189             }
02190          }
02191 
02192          /* Write over the CLI prompt */
02193          if (!ast_opt_exec && !lastpos) {
02194             if (write(STDOUT_FILENO, "\r", 5) < 0) {
02195             }
02196          }
02197          if (write(STDOUT_FILENO, buf, res) < 0) {
02198          }
02199          if ((res < EL_BUF_SIZE - 1) && ((buf[res-1] == '\n') || (buf[res-2] == '\n'))) {
02200             *cp = CC_REFRESH;
02201             return(1);
02202          } else
02203             lastpos = 1;
02204       }
02205    }
02206 
02207    *cp = '\0';
02208    return (0);
02209 }

static int ast_el_read_history ( char *  filename  )  [static]

Definition at line 2617 of file asterisk.c.

References ast_all_zeros(), ast_el_add_history(), ast_el_initialize(), el, el_hist, f, and MAX_HISTORY_COMMAND_LENGTH.

Referenced by ast_remotecontrol(), and main().

02618 {
02619    char buf[MAX_HISTORY_COMMAND_LENGTH];
02620    FILE *f;
02621    int ret = -1;
02622 
02623    if (el_hist == NULL || el == NULL)
02624       ast_el_initialize();
02625 
02626    if ((f = fopen(filename, "r")) == NULL)
02627       return ret;
02628 
02629    while (!feof(f)) {
02630       if (!fgets(buf, sizeof(buf), f))
02631          break;
02632       if (!strcmp(buf, "_HiStOrY_V2_\n"))
02633          continue;
02634       if (ast_all_zeros(buf))
02635          continue;
02636       if ((ret = ast_el_add_history(buf)) == -1)
02637          break;
02638    }
02639    fclose(f);
02640 
02641    return ret;
02642 }

static int ast_el_sort_compare ( const void *  i1,
const void *  i2 
) [static]

Definition at line 2383 of file asterisk.c.

Referenced by ast_cli_display_match_list().

02384 {
02385    char *s1, *s2;
02386 
02387    s1 = ((char **)i1)[0];
02388    s2 = ((char **)i2)[0];
02389 
02390    return strcasecmp(s1, s2);
02391 }

static char** ast_el_strtoarr ( char *  buf  )  [static]

Definition at line 2340 of file asterisk.c.

References AST_CLI_COMPLETE_EOF, ast_free, ast_realloc, ast_strdup, and strsep().

Referenced by cli_complete().

02341 {
02342    char **match_list = NULL, **match_list_tmp, *retstr;
02343    size_t match_list_len;
02344    int matches = 0;
02345 
02346    match_list_len = 1;
02347    while ( (retstr = strsep(&buf, " ")) != NULL) {
02348 
02349       if (!strcmp(retstr, AST_CLI_COMPLETE_EOF))
02350          break;
02351       if (matches + 1 >= match_list_len) {
02352          match_list_len <<= 1;
02353          if ((match_list_tmp = ast_realloc(match_list, match_list_len * sizeof(char *)))) {
02354             match_list = match_list_tmp;
02355          } else {
02356             if (match_list)
02357                ast_free(match_list);
02358             return (char **) NULL;
02359          }
02360       }
02361 
02362       match_list[matches++] = ast_strdup(retstr);
02363    }
02364 
02365    if (!match_list)
02366       return (char **) NULL;
02367 
02368    if (matches >= match_list_len) {
02369       if ((match_list_tmp = ast_realloc(match_list, (match_list_len + 1) * sizeof(char *)))) {
02370          match_list = match_list_tmp;
02371       } else {
02372          if (match_list)
02373             ast_free(match_list);
02374          return (char **) NULL;
02375       }
02376    }
02377 
02378    match_list[matches] = (char *) NULL;
02379 
02380    return match_list;
02381 }

static int ast_el_write_history ( char *  filename  )  [static]

Definition at line 2607 of file asterisk.c.

References ast_el_initialize(), el, and el_hist.

Referenced by quit_handler().

02608 {
02609    HistEvent ev;
02610 
02611    if (el_hist == NULL || el == NULL)
02612       ast_el_initialize();
02613 
02614    return (history(el_hist, &ev, H_SAVE, filename));
02615 }

const char* ast_file_version_find ( const char *  file  ) 

Find version for given module name.

Parameters:
file Module name (i.e. chan_sip.so)
Returns:
version string or NULL if the module is not found

Definition at line 360 of file asterisk.c.

References AST_RWLIST_TRAVERSE_SAFE_BEGIN, AST_RWLIST_TRAVERSE_SAFE_END, AST_RWLIST_UNLOCK, AST_RWLIST_WRLOCK, file_version::file, ast_atexit::list, and file_version::version.

Referenced by manager_modulecheck().

00361 {
00362    struct file_version *iterator;
00363 
00364    AST_RWLIST_WRLOCK(&file_versions);
00365    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&file_versions, iterator, list) {
00366       if (!strcasecmp(iterator->file, file))
00367          break;
00368    }
00369    AST_RWLIST_TRAVERSE_SAFE_END;
00370    AST_RWLIST_UNLOCK(&file_versions);
00371    if (iterator)
00372       return iterator->version;
00373    return NULL;
00374 }      

static int ast_makesocket ( void   )  [static]

Definition at line 1361 of file asterisk.c.

References AF_LOCAL, ast_config_AST_CTL_GROUP, ast_config_AST_CTL_OWNER, ast_config_AST_CTL_PERMISSIONS, ast_config_AST_SOCKET, ast_copy_string(), ast_log(), AST_MAX_CONNECTS, ast_pthread_create_background, ast_register_verbose(), ast_strlen_zero(), consoles, errno, listener(), LOG_WARNING, lthread, network_verboser(), and PF_LOCAL.

Referenced by main().

01362 {
01363    struct sockaddr_un sunaddr;
01364    int res;
01365    int x;
01366    uid_t uid = -1;
01367    gid_t gid = -1;
01368 
01369    for (x = 0; x < AST_MAX_CONNECTS; x++) 
01370       consoles[x].fd = -1;
01371    unlink(ast_config_AST_SOCKET);
01372    ast_socket = socket(PF_LOCAL, SOCK_STREAM, 0);
01373    if (ast_socket < 0) {
01374       ast_log(LOG_WARNING, "Unable to create control socket: %s\n", strerror(errno));
01375       return -1;
01376    }     
01377    memset(&sunaddr, 0, sizeof(sunaddr));
01378    sunaddr.sun_family = AF_LOCAL;
01379    ast_copy_string(sunaddr.sun_path, ast_config_AST_SOCKET, sizeof(sunaddr.sun_path));
01380    res = bind(ast_socket, (struct sockaddr *)&sunaddr, sizeof(sunaddr));
01381    if (res) {
01382       ast_log(LOG_WARNING, "Unable to bind socket to %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
01383       close(ast_socket);
01384       ast_socket = -1;
01385       return -1;
01386    }
01387    res = listen(ast_socket, 2);
01388    if (res < 0) {
01389       ast_log(LOG_WARNING, "Unable to listen on socket %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
01390       close(ast_socket);
01391       ast_socket = -1;
01392       return -1;
01393    }
01394    if (ast_register_verbose(network_verboser)) {
01395       ast_log(LOG_WARNING, "Unable to register network verboser?\n");
01396    }
01397 
01398    ast_pthread_create_background(&lthread, NULL, listener, NULL);
01399 
01400    if (!ast_strlen_zero(ast_config_AST_CTL_OWNER)) {
01401       struct passwd *pw;
01402       if ((pw = getpwnam(ast_config_AST_CTL_OWNER)) == NULL)
01403          ast_log(LOG_WARNING, "Unable to find uid of user %s\n", ast_config_AST_CTL_OWNER);
01404       else
01405          uid = pw->pw_uid;
01406    }
01407       
01408    if (!ast_strlen_zero(ast_config_AST_CTL_GROUP)) {
01409       struct group *grp;
01410       if ((grp = getgrnam(ast_config_AST_CTL_GROUP)) == NULL)
01411          ast_log(LOG_WARNING, "Unable to find gid of group %s\n", ast_config_AST_CTL_GROUP);
01412       else
01413          gid = grp->gr_gid;
01414    }
01415 
01416    if (chown(ast_config_AST_SOCKET, uid, gid) < 0)
01417       ast_log(LOG_WARNING, "Unable to change ownership of %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
01418 
01419    if (!ast_strlen_zero(ast_config_AST_CTL_PERMISSIONS)) {
01420       int p1;
01421       mode_t p;
01422       sscanf(ast_config_AST_CTL_PERMISSIONS, "%30o", &p1);
01423       p = p1;
01424       if ((chmod(ast_config_AST_SOCKET, p)) < 0)
01425          ast_log(LOG_WARNING, "Unable to change file permissions of %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
01426    }
01427 
01428    return 0;
01429 }

int64_t ast_mark ( int  i,
int  startstop 
)

Definition at line 756 of file asterisk.c.

References profile_data::e, profile_data::entries, profile_entry::events, profile_entry::mark, prof_data, rdtsc(), profile_entry::scale, and profile_entry::value.

Referenced by __ast_pthread_mutex_lock(), and extension_match_core().

00757 {
00758    if (!prof_data || i < 0 || i > prof_data->entries) /* invalid index */
00759       return 0;
00760    if (startstop == 1)
00761       prof_data->e[i].mark = rdtsc();
00762    else {
00763       prof_data->e[i].mark = (rdtsc() - prof_data->e[i].mark);
00764       if (prof_data->e[i].scale > 1)
00765          prof_data->e[i].mark /= prof_data->e[i].scale;
00766       prof_data->e[i].value += prof_data->e[i].mark;
00767       prof_data->e[i].events++;
00768    }
00769    return prof_data->e[i].mark;
00770 }

static void ast_network_puts ( const char *  string  )  [static]

write the string to all attached console clients

Definition at line 1149 of file asterisk.c.

References AST_MAX_CONNECTS, consoles, and fdprint().

Referenced by ast_console_puts().

01150 {
01151    int x;
01152    for (x = 0; x < AST_MAX_CONNECTS; x++) {
01153       if (consoles[x].fd > -1) 
01154          fdprint(consoles[x].p[1], string);
01155    }
01156 }

static void ast_network_puts_mutable ( const char *  string,
int  level 
) [static]

log the string to all attached console clients

Definition at line 1122 of file asterisk.c.

References AST_MAX_CONNECTS, consoles, fdprint(), levels, and mute.

Referenced by ast_console_puts_mutable(), and network_verboser().

01123 {
01124    int x;
01125    for (x = 0;x < AST_MAX_CONNECTS; x++) {
01126       if (consoles[x].mute)
01127          continue;
01128       if (consoles[x].fd > -1) {
01129          if (!consoles[x].levels[level]) 
01130             fdprint(consoles[x].p[1], string);
01131       }
01132    }
01133 }

int64_t ast_profile ( int  i,
int64_t  delta 
)

Definition at line 721 of file asterisk.c.

References profile_data::e, profile_data::entries, profile_entry::events, prof_data, profile_entry::scale, and profile_entry::value.

00722 {
00723    if (!prof_data || i < 0 || i > prof_data->entries) /* invalid index */
00724       return 0;
00725    if (prof_data->e[i].scale > 1)
00726       delta /= prof_data->e[i].scale;
00727    prof_data->e[i].value += delta;
00728    prof_data->e[i].events++;
00729    return prof_data->e[i].value;
00730 }

static void ast_readconfig ( void   )  [static]

Definition at line 2834 of file asterisk.c.

References _cfg_paths::agi_dir, AST_CACHE_DIR_LEN, AST_COMPAT_APP_SET, AST_COMPAT_DELIM_PBX_REALTIME, AST_COMPAT_DELIM_RES_AGI, ast_config_AST_CONFIG_FILE, ast_config_AST_CTL, ast_config_AST_CTL_GROUP, ast_config_AST_CTL_OWNER, ast_config_AST_CTL_PERMISSIONS, ast_config_AST_SYSTEM_NAME, ast_config_destroy(), ast_config_load2(), ast_copy_string(), ast_eid_default, ast_language_is_prefix, AST_LOCK_TYPE_FLOCK, AST_LOCK_TYPE_LOCKFILE, ast_log(), AST_OPT_FLAG_ALWAYS_FORK, AST_OPT_FLAG_CACHE_RECORD_FILES, AST_OPT_FLAG_CONSOLE, AST_OPT_FLAG_DONT_WARN, AST_OPT_FLAG_DUMP_CORE, AST_OPT_FLAG_EXEC_INCLUDES, AST_OPT_FLAG_FORCE_BLACK_BACKGROUND, AST_OPT_FLAG_HIDE_CONSOLE_CONNECT, AST_OPT_FLAG_HIGH_PRIORITY, AST_OPT_FLAG_INIT_KEYS, AST_OPT_FLAG_INTERNAL_TIMING, AST_OPT_FLAG_LIGHT_BACKGROUND, AST_OPT_FLAG_LOCK_CONFIG_DIR, AST_OPT_FLAG_NO_COLOR, AST_OPT_FLAG_NO_FORK, AST_OPT_FLAG_QUIET, AST_OPT_FLAG_TIMESTAMP, AST_OPT_FLAG_TRANSCODE_VIA_SLIN, AST_OPT_FLAG_TRANSMIT_SILENCE, ast_opt_override_config, ast_set2_flag, ast_set_default_eid(), ast_set_lock_type(), ast_str_to_eid(), ast_strlen_zero(), ast_true(), ast_variable_browse(), ast_verbose, cfg_paths, config, _cfg_paths::config_dir, CONFIG_FLAG_NOREALTIME, CONFIG_STATUS_FILEINVALID, CONFIG_STATUS_FILEMISSING, CONFIG_STATUS_FILEUNCHANGED, _cfg_paths::data_dir, _cfg_paths::db_path, getloadavg(), hostname, _cfg_paths::key_dir, _cfg_paths::log_dir, LOG_ERROR, LOG_WARNING, MAXHOSTNAMELEN, _cfg_paths::module_dir, _cfg_paths::monitor_dir, ast_variable::name, ast_variable::next, _cfg_paths::pid_path, _cfg_paths::run_dir, _cfg_paths::run_group, _cfg_paths::run_user, set_ulimit(), _cfg_paths::socket_path, _cfg_paths::spool_dir, _cfg_paths::system_name, ast_variable::value, _cfg_paths::var_dir, and version.

Referenced by main().

02835 {
02836    struct ast_config *cfg;
02837    struct ast_variable *v;
02838    char *config = DEFAULT_CONFIG_FILE;
02839    char hostname[MAXHOSTNAMELEN] = "";
02840    struct ast_flags config_flags = { CONFIG_FLAG_NOREALTIME };
02841    struct {
02842       unsigned int dbdir:1;
02843       unsigned int keydir:1;
02844    } found = { 0, 0 };
02845 
02846    if (ast_opt_override_config) {
02847       cfg = ast_config_load2(ast_config_AST_CONFIG_FILE, "" /* core, can't reload */, config_flags);
02848       if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID)
02849          ast_log(LOG_WARNING, "Unable to open specified master config file '%s', using built-in defaults\n", ast_config_AST_CONFIG_FILE);
02850    } else 
02851       cfg = ast_config_load2(config, "" /* core, can't reload */, config_flags);
02852 
02853    /* init with buildtime config */
02854    ast_copy_string(cfg_paths.config_dir, DEFAULT_CONFIG_DIR, sizeof(cfg_paths.config_dir));
02855    ast_copy_string(cfg_paths.spool_dir, DEFAULT_SPOOL_DIR, sizeof(cfg_paths.spool_dir));
02856    ast_copy_string(cfg_paths.module_dir, DEFAULT_MODULE_DIR, sizeof(cfg_paths.module_dir));
02857    snprintf(cfg_paths.monitor_dir, sizeof(cfg_paths.monitor_dir), "%s/monitor", cfg_paths.spool_dir);
02858    ast_copy_string(cfg_paths.var_dir, DEFAULT_VAR_DIR, sizeof(cfg_paths.var_dir));
02859    ast_copy_string(cfg_paths.data_dir, DEFAULT_DATA_DIR, sizeof(cfg_paths.data_dir));
02860    ast_copy_string(cfg_paths.log_dir, DEFAULT_LOG_DIR, sizeof(cfg_paths.log_dir));
02861    ast_copy_string(cfg_paths.agi_dir, DEFAULT_AGI_DIR, sizeof(cfg_paths.agi_dir));
02862    ast_copy_string(cfg_paths.db_path, DEFAULT_DB, sizeof(cfg_paths.db_path));
02863    ast_copy_string(cfg_paths.key_dir, DEFAULT_KEY_DIR, sizeof(cfg_paths.key_dir));
02864    ast_copy_string(cfg_paths.pid_path, DEFAULT_PID, sizeof(cfg_paths.pid_path));
02865    ast_copy_string(cfg_paths.socket_path, DEFAULT_SOCKET, sizeof(cfg_paths.socket_path));
02866    ast_copy_string(cfg_paths.run_dir, DEFAULT_RUN_DIR, sizeof(cfg_paths.run_dir));
02867 
02868    ast_set_default_eid(&ast_eid_default);
02869 
02870    /* no asterisk.conf? no problem, use buildtime config! */
02871    if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
02872       return;
02873    }
02874 
02875    for (v = ast_variable_browse(cfg, "files"); v; v = v->next) {
02876       if (!strcasecmp(v->name, "astctlpermissions"))
02877          ast_copy_string(ast_config_AST_CTL_PERMISSIONS, v->value, sizeof(ast_config_AST_CTL_PERMISSIONS));
02878       else if (!strcasecmp(v->name, "astctlowner"))
02879          ast_copy_string(ast_config_AST_CTL_OWNER, v->value, sizeof(ast_config_AST_CTL_OWNER));
02880       else if (!strcasecmp(v->name, "astctlgroup"))
02881          ast_copy_string(ast_config_AST_CTL_GROUP, v->value, sizeof(ast_config_AST_CTL_GROUP));
02882       else if (!strcasecmp(v->name, "astctl"))
02883          ast_copy_string(ast_config_AST_CTL, v->value, sizeof(ast_config_AST_CTL));
02884    }
02885 
02886    for (v = ast_variable_browse(cfg, "directories"); v; v = v->next) {
02887       if (!strcasecmp(v->name, "astetcdir")) {
02888          ast_copy_string(cfg_paths.config_dir, v->value, sizeof(cfg_paths.config_dir));
02889       } else if (!strcasecmp(v->name, "astspooldir")) {
02890          ast_copy_string(cfg_paths.spool_dir, v->value, sizeof(cfg_paths.spool_dir));
02891          snprintf(cfg_paths.monitor_dir, sizeof(cfg_paths.monitor_dir), "%s/monitor", v->value);
02892       } else if (!strcasecmp(v->name, "astvarlibdir")) {
02893          ast_copy_string(cfg_paths.var_dir, v->value, sizeof(cfg_paths.var_dir));
02894          if (!found.dbdir)
02895             snprintf(cfg_paths.db_path, sizeof(cfg_paths.db_path), "%s/astdb", v->value);
02896       } else if (!strcasecmp(v->name, "astdbdir")) {
02897          snprintf(cfg_paths.db_path, sizeof(cfg_paths.db_path), "%s/astdb", v->value);
02898          found.dbdir = 1;
02899       } else if (!strcasecmp(v->name, "astdatadir")) {
02900          ast_copy_string(cfg_paths.data_dir, v->value, sizeof(cfg_paths.data_dir));
02901          if (!found.keydir)
02902             snprintf(cfg_paths.key_dir, sizeof(cfg_paths.key_dir), "%s/keys", v->value);
02903       } else if (!strcasecmp(v->name, "astkeydir")) {
02904          snprintf(cfg_paths.key_dir, sizeof(cfg_paths.key_dir), "%s/keys", v->value);
02905          found.keydir = 1;
02906       } else if (!strcasecmp(v->name, "astlogdir")) {
02907          ast_copy_string(cfg_paths.log_dir, v->value, sizeof(cfg_paths.log_dir));
02908       } else if (!strcasecmp(v->name, "astagidir")) {
02909          ast_copy_string(cfg_paths.agi_dir, v->value, sizeof(cfg_paths.agi_dir));
02910       } else if (!strcasecmp(v->name, "astrundir")) {
02911          snprintf(cfg_paths.pid_path, sizeof(cfg_paths.pid_path), "%s/%s", v->value, "asterisk.pid");
02912          snprintf(cfg_paths.socket_path, sizeof(cfg_paths.socket_path), "%s/%s", v->value, ast_config_AST_CTL);
02913          ast_copy_string(cfg_paths.run_dir, v->value, sizeof(cfg_paths.run_dir));
02914       } else if (!strcasecmp(v->name, "astmoddir")) {
02915          ast_copy_string(cfg_paths.module_dir, v->value, sizeof(cfg_paths.module_dir));
02916       }
02917    }
02918 
02919    for (v = ast_variable_browse(cfg, "options"); v; v = v->next) {
02920       /* verbose level (-v at startup) */
02921       if (!strcasecmp(v->name, "verbose")) {
02922          option_verbose = atoi(v->value);
02923       /* whether or not to force timestamping in CLI verbose output. (-T at startup) */
02924       } else if (!strcasecmp(v->name, "timestamp")) {
02925          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_TIMESTAMP);
02926       /* whether or not to support #exec in config files */
02927       } else if (!strcasecmp(v->name, "execincludes")) {
02928          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_EXEC_INCLUDES);
02929       /* debug level (-d at startup) */
02930       } else if (!strcasecmp(v->name, "debug")) {
02931          option_debug = 0;
02932          if (sscanf(v->value, "%30d", &option_debug) != 1) {
02933             option_debug = ast_true(v->value);
02934          }
02935 #if HAVE_WORKING_FORK
02936       /* Disable forking (-f at startup) */
02937       } else if (!strcasecmp(v->name, "nofork")) {
02938          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_NO_FORK);
02939       /* Always fork, even if verbose or debug are enabled (-F at startup) */
02940       } else if (!strcasecmp(v->name, "alwaysfork")) {
02941          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_ALWAYS_FORK);
02942 #endif
02943       /* Run quietly (-q at startup ) */
02944       } else if (!strcasecmp(v->name, "quiet")) {
02945          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_QUIET);
02946       /* Run as console (-c at startup, implies nofork) */
02947       } else if (!strcasecmp(v->name, "console")) {
02948          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_NO_FORK | AST_OPT_FLAG_CONSOLE);
02949       /* Run with high priority if the O/S permits (-p at startup) */
02950       } else if (!strcasecmp(v->name, "highpriority")) {
02951          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_HIGH_PRIORITY);
02952       /* Initialize RSA auth keys (IAX2) (-i at startup) */
02953       } else if (!strcasecmp(v->name, "initcrypto")) {
02954          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_INIT_KEYS);
02955       /* Disable ANSI colors for console (-c at startup) */
02956       } else if (!strcasecmp(v->name, "nocolor")) {
02957          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_NO_COLOR);
02958       /* Disable some usage warnings for picky people :p */
02959       } else if (!strcasecmp(v->name, "dontwarn")) {
02960          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_DONT_WARN);
02961       /* Dump core in case of crash (-g) */
02962       } else if (!strcasecmp(v->name, "dumpcore")) {
02963          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_DUMP_CORE);
02964       /* Cache recorded sound files to another directory during recording */
02965       } else if (!strcasecmp(v->name, "cache_record_files")) {
02966          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_CACHE_RECORD_FILES);
02967       /* Specify cache directory */
02968       }  else if (!strcasecmp(v->name, "record_cache_dir")) {
02969          ast_copy_string(record_cache_dir, v->value, AST_CACHE_DIR_LEN);
02970       /* Build transcode paths via SLINEAR, instead of directly */
02971       } else if (!strcasecmp(v->name, "transcode_via_sln")) {
02972          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_TRANSCODE_VIA_SLIN);
02973       /* Transmit SLINEAR silence while a channel is being recorded or DTMF is being generated on a channel */
02974       } else if (!strcasecmp(v->name, "transmit_silence_during_record") || !strcasecmp(v->name, "transmit_silence")) {
02975          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_TRANSMIT_SILENCE);
02976       /* Enable internal timing */
02977       } else if (!strcasecmp(v->name, "internal_timing")) {
02978          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_INTERNAL_TIMING);
02979       } else if (!strcasecmp(v->name, "maxcalls")) {
02980          if ((sscanf(v->value, "%30d", &option_maxcalls) != 1) || (option_maxcalls < 0)) {
02981             option_maxcalls = 0;
02982          }
02983       } else if (!strcasecmp(v->name, "maxload")) {
02984          double test[1];
02985 
02986          if (getloadavg(test, 1) == -1) {
02987             ast_log(LOG_ERROR, "Cannot obtain load average on this system. 'maxload' option disabled.\n");
02988             option_maxload = 0.0;
02989          } else if ((sscanf(v->value, "%30lf", &option_maxload) != 1) || (option_maxload < 0.0)) {
02990             option_maxload = 0.0;
02991          }
02992       /* Set the maximum amount of open files */
02993       } else if (!strcasecmp(v->name, "maxfiles")) {
02994          option_maxfiles = atoi(v->value);
02995          set_ulimit(option_maxfiles);
02996       /* What user to run as */
02997       } else if (!strcasecmp(v->name, "runuser")) {
02998          ast_copy_string(cfg_paths.run_user, v->value, sizeof(cfg_paths.run_user));
02999       /* What group to run as */
03000       } else if (!strcasecmp(v->name, "rungroup")) {
03001          ast_copy_string(cfg_paths.run_group, v->value, sizeof(cfg_paths.run_group));
03002       } else if (!strcasecmp(v->name, "systemname")) {
03003          ast_copy_string(cfg_paths.system_name, v->value, sizeof(cfg_paths.system_name));
03004       } else if (!strcasecmp(v->name, "autosystemname")) {
03005          if (ast_true(v->value)) {
03006             if (!gethostname(hostname, sizeof(hostname) - 1))
03007                ast_copy_string(cfg_paths.system_name, hostname, sizeof(cfg_paths.system_name));
03008             else {
03009                if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)){
03010                   ast_copy_string(cfg_paths.system_name, "localhost", sizeof(cfg_paths.system_name));
03011                }
03012                ast_log(LOG_ERROR, "Cannot obtain hostname for this system.  Using '%s' instead.\n", ast_config_AST_SYSTEM_NAME);
03013             }
03014          }
03015       } else if (!strcasecmp(v->name, "languageprefix")) {
03016          ast_language_is_prefix = ast_true(v->value);
03017       } else if (!strcasecmp(v->name, "lockmode")) {
03018          if (!strcasecmp(v->value, "lockfile")) {
03019             ast_set_lock_type(AST_LOCK_TYPE_LOCKFILE);
03020          } else if (!strcasecmp(v->value, "flock")) {
03021             ast_set_lock_type(AST_LOCK_TYPE_FLOCK);
03022          } else {
03023             ast_log(LOG_WARNING, "'%s' is not a valid setting for the lockmode option, "
03024                "defaulting to 'lockfile'\n", v->value);
03025             ast_set_lock_type(AST_LOCK_TYPE_LOCKFILE);
03026          }
03027 #if defined(HAVE_SYSINFO)
03028       } else if (!strcasecmp(v->name, "minmemfree")) {
03029          /* specify the minimum amount of free memory to retain.  Asterisk should stop accepting new calls
03030           * if the amount of free memory falls below this watermark */
03031          if ((sscanf(v->value, "%30ld", &option_minmemfree) != 1) || (option_minmemfree < 0)) {
03032             option_minmemfree = 0;
03033          }
03034 #endif
03035       } else if (!strcasecmp(v->name, "entityid")) {
03036          struct ast_eid tmp_eid;
03037          if (!ast_str_to_eid(&tmp_eid, v->value)) {
03038             ast_verbose("Successfully set global EID to '%s'\n", v->value);
03039             ast_eid_default = tmp_eid;
03040          } else
03041             ast_verbose("Invalid Entity ID '%s' provided\n", v->value);
03042       } else if (!strcasecmp(v->name, "lightbackground")) {
03043          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_LIGHT_BACKGROUND);
03044       } else if (!strcasecmp(v->name, "forceblackbackground")) {
03045          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_FORCE_BLACK_BACKGROUND);
03046       } else if (!strcasecmp(v->name, "hideconnect")) {
03047          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_HIDE_CONSOLE_CONNECT);
03048       } else if (!strcasecmp(v->name, "lockconfdir")) {
03049          ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_LOCK_CONFIG_DIR);
03050       }
03051    }
03052    for (v = ast_variable_browse(cfg, "compat"); v; v = v->next) {
03053       float version;
03054       if (sscanf(v->value, "%30f", &version) != 1) {
03055          ast_log(LOG_WARNING, "Compatibility version for option '%s' is not a number: '%s'\n", v->name, v->value);
03056          continue;
03057       }
03058       if (!strcasecmp(v->name, "app_set")) {
03059          ast_set2_flag(&ast_compat, version < 1.5 ? 1 : 0, AST_COMPAT_APP_SET);
03060       } else if (!strcasecmp(v->name, "res_agi")) {
03061          ast_set2_flag(&ast_compat, version < 1.5 ? 1 : 0, AST_COMPAT_DELIM_RES_AGI);
03062       } else if (!strcasecmp(v->name, "pbx_realtime")) {
03063          ast_set2_flag(&ast_compat, version < 1.5 ? 1 : 0, AST_COMPAT_DELIM_PBX_REALTIME);
03064       }
03065    }
03066    ast_config_destroy(cfg);
03067 }

int ast_register_atexit ( void(*)(void)  func  ) 

Register a function to be executed before Asterisk exits.

Parameters:
func The callback function to use.
Return values:
0 on success.
-1 on error.

Definition at line 932 of file asterisk.c.

References ast_calloc, AST_RWLIST_INSERT_HEAD, AST_RWLIST_UNLOCK, AST_RWLIST_WRLOCK, ast_unregister_atexit(), ast_atexit::func, and ast_atexit::list.

Referenced by ast_cel_engine_init(), do_reload(), load_module(), and main().

00933 {
00934    struct ast_atexit *ae;
00935 
00936    if (!(ae = ast_calloc(1, sizeof(*ae))))
00937       return -1;
00938 
00939    ae->func = func;
00940 
00941    ast_unregister_atexit(func);  
00942 
00943    AST_RWLIST_WRLOCK(&atexits);
00944    AST_RWLIST_INSERT_HEAD(&atexits, ae, list);
00945    AST_RWLIST_UNLOCK(&atexits);
00946 
00947    return 0;
00948 }

void ast_register_file_version ( const char *  file,
const char *  version 
)

Register the version of a source code file with the core.

Parameters:
file the source file name
version the version string (typically a SVN revision keyword string)
Returns:
nothing
This function should not be called directly, but instead the ASTERISK_FILE_VERSION macro should be used to register a file with the core.

Definition at line 302 of file asterisk.c.

References ast_calloc, AST_RWLIST_INSERT_HEAD, AST_RWLIST_UNLOCK, AST_RWLIST_WRLOCK, ast_strdupa, ast_strip(), and ast_strip_quoted().

00303 {
00304    struct file_version *new;
00305    char *work;
00306    size_t version_length;
00307 
00308    work = ast_strdupa(version);
00309    work = ast_strip(ast_strip_quoted(work, "$", "$"));
00310    version_length = strlen(work) + 1;
00311    
00312    if (!(new = ast_calloc(1, sizeof(*new) + version_length)))
00313       return;
00314 
00315    new->file = file;
00316    new->version = (char *) new + sizeof(*new);
00317    memcpy(new->version, work, version_length);
00318    AST_RWLIST_WRLOCK(&file_versions);
00319    AST_RWLIST_INSERT_HEAD(&file_versions, new, list);
00320    AST_RWLIST_UNLOCK(&file_versions);
00321 }

void ast_register_thread ( char *  name  ) 

Definition at line 386 of file asterisk.c.

References ast_calloc, AST_RWLIST_INSERT_HEAD, AST_RWLIST_UNLOCK, and AST_RWLIST_WRLOCK.

Referenced by dummy_start().

00387 { 
00388    struct thread_list_t *new = ast_calloc(1, sizeof(*new));
00389 
00390    if (!new)
00391       return;
00392    new->id = pthread_self();
00393    new->name = name; /* steal the allocated memory for the thread name */
00394    AST_RWLIST_WRLOCK(&thread_list);
00395    AST_RWLIST_INSERT_HEAD(&thread_list, new, list);
00396    AST_RWLIST_UNLOCK(&thread_list);
00397 }

static void ast_remotecontrol ( char *  data  )  [static]

Definition at line 2644 of file asterisk.c.

References __remote_quit_handler(), ast_el_initialize(), ast_el_read_char(), ast_el_read_history(), ast_log(), ast_opt_exec, ast_opt_mute, ast_poll, ast_strlen_zero(), ast_verbose, el, el_hist, errno, fdsend(), hostname, LOG_ERROR, LOG_WARNING, prefix, remoteconsolehandler(), remotehostname, sig_flags, strsep(), and version.

Referenced by main().

02645 {
02646    char buf[80];
02647    int res;
02648    char filename[80] = "";
02649    char *hostname;
02650    char *cpid;
02651    char *version;
02652    int pid;
02653    char *stringp = NULL;
02654 
02655    char *ebuf;
02656    int num = 0;
02657 
02658    memset(&sig_flags, 0, sizeof(sig_flags));
02659    signal(SIGINT, __remote_quit_handler);
02660    signal(SIGTERM, __remote_quit_handler);
02661    signal(SIGHUP, __remote_quit_handler);
02662 
02663    if (read(ast_consock, buf, sizeof(buf)) < 0) {
02664       ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
02665       return;
02666    }
02667    if (data) {
02668       char prefix[] = "cli quit after ";
02669       char *tmp = alloca(strlen(data) + strlen(prefix) + 1);
02670       sprintf(tmp, "%s%s", prefix, data);
02671       if (write(ast_consock, tmp, strlen(tmp) + 1) < 0) {
02672          ast_log(LOG_ERROR, "write() failed: %s\n", strerror(errno));
02673          if (sig_flags.need_quit == 1) {
02674             return;
02675          }
02676       }
02677    }
02678    stringp = buf;
02679    hostname = strsep(&stringp, "/");
02680    cpid = strsep(&stringp, "/");
02681    version = strsep(&stringp, "\n");
02682    if (!version)
02683       version = "<Version Unknown>";
02684    stringp = hostname;
02685    strsep(&stringp, ".");
02686    if (cpid)
02687       pid = atoi(cpid);
02688    else
02689       pid = -1;
02690    if (!data) {
02691       char tmp[80];
02692       snprintf(tmp, sizeof(tmp), "core set verbose atleast %d", option_verbose);
02693       fdsend(ast_consock, tmp);
02694       snprintf(tmp, sizeof(tmp), "core set debug atleast %d", option_debug);
02695       fdsend(ast_consock, tmp);
02696       if (!ast_opt_mute)
02697          fdsend(ast_consock, "logger mute silent");
02698       else 
02699          printf("log and verbose output currently muted ('logger mute' to unmute)\n");
02700    }
02701 
02702    if (ast_opt_exec && data) {  /* hack to print output then exit if asterisk -rx is used */
02703       struct pollfd fds;
02704       fds.fd = ast_consock;
02705       fds.events = POLLIN;
02706       fds.revents = 0;
02707       while (ast_poll(&fds, 1, 60000) > 0) {
02708          char buffer[512] = "", *curline = buffer, *nextline;
02709          int not_written = 1;
02710 
02711          if (sig_flags.need_quit == 1) {
02712             break;
02713          }
02714 
02715          if (read(ast_consock, buffer, sizeof(buffer) - 1) <= 0) {
02716             break;
02717          }
02718 
02719          do {
02720             if ((nextline = strchr(curline, '\n'))) {
02721                nextline++;
02722             } else {
02723                nextline = strchr(curline, '\0');
02724             }
02725 
02726             /* Skip verbose lines */
02727             if (*curline != 127) {
02728                not_written = 0;
02729                if (write(STDOUT_FILENO, curline, nextline - curline) < 0) {
02730                   ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
02731                }
02732             }
02733             curline = nextline;
02734          } while (!ast_strlen_zero(curline));
02735 
02736          /* No non-verbose output in 60 seconds. */
02737          if (not_written) {
02738             break;
02739          }
02740       }
02741       return;
02742    }
02743 
02744    ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
02745    remotehostname = hostname;
02746    if (getenv("HOME")) 
02747       snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
02748    if (el_hist == NULL || el == NULL)
02749       ast_el_initialize();
02750 
02751    el_set(el, EL_GETCFN, ast_el_read_char);
02752 
02753    if (!ast_strlen_zero(filename))
02754       ast_el_read_history(filename);
02755 
02756    for (;;) {
02757       ebuf = (char *)el_gets(el, &num);
02758 
02759       if (sig_flags.need_quit == 1) {
02760          break;
02761       }
02762 
02763       if (!ebuf && write(1, "", 1) < 0)
02764          break;
02765 
02766       if (!ast_strlen_zero(ebuf)) {
02767          if (ebuf[strlen(ebuf)-1] == '\n')
02768             ebuf[strlen(ebuf)-1] = '\0';
02769          if (!remoteconsolehandler(ebuf)) {
02770             /* Strip preamble from output */
02771             char *temp;
02772             for (temp = ebuf; *temp; temp++) {
02773                if (*temp == 127) {
02774                   memmove(temp, temp + 1, strlen(temp));
02775                   temp--;
02776                }
02777             }
02778             res = write(ast_consock, ebuf, strlen(ebuf) + 1);
02779             if (res < 1) {
02780                ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
02781                break;
02782             }
02783          }
02784       }
02785    }
02786    printf("\nDisconnected from Asterisk server\n");
02787 }

void ast_replace_sigchld ( void   ) 

Replace the SIGCHLD handler.

Normally, Asterisk has a SIGCHLD handler that is cleaning up all zombie processes from forking elsewhere in Asterisk. However, if you want to wait*() on the process to retrieve information about it's exit status, then this signal handler needs to be temporarily replaced.

Code that executes this function *must* call ast_unreplace_sigchld() after it is finished doing the wait*().

Definition at line 1000 of file asterisk.c.

References ast_mutex_lock, ast_mutex_unlock, null_sig_handler, safe_system_level, safe_system_lock, and safe_system_prev_handler.

Referenced by ast_safe_fork(), and ast_safe_system().

01001 {
01002    unsigned int level;
01003 
01004    ast_mutex_lock(&safe_system_lock);
01005    level = safe_system_level++;
01006 
01007    /* only replace the handler if it has not already been done */
01008    if (level == 0) {
01009       sigaction(SIGCHLD, &null_sig_handler, &safe_system_prev_handler);
01010    }
01011 
01012    ast_mutex_unlock(&safe_system_lock);
01013 }

static void ast_run_atexits ( void   )  [static]

Definition at line 1579 of file asterisk.c.

References AST_RWLIST_RDLOCK, AST_RWLIST_TRAVERSE, AST_RWLIST_UNLOCK, ast_atexit::func, and ast_atexit::list.

Referenced by quit_handler().

01580 {
01581    struct ast_atexit *ae;
01582    AST_RWLIST_RDLOCK(&atexits);
01583    AST_RWLIST_TRAVERSE(&atexits, ae, list) {
01584       if (ae->func) 
01585          ae->func();
01586    }
01587    AST_RWLIST_UNLOCK(&atexits);
01588 }

int ast_safe_system ( const char *  s  ) 

Safely spawn an external program while closing file descriptors.

Note:
This replaces the system call in all Asterisk modules

Definition at line 1030 of file asterisk.c.

References ast_close_fds_above_n(), ast_log(), ast_opt_high_priority, ast_replace_sigchld(), ast_set_priority(), ast_unreplace_sigchld(), errno, LOG_WARNING, status, WEXITSTATUS, and WIFEXITED.

Referenced by add_email_attachment(), alarmreceiver_exec(), ast_monitor_stop(), consolehandler(), filestream_destructor(), mixmonitor_thread(), notify_message(), process_text_line(), remoteconsolehandler(), rotate_file(), run_externnotify(), sendmail(), sendpage(), system_exec_helper(), and vm_change_password_shell().

01031 {
01032    pid_t pid;
01033    int res;
01034    struct rusage rusage;
01035    int status;
01036 
01037 #if defined(HAVE_WORKING_FORK) || defined(HAVE_WORKING_VFORK)
01038    ast_replace_sigchld();
01039 
01040 #ifdef HAVE_WORKING_FORK
01041    pid = fork();
01042 #else
01043    pid = vfork();
01044 #endif   
01045 
01046    if (pid == 0) {
01047 #ifdef HAVE_CAP
01048       cap_t cap = cap_from_text("cap_net_admin-eip");
01049 
01050       if (cap_set_proc(cap)) {
01051          /* Careful with order! Logging cannot happen after we close FDs */
01052          ast_log(LOG_WARNING, "Unable to remove capabilities.\n");
01053       }
01054       cap_free(cap);
01055 #endif
01056 #ifdef HAVE_WORKING_FORK
01057       if (ast_opt_high_priority)
01058          ast_set_priority(0);
01059       /* Close file descriptors and launch system command */
01060       ast_close_fds_above_n(STDERR_FILENO);
01061 #endif
01062       execl("/bin/sh", "/bin/sh", "-c", s, (char *) NULL);
01063       _exit(1);
01064    } else if (pid > 0) {
01065       for (;;) {
01066          res = wait4(pid, &status, 0, &rusage);
01067          if (res > -1) {
01068             res = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
01069             break;
01070          } else if (errno != EINTR) 
01071             break;
01072       }
01073    } else {
01074       ast_log(LOG_WARNING, "Fork failed: %s\n", strerror(errno));
01075       res = -1;
01076    }
01077 
01078    ast_unreplace_sigchld();
01079 #else /* !defined(HAVE_WORKING_FORK) && !defined(HAVE_WORKING_VFORK) */
01080    res = -1;
01081 #endif
01082 
01083    return res;
01084 }

int ast_set_priority ( int   ) 

We set ourselves to a high priority, that we might pre-empt everything else. If your PBX has heavy activity on it, this is a good thing.

Provided by asterisk.c

Definition at line 1545 of file asterisk.c.

References ast_log(), ast_verbose, LOG_WARNING, sched_setscheduler, and setpriority.

Referenced by app_exec(), ast_safe_system(), canary_thread(), icesencode(), launch_script(), main(), mp3play(), NBScatplay(), send_waveform_to_fd(), spawn_mp3(), and spawn_ras().

01546 {
01547    struct sched_param sched;
01548    memset(&sched, 0, sizeof(sched));
01549 #ifdef __linux__
01550    if (pri) {  
01551       sched.sched_priority = 10;
01552       if (sched_setscheduler(0, SCHED_RR, &sched)) {
01553          ast_log(LOG_WARNING, "Unable to set high priority\n");
01554          return -1;
01555       } else
01556          if (option_verbose)
01557             ast_verbose("Set to realtime thread\n");
01558    } else {
01559       sched.sched_priority = 0;
01560       /* According to the manpage, these parameters can never fail. */
01561       sched_setscheduler(0, SCHED_OTHER, &sched);
01562    }
01563 #else
01564    if (pri) {
01565       if (setpriority(PRIO_PROCESS, 0, -10) == -1) {
01566          ast_log(LOG_WARNING, "Unable to set high priority\n");
01567          return -1;
01568       } else
01569          if (option_verbose)
01570             ast_verbose("Set to high priority\n");
01571    } else {
01572       /* According to the manpage, these parameters can never fail. */
01573       setpriority(PRIO_PROCESS, 0, 0);
01574    }
01575 #endif
01576    return 0;
01577 }

static int ast_tryconnect ( void   )  [static]

Definition at line 1431 of file asterisk.c.

References AF_LOCAL, ast_config_AST_SOCKET, ast_copy_string(), ast_log(), errno, LOG_WARNING, and PF_LOCAL.

Referenced by ast_el_read_char(), and main().

01432 {
01433    struct sockaddr_un sunaddr;
01434    int res;
01435    ast_consock = socket(PF_LOCAL, SOCK_STREAM, 0);
01436    if (ast_consock < 0) {
01437       ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
01438       return 0;
01439    }
01440    memset(&sunaddr, 0, sizeof(sunaddr));
01441    sunaddr.sun_family = AF_LOCAL;
01442    ast_copy_string(sunaddr.sun_path, ast_config_AST_SOCKET, sizeof(sunaddr.sun_path));
01443    res = connect(ast_consock, (struct sockaddr *)&sunaddr, sizeof(sunaddr));
01444    if (res) {
01445       close(ast_consock);
01446       ast_consock = -1;
01447       return 0;
01448    } else
01449       return 1;
01450 }

void ast_unregister_atexit ( void(*)(void)  func  ) 

Unregister a function registered with ast_register_atexit().

Parameters:
func The callback function to unregister.

Definition at line 950 of file asterisk.c.

References AST_RWLIST_REMOVE_CURRENT, AST_RWLIST_TRAVERSE_SAFE_BEGIN, AST_RWLIST_TRAVERSE_SAFE_END, AST_RWLIST_UNLOCK, AST_RWLIST_WRLOCK, free, ast_atexit::func, and ast_atexit::list.

Referenced by ast_register_atexit(), do_reload(), and unload_module().

00951 {
00952    struct ast_atexit *ae = NULL;
00953 
00954    AST_RWLIST_WRLOCK(&atexits);
00955    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&atexits, ae, list) {
00956       if (ae->func == func) {
00957          AST_RWLIST_REMOVE_CURRENT(list);
00958          break;
00959       }
00960    }
00961    AST_RWLIST_TRAVERSE_SAFE_END;
00962    AST_RWLIST_UNLOCK(&atexits);
00963 
00964    free(ae);
00965 }

void ast_unregister_file_version ( const char *  file  ) 

Unregister a source code file from the core.

Parameters:
file the source file name
Returns:
nothing
This function should not be called directly, but instead the ASTERISK_FILE_VERSION macro should be used to automatically unregister the file when the module is unloaded.

Definition at line 323 of file asterisk.c.

References ast_free, AST_RWLIST_REMOVE_CURRENT, AST_RWLIST_TRAVERSE_SAFE_BEGIN, AST_RWLIST_TRAVERSE_SAFE_END, AST_RWLIST_UNLOCK, AST_RWLIST_WRLOCK, file_version::file, and ast_atexit::list.

00324 {
00325    struct file_version *find;
00326 
00327    AST_RWLIST_WRLOCK(&file_versions);
00328    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&file_versions, find, list) {
00329       if (!strcasecmp(find->file, file)) {
00330          AST_RWLIST_REMOVE_CURRENT(list);
00331          break;
00332       }
00333    }
00334    AST_RWLIST_TRAVERSE_SAFE_END;
00335    AST_RWLIST_UNLOCK(&file_versions);
00336 
00337    if (find)
00338       ast_free(find);
00339 }

void ast_unregister_thread ( void *  id  ) 

Definition at line 399 of file asterisk.c.

References ast_free, AST_RWLIST_REMOVE_CURRENT, AST_RWLIST_TRAVERSE_SAFE_BEGIN, AST_RWLIST_TRAVERSE_SAFE_END, AST_RWLIST_UNLOCK, AST_RWLIST_WRLOCK, thread_list_t::id, ast_atexit::list, and thread_list_t::name.

Referenced by dummy_start().

00400 {
00401    struct thread_list_t *x;
00402 
00403    AST_RWLIST_WRLOCK(&thread_list);
00404    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&thread_list, x, list) {
00405       if ((void *) x->id == id) {
00406          AST_RWLIST_REMOVE_CURRENT(list);
00407          break;
00408       }
00409    }
00410    AST_RWLIST_TRAVERSE_SAFE_END;
00411    AST_RWLIST_UNLOCK(&thread_list);
00412    if (x) {
00413       ast_free(x->name);
00414       ast_free(x);
00415    }
00416 }

void ast_unreplace_sigchld ( void   ) 

Restore the SIGCHLD handler.

This function is called after a call to ast_replace_sigchld. It restores the SIGCHLD handler that cleans up any zombie processes.

Definition at line 1015 of file asterisk.c.

References ast_mutex_lock, ast_mutex_unlock, safe_system_level, safe_system_lock, and safe_system_prev_handler.

Referenced by ast_safe_fork_cleanup(), and ast_safe_system().

01016 {
01017    unsigned int level;
01018 
01019    ast_mutex_lock(&safe_system_lock);
01020    level = --safe_system_level;
01021 
01022    /* only restore the handler if we are the last one */
01023    if (level == 0) {
01024       sigaction(SIGCHLD, &safe_system_prev_handler, NULL);
01025    }
01026 
01027    ast_mutex_unlock(&safe_system_lock);
01028 }

static void canary_exit ( void   )  [static]

Definition at line 3113 of file asterisk.c.

References canary_pid.

Referenced by main().

03114 {
03115    if (canary_pid > 0)
03116       kill(canary_pid, SIGKILL);
03117 }

static void* canary_thread ( void *  unused  )  [static]

Definition at line 3090 of file asterisk.c.

References ast_log(), ast_set_priority(), ast_tvnow(), canary_filename, and LOG_WARNING.

Referenced by main().

03091 {
03092    struct stat canary_stat;
03093    struct timeval now;
03094 
03095    /* Give the canary time to sing */
03096    sleep(120);
03097 
03098    for (;;) {
03099       stat(canary_filename, &canary_stat);
03100       now = ast_tvnow();
03101       if (now.tv_sec > canary_stat.st_mtime + 60) {
03102          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");
03103          ast_set_priority(0);
03104          pthread_exit(NULL);
03105       }
03106 
03107       /* Check the canary once a minute */
03108       sleep(60);
03109    }
03110 }

static char* cli_complete ( EditLine *  editline,
int  ch 
) [static]

Definition at line 2441 of file asterisk.c.

References AST_CLI_COMPLETE_EOF, ast_cli_completion_matches(), ast_cli_display_match_list(), ast_el_strtoarr(), ast_free, ast_malloc, ast_opt_remote, ast_realloc, and fdsend().

Referenced by ast_el_initialize().

02442 {
02443    int len = 0;
02444    char *ptr;
02445    int nummatches = 0;
02446    char **matches;
02447    int retval = CC_ERROR;
02448    char buf[2048], savechr;
02449    int res;
02450 
02451    LineInfo *lf = (LineInfo *)el_line(editline);
02452 
02453    savechr = *(char *)lf->cursor;
02454    *(char *)lf->cursor = '\0';
02455    ptr = (char *)lf->cursor;
02456    if (ptr) {
02457       while (ptr > lf->buffer) {
02458          if (isspace(*ptr)) {
02459             ptr++;
02460             break;
02461          }
02462          ptr--;
02463       }
02464    }
02465 
02466    len = lf->cursor - ptr;
02467 
02468    if (ast_opt_remote) {
02469       snprintf(buf, sizeof(buf), "_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr); 
02470       fdsend(ast_consock, buf);
02471       res = read(ast_consock, buf, sizeof(buf) - 1);
02472       buf[res] = '\0';
02473       nummatches = atoi(buf);
02474 
02475       if (nummatches > 0) {
02476          char *mbuf;
02477          int mlen = 0, maxmbuf = 2048;
02478          /* Start with a 2048 byte buffer */       
02479          if (!(mbuf = ast_malloc(maxmbuf))) {
02480             lf->cursor[0] = savechr;
02481             return (char *)(CC_ERROR);
02482          }
02483          snprintf(buf, sizeof(buf), "_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr); 
02484          fdsend(ast_consock, buf);
02485          res = 0;
02486          mbuf[0] = '\0';
02487          while (!strstr(mbuf, AST_CLI_COMPLETE_EOF) && res != -1) {
02488             if (mlen + 1024 > maxmbuf) {
02489                /* Every step increment buffer 1024 bytes */
02490                maxmbuf += 1024;              
02491                if (!(mbuf = ast_realloc(mbuf, maxmbuf))) {
02492                   lf->cursor[0] = savechr;
02493                   return (char *)(CC_ERROR);
02494                }
02495             }
02496             /* Only read 1024 bytes at a time */
02497             res = read(ast_consock, mbuf + mlen, 1024);
02498             if (res > 0)
02499                mlen += res;
02500          }
02501          mbuf[mlen] = '\0';
02502 
02503          matches = ast_el_strtoarr(mbuf);
02504          ast_free(mbuf);
02505       } else
02506          matches = (char **) NULL;
02507    } else {
02508       char **p, *oldbuf=NULL;
02509       nummatches = 0;
02510       matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
02511       for (p = matches; p && *p; p++) {
02512          if (!oldbuf || strcmp(*p,oldbuf))
02513             nummatches++;
02514          oldbuf = *p;
02515       }
02516    }
02517 
02518    if (matches) {
02519       int i;
02520       int matches_num, maxlen, match_len;
02521 
02522       if (matches[0][0] != '\0') {
02523          el_deletestr(editline, (int) len);
02524          el_insertstr(editline, matches[0]);
02525          retval = CC_REFRESH;
02526       }
02527 
02528       if (nummatches == 1) {
02529          /* Found an exact match */
02530          el_insertstr(editline, " ");
02531          retval = CC_REFRESH;
02532       } else {
02533          /* Must be more than one match */
02534          for (i = 1, maxlen = 0; matches[i]; i++) {
02535             match_len = strlen(matches[i]);
02536             if (match_len > maxlen)
02537                maxlen = match_len;
02538          }
02539          matches_num = i - 1;
02540          if (matches_num >1) {
02541             fprintf(stdout, "\n");
02542             ast_cli_display_match_list(matches, nummatches, maxlen);
02543             retval = CC_REDISPLAY;
02544          } else { 
02545             el_insertstr(editline," ");
02546             retval = CC_REFRESH;
02547          }
02548       }
02549       for (i = 0; matches[i]; i++)
02550          ast_free(matches[i]);
02551       ast_free(matches);
02552    }
02553 
02554    lf->cursor[0] = savechr;
02555 
02556    return (char *)(long)retval;
02557 }

static char* cli_prompt ( EditLine *  editline  )  [static]

Definition at line 2213 of file asterisk.c.

References ast_config_AST_SYSTEM_NAME, ast_localtime(), ast_opt_remote, ast_str_append(), ast_str_buffer(), ast_str_create(), ast_str_reset(), ast_str_set(), ast_strftime(), ast_tvnow(), ASTERISK_PROMPT, ASTERISK_PROMPT2, COLOR_BLACK, COLOR_WHITE, getloadavg(), hostname, ast_atexit::list, MAXHOSTNAMELEN, remotehostname, and term_color_code().

Referenced by ast_el_initialize().

02214 {
02215    char tmp[100];
02216    char *pfmt;
02217    int color_used = 0;
02218    static int cli_prompt_changes = 0;
02219    char term_code[20];
02220    struct passwd *pw;
02221    struct group *gr;
02222 
02223    if (prompt == NULL) {
02224       prompt = ast_str_create(100);
02225    } else if (!cli_prompt_changes) {
02226       return ast_str_buffer(prompt);
02227    } else {
02228       ast_str_reset(prompt);
02229    }
02230 
02231    if ((pfmt = getenv("ASTERISK_PROMPT"))) {
02232       char *t = pfmt;
02233       struct timeval ts = ast_tvnow();
02234       while (*t != '\0') {
02235          if (*t == '%') {
02236             char hostname[MAXHOSTNAMELEN] = "";
02237             int i, which;
02238             struct ast_tm tm = { 0, };
02239             int fgcolor = COLOR_WHITE, bgcolor = COLOR_BLACK;
02240 
02241             t++;
02242             switch (*t) {
02243             case 'C': /* color */
02244                t++;
02245                if (sscanf(t, "%30d;%30d%n", &fgcolor, &bgcolor, &i) == 2) {
02246                   ast_str_append(&prompt, 0, "%s", term_color_code(term_code, fgcolor, bgcolor, sizeof(term_code)));
02247                   t += i - 1;
02248                } else if (sscanf(t, "%30d%n", &fgcolor, &i) == 1) {
02249                   ast_str_append(&prompt, 0, "%s", term_color_code(term_code, fgcolor, 0, sizeof(term_code)));
02250                   t += i - 1;
02251                }
02252 
02253                /* If the color has been reset correctly, then there's no need to reset it later */
02254                color_used = ((fgcolor == COLOR_WHITE) && (bgcolor == COLOR_BLACK)) ? 0 : 1;
02255                break;
02256             case 'd': /* date */
02257                if (ast_localtime(&ts, &tm, NULL)) {
02258                   ast_strftime(tmp, sizeof(tmp), "%Y-%m-%d", &tm);
02259                   ast_str_append(&prompt, 0, "%s", tmp);
02260                   cli_prompt_changes++;
02261                }
02262                break;
02263             case 'g': /* group */
02264                if ((gr = getgrgid(getgid()))) {
02265                   ast_str_append(&prompt, 0, "%s", gr->gr_name);
02266                }
02267                break;
02268             case 'h': /* hostname */
02269                if (!gethostname(hostname, sizeof(hostname) - 1)) {
02270                   ast_str_append(&prompt, 0, "%s", hostname);
02271                } else {
02272                   ast_str_append(&prompt, 0, "%s", "localhost");
02273                }
02274                break;
02275             case 'H': /* short hostname */
02276                if (!gethostname(hostname, sizeof(hostname) - 1)) {
02277                   char *dotptr;
02278                   if ((dotptr = strchr(hostname, '.'))) {
02279                      *dotptr = '\0';
02280                   }
02281                   ast_str_append(&prompt, 0, "%s", hostname);
02282                } else {
02283                   ast_str_append(&prompt, 0, "%s", "localhost");
02284                }
02285                break;
02286 #ifdef HAVE_GETLOADAVG
02287             case 'l': /* load avg */
02288                t++;
02289                if (sscanf(t, "%30d", &which) == 1 && which > 0 && which <= 3) {
02290                   double list[3];
02291                   getloadavg(list, 3);
02292                   ast_str_append(&prompt, 0, "%.2f", list[which - 1]);
02293                   cli_prompt_changes++;
02294                }
02295                break;
02296 #endif
02297             case 's': /* Asterisk system name (from asterisk.conf) */
02298                ast_str_append(&prompt, 0, "%s", ast_config_AST_SYSTEM_NAME);
02299                break;
02300             case 't': /* time */
02301                if (ast_localtime(&ts, &tm, NULL)) {
02302                   ast_strftime(tmp, sizeof(tmp), "%H:%M:%S", &tm);
02303                   ast_str_append(&prompt, 0, "%s", tmp);
02304                   cli_prompt_changes++;
02305                }
02306                break;
02307             case 'u': /* username */
02308                if ((pw = getpwuid(getuid()))) {
02309                   ast_str_append(&prompt, 0, "%s", pw->pw_name);
02310                }
02311                break;
02312             case '#': /* process console or remote? */
02313                ast_str_append(&prompt, 0, "%c", ast_opt_remote ? '>' : '#');
02314                break;
02315             case '%': /* literal % */
02316                ast_str_append(&prompt, 0, "%c", '%');
02317                break;
02318             case '\0': /* % is last character - prevent bug */
02319                t--;
02320                break;
02321             }
02322          } else {
02323             ast_str_append(&prompt, 0, "%c", *t);
02324          }
02325          t++;
02326       }
02327       if (color_used) {
02328          /* Force colors back to normal at end */
02329          ast_str_append(&prompt, 0, "%s", term_color_code(term_code, 0, 0, sizeof(term_code)));
02330       }
02331    } else if (remotehostname) {
02332       ast_str_set(&prompt, 0, ASTERISK_PROMPT2, remotehostname);
02333    } else {
02334       ast_str_set(&prompt, 0, "%s", ASTERISK_PROMPT);
02335    }
02336 
02337    return ast_str_buffer(prompt);   
02338 }

static void console_verboser ( const char *  s  )  [static]

Definition at line 1742 of file asterisk.c.

References ast_opt_console, AST_PTHREADT_NULL, consolethread, fix_header(), VERBOSE_PREFIX_1, VERBOSE_PREFIX_2, VERBOSE_PREFIX_3, and VERBOSE_PREFIX_4.

Referenced by main().

01743 {
01744    char tmp[80];
01745    const char *c = NULL;
01746 
01747    if ((c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_4)) ||
01748        (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_3)) ||
01749        (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_2)) ||
01750        (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_1))) {
01751       fputs(tmp, stdout);
01752       fputs(c, stdout);
01753    } else {
01754       if (*s == 127) {
01755          s++;
01756       }
01757       fputs(s, stdout);
01758    }
01759 
01760    fflush(stdout);
01761    
01762    /* Wake up a poll()ing console */
01763    if (ast_opt_console && consolethread != AST_PTHREADT_NULL)
01764       pthread_kill(consolethread, SIGURG);
01765 }

static void consolehandler ( char *  s  )  [static]

Definition at line 1777 of file asterisk.c.

References ast_all_zeros(), ast_cli_command, ast_el_add_history(), ast_safe_system(), and term_end().

Referenced by main().

01778 {
01779    printf("%s", term_end());
01780    fflush(stdout);
01781 
01782    /* Called when readline data is available */
01783    if (!ast_all_zeros(s))
01784       ast_el_add_history(s);
01785    /* The real handler for bang */
01786    if (s[0] == '!') {
01787       if (s[1])
01788          ast_safe_system(s+1);
01789       else
01790          ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
01791    } else 
01792       ast_cli_command(STDOUT_FILENO, s);
01793 }

static void env_init ( void   )  [static]

Definition at line 3147 of file asterisk.c.

References ast_build_date, ast_build_hostname, ast_build_kernel, ast_build_machine, ast_build_os, ast_build_user, ast_config_AST_SYSTEM_NAME, ast_get_version(), and setenv().

Referenced by main().

03148 {
03149    setenv("AST_SYSTEMNAME", ast_config_AST_SYSTEM_NAME, 1);
03150    setenv("AST_BUILD_HOST", ast_build_hostname, 1);
03151    setenv("AST_BUILD_DATE", ast_build_date, 1);
03152    setenv("AST_BUILD_KERNEL", ast_build_kernel, 1);
03153    setenv("AST_BUILD_MACHINE", ast_build_machine, 1);
03154    setenv("AST_BUILD_OS", ast_build_os, 1);
03155    setenv("AST_BUILD_USER", ast_build_user, 1);
03156    setenv("AST_VERSION", ast_get_version(), 1);
03157 }

static int fdprint ( int  fd,
const char *  s 
) [static]

Definition at line 974 of file asterisk.c.

Referenced by ast_network_puts(), ast_network_puts_mutable(), listener(), and netconsole().

00975 {
00976    return write(fd, s, strlen(s));
00977 }

static int fdsend ( int  fd,
const char *  s 
) [static]

Definition at line 968 of file asterisk.c.

Referenced by ast_el_read_char(), ast_remotecontrol(), and cli_complete().

00969 {
00970    return write(fd, s, strlen(s) + 1);
00971 }

static const char* fix_header ( char *  outbuf,
int  maxout,
const char *  s,
char *  cmp 
) [static]

Definition at line 1725 of file asterisk.c.

References COLOR_GRAY, and term_color().

Referenced by console_verboser().

01726 {
01727    const char *c;
01728 
01729    /* Check for verboser preamble */
01730    if (*s == 127) {
01731       s++;
01732    }
01733 
01734    if (!strncmp(s, cmp, strlen(cmp))) {
01735       c = s + strlen(cmp);
01736       term_color(outbuf, cmp, COLOR_GRAY, 0, maxout);
01737       return c;
01738    }
01739    return NULL;
01740 }

static char* handle_abort_shutdown ( struct ast_cli_entry *  e,
int  cmd,
struct ast_cli_args *  a 
) [static]

Definition at line 1969 of file asterisk.c.

References ast_cli_args::argc, ast_cli_entry::args, ast_cancel_shutdown(), CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, ast_cli_entry::command, shuttingdown, and ast_cli_entry::usage.

01970 {
01971    switch (cmd) {
01972    case CLI_INIT:
01973       e->command = "core abort shutdown";
01974       e->usage = 
01975          "Usage: core abort shutdown\n"
01976          "       Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
01977          "       call operations.\n";
01978       return NULL;
01979    case CLI_GENERATE:
01980       return NULL;
01981    }
01982 
01983    if (a->argc != e->args)
01984       return CLI_SHOWUSAGE;
01985    ast_cancel_shutdown();
01986    shuttingdown = 0;
01987    return CLI_SUCCESS;
01988 }

static char* handle_bang ( struct ast_cli_entry *  e,
int  cmd,
struct ast_cli_args *  a 
) [static]

Definition at line 1990 of file asterisk.c.

References CLI_GENERATE, CLI_INIT, CLI_SUCCESS, ast_cli_entry::command, and ast_cli_entry::usage.

01991 {
01992    switch (cmd) {
01993    case CLI_INIT:
01994       e->command = "!";
01995       e->usage = 
01996          "Usage: !<command>\n"
01997          "       Executes a given shell command\n";
01998       return NULL;
01999    case CLI_GENERATE:
02000       return NULL;
02001    }
02002 
02003    return CLI_SUCCESS;
02004 }

static char* handle_clear_profile ( struct ast_cli_entry *  e,
int  cmd,
struct ast_cli_args *  a 
) [static]

Definition at line 820 of file asterisk.c.

References CLI_GENERATE, CLI_INIT, CLI_SUCCESS, ast_cli_entry::command, DEFINE_PROFILE_MIN_MAX_VALUES, profile_data::e, profile_entry::events, profile_entry::name, prof_data, ast_cli_entry::usage, and profile_entry::value.

00821 {
00822    int i, min, max;
00823    const char *search = NULL;
00824    switch (cmd) {
00825    case CLI_INIT:
00826       e->command = "core clear profile";
00827       e->usage = "Usage: core clear profile\n"
00828             "       clear profile information";
00829       return NULL;
00830    case CLI_GENERATE:
00831       return NULL;
00832    }
00833 
00834    if (prof_data == NULL)
00835       return 0;
00836 
00837    DEFINE_PROFILE_MIN_MAX_VALUES;
00838    for (i= min; i < max; i++) {
00839       if (!search || strstr(prof_data->e[i].name, search)) {
00840          prof_data->e[i].value = 0;
00841          prof_data->e[i].events = 0;
00842       }
00843    }
00844    return CLI_SUCCESS;
00845 }

static char* handle_restart_gracefully ( struct ast_cli_entry *  e,
int  cmd,
struct ast_cli_args *  a 
) [static]

Definition at line 1929 of file asterisk.c.

References ast_cli_args::argc, ast_cli_entry::args, CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, ast_cli_entry::command, quit_handler(), and ast_cli_entry::usage.

01930 {
01931    switch (cmd) {
01932    case CLI_INIT:
01933       e->command = "core restart gracefully";
01934       e->usage = 
01935          "Usage: core restart gracefully\n"
01936          "       Causes Asterisk to stop accepting new calls and exec() itself performing a cold\n"
01937          "       restart when all active calls have ended.\n";
01938       return NULL;
01939    case CLI_GENERATE:
01940       return NULL;
01941    }
01942 
01943    if (a->argc != e->args)
01944       return CLI_SHOWUSAGE;
01945    quit_handler(0, 1 /* nicely */, 1 /* safely */, 1 /* restart */);
01946    return CLI_SUCCESS;
01947 }

static char* handle_restart_now ( struct ast_cli_entry *  e,
int  cmd,
struct ast_cli_args *  a 
) [static]

Definition at line 1909 of file asterisk.c.

References ast_cli_args::argc, ast_cli_entry::args, CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, ast_cli_entry::command, quit_handler(), and ast_cli_entry::usage.

01910 {
01911    switch (cmd) {
01912    case CLI_INIT:
01913       e->command = "core restart now";
01914       e->usage = 
01915          "Usage: core restart now\n"
01916          "       Causes Asterisk to hangup all calls and exec() itself performing a cold\n"
01917          "       restart.\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, 0 /* not nicely */, 1 /* safely */, 1 /* restart */);
01926    return CLI_SUCCESS;
01927 }

static char* handle_restart_when_convenient ( struct ast_cli_entry *  e,
int  cmd,
struct ast_cli_args *  a 
) [static]

Definition at line 1949 of file asterisk.c.

References ast_cli_args::argc, ast_cli_entry::args, ast_cli(), CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, ast_cli_entry::command, ast_cli_args::fd, quit_handler(), and ast_cli_entry::usage.

01950 {
01951    switch (cmd) {
01952    case CLI_INIT:
01953       e->command = "core restart when convenient";
01954       e->usage = 
01955          "Usage: core restart when convenient\n"
01956          "       Causes Asterisk to perform a cold restart when all active calls have ended.\n";
01957       return NULL;
01958    case CLI_GENERATE:
01959       return NULL;
01960    }
01961 
01962    if (a->argc != e->args)
01963       return CLI_SHOWUSAGE;
01964    ast_cli(a->fd, "Waiting for inactivity to perform restart\n");
01965    quit_handler(0, 2 /* really nicely */, 1 /* safely */, 1 /* restart */);
01966    return CLI_SUCCESS;
01967 }

static char* handle_show_profile ( struct ast_cli_entry *  e,
int  cmd,
struct ast_cli_args *  a 
) [static]

Definition at line 785 of file asterisk.c.

References ast_cli(), CLI_GENERATE, CLI_INIT, CLI_SUCCESS, ast_cli_entry::command, DEFINE_PROFILE_MIN_MAX_VALUES, profile_data::e, profile_data::entries, profile_entry::events, ast_cli_args::fd, profile_data::max_size, profile_entry::name, prof_data, profile_entry::scale, ast_cli_entry::usage, and profile_entry::value.

00786 {
00787    int i, min, max;
00788    const char *search = NULL;
00789    switch (cmd) {
00790    case CLI_INIT:
00791       e->command = "core show profile";
00792       e->usage = "Usage: core show profile\n"
00793             "       show profile information";
00794       return NULL;
00795    case CLI_GENERATE:
00796       return NULL;
00797    }
00798 
00799    if (prof_data == NULL)
00800       return 0;
00801 
00802    DEFINE_PROFILE_MIN_MAX_VALUES;
00803    ast_cli(a->fd, "profile values (%d, allocated %d)\n-------------------\n",
00804       prof_data->entries, prof_data->max_size);
00805    ast_cli(a->fd, "%6s   %8s  %10s %12s %12s  %s\n", "ID", "Scale", "Events",
00806          "Value", "Average", "Name");
00807    for (i = min; i < max; i++) {
00808       struct profile_entry *entry = &prof_data->e[i];
00809       if (!search || strstr(entry->name, search))
00810           ast_cli(a->fd, "%6d: [%8ld] %10ld %12lld %12lld  %s\n",
00811          i,
00812          (long)entry->scale,
00813          (long)entry->events, (long long)entry->value,
00814          (long long)(entry->events ? entry->value / entry->events : entry->value),
00815          entry->name);
00816    }
00817    return CLI_SUCCESS;
00818 }

static char* handle_show_settings ( struct ast_cli_entry *  e,
int  cmd,
struct ast_cli_args *  a 
) [static]

Give an overview of core settings.

Todo:
we could check musiconhold, voicemail, smdi, adsi, queues

Definition at line 419 of file asterisk.c.

References ast_active_channels(), ast_build_date, ast_build_kernel, ast_build_machine, ast_build_os, ast_build_user, ast_cli(), ast_config_AST_AGI_DIR, ast_config_AST_CONFIG_DIR, ast_config_AST_CONFIG_FILE, ast_config_AST_DATA_DIR, ast_config_AST_DB, ast_config_AST_KEY_DIR, ast_config_AST_LOG_DIR, ast_config_AST_MODULE_DIR, ast_config_AST_PID, ast_config_AST_RUN_DIR, ast_config_AST_RUN_GROUP, ast_config_AST_RUN_USER, ast_config_AST_SPOOL_DIR, ast_config_AST_SYSTEM_NAME, ast_config_AST_VAR_DIR, ast_eid_default, ast_eid_to_str(), ast_get_version(), ast_language_is_prefix, ast_lastreloadtime, ast_localtime(), AST_OPT_FLAG_EXEC_INCLUDES, AST_OPT_FLAG_GENERIC_PLC, AST_OPT_FLAG_INTERNAL_TIMING, AST_OPT_FLAG_TRANSCODE_VIA_SLIN, AST_OPT_FLAG_TRANSMIT_SILENCE, ast_realtime_enabled(), ast_startuptime, ast_strftime(), ast_test_flag, check_cdr_enabled(), check_manager_enabled(), check_webmanager_enabled(), CLI_GENERATE, CLI_INIT, CLI_SUCCESS, ast_cli_entry::command, defaultlanguage, ast_cli_args::fd, S_OR, and ast_cli_entry::usage.

00420 {
00421    char buf[BUFSIZ];
00422    struct ast_tm tm;
00423    char eid_str[128];
00424 
00425    switch (cmd) {
00426    case CLI_INIT:
00427       e->command = "core show settings";
00428       e->usage = "Usage: core show settings\n"
00429             "       Show core misc settings";
00430       return NULL;
00431    case CLI_GENERATE:
00432       return NULL;
00433    }
00434 
00435    ast_eid_to_str(eid_str, sizeof(eid_str), &ast_eid_default);
00436 
00437    ast_cli(a->fd, "\nPBX Core settings\n");
00438    ast_cli(a->fd, "-----------------\n");
00439    ast_cli(a->fd, "  Version:                     %s\n", ast_get_version());
00440    ast_cli(a->fd, "  Build Options:               %s\n", S_OR(AST_BUILDOPTS, "(none)"));
00441    if (option_maxcalls)
00442       ast_cli(a->fd, "  Maximum calls:               %d (Current %d)\n", option_maxcalls, ast_active_channels());
00443    else
00444       ast_cli(a->fd, "  Maximum calls:               Not set\n");
00445    if (option_maxfiles)
00446       ast_cli(a->fd, "  Maximum open file handles:   %d\n", option_maxfiles); 
00447    else
00448       ast_cli(a->fd, "  Maximum open file handles:   Not set\n");
00449    ast_cli(a->fd, "  Verbosity:                   %d\n", option_verbose);
00450    ast_cli(a->fd, "  Debug level:                 %d\n", option_debug);
00451    ast_cli(a->fd, "  Maximum load average:        %lf\n", option_maxload);
00452 #if defined(HAVE_SYSINFO)
00453    ast_cli(a->fd, "  Minimum free memory:         %ld MB\n", option_minmemfree);
00454 #endif
00455    if (ast_localtime(&ast_startuptime, &tm, NULL)) {
00456       ast_strftime(buf, sizeof(buf), "%H:%M:%S", &tm);
00457       ast_cli(a->fd, "  Startup time:                %s\n", buf);
00458    }
00459    if (ast_localtime(&ast_lastreloadtime, &tm, NULL)) {
00460       ast_strftime(buf, sizeof(buf), "%H:%M:%S", &tm);
00461       ast_cli(a->fd, "  Last reload time:            %s\n", buf);
00462    }
00463    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);
00464    ast_cli(a->fd, "  System name:                 %s\n", ast_config_AST_SYSTEM_NAME);
00465    ast_cli(a->fd, "  Entity ID:                   %s\n", eid_str);
00466    ast_cli(a->fd, "  Default language:            %s\n", defaultlanguage);
00467    ast_cli(a->fd, "  Language prefix:             %s\n", ast_language_is_prefix ? "Enabled" : "Disabled");
00468    ast_cli(a->fd, "  User name and group:         %s/%s\n", ast_config_AST_RUN_USER, ast_config_AST_RUN_GROUP);
00469    ast_cli(a->fd, "  Executable includes:         %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_EXEC_INCLUDES) ? "Enabled" : "Disabled");
00470    ast_cli(a->fd, "  Transcode via SLIN:          %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_TRANSCODE_VIA_SLIN) ? "Enabled" : "Disabled");
00471    ast_cli(a->fd, "  Internal timing:             %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_INTERNAL_TIMING) ? "Enabled" : "Disabled");
00472    ast_cli(a->fd, "  Transmit silence during rec: %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_TRANSMIT_SILENCE) ? "Enabled" : "Disabled");
00473    ast_cli(a->fd, "  Generic PLC:                 %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_GENERIC_PLC) ? "Enabled" : "Disabled");
00474 
00475    ast_cli(a->fd, "\n* Subsystems\n");
00476    ast_cli(a->fd, "  -------------\n");
00477    ast_cli(a->fd, "  Manager (AMI):               %s\n", check_manager_enabled() ? "Enabled" : "Disabled");
00478    ast_cli(a->fd, "  Web Manager (AMI/HTTP):      %s\n", check_webmanager_enabled() ? "Enabled" : "Disabled");
00479    ast_cli(a->fd, "  Call data records:           %s\n", check_cdr_enabled() ? "Enabled" : "Disabled");
00480    ast_cli(a->fd, "  Realtime Architecture (ARA): %s\n", ast_realtime_enabled() ? "Enabled" : "Disabled");
00481 
00482    /*! \todo we could check musiconhold, voicemail, smdi, adsi, queues  */
00483 
00484    ast_cli(a->fd, "\n* Directories\n");
00485    ast_cli(a->fd, "  -------------\n");
00486    ast_cli(a->fd, "  Configuration file:          %s\n", ast_config_AST_CONFIG_FILE);
00487    ast_cli(a->fd, "  Configuration directory:     %s\n", ast_config_AST_CONFIG_DIR);
00488    ast_cli(a->fd, "  Module directory:            %s\n", ast_config_AST_MODULE_DIR);
00489    ast_cli(a->fd, "  Spool directory:             %s\n", ast_config_AST_SPOOL_DIR);
00490    ast_cli(a->fd, "  Log directory:               %s\n", ast_config_AST_LOG_DIR);
00491    ast_cli(a->fd, "  Run/Sockets directory:       %s\n", ast_config_AST_RUN_DIR);
00492    ast_cli(a->fd, "  PID file:                    %s\n", ast_config_AST_PID);
00493    ast_cli(a->fd, "  VarLib directory:            %s\n", ast_config_AST_VAR_DIR);
00494    ast_cli(a->fd, "  Data directory:              %s\n", ast_config_AST_DATA_DIR);
00495    ast_cli(a->fd, "  ASTDB:                       %s\n", ast_config_AST_DB);
00496    ast_cli(a->fd, "  IAX2 Keys directory:         %s\n", ast_config_AST_KEY_DIR);
00497    ast_cli(a->fd, "  AGI Scripts directory:       %s\n", ast_config_AST_AGI_DIR);
00498    ast_cli(a->fd, "\n\n");
00499    return CLI_SUCCESS;
00500 }

static char* handle_show_sysinfo ( struct ast_cli_entry *  e,
int  cmd,
struct ast_cli_args *  a 
) [static]

Give an overview of system statistics.

Definition at line 574 of file asterisk.c.

References ast_cli(), CLI_GENERATE, CLI_INIT, CLI_SUCCESS, ast_cli_entry::command, ast_cli_args::fd, len(), and ast_cli_entry::usage.

00575 {
00576    uint64_t physmem, freeram;
00577    uint64_t freeswap = 0;
00578    int totalswap = 0;
00579    int nprocs = 0;
00580    long uptime = 0;
00581 #if defined(HAVE_SYSINFO)
00582    struct sysinfo sys_info;
00583    sysinfo(&sys_info);
00584    uptime = sys_info.uptime / 3600;
00585    physmem = sys_info.totalram * sys_info.mem_unit;
00586    freeram = (sys_info.freeram * sys_info.mem_unit) / 1024;
00587    totalswap = (sys_info.totalswap * sys_info.mem_unit) / 1024;
00588    freeswap = (sys_info.freeswap * sys_info.mem_unit) / 1024;
00589    nprocs = sys_info.procs;
00590 #elif defined(HAVE_SYSCTL)
00591    static int pageshift;
00592    struct vmtotal vmtotal;
00593    struct timeval boottime;
00594    time_t   now;
00595    int mib[2], pagesize, usedswap = 0;
00596    size_t len;
00597    /* calculate the uptime by looking at boottime */
00598    time(&now);
00599    mib[0] = CTL_KERN;
00600    mib[1] = KERN_BOOTTIME;
00601    len = sizeof(boottime);
00602    if (sysctl(mib, 2, &boottime, &len, NULL, 0) != -1) {
00603       uptime = now - boottime.tv_sec;
00604    }
00605    uptime = uptime/3600;
00606    /* grab total physical memory  */
00607    mib[0] = CTL_HW;
00608 #if defined(HW_PHYSMEM64)
00609    mib[1] = HW_PHYSMEM64;
00610 #else
00611    mib[1] = HW_PHYSMEM;
00612 #endif
00613    len = sizeof(physmem);
00614    sysctl(mib, 2, &physmem, &len, NULL, 0);
00615 
00616    pagesize = getpagesize();
00617    pageshift = 0;
00618    while (pagesize > 1) {
00619       pageshift++;
00620       pagesize >>= 1;
00621    }
00622 
00623    /* we only need the amount of log(2)1024 for our conversion */
00624    pageshift -= 10;
00625 
00626    /* grab vm totals */
00627    mib[0] = CTL_VM;
00628    mib[1] = VM_METER;
00629    len = sizeof(vmtotal);
00630    sysctl(mib, 2, &vmtotal, &len, NULL, 0);
00631    freeram = (vmtotal.t_free << pageshift);
00632    /* generate swap usage and totals */
00633    swapmode(&usedswap, &totalswap);
00634    freeswap = (totalswap - usedswap);
00635    /* grab number of processes */
00636 #if defined(__OpenBSD__)
00637    mib[0] = CTL_KERN;
00638    mib[1] = KERN_NPROCS;
00639    len = sizeof(nprocs);
00640    sysctl(mib, 2, &nprocs, &len, NULL, 0);
00641 #endif
00642 #endif
00643 
00644    switch (cmd) {
00645    case CLI_INIT:
00646       e->command = "core show sysinfo";
00647       e->usage =
00648          "Usage: core show sysinfo\n"
00649          "       List current system information.\n";
00650       return NULL;
00651    case CLI_GENERATE:
00652       return NULL;
00653    }
00654 
00655    ast_cli(a->fd, "\nSystem Statistics\n");
00656    ast_cli(a->fd, "-----------------\n");
00657    ast_cli(a->fd, "  System Uptime:             %lu hours\n", uptime);
00658    ast_cli(a->fd, "  Total RAM:                 %" PRIu64 " KiB\n", physmem / 1024);
00659    ast_cli(a->fd, "  Free RAM:                  %" PRIu64 " KiB\n", freeram);
00660 #if defined(HAVE_SYSINFO)
00661    ast_cli(a->fd, "  Buffer RAM:                %" PRIu64 " KiB\n", ((uint64_t) sys_info.bufferram * sys_info.mem_unit) / 1024);
00662 #endif
00663 #if defined (HAVE_SYSCTL) && defined(HAVE_SWAPCTL)
00664    ast_cli(a->fd, "  Total Swap Space:          %u KiB\n", totalswap);
00665    ast_cli(a->fd, "  Free Swap Space:           %" PRIu64 " KiB\n\n", freeswap);
00666 #endif
00667    ast_cli(a->fd, "  Number of Processes:       %d \n\n", nprocs);
00668    return CLI_SUCCESS;
00669 }

static char* handle_show_threads ( struct ast_cli_entry *  e,
int  cmd,
struct ast_cli_args *  a 
) [static]

Definition at line 502 of file asterisk.c.

References ast_cli(), AST_RWLIST_RDLOCK, AST_RWLIST_TRAVERSE, AST_RWLIST_UNLOCK, CLI_GENERATE, CLI_INIT, CLI_SUCCESS, ast_cli_entry::command, ast_cli_args::fd, thread_list_t::id, ast_atexit::list, thread_list_t::name, and ast_cli_entry::usage.

00503 {
00504    int count = 0;
00505    struct thread_list_t *cur;
00506    switch (cmd) {
00507    case CLI_INIT:
00508       e->command = "core show threads";
00509       e->usage = 
00510          "Usage: core show threads\n"
00511          "       List threads currently active in the system.\n";
00512       return NULL;
00513    case CLI_GENERATE:
00514       return NULL;
00515    }
00516 
00517    AST_RWLIST_RDLOCK(&thread_list);
00518    AST_RWLIST_TRAVERSE(&thread_list, cur, list) {
00519       ast_cli(a->fd, "%p %s\n", (void *)cur->id, cur->name);
00520       count++;
00521    }
00522         AST_RWLIST_UNLOCK(&thread_list);
00523    ast_cli(a->fd, "%d threads listed.\n", count);
00524    return CLI_SUCCESS;
00525 }

static char* handle_show_version_files ( struct ast_cli_entry *  e,
int  cmd,
struct ast_cli_args *  a 
) [static]

CLI command to list module versions.

Definition at line 849 of file asterisk.c.

References ast_cli_args::argc, ast_cli_args::argv, ast_cli(), AST_RWLIST_RDLOCK, AST_RWLIST_TRAVERSE, AST_RWLIST_UNLOCK, ast_strdup, CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, ast_cli_entry::command, ast_cli_args::fd, file_version::file, FORMAT, ast_atexit::list, ast_cli_args::n, ast_cli_args::pos, ast_cli_entry::usage, file_version::version, and ast_cli_args::word.

00850 {
00851 #define FORMAT "%-25.25s %-40.40s\n"
00852    struct file_version *iterator;
00853    regex_t regexbuf;
00854    int havepattern = 0;
00855    int havename = 0;
00856    int count_files = 0;
00857    char *ret = NULL;
00858    int matchlen, which = 0;
00859    struct file_version *find;
00860 
00861    switch (cmd) {
00862    case CLI_INIT:
00863       e->command = "core show file version [like]";
00864       e->usage = 
00865          "Usage: core show file version [like <pattern>]\n"
00866          "       Lists the revision numbers of the files used to build this copy of Asterisk.\n"
00867          "       Optional regular expression pattern is used to filter the file list.\n";
00868       return NULL;
00869    case CLI_GENERATE:
00870       matchlen = strlen(a->word);
00871       if (a->pos != 3)
00872          return NULL;
00873       AST_RWLIST_RDLOCK(&file_versions);
00874       AST_RWLIST_TRAVERSE(&file_versions, find, list) {
00875          if (!strncasecmp(a->word, find->file, matchlen) && ++which > a->n) {
00876             ret = ast_strdup(find->file);
00877             break;
00878          }
00879       }
00880       AST_RWLIST_UNLOCK(&file_versions);
00881       return ret;
00882    }
00883 
00884 
00885    switch (a->argc) {
00886    case 6:
00887       if (!strcasecmp(a->argv[4], "like")) {
00888          if (regcomp(&regexbuf, a->argv[5], REG_EXTENDED | REG_NOSUB))
00889             return CLI_SHOWUSAGE;
00890          havepattern = 1;
00891       } else
00892          return CLI_SHOWUSAGE;
00893       break;
00894    case 5:
00895       havename = 1;
00896       break;
00897    case 4:
00898       break;
00899    default:
00900       return CLI_SHOWUSAGE;
00901    }
00902 
00903    ast_cli(a->fd, FORMAT, "File", "Revision");
00904    ast_cli(a->fd, FORMAT, "----", "--------");
00905    AST_RWLIST_RDLOCK(&file_versions);
00906    AST_RWLIST_TRAVERSE(&file_versions, iterator, list) {
00907       if (havename && strcasecmp(iterator->file, a->argv[4]))
00908          continue;
00909 
00910       if (havepattern && regexec(&regexbuf, iterator->file, 0, NULL, 0))
00911          continue;
00912 
00913       ast_cli(a->fd, FORMAT, iterator->file, iterator->version);
00914       count_files++;
00915       if (havename)
00916          break;
00917    }
00918    AST_RWLIST_UNLOCK(&file_versions);
00919    if (!havename) {
00920       ast_cli(a->fd, "%d files listed.\n", count_files);
00921    }
00922 
00923    if (havepattern)
00924       regfree(&regexbuf);
00925 
00926    return CLI_SUCCESS;
00927 #undef FORMAT
00928 }

static char* handle_stop_gracefully ( struct ast_cli_entry *  e,
int  cmd,
struct ast_cli_args *  a 
) [static]

Definition at line 1869 of file asterisk.c.

References ast_cli_args::argc, ast_cli_entry::args, CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, ast_cli_entry::command, quit_handler(), and ast_cli_entry::usage.

01870 {
01871    switch (cmd) {
01872    case CLI_INIT:
01873       e->command = "core stop gracefully";
01874       e->usage = 
01875          "Usage: core stop gracefully\n"
01876          "       Causes Asterisk to not accept new calls, and exit when all\n"
01877          "       active calls have terminated normally.\n";
01878       return NULL;
01879    case CLI_GENERATE:
01880       return NULL;
01881    }
01882 
01883    if (a->argc != e->args)
01884       return CLI_SHOWUSAGE;
01885    quit_handler(0, 1 /* nicely */, 1 /* safely */, 0 /* no restart */);
01886    return CLI_SUCCESS;
01887 }

static char* handle_stop_now ( struct ast_cli_entry *  e,
int  cmd,
struct ast_cli_args *  a 
) [static]

Definition at line 1850 of file asterisk.c.

References ast_cli_args::argc, ast_cli_entry::args, CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, ast_cli_entry::command, quit_handler(), and ast_cli_entry::usage.

01851 {
01852    switch (cmd) {
01853    case CLI_INIT:
01854       e->command = "core stop now";
01855       e->usage = 
01856          "Usage: core stop now\n"
01857          "       Shuts down a running Asterisk immediately, hanging up all active calls .\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, 0 /* Not nice */, 1 /* safely */, 0 /* not restart */);
01866    return CLI_SUCCESS;
01867 }

static char* handle_stop_when_convenient ( struct ast_cli_entry *  e,
int  cmd,
struct ast_cli_args *  a 
) [static]

Definition at line 1889 of file asterisk.c.

References ast_cli_args::argc, ast_cli_entry::args, ast_cli(), CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, ast_cli_entry::command, ast_cli_args::fd, quit_handler(), and ast_cli_entry::usage.

01890 {
01891    switch (cmd) {
01892    case CLI_INIT:
01893       e->command = "core stop when convenient";
01894       e->usage = 
01895          "Usage: core stop when convenient\n"
01896          "       Causes Asterisk to perform a shutdown when all active calls have ended.\n";
01897       return NULL;
01898    case CLI_GENERATE:
01899       return NULL;
01900    }
01901 
01902    if (a->argc != e->args)
01903       return CLI_SHOWUSAGE;
01904    ast_cli(a->fd, "Waiting for inactivity to perform halt\n");
01905    quit_handler(0, 2 /* really nicely */, 1 /* safely */, 0 /* don't restart */);
01906    return CLI_SUCCESS;
01907 }

static char* handle_version ( struct ast_cli_entry *  e,
int  cmd,
struct ast_cli_args *  a 
) [static]

Definition at line 1819 of file asterisk.c.

References ast_cli_args::argc, ast_build_date, ast_build_hostname, ast_build_machine, ast_build_os, ast_build_user, ast_cli(), ast_get_version(), CLI_GENERATE, CLI_INIT, CLI_SHOWUSAGE, CLI_SUCCESS, ast_cli_entry::command, ast_cli_args::fd, and ast_cli_entry::usage.

01820 {
01821    switch (cmd) {
01822    case CLI_INIT:
01823       e->command = "core show version";
01824       e->usage = 
01825          "Usage: core show version\n"
01826          "       Shows Asterisk version information.\n";
01827       return NULL;
01828    case CLI_GENERATE:
01829       return NULL;
01830    }
01831 
01832    if (a->argc != 3)
01833       return CLI_SHOWUSAGE;
01834    ast_cli(a->fd, "Asterisk %s built by %s @ %s on a %s running %s on %s\n",
01835       ast_get_version(), ast_build_user, ast_build_hostname,
01836       ast_build_machine, ast_build_os, ast_build_date);
01837    return CLI_SUCCESS;
01838 }

static void* listener ( void *  unused  )  [static]

Definition at line 1284 of file asterisk.c.

References AF_LOCAL, ast_log(), AST_MAX_CONNECTS, ast_opt_hide_connect, ast_poll, ast_pthread_create_detached_background, ast_verb, consoles, errno, console::fd, fdprint(), console::gid, len(), LOG_ERROR, LOG_WARNING, console::mute, netconsole(), and console::uid.

Referenced by ast_makesocket().

01285 {
01286    struct sockaddr_un sunaddr;
01287    int s;
01288    socklen_t len;
01289    int x;
01290    int flags;
01291    struct pollfd fds[1];
01292    for (;;) {
01293       if (ast_socket < 0)
01294          return NULL;
01295       fds[0].fd = ast_socket;
01296       fds[0].events = POLLIN;
01297       s = ast_poll(fds, 1, -1);
01298       pthread_testcancel();
01299       if (s < 0) {
01300          if (errno != EINTR)
01301             ast_log(LOG_WARNING, "poll returned error: %s\n", strerror(errno));
01302          continue;
01303       }
01304       len = sizeof(sunaddr);
01305       s = accept(ast_socket, (struct sockaddr *)&sunaddr, &len);
01306       if (s < 0) {
01307          if (errno != EINTR)
01308             ast_log(LOG_WARNING, "Accept returned %d: %s\n", s, strerror(errno));
01309       } else {
01310 #if !defined(SO_PASSCRED)
01311          {
01312 #else
01313          int sckopt = 1;
01314          /* turn on socket credentials passing. */
01315          if (setsockopt(s, SOL_SOCKET, SO_PASSCRED, &sckopt, sizeof(sckopt)) < 0) {
01316             ast_log(LOG_WARNING, "Unable to turn on socket credentials passing\n");
01317          } else {
01318 #endif
01319             for (x = 0; x < AST_MAX_CONNECTS; x++) {
01320                if (consoles[x].fd >= 0) {
01321                   continue;
01322                }
01323                if (socketpair(AF_LOCAL, SOCK_STREAM, 0, consoles[x].p)) {
01324                   ast_log(LOG_ERROR, "Unable to create pipe: %s\n", strerror(errno));
01325                   consoles[x].fd = -1;
01326                   fdprint(s, "Server failed to create pipe\n");
01327                   close(s);
01328                   break;
01329                }
01330                flags = fcntl(consoles[x].p[1], F_GETFL);
01331                fcntl(consoles[x].p[1], F_SETFL, flags | O_NONBLOCK);
01332                consoles[x].fd = s;
01333                consoles[x].mute = 1; /* Default is muted, we will un-mute if necessary */
01334                /* Default uid and gid to -2, so then in cli.c/cli_has_permissions() we will be able
01335                   to know if the user didn't send the credentials. */
01336                consoles[x].uid = -2;
01337                consoles[x].gid = -2;
01338                if (ast_pthread_create_detached_background(&consoles[x].t, NULL, netconsole, &consoles[x])) {
01339                   ast_log(LOG_ERROR, "Unable to spawn thread to handle connection: %s\n", strerror(errno));
01340                   close(consoles[x].p[0]);
01341                   close(consoles[x].p[1]);
01342                   consoles[x].fd = -1;
01343                   fdprint(s, "Server failed to spawn thread\n");
01344                   close(s);
01345                }
01346                break;
01347             }
01348             if (x >= AST_MAX_CONNECTS) {
01349                fdprint(s, "No more connections allowed\n");
01350                ast_log(LOG_WARNING, "No more connections allowed\n");
01351                close(s);
01352             } else if ((consoles[x].fd > -1) && (!ast_opt_hide_connect)) {
01353                ast_verb(3, "Remote UNIX connection\n");
01354             }
01355          }
01356       }
01357    }
01358    return NULL;
01359 }

int main ( int  argc,
char *  argv[] 
)

< Result from the module load subsystem

Note:
Please keep the ordering here to alphabetical, capital letters first. This will make it easier in the future to select unused option flags for new features.

Definition at line 3159 of file asterisk.c.

References __ast_mm_init(), __quit_handler(), _argv, ARRAY_LEN, ast_alaw_init(), ast_aoc_cli_init(), ast_autoservice_init(), ast_builtins_init(), ast_cc_init(), ast_cdr_engine_init(), ast_cel_engine_init(), ast_channels_init(), ast_clear_flag, ast_cli_perms_init(), ast_cli_register_multiple(), ast_close_fds_above_n(), ast_config_AST_PID, ast_config_AST_RUN_DIR, ast_config_AST_RUN_GROUP, ast_config_AST_RUN_USER, ast_config_AST_SOCKET, ast_copy_string(), ast_data_init(), ast_device_state_engine_init(), ast_dsp_init(), ast_el_initialize(), ast_el_read_history(), ast_enum_init(), ast_event_init(), ast_fd_init(), ast_FD_SETSIZE, ast_features_init(), ast_file_init(), ast_http_init(), ast_image_init(), ast_indications_init(), ast_language_is_prefix, ast_lastreloadtime, ast_log(), ast_makesocket(), ast_opt_always_fork, ast_opt_console, ast_opt_dump_core, ast_opt_exec, AST_OPT_FLAG_ALWAYS_FORK, AST_OPT_FLAG_CACHE_RECORD_FILES, AST_OPT_FLAG_CONSOLE, AST_OPT_FLAG_DUMP_CORE, AST_OPT_FLAG_EXEC, AST_OPT_FLAG_EXEC_INCLUDES, AST_OPT_FLAG_FORCE_BLACK_BACKGROUND, AST_OPT_FLAG_FULLY_BOOTED, AST_OPT_FLAG_HIGH_PRIORITY, AST_OPT_FLAG_INIT_KEYS, AST_OPT_FLAG_INTERNAL_TIMING, AST_OPT_FLAG_LIGHT_BACKGROUND, AST_OPT_FLAG_MUTE, AST_OPT_FLAG_NO_COLOR, AST_OPT_FLAG_NO_FORK, AST_OPT_FLAG_OVERRIDE_CONFIG, AST_OPT_FLAG_QUIET, AST_OPT_FLAG_RECONNECT, AST_OPT_FLAG_REMOTE, AST_OPT_FLAG_TIMESTAMP, ast_opt_high_priority, ast_opt_no_fork, ast_opt_remote, ast_process_pending_reloads(), ast_pthread_create_detached, ast_readconfig(), ast_register_atexit(), ast_register_verbose(), ast_remotecontrol(), ast_select(), ast_set_flag, ast_set_priority(), ast_ssl_init(), ast_startuptime, ast_strdupa, ast_strlen_zero(), ast_stun_init(), ast_term_init(), ast_test_flag, ast_test_init(), ast_timing_init(), ast_tps_init(), ast_tryconnect(), ast_tvnow(), ast_udptl_init(), ast_ulaw_init(), ast_utils_init(), ast_verbose, ast_xmldoc_load_documentation(), astdb_init(), astobj2_init(), callerid_init(), canary_exit(), canary_filename, canary_pid, canary_thread(), cfg_paths, COLOR_BLACK, COLOR_BRWHITE, _cfg_paths::config_file, console_verboser(), consolehandler(), consolethread, dnsmgr_init(), dnsmgr_start_refresh(), el, el_hist, env_init(), errno, EVENT_FLAG_SYSTEM, f, FD_SET, FD_ZERO, hostname, ignore_sig_handler, init_framer(), init_logger(), init_manager(), load_modules(), load_pbx(), LOG_ERROR, LOG_WARNING, manager_event, MAXHOSTNAMELEN, mon_sig_flags, monitor_sig_flags(), quit_handler(), randompool, read_config_maps(), register_config_cli(), run_startup_commands(), set_icon(), set_title(), show_cli_help(), show_version(), sig_alert_pipe, _cfg_paths::socket_path, tdd_init(), term_color(), term_end(), term_quit(), threadstorage_init(), and WELCOME_MESSAGE.

03160 {
03161    int c;
03162    char filename[80] = "";
03163    char hostname[MAXHOSTNAMELEN] = "";
03164    char tmp[80];
03165    char * xarg = NULL;
03166    int x;
03167    FILE *f;
03168    sigset_t sigs;
03169    int num;
03170    int isroot = 1, rundir_exists = 0;
03171    char *buf;
03172    const char *runuser = NULL, *rungroup = NULL;
03173    char *remotesock = NULL;
03174    int moduleresult;         /*!< Result from the module load subsystem */
03175    struct rlimit l;
03176 
03177    /* Remember original args for restart */
03178    if (argc > ARRAY_LEN(_argv) - 1) {
03179       fprintf(stderr, "Truncating argument size to %d\n", (int)ARRAY_LEN(_argv) - 1);
03180       argc = ARRAY_LEN(_argv) - 1;
03181    }
03182    for (x = 0; x < argc; x++)
03183       _argv[x] = argv[x];
03184    _argv[x] = NULL;
03185 
03186    if (geteuid() != 0)
03187       isroot = 0;
03188 
03189    /* if the progname is rasterisk consider it a remote console */
03190    if (argv[0] && (strstr(argv[0], "rasterisk")) != NULL) {
03191       ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK | AST_OPT_FLAG_REMOTE);
03192    }
03193    if (gethostname(hostname, sizeof(hostname)-1))
03194       ast_copy_string(hostname, "<Unknown>", sizeof(hostname));
03195    ast_mainpid = getpid();
03196    ast_ulaw_init();
03197    ast_alaw_init();
03198    callerid_init();
03199    ast_builtins_init();
03200    ast_utils_init();
03201    tdd_init();
03202    ast_tps_init();
03203    ast_fd_init();
03204 
03205    if (getenv("HOME")) 
03206       snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
03207    /* Check for options */
03208    while ((c = getopt(argc, argv, "BC:cde:FfG:ghIiL:M:mnpqRrs:TtU:VvWXx:")) != -1) {
03209       /*!\note Please keep the ordering here to alphabetical, capital letters
03210        * first.  This will make it easier in the future to select unused
03211        * option flags for new features. */
03212       switch (c) {
03213       case 'B': /* Force black background */
03214          ast_set_flag(&ast_options, AST_OPT_FLAG_FORCE_BLACK_BACKGROUND);
03215          ast_clear_flag(&ast_options, AST_OPT_FLAG_LIGHT_BACKGROUND);
03216          break;
03217       case 'X':
03218          ast_set_flag(&ast_options, AST_OPT_FLAG_EXEC_INCLUDES);
03219          break;
03220       case 'C':
03221          ast_copy_string(cfg_paths.config_file, optarg, sizeof(cfg_paths.config_file));
03222          ast_set_flag(&ast_options, AST_OPT_FLAG_OVERRIDE_CONFIG);
03223          break;
03224       case 'c':
03225          ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK | AST_OPT_FLAG_CONSOLE);
03226          break;
03227       case 'd':
03228          option_debug++;
03229          ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK);
03230          break;
03231 #if defined(HAVE_SYSINFO)
03232       case 'e':
03233          if ((sscanf(&optarg[1], "%30ld", &option_minmemfree) != 1) || (option_minmemfree < 0)) {
03234             option_minmemfree = 0;
03235          }
03236          break;
03237 #endif
03238 #if HAVE_WORKING_FORK
03239       case 'F':
03240          ast_set_flag(&ast_options, AST_OPT_FLAG_ALWAYS_FORK);
03241          break;
03242       case 'f':
03243          ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK);
03244          break;
03245 #endif
03246       case 'G':
03247          rungroup = ast_strdupa(optarg);
03248          break;
03249       case 'g':
03250          ast_set_flag(&ast_options, AST_OPT_FLAG_DUMP_CORE);
03251          break;
03252       case 'h':
03253          show_cli_help();
03254          exit(0);
03255       case 'I':
03256          ast_set_flag(&ast_options, AST_OPT_FLAG_INTERNAL_TIMING);
03257          break;
03258       case 'i':
03259          ast_set_flag(&ast_options, AST_OPT_FLAG_INIT_KEYS);
03260          break;
03261       case 'L':
03262          if ((sscanf(optarg, "%30lf", &option_maxload) != 1) || (option_maxload < 0.0)) {
03263             option_maxload = 0.0;
03264          }
03265          break;
03266       case 'M':
03267          if ((sscanf(optarg, "%30d", &option_maxcalls) != 1) || (option_maxcalls < 0)) {
03268             option_maxcalls = 0;
03269          }
03270          break;
03271       case 'm':
03272          ast_set_flag(&ast_options, AST_OPT_FLAG_MUTE);
03273          break;
03274       case 'n':
03275          ast_set_flag(&ast_options, AST_OPT_FLAG_NO_COLOR);
03276          break;
03277       case 'p':
03278          ast_set_flag(&ast_options, AST_OPT_FLAG_HIGH_PRIORITY);
03279          break;
03280       case 'q':
03281          ast_set_flag(&ast_options, AST_OPT_FLAG_QUIET);
03282          break;
03283       case 'R':
03284          ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK | AST_OPT_FLAG_REMOTE | AST_OPT_FLAG_RECONNECT);
03285          break;
03286       case 'r':
03287          ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK | AST_OPT_FLAG_REMOTE);
03288          break;
03289       case 's':
03290          remotesock = ast_strdupa(optarg);
03291          break;
03292       case 'T':
03293          ast_set_flag(&ast_options, AST_OPT_FLAG_TIMESTAMP);
03294          break;
03295       case 't':
03296          ast_set_flag(&ast_options, AST_OPT_FLAG_CACHE_RECORD_FILES);
03297          break;
03298       case 'U':
03299          runuser = ast_strdupa(optarg);
03300          break;
03301       case 'V':
03302          show_version();
03303          exit(0);
03304       case 'v':
03305          option_verbose++;
03306          ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK);
03307          break;
03308       case 'W': /* White background */
03309          ast_set_flag(&ast_options, AST_OPT_FLAG_LIGHT_BACKGROUND);
03310          ast_clear_flag(&ast_options, AST_OPT_FLAG_FORCE_BLACK_BACKGROUND);
03311          break;
03312       case 'x':
03313          ast_set_flag(&ast_options, AST_OPT_FLAG_EXEC);
03314          xarg = ast_strdupa(optarg);
03315          break;
03316       case '?':
03317          exit(1);
03318       }
03319    }
03320 
03321    if (ast_opt_console || option_verbose || (ast_opt_remote && !ast_opt_exec)) {
03322       if (ast_register_verbose(console_verboser)) {
03323          ast_log(LOG_WARNING, "Unable to register console verboser?\n");
03324       }
03325       WELCOME_MESSAGE;
03326    }
03327 
03328    if (ast_opt_console && !option_verbose) 
03329       ast_verbose("[ Booting...\n");
03330 
03331    /* For remote connections, change the name of the remote connection.
03332     * We do this for the benefit of init scripts (which need to know if/when
03333     * the main asterisk process has died yet). */
03334    if (ast_opt_remote) {
03335       strcpy(argv[0], "rasterisk");
03336       for (x = 1; x < argc; x++) {
03337          argv[x] = argv[0] + 10;
03338       }
03339    }
03340 
03341    if (ast_opt_console && !option_verbose) {
03342       ast_verbose("[ Reading Master Configuration ]\n");
03343    }
03344 
03345    ast_readconfig();
03346    env_init();
03347 
03348    if (ast_opt_remote && remotesock != NULL)
03349       ast_copy_string((char *) cfg_paths.socket_path, remotesock, sizeof(cfg_paths.socket_path));
03350 
03351    if (!ast_language_is_prefix && !ast_opt_remote)
03352       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");
03353 
03354    if (ast_opt_always_fork && (ast_opt_remote || ast_opt_console)) {
03355       ast_log(LOG_WARNING, "'alwaysfork' is not compatible with console or remote console mode; ignored\n");
03356       ast_clear_flag(&ast_options, AST_OPT_FLAG_ALWAYS_FORK);
03357    }
03358 
03359    if (ast_opt_dump_core) {
03360       memset(&l, 0, sizeof(l));
03361       l.rlim_cur = RLIM_INFINITY;
03362       l.rlim_max = RLIM_INFINITY;
03363       if (setrlimit(RLIMIT_CORE, &l)) {
03364          ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
03365       }
03366    }
03367 
03368    if (getrlimit(RLIMIT_NOFILE, &l)) {
03369       ast_log(LOG_WARNING, "Unable to check file descriptor limit: %s\n", strerror(errno));
03370    }
03371 
03372 #if !defined(CONFIGURE_RAN_AS_ROOT)
03373    /* Check if select(2) will run with more file descriptors */
03374    do {
03375       int fd, fd2;
03376       ast_fdset readers;
03377       struct timeval tv = { 0, };
03378 
03379       if (l.rlim_cur <= FD_SETSIZE) {
03380          /* The limit of select()able FDs is irrelevant, because we'll never
03381           * open one that high. */
03382          break;
03383       }
03384 
03385       if (!(fd = open("/dev/null", O_RDONLY))) {
03386          ast_log(LOG_ERROR, "Cannot open a file descriptor at boot? %s\n", strerror(errno));
03387          break; /* XXX Should we exit() here? XXX */
03388       }
03389 
03390       fd2 = (l.rlim_cur > sizeof(readers) * 8 ? sizeof(readers) * 8 : l.rlim_cur) - 1;
03391       if (dup2(fd, fd2) < 0) {
03392          ast_log(LOG_WARNING, "Cannot open maximum file descriptor %d at boot? %s\n", fd2, strerror(errno));
03393          break;
03394       }
03395 
03396       FD_ZERO(&readers);
03397       FD_SET(fd2, &readers);
03398       if (ast_select(fd2 + 1, &readers, NULL, NULL, &tv) < 0) {
03399          ast_log(LOG_WARNING, "Maximum select()able file descriptor is %d\n", FD_SETSIZE);
03400       }
03401    } while (0);
03402 #elif defined(HAVE_VARIABLE_FDSET)
03403    ast_FD_SETSIZE = l.rlim_cur;
03404 #endif /* !defined(CONFIGURE_RAN_AS_ROOT) */
03405 
03406    if ((!rungroup) && !ast_strlen_zero(ast_config_AST_RUN_GROUP))
03407       rungroup = ast_config_AST_RUN_GROUP;
03408    if ((!runuser) && !ast_strlen_zero(ast_config_AST_RUN_USER))
03409       runuser = ast_config_AST_RUN_USER;
03410 
03411    /* Must install this signal handler up here to ensure that if the canary
03412     * fails to execute that it doesn't kill the Asterisk process.
03413     */
03414    sigaction(SIGCHLD, &child_handler, NULL);
03415 
03416    /* It's common on some platforms to clear /var/run at boot.  Create the
03417     * socket file directory before we drop privileges. */
03418    if (mkdir(ast_config_AST_RUN_DIR, 0755)) {
03419       if (errno == EEXIST) {
03420          rundir_exists = 1;
03421       } else {
03422          ast_log(LOG_WARNING, "Unable to create socket file directory.  Remote consoles will not be able to connect! (%s)\n", strerror(x));
03423       }
03424    }
03425 
03426 #ifndef __CYGWIN__
03427 
03428    if (isroot) {
03429       ast_set_priority(ast_opt_high_priority);
03430    }
03431 
03432    if (isroot && rungroup) {
03433       struct group *gr;
03434       gr = getgrnam(rungroup);
03435       if (!gr) {
03436          ast_log(LOG_WARNING, "No such group '%s'!\n", rungroup);
03437          exit(1);
03438       }
03439       if (!rundir_exists && chown(ast_config_AST_RUN_DIR, -1, gr->gr_gid)) {
03440          ast_log(LOG_WARNING, "Unable to chgrp run directory to %d (%s)\n", (int) gr->gr_gid, rungroup);
03441       }
03442       if (setgid(gr->gr_gid)) {
03443          ast_log(LOG_WARNING, "Unable to setgid to %d (%s)\n", (int)gr->gr_gid, rungroup);
03444          exit(1);
03445       }
03446       if (setgroups(0, NULL)) {
03447          ast_log(LOG_WARNING, "Unable to drop unneeded groups\n");
03448          exit(1);
03449       }
03450       if (option_verbose)
03451          ast_verbose("Running as group '%s'\n", rungroup);
03452    }
03453 
03454    if (runuser && !ast_test_flag(&ast_options, AST_OPT_FLAG_REMOTE)) {
03455 #ifdef HAVE_CAP
03456       int has_cap = 1;
03457 #endif /* HAVE_CAP */
03458       struct passwd *pw;
03459       pw = getpwnam(runuser);
03460       if (!pw) {
03461          ast_log(LOG_WARNING, "No such user '%s'!\n", runuser);
03462          exit(1);
03463       }
03464       if (chown(ast_config_AST_RUN_DIR, pw->pw_uid, -1)) {
03465          ast_log(LOG_WARNING, "Unable to chown run directory to %d (%s)\n", (int) pw->pw_uid, runuser);
03466       }
03467 #ifdef HAVE_CAP
03468       if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0)) {
03469          ast_log(LOG_WARNING, "Unable to keep capabilities.\n");
03470          has_cap = 0;
03471       }
03472 #endif /* HAVE_CAP */
03473       if (!isroot && pw->pw_uid != geteuid()) {
03474          ast_log(LOG_ERROR, "Asterisk started as nonroot, but runuser '%s' requested.\n", runuser);
03475          exit(1);
03476       }
03477       if (!rungroup) {
03478          if (setgid(pw->pw_gid)) {
03479             ast_log(LOG_WARNING, "Unable to setgid to %d!\n", (int)pw->pw_gid);
03480             exit(1);
03481          }
03482          if (isroot && initgroups(pw->pw_name, pw->pw_gid)) {
03483             ast_log(LOG_WARNING, "Unable to init groups for '%s'\n", runuser);
03484             exit(1);
03485          }
03486       }
03487       if (setuid(pw->pw_uid)) {
03488          ast_log(LOG_WARNING, "Unable to setuid to %d (%s)\n", (int)pw->pw_uid, runuser);
03489          exit(1);
03490       }
03491       if (option_verbose)
03492          ast_verbose("Running as user '%s'\n", runuser);
03493 #ifdef HAVE_CAP
03494       if (has_cap) {
03495          cap_t cap;
03496 
03497          cap = cap_from_text("cap_net_admin=eip");
03498 
03499          if (cap_set_proc(cap))
03500             ast_log(LOG_WARNING, "Unable to install capabilities.\n");
03501 
03502          if (cap_free(cap))
03503             ast_log(LOG_WARNING, "Unable to drop capabilities.\n");
03504       }
03505 #endif /* HAVE_CAP */
03506    }
03507 
03508 #endif /* __CYGWIN__ */
03509 
03510 #ifdef linux
03511    if (geteuid() && ast_opt_dump_core) {
03512       if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) < 0) {
03513          ast_log(LOG_WARNING, "Unable to set the process for core dumps after changing to a non-root user. %s\n", strerror(errno));
03514       }
03515    }
03516 #endif
03517 
03518    {
03519 #if defined(HAVE_EACCESS) || defined(HAVE_EUIDACCESS)
03520 #if defined(HAVE_EUIDACCESS) && !defined(HAVE_EACCESS)
03521 #define eaccess euidaccess
03522 #endif
03523       char dir[PATH_MAX];
03524       if (!getcwd(dir, sizeof(dir)) || eaccess(dir, R_OK | X_OK | F_OK)) {
03525          ast_log(LOG_ERROR, "Unable to access the running directory (%s).  Changing to '/' for compatibility.\n", strerror(errno));
03526          /* If we cannot access the CWD, then we couldn't dump core anyway,
03527           * so chdir("/") won't break anything. */
03528          if (chdir("/")) {
03529             /* chdir(/) should never fail, so this ends up being a no-op */
03530             ast_log(LOG_ERROR, "chdir(\"/\") failed?!! %s\n", strerror(errno));
03531          }
03532       } else
03533 #endif /* defined(HAVE_EACCESS) || defined(HAVE_EUIDACCESS) */
03534       if (!ast_opt_no_fork && !ast_opt_dump_core) {
03535          /* Backgrounding, but no cores, so chdir won't break anything. */
03536          if (chdir("/")) {
03537             ast_log(LOG_ERROR, "Unable to chdir(\"/\") ?!! %s\n", strerror(errno));
03538          }
03539       }
03540    }
03541 
03542    ast_term_init();
03543    printf("%s", term_end());
03544    fflush(stdout);
03545 
03546    if (ast_opt_console && !option_verbose) 
03547       ast_verbose("[ Initializing Custom Configuration Options ]\n");
03548    /* custom config setup */
03549    register_config_cli();
03550    read_config_maps();
03551    
03552    if (ast_opt_console) {
03553       if (el_hist == NULL || el == NULL)
03554          ast_el_initialize();
03555 
03556       if (!ast_strlen_zero(filename))
03557          ast_el_read_history(filename);
03558    }
03559 
03560    if (ast_tryconnect()) {
03561       /* One is already running */
03562       if (ast_opt_remote) {
03563          if (ast_opt_exec) {
03564             ast_remotecontrol(xarg);
03565             quit_handler(0, 0, 0, 0);
03566             exit(0);
03567          }
03568          printf("%s", term_quit());
03569          ast_remotecontrol(NULL);
03570          quit_handler(0, 0, 0, 0);
03571          exit(0);
03572       } else {
03573          ast_log(LOG_ERROR, "Asterisk already running on %s.  Use 'asterisk -r' to connect.\n", ast_config_AST_SOCKET);
03574          printf("%s", term_quit());
03575          exit(1);
03576       }
03577    } else if (ast_opt_remote || ast_opt_exec) {
03578       ast_log(LOG_ERROR, "Unable to connect to remote asterisk (does %s exist?)\n", ast_config_AST_SOCKET);
03579       printf("%s", term_quit());
03580       exit(1);
03581    }
03582    /* Blindly write pid file since we couldn't connect */
03583    unlink(ast_config_AST_PID);
03584    f = fopen(ast_config_AST_PID, "w");
03585    if (f) {
03586       fprintf(f, "%ld\n", (long)getpid());
03587       fclose(f);
03588    } else
03589       ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", ast_config_AST_PID, strerror(errno));
03590 
03591 #if HAVE_WORKING_FORK
03592    if (ast_opt_always_fork || !ast_opt_no_fork) {
03593 #ifndef HAVE_SBIN_LAUNCHD
03594       if (daemon(1, 0) < 0) {
03595          ast_log(LOG_ERROR, "daemon() failed: %s\n", strerror(errno));
03596       }
03597       ast_mainpid = getpid();
03598       /* Blindly re-write pid file since we are forking */
03599       unlink(ast_config_AST_PID);
03600       f = fopen(ast_config_AST_PID, "w");
03601       if (f) {
03602          fprintf(f, "%ld\n", (long)ast_mainpid);
03603          fclose(f);
03604       } else
03605          ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", ast_config_AST_PID, strerror(errno));
03606 #else
03607       ast_log(LOG_WARNING, "Mac OS X detected.  Use 'launchctl load /Library/LaunchDaemon/org.asterisk.asterisk.plist'.\n");
03608 #endif
03609    }
03610 #endif
03611 
03612    /* Spawning of astcanary must happen AFTER the call to daemon(3) */
03613    if (isroot && ast_opt_high_priority) {
03614       snprintf(canary_filename, sizeof(canary_filename), "%s/alt.asterisk.canary.tweet.tweet.tweet", ast_config_AST_RUN_DIR);
03615 
03616       /* Don't let the canary child kill Asterisk, if it dies immediately */
03617       sigaction(SIGPIPE, &ignore_sig_handler, NULL);
03618 
03619       canary_pid = fork();
03620       if (canary_pid == 0) {
03621          char canary_binary[128], *lastslash, ppid[12];
03622 
03623          /* Reset signal handler */
03624          signal(SIGCHLD, SIG_DFL);
03625          signal(SIGPIPE, SIG_DFL);
03626 
03627          ast_close_fds_above_n(0);
03628          ast_set_priority(0);
03629          snprintf(ppid, sizeof(ppid), "%d", (int) ast_mainpid);
03630 
03631          execlp("astcanary", "astcanary", canary_filename, ppid, (char *)NULL);
03632 
03633          /* If not found, try the same path as used to execute asterisk */
03634          ast_copy_string(canary_binary, argv[0], sizeof(canary_binary));
03635          if ((lastslash = strrchr(canary_binary, '/'))) {
03636             ast_copy_string(lastslash + 1, "astcanary", sizeof(canary_binary) + canary_binary - (lastslash + 1));
03637             execl(canary_binary, "astcanary", canary_filename, (char *)NULL);
03638          }
03639 
03640          /* Should never happen */
03641          _exit(1);
03642       } else if (canary_pid > 0) {
03643          pthread_t dont_care;
03644          ast_pthread_create_detached(&dont_care, NULL, canary_thread, NULL);
03645       }
03646 
03647       /* Kill the canary when we exit */
03648       ast_register_atexit(canary_exit);
03649    }
03650 
03651    if (ast_event_init()) {
03652       printf("%s", term_quit());
03653       exit(1);
03654    }
03655 
03656 #ifdef TEST_FRAMEWORK
03657    if (ast_test_init()) {
03658       printf("%s", term_quit());
03659       exit(1);
03660    }
03661 #endif
03662 
03663    ast_aoc_cli_init();
03664 
03665    ast_makesocket();
03666    sigemptyset(&sigs);
03667    sigaddset(&sigs, SIGHUP);
03668    sigaddset(&sigs, SIGTERM);
03669    sigaddset(&sigs, SIGINT);
03670    sigaddset(&sigs, SIGPIPE);
03671    sigaddset(&sigs, SIGWINCH);
03672    pthread_sigmask(SIG_BLOCK, &sigs, NULL);
03673    sigaction(SIGURG, &urg_handler, NULL);
03674    signal(SIGINT, __quit_handler);
03675    signal(SIGTERM, __quit_handler);
03676    sigaction(SIGHUP, &hup_handler, NULL);
03677    sigaction(SIGPIPE, &ignore_sig_handler, NULL);
03678 
03679    /* ensure that the random number generators are seeded with a different value every time
03680       Asterisk is started
03681    */
03682    srand((unsigned int) getpid() + (unsigned int) time(NULL));
03683    initstate((unsigned int) getpid() * 65536 + (unsigned int) time(NULL), randompool, sizeof(randompool));
03684 
03685    if (init_logger()) {    /* Start logging subsystem */
03686       printf("%s", term_quit());
03687       exit(1);
03688    }
03689 
03690    threadstorage_init();
03691 
03692    astobj2_init();
03693 
03694    ast_autoservice_init();
03695 
03696    if (ast_timing_init()) {
03697       printf("%s", term_quit());
03698       exit(1);
03699    }
03700 
03701    if (ast_ssl_init()) {
03702       printf("%s", term_quit());
03703       exit(1);
03704    }
03705 
03706 #ifdef AST_XML_DOCS
03707    /* Load XML documentation. */
03708    ast_xmldoc_load_documentation();
03709 #endif
03710 
03711    /* initialize the data retrieval API */
03712    if (ast_data_init()) {
03713       printf ("%s", term_quit());
03714       exit(1);
03715    }
03716 
03717    ast_channels_init();
03718 
03719    if ((moduleresult = load_modules(1))) {      /* Load modules, pre-load only */
03720       printf("%s", term_quit());
03721       exit(moduleresult == -2 ? 2 : 1);
03722    }
03723 
03724    if (dnsmgr_init()) {    /* Initialize the DNS manager */
03725       printf("%s", term_quit());
03726       exit(1);
03727    }
03728 
03729    ast_http_init();     /* Start the HTTP server, if needed */
03730 
03731    if (init_manager()) {
03732       printf("%s", term_quit());
03733       exit(1);
03734    }
03735 
03736    if (ast_cdr_engine_init()) {
03737       printf("%s", term_quit());
03738       exit(1);
03739    }
03740 
03741    if (ast_cel_engine_init()) {
03742       printf("%s", term_quit());
03743       exit(1);
03744    }
03745 
03746    if (ast_device_state_engine_init()) {
03747       printf("%s", term_quit());
03748       exit(1);
03749    }
03750 
03751    ast_dsp_init();
03752    ast_udptl_init();
03753 
03754    if (ast_image_init()) {
03755       printf("%s", term_quit());
03756       exit(1);
03757    }
03758 
03759    if (ast_file_init()) {
03760       printf("%s", term_quit());
03761       exit(1);
03762    }
03763 
03764    if (load_pbx()) {
03765       printf("%s", term_quit());
03766       exit(1);
03767    }
03768 
03769    if (ast_indications_init()) {
03770       printf("%s", term_quit());
03771       exit(1);
03772    }
03773 
03774    ast_features_init();
03775 
03776    if (init_framer()) {
03777       printf("%s", term_quit());
03778       exit(1);
03779    }
03780 
03781    if (astdb_init()) {
03782       printf("%s", term_quit());
03783       exit(1);
03784    }
03785 
03786    if (ast_enum_init()) {
03787       printf("%s", term_quit());
03788       exit(1);
03789    }
03790 
03791    if (ast_cc_init()) {
03792       printf("%s", term_quit());
03793       exit(1);
03794    }
03795 
03796    if ((moduleresult = load_modules(0))) {      /* Load modules */
03797       printf("%s", term_quit());
03798       exit(moduleresult == -2 ? 2 : 1);
03799    }
03800 
03801    /* loads the cli_permissoins.conf file needed to implement cli restrictions. */
03802    ast_cli_perms_init(0);
03803 
03804    ast_stun_init();
03805 
03806    dnsmgr_start_refresh();
03807 
03808    /* We might have the option of showing a console, but for now just
03809       do nothing... */
03810    if (ast_opt_console && !option_verbose)
03811       ast_verbose(" ]\n");
03812    if (option_verbose || ast_opt_console)
03813       ast_verbose("%s", term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
03814    if (ast_opt_no_fork)
03815       consolethread = pthread_self();
03816 
03817    if (pipe(sig_alert_pipe))
03818       sig_alert_pipe[0] = sig_alert_pipe[1] = -1;
03819 
03820    ast_set_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED);
03821    manager_event(EVENT_FLAG_SYSTEM, "FullyBooted", "Status: Fully Booted\r\n");
03822 
03823    ast_process_pending_reloads();
03824 
03825    pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
03826 
03827 #ifdef __AST_DEBUG_MALLOC
03828    __ast_mm_init();
03829 #endif   
03830 
03831    ast_lastreloadtime = ast_startuptime = ast_tvnow();
03832    ast_cli_register_multiple(cli_asterisk, ARRAY_LEN(cli_asterisk));
03833 
03834    run_startup_commands();
03835 
03836    if (ast_opt_console) {
03837       /* Console stuff now... */
03838       /* Register our quit function */
03839       char title[256];
03840 
03841       ast_pthread_create_detached(&mon_sig_flags, NULL, monitor_sig_flags, NULL);
03842 
03843       set_icon("Asterisk");
03844       snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %ld)", hostname, (long)ast_mainpid);
03845       set_title(title);
03846 
03847       for (;;) {
03848          buf = (char *) el_gets(el, &num);
03849 
03850          if (!buf && write(1, "", 1) < 0)
03851             goto lostterm;
03852 
03853          if (buf) {
03854             if (buf[strlen(buf)-1] == '\n')
03855                buf[strlen(buf)-1] = '\0';
03856 
03857             consolehandler((char *)buf);
03858          } else if (ast_opt_remote && (write(STDOUT_FILENO, "\nUse EXIT or QUIT to exit the asterisk console\n",
03859                strlen("\nUse EXIT or QUIT to exit the asterisk console\n")) < 0)) {
03860             /* Whoa, stdout disappeared from under us... Make /dev/null's */
03861             int fd;
03862             fd = open("/dev/null", O_RDWR);
03863             if (fd > -1) {
03864                dup2(fd, STDOUT_FILENO);
03865                dup2(fd, STDIN_FILENO);
03866             } else
03867                ast_log(LOG_WARNING, "Failed to open /dev/null to recover from dead console. Bad things will happen!\n");
03868             break;
03869          }
03870       }
03871    }
03872 
03873    monitor_sig_flags(NULL);
03874 
03875 lostterm:
03876    return 0;
03877 }

static void* monitor_sig_flags ( void *  unused  )  [static]

Definition at line 3069 of file asterisk.c.

References ast_module_reload(), ast_poll, quit_handler(), sig_alert_pipe, and sig_flags.

Referenced by main().

03070 {
03071    for (;;) {
03072       struct pollfd p = { sig_alert_pipe[0], POLLIN, 0 };
03073       int a;
03074       ast_poll(&p, 1, -1);
03075       if (sig_flags.need_reload) {
03076          sig_flags.need_reload = 0;
03077          ast_module_reload(NULL);
03078       }
03079       if (sig_flags.need_quit) {
03080          sig_flags.need_quit = 0;
03081          quit_handler(0, 0, 1, 0);
03082       }
03083       if (read(sig_alert_pipe[0], &a, sizeof(a)) != sizeof(a)) {
03084       }
03085    }
03086 
03087    return NULL;
03088 }

static void* netconsole ( void *  vconsole  )  [static]

Definition at line 1224 of file asterisk.c.

References ast_cli_command_multiple_full(), ast_copy_string(), ast_get_version(), ast_log(), ast_opt_hide_connect, ast_poll, ast_verb, errno, console::fd, fdprint(), console::gid, hostname, LOG_ERROR, LOG_WARNING, MAXHOSTNAMELEN, console::p, read_credentials(), and console::uid.

Referenced by listener().

01225 {
01226    struct console *con = vconsole;
01227    char hostname[MAXHOSTNAMELEN] = "";
01228    char tmp[512];
01229    int res;
01230    struct pollfd fds[2];
01231    
01232    if (gethostname(hostname, sizeof(hostname)-1))
01233       ast_copy_string(hostname, "<Unknown>", sizeof(hostname));
01234    snprintf(tmp, sizeof(tmp), "%s/%ld/%s\n", hostname, (long)ast_mainpid, ast_get_version());
01235    fdprint(con->fd, tmp);
01236    for (;;) {
01237       fds[0].fd = con->fd;
01238       fds[0].events = POLLIN;
01239       fds[0].revents = 0;
01240       fds[1].fd = con->p[0];
01241       fds[1].events = POLLIN;
01242       fds[1].revents = 0;
01243 
01244       res = ast_poll(fds, 2, -1);
01245       if (res < 0) {
01246          if (errno != EINTR)
01247             ast_log(LOG_WARNING, "poll returned < 0: %s\n", strerror(errno));
01248          continue;
01249       }
01250       if (fds[0].revents) {
01251          res = read_credentials(con->fd, tmp, sizeof(tmp) - 1, con);
01252          if (res < 1) {
01253             break;
01254          }
01255          tmp[res] = 0;
01256          if (strncmp(tmp, "cli quit after ", 15) == 0) {
01257             ast_cli_command_multiple_full(con->uid, con->gid, con->fd, res - 15, tmp + 15);
01258             break;
01259          }
01260          ast_cli_command_multiple_full(con->uid, con->gid, con->fd, res, tmp);
01261       }
01262       if (fds[1].revents) {
01263          res = read_credentials(con->p[0], tmp, sizeof(tmp), con);
01264          if (res < 1) {
01265             ast_log(LOG_ERROR, "read returned %d\n", res);
01266             break;
01267          }
01268          res = write(con->fd, tmp, res);
01269          if (res < 1)
01270             break;
01271       }
01272    }
01273    if (!ast_opt_hide_connect) {
01274       ast_verb(3, "Remote UNIX connection disconnected\n");
01275    }
01276    close(con->fd);
01277    close(con->p[0]);
01278    close(con->p[1]);
01279    con->fd = -1;
01280    
01281    return NULL;
01282 }

static void network_verboser ( const char *  s  )  [static]

Definition at line 1169 of file asterisk.c.

References __LOG_VERBOSE, and ast_network_puts_mutable().

Referenced by ast_makesocket().

01170 {
01171    ast_network_puts_mutable(s, __LOG_VERBOSE);
01172 }

static void quit_handler ( int  num,
int  niceness,
int  safeshutdown,
int  restart 
) [static]

Definition at line 1590 of file asterisk.c.

References _argv, ast_active_channels(), ast_begin_shutdown(), ast_cdr_engine_term(), ast_config_AST_PID, ast_config_AST_SOCKET, ast_debug, ast_el_write_history(), ast_module_shutdown(), ast_opt_console, ast_opt_exec, ast_opt_remote, AST_PTHREADT_NULL, ast_run_atexits(), ast_strlen_zero(), ast_verbose, close_logger(), consolethread, el, el_hist, EVENT_FLAG_SYSTEM, lthread, manager_event, mon_sig_flags, restartnow, shuttingdown, and term_quit().

Referenced by ast_el_read_char(), handle_restart_gracefully(), handle_restart_now(), handle_restart_when_convenient(), handle_stop_gracefully(), handle_stop_now(), handle_stop_when_convenient(), main(), monitor_sig_flags(), and remoteconsolehandler().

01591 {
01592    char filename[80] = "";
01593    time_t s,e;
01594    int x;
01595    /* Try to get as many CDRs as possible submitted to the backend engines (if in batch mode) */
01596    ast_cdr_engine_term();
01597    if (safeshutdown) {
01598       shuttingdown = 1;
01599       if (!niceness) {
01600          /* Begin shutdown routine, hanging up active channels */
01601          ast_begin_shutdown(1);
01602          if (option_verbose && ast_opt_console)
01603             ast_verbose("Beginning asterisk %s....\n", restart ? "restart" : "shutdown");
01604          time(&s);
01605          for (;;) {
01606             time(&e);
01607             /* Wait up to 15 seconds for all channels to go away */
01608             if ((e - s) > 15)
01609                break;
01610             if (!ast_active_channels())
01611                break;
01612             if (!shuttingdown)
01613                break;
01614             /* Sleep 1/10 of a second */
01615             usleep(100000);
01616          }
01617       } else {
01618          if (niceness < 2)
01619             ast_begin_shutdown(0);
01620          if (option_verbose && ast_opt_console)
01621             ast_verbose("Waiting for inactivity to perform %s...\n", restart ? "restart" : "halt");
01622          for (;;) {
01623             if (!ast_active_channels())
01624                break;
01625             if (!shuttingdown)
01626                break;
01627             sleep(1);
01628          }
01629       }
01630 
01631       if (!shuttingdown) {
01632          if (option_verbose && ast_opt_console)
01633             ast_verbose("Asterisk %s cancelled.\n", restart ? "restart" : "shutdown");
01634          return;
01635       }
01636 
01637       if (niceness)
01638          ast_module_shutdown();
01639    }
01640    if (ast_opt_console || (ast_opt_remote && !ast_opt_exec)) {
01641       pthread_t thisthread = pthread_self();
01642       if (getenv("HOME")) {
01643          snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
01644       }
01645       if (!ast_strlen_zero(filename)) {
01646          ast_el_write_history(filename);
01647       }
01648       if (consolethread == AST_PTHREADT_NULL || consolethread == thisthread || mon_sig_flags == thisthread) {
01649          /* Only end if we are the consolethread or signal handler, otherwise there's a race with that thread. */
01650          if (el != NULL) {
01651             el_end(el);
01652          }
01653          if (el_hist != NULL) {
01654             history_end(el_hist);
01655          }
01656       }
01657    }
01658    if (option_verbose)
01659       ast_verbose("Executing last minute cleanups\n");
01660    ast_run_atexits();
01661    /* Called on exit */
01662    if (option_verbose && ast_opt_console)
01663       ast_verbose("Asterisk %s ending (%d).\n", ast_active_channels() ? "uncleanly" : "cleanly", num);
01664    ast_debug(1, "Asterisk ending (%d).\n", num);
01665    manager_event(EVENT_FLAG_SYSTEM, "Shutdown", "Shutdown: %s\r\nRestart: %s\r\n", ast_active_channels() ? "Uncleanly" : "Cleanly", restart ? "True" : "False");
01666    if (ast_socket > -1) {
01667       pthread_cancel(lthread);
01668       close(ast_socket);
01669       ast_socket = -1;
01670       unlink(ast_config_AST_SOCKET);
01671    }
01672    if (ast_consock > -1)
01673       close(ast_consock);
01674    if (!ast_opt_remote)
01675       unlink(ast_config_AST_PID);
01676    printf("%s", term_quit());
01677    if (restart) {
01678       if (option_verbose || ast_opt_console)
01679          ast_verbose("Preparing for Asterisk restart...\n");
01680       /* Mark all FD's for closing on exec */
01681       for (x=3; x < 32768; x++) {
01682          fcntl(x, F_SETFD, FD_CLOEXEC);
01683       }
01684       if (option_verbose || ast_opt_console)
01685          ast_verbose("Asterisk is now restarting...\n");
01686       restartnow = 1;
01687 
01688       /* close logger */
01689       close_logger();
01690 
01691       /* If there is a consolethread running send it a SIGHUP 
01692          so it can execvp, otherwise we can do it ourselves */
01693       if ((consolethread != AST_PTHREADT_NULL) && (consolethread != pthread_self())) {
01694          pthread_kill(consolethread, SIGHUP);
01695          /* Give the signal handler some time to complete */
01696          sleep(2);
01697       } else
01698          execvp(_argv[0], _argv);
01699    
01700    } else {
01701       /* close logger */
01702       close_logger();
01703    }
01704    exit(0);
01705 }

static __inline uint64_t rdtsc ( void   )  [static]

Definition at line 750 of file asterisk.c.

Referenced by ast_mark().

00751 {
00752    return 0;
00753 }

static int read_credentials ( int  fd,
char *  buffer,
size_t  size,
struct console *  con 
) [static]

read() function supporting the reception of user credentials.

Parameters:
fd Socket file descriptor.
buffer Receive buffer.
size 'buffer' size.
con Console structure to set received credentials
Return values:
-1 on error
the number of bytes received on success.

Definition at line 1186 of file asterisk.c.

References console::gid, len(), and console::uid.

Referenced by netconsole().

01187 {
01188 #if defined(SO_PEERCRED)
01189    struct ucred cred;
01190    socklen_t len = sizeof(cred);
01191 #endif
01192 #if defined(HAVE_GETPEEREID)
01193    uid_t uid;
01194    gid_t gid;
01195 #else
01196    int uid, gid;
01197 #endif
01198    int result;
01199 
01200    result = read(fd, buffer, size);
01201    if (result < 0) {
01202       return result;
01203    }
01204 
01205 #if defined(SO_PEERCRED)
01206    if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &len)) {
01207       return result;
01208    }
01209    uid = cred.uid;
01210    gid = cred.gid;
01211 #elif defined(HAVE_GETPEEREID)
01212    if (getpeereid(fd, &uid, &gid)) {
01213       return result;
01214    }
01215 #else
01216    return result;
01217 #endif
01218    con->uid = uid;
01219    con->gid = gid;
01220 
01221    return result;
01222 }

static int remoteconsolehandler ( char *  s  )  [static]

Definition at line 1795 of file asterisk.c.

References ast_all_zeros(), ast_el_add_history(), ast_safe_system(), and quit_handler().

Referenced by ast_remotecontrol().

01796 {
01797    int ret = 0;
01798 
01799    /* Called when readline data is available */
01800    if (!ast_all_zeros(s))
01801       ast_el_add_history(s);
01802    /* The real handler for bang */
01803    if (s[0] == '!') {
01804       if (s[1])
01805          ast_safe_system(s+1);
01806       else
01807          ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
01808       ret = 1;
01809    }
01810    if ((strncasecmp(s, "quit", 4) == 0 || strncasecmp(s, "exit", 4) == 0) &&
01811        (s[4] == '\0' || isspace(s[4]))) {
01812       quit_handler(0, 0, 0, 0);
01813       ret = 1;
01814    }
01815 
01816    return ret;
01817 }

static void run_startup_commands ( void   )  [static]

Definition at line 3119 of file asterisk.c.

References ast_cli_command, ast_config_destroy(), ast_config_load2(), ast_true(), ast_variable_browse(), CONFIG_STATUS_FILEINVALID, CONFIG_STATUS_FILEMISSING, CONFIG_STATUS_FILEUNCHANGED, ast_variable::name, ast_variable::next, and ast_variable::value.

Referenced by main().

03120 {
03121    int fd;
03122    struct ast_config *cfg;
03123    struct ast_flags cfg_flags = { 0 };
03124    struct ast_variable *v;
03125 
03126    if (!(cfg = ast_config_load2("cli.conf", "" /* core, can't reload */, cfg_flags)))
03127       return;
03128    if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
03129       return;
03130    }
03131 
03132    fd = open("/dev/null", O_RDWR);
03133    if (fd < 0) {
03134       ast_config_destroy(cfg);
03135       return;
03136    }
03137 
03138    for (v = ast_variable_browse(cfg, "startup_commands"); v; v = v->next) {
03139       if (ast_true(v->value))
03140          ast_cli_command(fd, v->name);
03141    }
03142 
03143    close(fd);
03144    ast_config_destroy(cfg);
03145 }

static void set_icon ( char *  text  )  [static]

Definition at line 1537 of file asterisk.c.

Referenced by main().

01538 {
01539    if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
01540       fprintf(stdout, "\033]1;%s\007", text);
01541 }

static void set_title ( char *  text  )  [static]

Set an X-term or screen title.

Definition at line 1531 of file asterisk.c.

Referenced by main().

01532 {
01533    if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
01534       fprintf(stdout, "\033]2;%s\007", text);
01535 }

static void set_ulimit ( int  value  )  [static]

Set maximum open files.

Definition at line 1508 of file asterisk.c.

References ast_log(), errno, LOG_NOTICE, and LOG_WARNING.

Referenced by ast_readconfig().

01509 {
01510    struct rlimit l = {0, 0};
01511    
01512    if (value <= 0) {
01513       ast_log(LOG_WARNING, "Unable to change max files open to invalid value %i\n",value);
01514       return;
01515    }
01516    
01517    l.rlim_cur = value;
01518    l.rlim_max = value;
01519    
01520    if (setrlimit(RLIMIT_NOFILE, &l)) {
01521       ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n",strerror(errno));
01522       return;
01523    }
01524    
01525    ast_log(LOG_NOTICE, "Setting max files open to %d\n",value);
01526    
01527    return;
01528 }

static int show_cli_help ( void   )  [static]

Definition at line 2795 of file asterisk.c.

References ast_get_version().

Referenced by main().

02795                                {
02796    printf("Asterisk %s, Copyright (C) 1999 - 2010, Digium, Inc. and others.\n", ast_get_version());
02797    printf("Usage: asterisk [OPTIONS]\n");
02798    printf("Valid Options:\n");
02799    printf("   -V              Display version number and exit\n");
02800    printf("   -C <configfile> Use an alternate configuration file\n");
02801    printf("   -G <group>      Run as a group other than the caller\n");
02802    printf("   -U <user>       Run as a user other than the caller\n");
02803    printf("   -c              Provide console CLI\n");
02804    printf("   -d              Enable extra debugging\n");
02805 #if HAVE_WORKING_FORK
02806    printf("   -f              Do not fork\n");
02807    printf("   -F              Always fork\n");
02808 #endif
02809    printf("   -g              Dump core in case of a crash\n");
02810    printf("   -h              This help screen\n");
02811    printf("   -i              Initialize crypto keys at startup\n");
02812    printf("   -I              Enable internal timing if DAHDI timer is available\n");
02813    printf("   -L <load>       Limit the maximum load average before rejecting new calls\n");
02814    printf("   -M <value>      Limit the maximum number of calls to the specified value\n");
02815    printf("   -m              Mute debugging and console output on the console\n");
02816    printf("   -n              Disable console colorization\n");
02817    printf("   -p              Run as pseudo-realtime thread\n");
02818    printf("   -q              Quiet mode (suppress output)\n");
02819    printf("   -r              Connect to Asterisk on this machine\n");
02820    printf("   -R              Same as -r, except attempt to reconnect if disconnected\n");
02821    printf("   -s <socket>     Connect to Asterisk via socket <socket> (only valid with -r)\n");
02822    printf("   -t              Record soundfiles in /var/tmp and move them where they\n");
02823    printf("                   belong after they are done\n");
02824    printf("   -T              Display the time in [Mmm dd hh:mm:ss] format for each line\n");
02825    printf("                   of output to the CLI\n");
02826    printf("   -v              Increase verbosity (multiple v's = more verbose)\n");
02827    printf("   -x <cmd>        Execute command <cmd> (only valid with -r)\n");
02828    printf("   -X              Execute includes by default (allows #exec in asterisk.conf)\n");
02829    printf("   -W              Adjust terminal colors to compensate for a light background\n");
02830    printf("\n");
02831    return 0;
02832 }

static char* show_license ( struct ast_cli_entry *  e,
int  cmd,
struct ast_cli_args *  a 
) [static]

Definition at line 2067 of file asterisk.c.

References ast_cli(), CLI_GENERATE, CLI_INIT, CLI_SUCCESS, ast_cli_entry::command, ast_cli_args::fd, and ast_cli_entry::usage.

02068 {
02069    switch (cmd) {
02070    case CLI_INIT:
02071       e->command = "core show license";
02072       e->usage = 
02073          "Usage: core show license\n"
02074          "       Shows the license(s) for this copy of Asterisk.\n";
02075       return NULL;
02076    case CLI_GENERATE:
02077       return NULL;
02078    }
02079 
02080    ast_cli(a->fd, "%s", license_lines);
02081 
02082    return CLI_SUCCESS;
02083 }

static int show_version ( void   )  [static]

Definition at line 2789 of file asterisk.c.

References ast_get_version().

Referenced by main().

02790 {
02791    printf("Asterisk %s\n", ast_get_version());
02792    return 0;
02793 }

static char* show_warranty ( struct ast_cli_entry *  e,
int  cmd,
struct ast_cli_args *  a 
) [static]

Definition at line 2030 of file asterisk.c.

References ast_cli(), CLI_GENERATE, CLI_INIT, CLI_SUCCESS, ast_cli_entry::command, ast_cli_args::fd, and ast_cli_entry::usage.

02031 {
02032    switch (cmd) {
02033    case CLI_INIT:
02034       e->command = "core show warranty";
02035       e->usage = 
02036          "Usage: core show warranty\n"
02037          "       Shows the warranty (if any) for this copy of Asterisk.\n";
02038       return NULL;
02039    case CLI_GENERATE:
02040       return NULL;
02041    }
02042 
02043    ast_cli(a->fd, "%s", warranty_lines);
02044 
02045    return CLI_SUCCESS;
02046 }


Variable Documentation

char* _argv[256] [static]

Definition at line 277 of file asterisk.c.

Referenced by _hup_handler(), main(), and quit_handler().

const char* ast_config_AST_AGI_DIR = cfg_paths.agi_dir

Definition at line 259 of file asterisk.c.

Referenced by handle_show_settings(), and launch_script().

const char* ast_config_AST_CONFIG_DIR = cfg_paths.config_dir

Definition at line 252 of file asterisk.c.

Referenced by ast_readconfig(), handle_show_settings(), and launch_script().

char ast_config_AST_CTL[PATH_MAX] = "asterisk.ctl" [static]

Definition at line 273 of file asterisk.c.

Referenced by ast_readconfig().

char ast_config_AST_CTL_GROUP[PATH_MAX] = "\0" [static]

Definition at line 272 of file asterisk.c.

Referenced by ast_makesocket(), and ast_readconfig().

char ast_config_AST_CTL_OWNER[PATH_MAX] = "\0" [static]

Definition at line 271 of file asterisk.c.

Referenced by ast_makesocket(), and ast_readconfig().

char ast_config_AST_CTL_PERMISSIONS[PATH_MAX] [static]

Definition at line 270 of file asterisk.c.

Referenced by ast_makesocket(), and ast_readconfig().

const char* ast_config_AST_DATA_DIR = cfg_paths.data_dir

const char* ast_config_AST_DB = cfg_paths.db_path

Definition at line 263 of file asterisk.c.

Referenced by dbinit(), and handle_show_settings().

const char* ast_config_AST_KEY_DIR = cfg_paths.key_dir

const char* ast_config_AST_LOG_DIR = cfg_paths.log_dir

const char* ast_config_AST_MODULE_DIR = cfg_paths.module_dir

Definition at line 253 of file asterisk.c.

Referenced by complete_fn(), handle_show_settings(), launch_script(), and load_modules().

const char* ast_config_AST_MONITOR_DIR = cfg_paths.monitor_dir

const char* ast_config_AST_PID = cfg_paths.pid_path

Definition at line 264 of file asterisk.c.

Referenced by handle_show_settings(), main(), and quit_handler().

const char* ast_config_AST_RUN_DIR = cfg_paths.run_dir

Definition at line 261 of file asterisk.c.

Referenced by handle_show_settings(), launch_script(), and main().

const char* ast_config_AST_RUN_GROUP = cfg_paths.run_group

Definition at line 267 of file asterisk.c.

Referenced by action_coresettings(), handle_show_settings(), and main().

const char* ast_config_AST_RUN_USER = cfg_paths.run_user

Definition at line 266 of file asterisk.c.

Referenced by action_coresettings(), handle_show_settings(), and main().

const char* ast_config_AST_SOCKET = cfg_paths.socket_path

Definition at line 265 of file asterisk.c.

Referenced by ast_makesocket(), ast_tryconnect(), ast_var_Config(), main(), and quit_handler().

const char* ast_config_AST_SPOOL_DIR = cfg_paths.spool_dir

const char* ast_config_AST_SYSTEM_NAME = cfg_paths.system_name

const char* ast_config_AST_VAR_DIR = cfg_paths.var_dir

Definition at line 256 of file asterisk.c.

Referenced by ael2_semantic_check(), handle_show_settings(), and launch_script().

int ast_consock = -1 [static]

UNIX Socket for controlling another asterisk

Definition at line 194 of file asterisk.c.

Global EID.

This is set in asterisk.conf, or determined automatically by taking the mac address of an Ethernet interface on the system.

Definition at line 188 of file asterisk.c.

Referenced by aji_devstate_cb(), aji_handle_pubsub_event(), aji_mwi_cb(), aji_publish_device_state(), aji_publish_mwi(), ast_event_append_eid(), ast_event_cb(), ast_readconfig(), ast_str_retrieve_variable(), evt_event_deliver_cb(), handle_show_settings(), and set_config().

unsigned int ast_FD_SETSIZE

Definition at line 86 of file poll.c.

struct timeval ast_lastreloadtime

pid_t ast_mainpid

Definition at line 195 of file asterisk.c.

Referenced by safe_append(), and scan_service().

int ast_socket = -1 [static]

UNIX Socket for allowing remote control

Definition at line 193 of file asterisk.c.

struct timeval ast_startuptime

char canary_filename[128] [static]

Definition at line 283 of file asterisk.c.

Referenced by canary_thread(), and main().

int canary_pid = 0 [static]

Definition at line 282 of file asterisk.c.

Referenced by canary_exit(), and main().

struct _cfg_paths cfg_paths [static]

Definition at line 249 of file asterisk.c.

Referenced by ast_readconfig(), and main().

struct sigaction child_handler [static]

Initial value:

 {
   .sa_handler = _child_handler,
   .sa_flags = SA_RESTART,
}

Definition at line 1502 of file asterisk.c.

struct ast_cli_entry cli_asterisk[] [static]

Definition at line 2089 of file asterisk.c.

struct console consoles[AST_MAX_CONNECTS]

pthread_t consolethread = AST_PTHREADT_NULL [static]

Definition at line 280 of file asterisk.c.

Referenced by console_verboser(), main(), and quit_handler().

char defaultlanguage[MAX_LANGUAGE] = DEFAULT_LANGUAGE

Definition at line 222 of file asterisk.c.

Referenced by __ast_channel_alloc_ap(), and handle_show_settings().

EditLine* el [static]

History* el_hist [static]

struct sigaction hup_handler [static]

Initial value:

 {
   .sa_handler = _hup_handler,
   .sa_flags = SA_RESTART,
}

Definition at line 1483 of file asterisk.c.

struct sigaction ignore_sig_handler [static]

Initial value:

 {
   .sa_handler = SIG_IGN,
}

Definition at line 990 of file asterisk.c.

Referenced by main().

const char license_lines[] [static]

Definition at line 2048 of file asterisk.c.

pthread_t lthread [static]

Definition at line 1174 of file asterisk.c.

Referenced by ast_makesocket(), and quit_handler().

pthread_t mon_sig_flags [static]

Definition at line 281 of file asterisk.c.

Referenced by main(), and quit_handler().

unsigned int need_quit

Definition at line 290 of file asterisk.c.

unsigned int need_reload

Definition at line 289 of file asterisk.c.

struct sigaction null_sig_handler [static]

Initial value:

 {
   .sa_handler = _null_sig_handler,
   .sa_flags = SA_RESTART,
}

Definition at line 985 of file asterisk.c.

Referenced by ast_replace_sigchld().

struct profile_data* prof_data [static]

struct ast_str* prompt = NULL [static]

Definition at line 2211 of file asterisk.c.

Referenced by auth_exec(), handle_speechrecognize(), minivm_accmess_exec(), and pw_cb().

char randompool[256] [static]

Definition at line 285 of file asterisk.c.

Referenced by main().

char record_cache_dir[AST_CACHE_DIR_LEN] = DEFAULT_TMP_DIR

Definition at line 191 of file asterisk.c.

Referenced by ast_writefile().

char* remotehostname [static]

Definition at line 218 of file asterisk.c.

Referenced by ast_remotecontrol(), and cli_prompt().

int restartnow [static]

Definition at line 279 of file asterisk.c.

Referenced by _hup_handler(), and quit_handler().

unsigned int safe_system_level = 0 [static]

Keep track of how many threads are currently trying to wait*() on a child process.

Definition at line 997 of file asterisk.c.

Referenced by ast_replace_sigchld(), and ast_unreplace_sigchld().

ast_mutex_t safe_system_lock = { { { NULL }, { 0 }, 0, { NULL }, { 0 }, {{{ 0 }}}, PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP } , 1, PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP } [static]

Definition at line 994 of file asterisk.c.

Referenced by ast_replace_sigchld(), and ast_unreplace_sigchld().

struct sigaction safe_system_prev_handler [static]

Definition at line 998 of file asterisk.c.

Referenced by ast_replace_sigchld(), and ast_unreplace_sigchld().

int shuttingdown [static]

Definition at line 278 of file asterisk.c.

Referenced by handle_abort_shutdown(), and quit_handler().

int sig_alert_pipe[2] = { -1, -1 } [static]

Definition at line 287 of file asterisk.c.

Referenced by __quit_handler(), _hup_handler(), main(), and monitor_sig_flags().

struct { ... } sig_flags [static]

struct sigaction urg_handler [static]

Initial value:

 {
   .sa_handler = _urg_handler,
   .sa_flags = SA_RESTART,
}

Definition at line 1463 of file asterisk.c.

const char warranty_lines[] [static]

Definition at line 2005 of file asterisk.c.


Generated on Sat Mar 26 11:13:01 2011 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.9