Sat Mar 26 11:13:32 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/pbx.h"
#include "asterisk/enum.h"
#include "asterisk/rtp.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/doxyref.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 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 = { 7 }
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 = ((ast_mutex_t) 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 147 of file asterisk.c.

#define AST_MAX_CONNECTS   128

#define ASTERISK_PROMPT   "*CLI> "

Definition at line 2076 of file asterisk.c.

Referenced by cli_prompt().

#define ASTERISK_PROMPT2   "%s*CLI> "

Definition at line 2078 of file asterisk.c.

Referenced by cli_prompt().

#define DEFINE_PROFILE_MIN_MAX_VALUES

Definition at line 763 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 2585 of file asterisk.c.

Referenced by ast_el_add_history(), and ast_el_read_history().

#define NUM_MSGS   64

Definition at line 152 of file asterisk.c.

#define PF_LOCAL   PF_UNIX

Definition at line 148 of file asterisk.c.

Referenced by ast_makesocket(), and ast_tryconnect().

#define WELCOME_MESSAGE

Welcome message when starting a CLI interface.

Definition at line 155 of file asterisk.c.

Referenced by ast_el_read_char(), and main().


Function Documentation

static void __quit_handler ( int  num  )  [static]

Definition at line 1698 of file asterisk.c.

References errno, sig_alert_pipe, and sig_flags.

Referenced by main().

01699 {
01700    int a = 0;
01701    sig_flags.need_quit = 1;
01702    if (sig_alert_pipe[1] != -1) {
01703       if (write(sig_alert_pipe[1], &a, sizeof(a)) < 0) {
01704          fprintf(stderr, "quit_handler: write() failed: %s\n", strerror(errno));
01705       }
01706    }
01707    /* There is no need to restore the signal handler here, since the app
01708     * is going to exit */
01709 }

static void __remote_quit_handler ( int  num  )  [static]

Definition at line 1711 of file asterisk.c.

References sig_flags.

Referenced by ast_remotecontrol().

01712 {
01713    sig_flags.need_quit = 1;
01714 }

static void _child_handler ( int  sig  )  [static]

Definition at line 1479 of file asterisk.c.

References status.

01480 {
01481    /* Must not ever ast_log or ast_verbose within signal handler */
01482    int n, status;
01483 
01484    /*
01485     * Reap all dead children -- not just one
01486     */
01487    for (n = 0; wait4(-1, &status, WNOHANG, NULL) > 0; n++)
01488       ;
01489    if (n == 0 && option_debug)   
01490       printf("Huh?  Child handler, but nobody there?\n");
01491 }

static void _hup_handler ( int  num  )  [static]

Definition at line 1459 of file asterisk.c.

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

01460 {
01461    int a = 0;
01462    if (option_verbose > 1) 
01463       printf("Received HUP signal -- Reloading configs\n");
01464    if (restartnow)
01465       execvp(_argv[0], _argv);
01466    sig_flags.need_reload = 1;
01467    if (sig_alert_pipe[1] != -1) {
01468       if (write(sig_alert_pipe[1], &a, sizeof(a)) < 0) {
01469          fprintf(stderr, "hup_handler: write() failed: %s\n", strerror(errno));
01470       }
01471    }
01472 }

static void _null_sig_handler ( int  sig  )  [static]

NULL handler so we can collect the child exit status.

Definition at line 971 of file asterisk.c.

00972 {
00973 
00974 }

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 1449 of file asterisk.c.

01450 {
01451    return;
01452 }

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 682 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().

00683 {
00684    int l = sizeof(struct profile_data);
00685    int n = 10; /* default entries */
00686 
00687    if (prof_data == NULL) {
00688       prof_data = ast_calloc(1, l + n*sizeof(struct profile_entry));
00689       if (prof_data == NULL)
00690          return -1;
00691       prof_data->entries = 0;
00692       prof_data->max_size = n;
00693    }
00694    if (prof_data->entries >= prof_data->max_size) {
00695       void *p;
00696       n = prof_data->max_size + 20;
00697       p = ast_realloc(prof_data, l + n*sizeof(struct profile_entry));
00698       if (p == NULL)
00699          return -1;
00700       prof_data = p;
00701       prof_data->max_size = n;
00702    }
00703    n = prof_data->entries++;
00704    prof_data->e[n].name = ast_strdup(name);
00705    prof_data->e[n].value = 0;
00706    prof_data->e[n].events = 0;
00707    prof_data->e[n].mark = 0;
00708    prof_data->e[n].scale = scale;
00709    return n;
00710 }

static int ast_all_zeros ( char *  s  )  [static]

Definition at line 1758 of file asterisk.c.

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

01759 {
01760    while (*s) {
01761       if (*s > 32)
01762          return 0;
01763       s++;  
01764    }
01765    return 1;
01766 }

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

Definition at line 2384 of file asterisk.c.

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

Referenced by cli_complete().

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

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

Definition at line 338 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().

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

void ast_console_puts ( const char *  string  ) 

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

Definition at line 1153 of file asterisk.c.

References ast_network_puts().

Referenced by chan_misdn_log().

01154 {
01155    fputs(string, stdout);
01156    fflush(stdout);
01157    ast_network_puts(string);
01158 }

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 1130 of file asterisk.c.

References ast_network_puts_mutable().

Referenced by logger_print_normal().

01131 {
01132    fputs(string, stdout);
01133    fflush(stdout);
01134    ast_network_puts_mutable(string, level);
01135 }

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

Since:
1.6.1

Definition at line 1077 of file asterisk.c.

References AST_MAX_CONNECTS, consoles, and console::levels.

Referenced by handle_logger_set_level().

01078 {
01079    int x;
01080    for (x = 0;x < AST_MAX_CONNECTS; x++) {
01081       if (fd == consoles[x].fd) {
01082          consoles[x].levels[level] = state;
01083          return;
01084       }
01085    }
01086 }

void ast_console_toggle_mute ( int  fd,
int  silent 
)

mute or unmute a console from logging

Definition at line 1091 of file asterisk.c.

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

Referenced by handle_logger_mute().

01091                                                  {
01092    int x;
01093    for (x = 0;x < AST_MAX_CONNECTS; x++) {
01094       if (fd == consoles[x].fd) {
01095          if (consoles[x].mute) {
01096             consoles[x].mute = 0;
01097             if (!silent)
01098                ast_cli(fd, "Console is not muted anymore.\n");
01099          } else {
01100             consoles[x].mute = 1;
01101             if (!silent)
01102                ast_cli(fd, "Console is muted.\n");
01103          }
01104          return;
01105       }
01106    }
01107    ast_cli(fd, "Couldn't find remote console.\n");
01108 }

static int ast_el_add_history ( char *  buf  )  [static]

Definition at line 2587 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().

02588 {
02589    HistEvent ev;
02590 
02591    if (el_hist == NULL || el == NULL)
02592       ast_el_initialize();
02593    if (strlen(buf) > (MAX_HISTORY_COMMAND_LENGTH - 1))
02594       return 0;
02595    return (history(el_hist, &ev, H_ENTER, ast_strip(ast_strdupa(buf))));
02596 }

static int ast_el_initialize ( void   )  [static]

Definition at line 2550 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().

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

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

Definition at line 2104 of file asterisk.c.

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

Referenced by ast_remotecontrol().

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

static int ast_el_read_history ( char *  filename  )  [static]

Definition at line 2608 of file asterisk.c.

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

Referenced by ast_remotecontrol(), and main().

02609 {
02610    char buf[MAX_HISTORY_COMMAND_LENGTH];
02611    FILE *f;
02612    int ret = -1;
02613 
02614    if (el_hist == NULL || el == NULL)
02615       ast_el_initialize();
02616 
02617    if ((f = fopen(filename, "r")) == NULL)
02618       return ret;
02619 
02620    while (!feof(f)) {
02621       if (!fgets(buf, sizeof(buf), f))
02622          break;
02623       if (!strcmp(buf, "_HiStOrY_V2_\n"))
02624          continue;
02625       if (ast_all_zeros(buf))
02626          continue;
02627       if ((ret = ast_el_add_history(buf)) == -1)
02628          break;
02629    }
02630    fclose(f);
02631 
02632    return ret;
02633 }

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

Definition at line 2374 of file asterisk.c.

Referenced by ast_cli_display_match_list().

02375 {
02376    char *s1, *s2;
02377 
02378    s1 = ((char **)i1)[0];
02379    s2 = ((char **)i2)[0];
02380 
02381    return strcasecmp(s1, s2);
02382 }

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

Definition at line 2331 of file asterisk.c.

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

Referenced by cli_complete().

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

static int ast_el_write_history ( char *  filename  )  [static]

Definition at line 2598 of file asterisk.c.

References ast_el_initialize(), el, and el_hist.

Referenced by quit_handler().

02599 {
02600    HistEvent ev;
02601 
02602    if (el_hist == NULL || el == NULL)
02603       ast_el_initialize();
02604 
02605    return (history(el_hist, &ev, H_SAVE, filename));
02606 }

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 357 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().

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

static int ast_makesocket ( void   )  [static]

Definition at line 1352 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().

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

int64_t ast_mark ( int  i,
int  startstop 
)

Definition at line 747 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 extension_match_core().

00748 {
00749    if (!prof_data || i < 0 || i > prof_data->entries) /* invalid index */
00750       return 0;
00751    if (startstop == 1)
00752       prof_data->e[i].mark = rdtsc();
00753    else {
00754       prof_data->e[i].mark = (rdtsc() - prof_data->e[i].mark);
00755       if (prof_data->e[i].scale > 1)
00756          prof_data->e[i].mark /= prof_data->e[i].scale;
00757       prof_data->e[i].value += prof_data->e[i].mark;
00758       prof_data->e[i].events++;
00759    }
00760    return prof_data->e[i].mark;
00761 }

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

write the string to all attached console clients

Definition at line 1140 of file asterisk.c.

References AST_MAX_CONNECTS, consoles, and fdprint().

Referenced by ast_console_puts().

01141 {
01142    int x;
01143    for (x = 0; x < AST_MAX_CONNECTS; x++) {
01144       if (consoles[x].fd > -1) 
01145          fdprint(consoles[x].p[1], string);
01146    }
01147 }

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

log the string to all attached console clients

Definition at line 1113 of file asterisk.c.

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

Referenced by ast_console_puts_mutable(), and network_verboser().

01114 {
01115    int x;
01116    for (x = 0;x < AST_MAX_CONNECTS; x++) {
01117       if (consoles[x].mute)
01118          continue;
01119       if (consoles[x].fd > -1) {
01120          if (!consoles[x].levels[level]) 
01121             fdprint(consoles[x].p[1], string);
01122       }
01123    }
01124 }

int64_t ast_profile ( int  i,
int64_t  delta 
)

Definition at line 712 of file asterisk.c.

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

00713 {
00714    if (!prof_data || i < 0 || i > prof_data->entries) /* invalid index */
00715       return 0;
00716    if (prof_data->e[i].scale > 1)
00717       delta /= prof_data->e[i].scale;
00718    prof_data->e[i].value += delta;
00719    prof_data->e[i].events++;
00720    return prof_data->e[i].value;
00721 }

static void ast_readconfig ( void   )  [static]

Definition at line 2824 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_NO_COLOR, AST_OPT_FLAG_NO_FORK, AST_OPT_FLAG_QUIET, AST_OPT_FLAG_SEND_FULLYBOOTED, 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_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().

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

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 923 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_xmldoc_load_documentation(), do_reload(), load_module(), and main().

00924 {
00925    struct ast_atexit *ae;
00926 
00927    if (!(ae = ast_calloc(1, sizeof(*ae))))
00928       return -1;
00929 
00930    ae->func = func;
00931 
00932    ast_unregister_atexit(func);  
00933 
00934    AST_RWLIST_WRLOCK(&atexits);
00935    AST_RWLIST_INSERT_HEAD(&atexits, ae, list);
00936    AST_RWLIST_UNLOCK(&atexits);
00937 
00938    return 0;
00939 }

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 299 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().

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

void ast_register_thread ( char *  name  ) 

Definition at line 383 of file asterisk.c.

References ast_calloc, AST_RWLIST_INSERT_HEAD, AST_RWLIST_UNLOCK, and AST_RWLIST_WRLOCK.

Referenced by dummy_start().

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

static void ast_remotecontrol ( char *  data  )  [static]

Definition at line 2635 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, buf, el, el_hist, errno, fdsend(), hostname, LOG_ERROR, LOG_WARNING, num, prefix, remoteconsolehandler(), remotehostname, sig_flags, strsep(), and version.

Referenced by main().

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

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 991 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().

00992 {
00993    unsigned int level;
00994 
00995    ast_mutex_lock(&safe_system_lock);
00996    level = safe_system_level++;
00997 
00998    /* only replace the handler if it has not already been done */
00999    if (level == 0) {
01000       sigaction(SIGCHLD, &null_sig_handler, &safe_system_prev_handler);
01001    }
01002 
01003    ast_mutex_unlock(&safe_system_lock);
01004 }

static void ast_run_atexits ( void   )  [static]

Definition at line 1570 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().

01571 {
01572    struct ast_atexit *ae;
01573    AST_RWLIST_RDLOCK(&atexits);
01574    AST_RWLIST_TRAVERSE(&atexits, ae, list) {
01575       if (ae->func) 
01576          ae->func();
01577    }
01578    AST_RWLIST_UNLOCK(&atexits);
01579 }

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 1021 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().

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

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 1536 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().

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

static int ast_tryconnect ( void   )  [static]

Definition at line 1422 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().

01423 {
01424    struct sockaddr_un sunaddr;
01425    int res;
01426    ast_consock = socket(PF_LOCAL, SOCK_STREAM, 0);
01427    if (ast_consock < 0) {
01428       ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
01429       return 0;
01430    }
01431    memset(&sunaddr, 0, sizeof(sunaddr));
01432    sunaddr.sun_family = AF_LOCAL;
01433    ast_copy_string(sunaddr.sun_path, ast_config_AST_SOCKET, sizeof(sunaddr.sun_path));
01434    res = connect(ast_consock, (struct sockaddr *)&sunaddr, sizeof(sunaddr));
01435    if (res) {
01436       close(ast_consock);
01437       ast_consock = -1;
01438       return 0;
01439    } else
01440       return 1;
01441 }

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 941 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().

00942 {
00943    struct ast_atexit *ae = NULL;
00944 
00945    AST_RWLIST_WRLOCK(&atexits);
00946    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&atexits, ae, list) {
00947       if (ae->func == func) {
00948          AST_RWLIST_REMOVE_CURRENT(list);
00949          break;
00950       }
00951    }
00952    AST_RWLIST_TRAVERSE_SAFE_END;
00953    AST_RWLIST_UNLOCK(&atexits);
00954 
00955    free(ae);
00956 }

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 320 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.

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

void ast_unregister_thread ( void *  id  ) 

Definition at line 396 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().

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

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 1006 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().

01007 {
01008    unsigned int level;
01009 
01010    ast_mutex_lock(&safe_system_lock);
01011    level = --safe_system_level;
01012 
01013    /* only restore the handler if we are the last one */
01014    if (level == 0) {
01015       sigaction(SIGCHLD, &safe_system_prev_handler, NULL);
01016    }
01017 
01018    ast_mutex_unlock(&safe_system_lock);
01019 }

static void canary_exit ( void   )  [static]

Definition at line 3103 of file asterisk.c.

References canary_pid.

Referenced by main().

03104 {
03105    if (canary_pid > 0)
03106       kill(canary_pid, SIGKILL);
03107 }

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

Definition at line 3080 of file asterisk.c.

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

Referenced by main().

03081 {
03082    struct stat canary_stat;
03083    struct timeval now;
03084 
03085    /* Give the canary time to sing */
03086    sleep(120);
03087 
03088    for (;;) {
03089       stat(canary_filename, &canary_stat);
03090       now = ast_tvnow();
03091       if (now.tv_sec > canary_stat.st_mtime + 60) {
03092          ast_log(LOG_WARNING, "The canary is no more.  He has ceased to be!  He's expired and gone to meet his maker!  He's a stiff!  Bereft of life, he rests in peace.  His metabolic processes are now history!  He's off the twig!  He's kicked the bucket.  He's shuffled off his mortal coil, run down the curtain, and joined the bleeding choir invisible!!  THIS is an EX-CANARY.  (Reducing priority)\n");
03093          ast_set_priority(0);
03094          pthread_exit(NULL);
03095       }
03096 
03097       /* Check the canary once a minute */
03098       sleep(60);
03099    }
03100 }

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

Definition at line 2432 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, buf, and fdsend().

Referenced by ast_el_initialize().

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

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

Definition at line 2204 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().

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

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

Definition at line 1733 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().

01734 {
01735    char tmp[80];
01736    const char *c = NULL;
01737 
01738    if ((c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_4)) ||
01739        (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_3)) ||
01740        (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_2)) ||
01741        (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_1))) {
01742       fputs(tmp, stdout);
01743       fputs(c, stdout);
01744    } else {
01745       if (*s == 127) {
01746          s++;
01747       }
01748       fputs(s, stdout);
01749    }
01750 
01751    fflush(stdout);
01752    
01753    /* Wake up a poll()ing console */
01754    if (ast_opt_console && consolethread != AST_PTHREADT_NULL)
01755       pthread_kill(consolethread, SIGURG);
01756 }

static void consolehandler ( char *  s  )  [static]

Definition at line 1768 of file asterisk.c.

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

Referenced by main().

01769 {
01770    printf("%s", term_end());
01771    fflush(stdout);
01772 
01773    /* Called when readline data is available */
01774    if (!ast_all_zeros(s))
01775       ast_el_add_history(s);
01776    /* The real handler for bang */
01777    if (s[0] == '!') {
01778       if (s[1])
01779          ast_safe_system(s+1);
01780       else
01781          ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
01782    } else 
01783       ast_cli_command(STDOUT_FILENO, s);
01784 }

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

Definition at line 965 of file asterisk.c.

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

00966 {
00967    return write(fd, s, strlen(s));
00968 }

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

Definition at line 959 of file asterisk.c.

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

00960 {
00961    return write(fd, s, strlen(s) + 1);
00962 }

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

Definition at line 1716 of file asterisk.c.

References COLOR_GRAY, and term_color().

Referenced by console_verboser().

01717 {
01718    const char *c;
01719 
01720    /* Check for verboser preamble */
01721    if (*s == 127) {
01722       s++;
01723    }
01724 
01725    if (!strncmp(s, cmp, strlen(cmp))) {
01726       c = s + strlen(cmp);
01727       term_color(outbuf, cmp, COLOR_GRAY, 0, maxout);
01728       return c;
01729    }
01730    return NULL;
01731 }

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

Definition at line 1960 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.

01961 {
01962    switch (cmd) {
01963    case CLI_INIT:
01964       e->command = "core abort shutdown";
01965       e->usage = 
01966          "Usage: core abort shutdown\n"
01967          "       Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
01968          "       call operations.\n";
01969       return NULL;
01970    case CLI_GENERATE:
01971       return NULL;
01972    }
01973 
01974    if (a->argc != e->args)
01975       return CLI_SHOWUSAGE;
01976    ast_cancel_shutdown();
01977    shuttingdown = 0;
01978    return CLI_SUCCESS;
01979 }

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

Definition at line 1981 of file asterisk.c.

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

01982 {
01983    switch (cmd) {
01984    case CLI_INIT:
01985       e->command = "!";
01986       e->usage = 
01987          "Usage: !<command>\n"
01988          "       Executes a given shell command\n";
01989       return NULL;
01990    case CLI_GENERATE:
01991       return NULL;
01992    }
01993 
01994    return CLI_SUCCESS;
01995 }

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

Definition at line 811 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.

00812 {
00813    int i, min, max;
00814    char *search = NULL;
00815    switch (cmd) {
00816    case CLI_INIT:
00817       e->command = "core clear profile";
00818       e->usage = "Usage: core clear profile\n"
00819             "       clear profile information";
00820       return NULL;
00821    case CLI_GENERATE:
00822       return NULL;
00823    }
00824 
00825    if (prof_data == NULL)
00826       return 0;
00827 
00828    DEFINE_PROFILE_MIN_MAX_VALUES;
00829    for (i= min; i < max; i++) {
00830       if (!search || strstr(prof_data->e[i].name, search)) {
00831          prof_data->e[i].value = 0;
00832          prof_data->e[i].events = 0;
00833       }
00834    }
00835    return CLI_SUCCESS;
00836 }

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

Definition at line 1920 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.

01921 {
01922    switch (cmd) {
01923    case CLI_INIT:
01924       e->command = "core restart gracefully";
01925       e->usage = 
01926          "Usage: core restart gracefully\n"
01927          "       Causes Asterisk to stop accepting new calls and exec() itself performing a cold\n"
01928          "       restart when all active calls have ended.\n";
01929       return NULL;
01930    case CLI_GENERATE:
01931       return NULL;
01932    }
01933 
01934    if (a->argc != e->args)
01935       return CLI_SHOWUSAGE;
01936    quit_handler(0, 1 /* nicely */, 1 /* safely */, 1 /* restart */);
01937    return CLI_SUCCESS;
01938 }

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

Definition at line 1900 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.

01901 {
01902    switch (cmd) {
01903    case CLI_INIT:
01904       e->command = "core restart now";
01905       e->usage = 
01906          "Usage: core restart now\n"
01907          "       Causes Asterisk to hangup all calls and exec() itself performing a cold\n"
01908          "       restart.\n";
01909       return NULL;
01910    case CLI_GENERATE:
01911       return NULL;
01912    }
01913 
01914    if (a->argc != e->args)
01915       return CLI_SHOWUSAGE;
01916    quit_handler(0, 0 /* not nicely */, 1 /* safely */, 1 /* restart */);
01917    return CLI_SUCCESS;
01918 }

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

Definition at line 1940 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.

01941 {
01942    switch (cmd) {
01943    case CLI_INIT:
01944       e->command = "core restart when convenient";
01945       e->usage = 
01946          "Usage: core restart when convenient\n"
01947          "       Causes Asterisk to perform a cold restart when all active calls have ended.\n";
01948       return NULL;
01949    case CLI_GENERATE:
01950       return NULL;
01951    }
01952 
01953    if (a->argc != e->args)
01954       return CLI_SHOWUSAGE;
01955    ast_cli(a->fd, "Waiting for inactivity to perform restart\n");
01956    quit_handler(0, 2 /* really nicely */, 1 /* safely */, 1 /* restart */);
01957    return CLI_SUCCESS;
01958 }

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

Definition at line 776 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.

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

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 416 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_CONFIG_DIR, ast_config_AST_CONFIG_FILE, ast_config_AST_LOG_DIR, ast_config_AST_MODULE_DIR, ast_config_AST_RUN_GROUP, ast_config_AST_RUN_USER, ast_config_AST_SPOOL_DIR, ast_config_AST_SYSTEM_NAME, 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_opt_send_fullybooted, ast_realtime_enabled(), ast_startuptime, ast_strftime(), ast_test_flag, buf, 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.

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

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 565 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.

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

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

Definition at line 493 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.

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

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 840 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.

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

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

Definition at line 1860 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.

01861 {
01862    switch (cmd) {
01863    case CLI_INIT:
01864       e->command = "core stop gracefully";
01865       e->usage = 
01866          "Usage: core stop gracefully\n"
01867          "       Causes Asterisk to not accept new calls, and exit when all\n"
01868          "       active calls have terminated normally.\n";
01869       return NULL;
01870    case CLI_GENERATE:
01871       return NULL;
01872    }
01873 
01874    if (a->argc != e->args)
01875       return CLI_SHOWUSAGE;
01876    quit_handler(0, 1 /* nicely */, 1 /* safely */, 0 /* no restart */);
01877    return CLI_SUCCESS;
01878 }

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

Definition at line 1841 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.

01842 {
01843    switch (cmd) {
01844    case CLI_INIT:
01845       e->command = "core stop now";
01846       e->usage = 
01847          "Usage: core stop now\n"
01848          "       Shuts down a running Asterisk immediately, hanging up all active calls .\n";
01849       return NULL;
01850    case CLI_GENERATE:
01851       return NULL;
01852    }
01853 
01854    if (a->argc != e->args)
01855       return CLI_SHOWUSAGE;
01856    quit_handler(0, 0 /* Not nice */, 1 /* safely */, 0 /* not restart */);
01857    return CLI_SUCCESS;
01858 }

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

Definition at line 1880 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.

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

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

Definition at line 1810 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.

01811 {
01812    switch (cmd) {
01813    case CLI_INIT:
01814       e->command = "core show version";
01815       e->usage = 
01816          "Usage: core show version\n"
01817          "       Shows Asterisk version information.\n";
01818       return NULL;
01819    case CLI_GENERATE:
01820       return NULL;
01821    }
01822 
01823    if (a->argc != 3)
01824       return CLI_SHOWUSAGE;
01825    ast_cli(a->fd, "Asterisk %s built by %s @ %s on a %s running %s on %s\n",
01826       ast_get_version(), ast_build_user, ast_build_hostname,
01827       ast_build_machine, ast_build_os, ast_build_date);
01828    return CLI_SUCCESS;
01829 }

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

Definition at line 1275 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(), s, and console::uid.

Referenced by ast_makesocket().

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

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

Definition at line 3137 of file asterisk.c.

References __ast_mm_init(), __quit_handler(), _argv, ARRAY_LEN, ast_alaw_init(), ast_autoservice_init(), ast_builtins_init(), ast_cdr_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_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_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_opt_send_fullybooted, ast_pbx_init(), ast_process_pending_reloads(), ast_pthread_create_detached, ast_readconfig(), ast_register_atexit(), ast_register_verbose(), ast_remotecontrol(), ast_rtp_init(), ast_select(), ast_set_flag, ast_set_priority(), ast_ssl_init(), ast_startuptime, ast_strdupa, ast_strlen_zero(), 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(), buf, callerid_init(), canary_exit(), canary_filename, canary_pid, canary_thread(), cfg_paths, COLOR_BLACK, COLOR_BRWHITE, _cfg_paths::config_file, console_verboser(), consolehandler(), consolethread, dir, dnsmgr_init(), dnsmgr_start_refresh(), el, el_hist, 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(), num, 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.

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

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

Definition at line 3059 of file asterisk.c.

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

Referenced by main().

03060 {
03061    for (;;) {
03062       struct pollfd p = { sig_alert_pipe[0], POLLIN, 0 };
03063       int a;
03064       ast_poll(&p, 1, -1);
03065       if (sig_flags.need_reload) {
03066          sig_flags.need_reload = 0;
03067          ast_module_reload(NULL);
03068       }
03069       if (sig_flags.need_quit) {
03070          sig_flags.need_quit = 0;
03071          quit_handler(0, 0, 1, 0);
03072       }
03073       if (read(sig_alert_pipe[0], &a, sizeof(a)) != sizeof(a)) {
03074       }
03075    }
03076 
03077    return NULL;
03078 }

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

Definition at line 1215 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().

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

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

Definition at line 1160 of file asterisk.c.

References __LOG_VERBOSE, and ast_network_puts_mutable().

Referenced by ast_makesocket().

01161 {
01162    ast_network_puts_mutable(s, __LOG_VERBOSE);
01163 }

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

Definition at line 1581 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().

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

static __inline uint64_t rdtsc ( void   )  [static]

Definition at line 741 of file asterisk.c.

Referenced by ast_mark().

00742 {
00743    return 0;
00744 }

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 1177 of file asterisk.c.

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

Referenced by netconsole().

01178 {
01179 #if defined(SO_PEERCRED)
01180    struct ucred cred;
01181    socklen_t len = sizeof(cred);
01182 #endif
01183 #if defined(HAVE_GETPEEREID)
01184    uid_t uid;
01185    gid_t gid;
01186 #else
01187    int uid, gid;
01188 #endif
01189    int result;
01190 
01191    result = read(fd, buffer, size);
01192    if (result < 0) {
01193       return result;
01194    }
01195 
01196 #if defined(SO_PEERCRED)
01197    if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &len)) {
01198       return result;
01199    }
01200    uid = cred.uid;
01201    gid = cred.gid;
01202 #elif defined(HAVE_GETPEEREID)
01203    if (getpeereid(fd, &uid, &gid)) {
01204       return result;
01205    }
01206 #else
01207    return result;
01208 #endif
01209    con->uid = uid;
01210    con->gid = gid;
01211 
01212    return result;
01213 }

static int remoteconsolehandler ( char *  s  )  [static]

Definition at line 1786 of file asterisk.c.

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

Referenced by ast_remotecontrol().

01787 {
01788    int ret = 0;
01789 
01790    /* Called when readline data is available */
01791    if (!ast_all_zeros(s))
01792       ast_el_add_history(s);
01793    /* The real handler for bang */
01794    if (s[0] == '!') {
01795       if (s[1])
01796          ast_safe_system(s+1);
01797       else
01798          ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
01799       ret = 1;
01800    }
01801    if ((strncasecmp(s, "quit", 4) == 0 || strncasecmp(s, "exit", 4) == 0) &&
01802        (s[4] == '\0' || isspace(s[4]))) {
01803       quit_handler(0, 0, 0, 0);
01804       ret = 1;
01805    }
01806 
01807    return ret;
01808 }

static void run_startup_commands ( void   )  [static]

Definition at line 3109 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().

03110 {
03111    int fd;
03112    struct ast_config *cfg;
03113    struct ast_flags cfg_flags = { 0 };
03114    struct ast_variable *v;
03115 
03116    if (!(cfg = ast_config_load2("cli.conf", "" /* core, can't reload */, cfg_flags)))
03117       return;
03118    if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
03119       return;
03120    }
03121 
03122    fd = open("/dev/null", O_RDWR);
03123    if (fd < 0) {
03124       ast_config_destroy(cfg);
03125       return;
03126    }
03127 
03128    for (v = ast_variable_browse(cfg, "startup_commands"); v; v = v->next) {
03129       if (ast_true(v->value))
03130          ast_cli_command(fd, v->name);
03131    }
03132 
03133    close(fd);
03134    ast_config_destroy(cfg);
03135 }

static void set_icon ( char *  text  )  [static]

Definition at line 1528 of file asterisk.c.

Referenced by main().

01529 {
01530    if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
01531       fprintf(stdout, "\033]1;%s\007", text);
01532 }

static void set_title ( char *  text  )  [static]

Set an X-term or screen title.

Definition at line 1522 of file asterisk.c.

Referenced by main().

01523 {
01524    if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
01525       fprintf(stdout, "\033]2;%s\007", text);
01526 }

static void set_ulimit ( int  value  )  [static]

Set maximum open files.

Definition at line 1499 of file asterisk.c.

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

Referenced by ast_readconfig().

01500 {
01501    struct rlimit l = {0, 0};
01502    
01503    if (value <= 0) {
01504       ast_log(LOG_WARNING, "Unable to change max files open to invalid value %i\n",value);
01505       return;
01506    }
01507    
01508    l.rlim_cur = value;
01509    l.rlim_max = value;
01510    
01511    if (setrlimit(RLIMIT_NOFILE, &l)) {
01512       ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n",strerror(errno));
01513       return;
01514    }
01515    
01516    ast_log(LOG_NOTICE, "Setting max files open to %d\n",value);
01517    
01518    return;
01519 }

static int show_cli_help ( void   )  [static]

Definition at line 2786 of file asterisk.c.

References ast_get_version().

Referenced by main().

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

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

Definition at line 2058 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.

02059 {
02060    switch (cmd) {
02061    case CLI_INIT:
02062       e->command = "core show license";
02063       e->usage = 
02064          "Usage: core show license\n"
02065          "       Shows the license(s) for this copy of Asterisk.\n";
02066       return NULL;
02067    case CLI_GENERATE:
02068       return NULL;
02069    }
02070 
02071    ast_cli(a->fd, "%s", license_lines);
02072 
02073    return CLI_SUCCESS;
02074 }

static int show_version ( void   )  [static]

Definition at line 2780 of file asterisk.c.

References ast_get_version().

Referenced by main().

02781 {
02782    printf("Asterisk %s\n", ast_get_version());
02783    return 0;
02784 }

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

Definition at line 2021 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.

02022 {
02023    switch (cmd) {
02024    case CLI_INIT:
02025       e->command = "core show warranty";
02026       e->usage = 
02027          "Usage: core show warranty\n"
02028          "       Shows the warranty (if any) for this copy of Asterisk.\n";
02029       return NULL;
02030    case CLI_GENERATE:
02031       return NULL;
02032    }
02033 
02034    ast_cli(a->fd, "%s", warranty_lines);
02035 
02036    return CLI_SUCCESS;
02037 }


Variable Documentation

char* _argv[256] [static]

Definition at line 274 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 256 of file asterisk.c.

Referenced by launch_script().

const char* ast_config_AST_CONFIG_DIR = cfg_paths.config_dir

Definition at line 249 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 270 of file asterisk.c.

Referenced by ast_readconfig().

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

Definition at line 269 of file asterisk.c.

Referenced by ast_makesocket(), and ast_readconfig().

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

Definition at line 268 of file asterisk.c.

Referenced by ast_makesocket(), and ast_readconfig().

char ast_config_AST_CTL_PERMISSIONS[PATH_MAX] [static]

Definition at line 267 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 260 of file asterisk.c.

Referenced by dbinit().

const char* ast_config_AST_KEY_DIR = cfg_paths.key_dir

Definition at line 257 of file asterisk.c.

Referenced by crypto_load(), handle_cli_keys_init(), launch_script(), and osp_create_provider().

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

Definition at line 261 of file asterisk.c.

Referenced by main(), and quit_handler().

const char* ast_config_AST_RUN_DIR = cfg_paths.run_dir

Definition at line 258 of file asterisk.c.

Referenced by launch_script(), and main().

const char* ast_config_AST_RUN_GROUP = cfg_paths.run_group

Definition at line 264 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 263 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 262 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 253 of file asterisk.c.

Referenced by ael2_semantic_check(), and launch_script().

int ast_consock = -1 [static]

UNIX Socket for controlling another asterisk

Definition at line 191 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 185 of file asterisk.c.

Referenced by ast_event_cb(), ast_event_new(), ast_readconfig(), evt_event_deliver_cb(), handle_show_settings(), pbx_retrieve_variable(), 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 192 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 190 of file asterisk.c.

struct timeval ast_startuptime

char canary_filename[128] [static]

Definition at line 280 of file asterisk.c.

Referenced by canary_thread(), and main().

int canary_pid = 0 [static]

Definition at line 279 of file asterisk.c.

Referenced by canary_exit(), and main().

struct _cfg_paths cfg_paths [static]

Definition at line 246 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 1493 of file asterisk.c.

struct ast_cli_entry cli_asterisk[] [static]

Definition at line 2080 of file asterisk.c.

struct console consoles[AST_MAX_CONNECTS]

pthread_t consolethread = AST_PTHREADT_NULL [static]

Definition at line 277 of file asterisk.c.

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

char defaultlanguage[MAX_LANGUAGE] = DEFAULT_LANGUAGE

Definition at line 219 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 1474 of file asterisk.c.

struct sigaction ignore_sig_handler [static]

Initial value:

 {
   .sa_handler = SIG_IGN,
}

Definition at line 981 of file asterisk.c.

Referenced by main().

const char license_lines[] [static]

Definition at line 2039 of file asterisk.c.

pthread_t lthread [static]

Definition at line 1165 of file asterisk.c.

Referenced by ast_makesocket(), and quit_handler().

pthread_t mon_sig_flags [static]

Definition at line 278 of file asterisk.c.

Referenced by main(), and quit_handler().

unsigned int need_quit

Definition at line 287 of file asterisk.c.

unsigned int need_reload

Definition at line 286 of file asterisk.c.

struct sigaction null_sig_handler [static]

Initial value:

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

Definition at line 976 of file asterisk.c.

Referenced by ast_replace_sigchld().

struct profile_data* prof_data [static]

struct ast_str* prompt = NULL [static]

Definition at line 2202 of file asterisk.c.

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

char randompool[256] [static]

Definition at line 282 of file asterisk.c.

Referenced by main().

char record_cache_dir[AST_CACHE_DIR_LEN] = DEFAULT_TMP_DIR

Definition at line 188 of file asterisk.c.

Referenced by ast_writefile().

char* remotehostname [static]

Definition at line 215 of file asterisk.c.

Referenced by ast_remotecontrol(), and cli_prompt().

int restartnow [static]

Definition at line 276 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 988 of file asterisk.c.

Referenced by ast_replace_sigchld(), and ast_unreplace_sigchld().

ast_mutex_t safe_system_lock = ((ast_mutex_t) PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP ) [static]

Definition at line 985 of file asterisk.c.

Referenced by ast_replace_sigchld(), and ast_unreplace_sigchld().

struct sigaction safe_system_prev_handler [static]

Definition at line 989 of file asterisk.c.

Referenced by ast_replace_sigchld(), and ast_unreplace_sigchld().

int shuttingdown [static]

Definition at line 275 of file asterisk.c.

Referenced by handle_abort_shutdown(), and quit_handler().

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

Definition at line 284 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 1454 of file asterisk.c.

const char warranty_lines[] [static]

Definition at line 1996 of file asterisk.c.


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