Asterisk - The Open Source Telephony Project  GIT-master-9ed6387
Data Structures | Macros | Enumerations | Functions | Variables
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 <histedit.h>
#include "asterisk/paths.h"
#include "asterisk/network.h"
#include "asterisk/cli.h"
#include "asterisk/channel.h"
#include "asterisk/translate.h"
#include "asterisk/pickup.h"
#include "asterisk/acl.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/app.h"
#include "asterisk/mwi.h"
#include "asterisk/lock.h"
#include "asterisk/utils.h"
#include "asterisk/file.h"
#include "asterisk/io.h"
#include "asterisk/config.h"
#include "asterisk/ast_version.h"
#include "asterisk/linkedlists.h"
#include "asterisk/devicestate.h"
#include "asterisk/presencestate.h"
#include "asterisk/module.h"
#include "asterisk/buildinfo.h"
#include "asterisk/xmldoc.h"
#include "asterisk/poll-compat.h"
#include "asterisk/test.h"
#include "asterisk/rtp_engine.h"
#include "asterisk/format.h"
#include "asterisk/aoc.h"
#include "asterisk/uuid.h"
#include "asterisk/sorcery.h"
#include "asterisk/bucket.h"
#include "asterisk/stasis.h"
#include "asterisk/json.h"
#include "asterisk/stasis_endpoints.h"
#include "asterisk/stasis_system.h"
#include "asterisk/security_events.h"
#include "asterisk/endpoints.h"
#include "asterisk/codec.h"
#include "asterisk/format_cache.h"
#include "asterisk/media_cache.h"
#include "asterisk/astdb.h"
#include "asterisk/options.h"
#include "asterisk/utf8.h"
#include "../defaults.h"

Go to the source code of this file.

Data Structures

struct  ast_atexit
 
struct  atexits
 
struct  console
 
struct  console_state_data
 
struct  profile_data
 
struct  profile_entry
 
struct  thread_list
 
struct  thread_list_t
 

Macros

#define AF_LOCAL   AF_UNIX
 
#define AST_MAX_CONNECTS   128
 
#define ASTERISK_PROMPT   "*CLI> "
 
#define CHAR_T_LIBEDIT   wchar_t
 
#define CHAR_TO_LIBEDIT(c)   btowc(c)
 
#define CMD_MATCHESARRAY   "_COMMAND MATCHESARRAY \"%s\" \"%s\""
 
#define COPYRIGHT_TAG   "Copyright (C) 1999 - 2018, Digium, Inc. and others."
 
#define DEFINE_PROFILE_MIN_MAX_VALUES
 
#define EL_BUF_SIZE   512
 
#define MAX_HISTORY_COMMAND_LENGTH   256
 
#define NUM_MSGS   64
 
#define PF_LOCAL   PF_UNIX
 
#define SHUTDOWN_TIMEOUT   15 /* Seconds */
 
#define WELCOME_MESSAGE
 Welcome message when starting a CLI interface. More...
 

Enumerations

enum  shutdown_nice_t {
  NOT_SHUTTING_DOWN, SHUTTING_DOWN_FINAL, SHUTTING_DOWN, SHUTDOWN_FAST,
  SHUTDOWN_NORMAL, SHUTDOWN_NICE, SHUTDOWN_REALLY_NICE
}
 

Functions

static void __ast_unregister_atexit (void(*func)(void))
 
static void __init_console_state (void)
 
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. More...
 
static void _urg_handler (int num)
 Urgent handler. More...
 
int ast_add_profile (const char *name, uint64_t scale)
 allocates a counter with a given name and scale. More...
 
static int ast_all_zeros (const char *s)
 
static void ast_begin_shutdown (void)
 
int ast_cancel_shutdown (void)
 Cancel an existing shutdown and return to normal operation. More...
 
static void ast_cli_display_match_list (struct ast_vector_string *matches, int max)
 
void ast_console_puts (const char *string)
 write the string to the root console, and all attached network console clients More...
 
void ast_console_puts_mutable (const char *string, int level)
 log the string to the root console, and all attached network console clients More...
 
void ast_console_puts_mutable_full (const char *message, int level, int sublevel)
 log the string to the console, and all attached console clients More...
 
void ast_console_toggle_loglevel (int fd, int level, int state)
 enable or disable a logging level to a specified console More...
 
void ast_console_toggle_mute (int fd, int silent)
 mute or unmute a console from logging More...
 
static int ast_el_add_history (const char *)
 
static int ast_el_initialize (void)
 
static int ast_el_read_char (EditLine *editline, CHAR_T_LIBEDIT *cp)
 
static void ast_el_read_default_histfile (void)
 
static int ast_el_read_history (const char *)
 
static struct ast_vector_string * ast_el_strtoarr (char *buf)
 
static void ast_el_write_default_histfile (void)
 
static int ast_el_write_history (const char *)
 
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 More...
 
static void ast_network_puts_mutable (const char *string, int level, int sublevel)
 log the string to all attached network console clients More...
 
int ast_pbx_uuid_get (char *pbx_uuid, int length)
 Retrieve the PBX UUID. More...
 
int64_t ast_profile (int i, int64_t delta)
 
int ast_register_atexit (void(*func)(void))
 Register a function to be executed before Asterisk exits. More...
 
int ast_register_cleanup (void(*func)(void))
 Register a function to be executed before Asterisk gracefully exits. More...
 
void ast_register_thread (char *name)
 
static void ast_remotecontrol (char *data)
 
void ast_replace_sigchld (void)
 Replace the SIGCHLD handler. More...
 
static void ast_run_atexits (int run_cleanups)
 
int ast_safe_execvp (int dualfork, const char *file, char *const argv[])
 Safely spawn an external program while closing file descriptors. More...
 
int ast_safe_system (const char *s)
 Safely spawn an OS shell command while closing file descriptors. More...
 
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. More...
 
int ast_shutdown_final (void)
 
int ast_shutting_down (void)
 
static int ast_tryconnect (void)
 
void ast_unregister_atexit (void(*func)(void))
 Unregister a function registered with ast_register_atexit(). More...
 
void ast_unregister_thread (void *id)
 
void ast_unreplace_sigchld (void)
 Restore the SIGCHLD handler. More...
 
static void asterisk_daemon (int isroot, const char *runuser, const char *rungroup)
 
static int can_safely_quit (shutdown_nice_t niceness, int restart)
 
static void canary_exit (void)
 
static void * canary_thread (void *unused)
 
static void check_init (int init_result, const char *name)
 
static char * cli_complete (EditLine *editline, int ch)
 
static char * cli_prompt (EditLine *editline)
 
static int console_print (const char *s)
 
static int console_state_init (void *ptr)
 
static void consolehandler (const char *s)
 
static void env_init (void)
 
static int fdprint (int fd, const char *s)
 
static int fdsend (int fd, const char *s)
 
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. More...
 
static char * handle_show_sysinfo (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 Give an overview of system statistics. More...
 
static char * handle_show_threads (struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 
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 int has_priority (void)
 Check whether we were set to high(er) priority. More...
 
static void * listener (void *unused)
 
int main (int argc, char *argv[])
 
static void main_atexit (void)
 
static void * monitor_sig_flags (void *unused)
 
static void * netconsole (void *vconsole)
 
static void print_intro_message (const char *runuser, const char *rungroup)
 
static void publish_fully_booted (void)
 
static void quit_handler (int num, shutdown_nice_t niceness, 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. More...
 
static void read_pjproject_startup_options (void)
 
static void really_quit (int num, shutdown_nice_t niceness, int restart)
 
static int register_atexit (void(*func)(void), int is_cleanup)
 
static int remoteconsolehandler (const char *s)
 
static void run_startup_commands (void)
 
static pid_t safe_exec_prep (int dualfork)
 fork and perform other preparations for spawning applications More...
 
static int safe_exec_wait (pid_t pid)
 wait for spawned application to complete and unreplace sigchld More...
 
static void send_rasterisk_connect_commands (void)
 
static void set_header (char *outbuf, int maxout, char level)
 
static void set_icon (char *text)
 
static int set_priority_all (int pri)
 Set priority on all known threads. More...
 
static void set_title (char *text)
 Set an X-term or screen title. More...
 
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)
 
static int wait_for_channels_to_die (shutdown_nice_t niceness, int seconds)
 

Variables

static char * _argv [256]
 
static int ast_consock = -1
 
struct timeval ast_lastreloadtime
 
pid_t ast_mainpid
 
static int ast_socket = -1
 
static int ast_socket_is_sd = 0
 
struct timeval ast_startuptime
 
static struct atexits atexits = { .first = NULL, .last = NULL, .lock = { PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP , NULL, {1, 0} } , }
 
static char canary_filename [128]
 
static int canary_pid = 0
 
static struct sigaction child_handler
 
static struct ast_cli_entry cli_asterisk []
 
static struct ast_cli_entry cli_asterisk_shutdown []
 Shutdown Asterisk CLI commands. More...
 
static struct ast_threadstorage console_state = { .once = PTHREAD_ONCE_INIT , .key_init = __init_console_state , .custom_init = console_state_init , }
 
struct console consoles [AST_MAX_CONNECTS]
 
static pthread_t consolethread = AST_PTHREADT_NULL
 
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 int multi_thread_safe
 
static struct sigaction null_sig_handler
 
static struct profile_dataprof_data
 
static struct ast_strprompt = NULL
 
static char randompool [256]
 
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. More...
 
static ast_mutex_t safe_system_lock = { PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP , NULL, {1, 0} }
 
static struct sigaction safe_system_prev_handler
 
static int shutdown_pending
 
static shutdown_nice_t shuttingdown = NOT_SHUTTING_DOWN
 
static int sig_alert_pipe [2] = { -1, -1 }
 
struct {
   unsigned int   need_el_end:1
 
   unsigned int   need_quit:1
 
   unsigned int   need_quit_handler:1
 
   unsigned int   need_reload:1
 
sig_flags
 
static struct thread_list thread_list = { .first = NULL, .last = NULL, .lock = { PTHREAD_RWLOCK_INITIALIZER , NULL, {1, 0} } , }
 
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.

Macro Definition Documentation

◆ AF_LOCAL

#define AF_LOCAL   AF_UNIX

Definition at line 292 of file asterisk.c.

Referenced by ast_makesocket(), ast_tryconnect(), and listener().

◆ AST_MAX_CONNECTS

#define AST_MAX_CONNECTS   128

◆ ASTERISK_PROMPT

#define ASTERISK_PROMPT   "*CLI> "

Definition at line 2554 of file asterisk.c.

Referenced by cli_prompt().

◆ CHAR_T_LIBEDIT

#define CHAR_T_LIBEDIT   wchar_t

Definition at line 2619 of file asterisk.c.

◆ CHAR_TO_LIBEDIT

#define CHAR_TO_LIBEDIT (   c)    btowc(c)

Definition at line 2620 of file asterisk.c.

Referenced by ast_el_read_char().

◆ CMD_MATCHESARRAY

#define CMD_MATCHESARRAY   "_COMMAND MATCHESARRAY \"%s\" \"%s\""

Referenced by cli_complete().

◆ COPYRIGHT_TAG

#define COPYRIGHT_TAG   "Copyright (C) 1999 - 2018, Digium, Inc. and others."

Displayed copyright tag

Definition at line 300 of file asterisk.c.

Referenced by show_cli_help().

◆ DEFINE_PROFILE_MIN_MAX_VALUES

#define DEFINE_PROFILE_MIN_MAX_VALUES

Definition at line 856 of file asterisk.c.

Referenced by handle_clear_profile(), and handle_show_profile().

◆ EL_BUF_SIZE

#define EL_BUF_SIZE   512

Referenced by ast_el_read_char().

◆ MAX_HISTORY_COMMAND_LENGTH

#define MAX_HISTORY_COMMAND_LENGTH   256

Definition at line 3076 of file asterisk.c.

Referenced by ast_el_add_history().

◆ NUM_MSGS

#define NUM_MSGS   64

Definition at line 297 of file asterisk.c.

◆ PF_LOCAL

#define PF_LOCAL   PF_UNIX

Definition at line 293 of file asterisk.c.

Referenced by ast_makesocket(), ast_tryconnect(), and ooh323c_start_call_thread().

◆ SHUTDOWN_TIMEOUT

#define SHUTDOWN_TIMEOUT   15 /* Seconds */

Definition at line 1878 of file asterisk.c.

Referenced by can_safely_quit().

◆ WELCOME_MESSAGE

#define WELCOME_MESSAGE

Welcome message when starting a CLI interface.

Definition at line 303 of file asterisk.c.

Referenced by ast_el_read_char(), and print_intro_message().

Enumeration Type Documentation

◆ shutdown_nice_t

Enumerator
NOT_SHUTTING_DOWN 

Normal operation

SHUTTING_DOWN_FINAL 

Committed to shutting down. Final phase

SHUTTING_DOWN 

Committed to shutting down. Initial phase

SHUTDOWN_FAST 

Valid values for quit_handler() niceness below. These shutdown/restart levels can be cancelled.

Remote console exit right now

SHUTDOWN_NORMAL 

core stop/restart now

SHUTDOWN_NICE 

core stop/restart gracefully

SHUTDOWN_REALLY_NICE 

core stop/restart when convenient

Definition at line 356 of file asterisk.c.

356  {
357  /*! Normal operation */
359  /*! Committed to shutting down. Final phase */
361  /*! Committed to shutting down. Initial phase */
363  /*!
364  * Valid values for quit_handler() niceness below.
365  * These shutdown/restart levels can be cancelled.
366  *
367  * Remote console exit right now
368  */
370  /*! core stop/restart now */
372  /*! core stop/restart gracefully */
374  /*! core stop/restart when convenient */
shutdown_nice_t
Definition: asterisk.c:356

Function Documentation

◆ __ast_unregister_atexit()

static void __ast_unregister_atexit ( void(*)(void)  func)
static

Definition at line 979 of file asterisk.c.

References ast_free, AST_LIST_REMOVE_CURRENT, AST_LIST_TRAVERSE_SAFE_BEGIN, AST_LIST_TRAVERSE_SAFE_END, ast_atexit::func, and ast_atexit::list.

Referenced by ast_unregister_atexit(), and register_atexit().

980 {
981  struct ast_atexit *ae;
982 
984  if (ae->func == func) {
986  ast_free(ae);
987  break;
988  }
989  }
991 }
struct ast_atexit::@330 list
#define AST_LIST_TRAVERSE_SAFE_END
Closes a safe loop traversal block.
Definition: linkedlists.h:614
#define AST_LIST_REMOVE_CURRENT(field)
Removes the current entry from a list during a traversal.
Definition: linkedlists.h:556
#define ast_free(a)
Definition: astmm.h:182
void(* func)(void)
Definition: asterisk.c:329
#define AST_LIST_TRAVERSE_SAFE_BEGIN(head, var, field)
Loops safely over (traverses) the entries in a list.
Definition: linkedlists.h:528

◆ __init_console_state()

static void __init_console_state ( void  )
static

Definition at line 2160 of file asterisk.c.

2163 {

◆ __quit_handler()

static void __quit_handler ( int  num)
static

Definition at line 2100 of file asterisk.c.

References ast_alertpipe_write(), errno, sig_alert_pipe, and sig_flags.

Referenced by asterisk_daemon().

2101 {
2102  sig_flags.need_quit = 1;
2104  fprintf(stderr, "quit_handler: write() failed: %s\n", strerror(errno));
2105  }
2106  /* There is no need to restore the signal handler here, since the app
2107  * is going to exit */
2108 }
static int sig_alert_pipe[2]
Definition: asterisk.c:396
ssize_t ast_alertpipe_write(int alert_pipe[2])
Write an event to an alert pipe.
Definition: alertpipe.c:120
static struct @329 sig_flags
int errno

◆ __remote_quit_handler()

static void __remote_quit_handler ( int  num)
static

Definition at line 2110 of file asterisk.c.

References sig_flags.

Referenced by ast_remotecontrol().

2111 {
2112  sig_flags.need_quit = 1;
2113 }
static struct @329 sig_flags

◆ _child_handler()

static void _child_handler ( int  sig)
static

Definition at line 1702 of file asterisk.c.

References errno, option_debug, and status.

1703 {
1704  /* Must not ever ast_log or ast_verbose within signal handler */
1705  int n, status, save_errno = errno;
1706 
1707  /*
1708  * Reap all dead children -- not just one
1709  */
1710  for (n = 0; waitpid(-1, &status, WNOHANG) > 0; n++)
1711  ;
1712  if (n == 0 && option_debug)
1713  printf("Huh? Child handler, but nobody there?\n");
1714  errno = save_errno;
1715 }
int option_debug
Definition: options.c:69
int errno
jack_status_t status
Definition: app_jack.c:146

◆ _hup_handler()

static void _hup_handler ( int  num)
static

Definition at line 1678 of file asterisk.c.

References _argv, ast_alertpipe_write(), el, errno, restartnow, sig_alert_pipe, and sig_flags.

1679 {
1680  int save_errno = errno;
1681 
1682  if (restartnow) {
1683  if (el) {
1684  el_end(el);
1685  }
1686  execvp(_argv[0], _argv);
1687  }
1688 
1689  printf("Received HUP signal -- Reloading configs\n");
1690  sig_flags.need_reload = 1;
1692  fprintf(stderr, "hup_handler: write() failed: %s\n", strerror(errno));
1693  }
1694  errno = save_errno;
1695 }
static int sig_alert_pipe[2]
Definition: asterisk.c:396
static EditLine * el
Definition: asterisk.c:340
static char * _argv[256]
Definition: asterisk.c:354
ssize_t ast_alertpipe_write(int alert_pipe[2])
Write an event to an alert pipe.
Definition: alertpipe.c:120
static struct @329 sig_flags
int errno
static int restartnow
Definition: asterisk.c:383

◆ _null_sig_handler()

static void _null_sig_handler ( int  sig)
static

NULL handler so we can collect the child exit status.

Definition at line 1042 of file asterisk.c.

1043 {
1044 }

◆ _urg_handler()

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

1670 {
1671  return;
1672 }

◆ ast_add_profile()

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 760 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, NULL, console::p, profile_entry::scale, and profile_entry::value.

761 {
762 #if !defined(LOW_MEMORY)
763  int l = sizeof(struct profile_data);
764  int n = 10; /* default entries */
765 
766  if (prof_data == NULL) {
767  prof_data = ast_calloc(1, l + n*sizeof(struct profile_entry));
768  if (prof_data == NULL)
769  return -1;
770  prof_data->entries = 0;
771  prof_data->max_size = n;
772  }
773  if (prof_data->entries >= prof_data->max_size) {
774  void *p;
775  n = prof_data->max_size + 20;
776  p = ast_realloc(prof_data, l + n*sizeof(struct profile_entry));
777  if (p == NULL)
778  return -1;
779  prof_data = p;
780  prof_data->max_size = n;
781  }
782  n = prof_data->entries++;
783  prof_data->e[n].name = ast_strdup(name);
784  prof_data->e[n].value = 0;
785  prof_data->e[n].events = 0;
786  prof_data->e[n].mark = 0;
787  prof_data->e[n].scale = scale;
788  return n;
789 #else /* if defined(LOW_MEMORY) */
790  return 0;
791 #endif
792 }
#define ast_realloc(p, len)
A wrapper for realloc()
Definition: astmm.h:228
const char * name
Definition: asterisk.c:741
static struct profile_data * prof_data
Definition: asterisk.c:754
#define ast_strdup(str)
A wrapper for strdup()
Definition: astmm.h:243
int64_t mark
Definition: asterisk.c:743
#define NULL
Definition: resample.c:96
int max_size
Definition: asterisk.c:750
uint64_t scale
Definition: asterisk.c:742
int64_t events
Definition: asterisk.c:745
struct profile_entry e[0]
Definition: asterisk.c:751
static const char name[]
Definition: cdr_mysql.c:74
#define ast_calloc(num, len)
A wrapper for calloc()
Definition: astmm.h:204
int64_t value
Definition: asterisk.c:744
Definition: asterisk.c:740

◆ ast_all_zeros()

static int ast_all_zeros ( const char *  s)
static

Definition at line 2233 of file asterisk.c.

Referenced by consolehandler(), and remoteconsolehandler().

2234 {
2235  while (*s) {
2236  if (*s > 32)
2237  return 0;
2238  s++;
2239  }
2240  return 1;
2241 }

◆ ast_begin_shutdown()

static void ast_begin_shutdown ( void  )
static

Definition at line 1857 of file asterisk.c.

References ast_mutex_lock, ast_mutex_unlock, can_safely_quit(), NOT_SHUTTING_DOWN, really_quit(), safe_system_lock, shutdown_pending, and shuttingdown.

Referenced by can_safely_quit().

1858 {
1861  shutdown_pending = 1;
1862  }
1864 }
static ast_mutex_t safe_system_lock
Definition: asterisk.c:1055
#define ast_mutex_lock(a)
Definition: lock.h:187
static int shutdown_pending
Definition: asterisk.c:381
static shutdown_nice_t shuttingdown
Definition: asterisk.c:378
#define ast_mutex_unlock(a)
Definition: lock.h:188

◆ ast_cancel_shutdown()

int ast_cancel_shutdown ( void  )

Cancel an existing shutdown and return to normal operation.

Note
Shutdown can be cancelled while the server is waiting for any existing channels to be destroyed before shutdown becomes irreversible.
Returns
non-zero if shutdown cancelled.

Definition at line 1839 of file asterisk.c.

References ast_mutex_lock, ast_mutex_unlock, NOT_SHUTTING_DOWN, safe_system_lock, SHUTDOWN_FAST, shutdown_pending, and shuttingdown.

Referenced by handle_abort_shutdown().

1840 {
1841  int shutdown_aborted = 0;
1842 
1844  if (shuttingdown >= SHUTDOWN_FAST) {
1846  shutdown_pending = 0;
1847  shutdown_aborted = 1;
1848  }
1850  return shutdown_aborted;
1851 }
static ast_mutex_t safe_system_lock
Definition: asterisk.c:1055
#define ast_mutex_lock(a)
Definition: lock.h:187
static int shutdown_pending
Definition: asterisk.c:381
static shutdown_nice_t shuttingdown
Definition: asterisk.c:378
#define ast_mutex_unlock(a)
Definition: lock.h:188

◆ ast_cli_display_match_list()

static void ast_cli_display_match_list ( struct ast_vector_string *  matches,
int  max 
)
static

Definition at line 2887 of file asterisk.c.

References ast_get_termcols(), AST_VECTOR_GET, and AST_VECTOR_SIZE.

Referenced by cli_complete().

2888 {
2889  int idx = 1;
2890  /* find out how many entries can be put on one line, with two spaces between strings */
2891  int limit = ast_get_termcols(STDOUT_FILENO) / (max + 2);
2892 
2893  if (limit == 0) {
2894  limit = 1;
2895  }
2896 
2897  for (;;) {
2898  int numoutputline;
2899 
2900  for (numoutputline = 0; numoutputline < limit && idx < AST_VECTOR_SIZE(matches); idx++) {
2901  numoutputline++;
2902  fprintf(stdout, "%-*s ", max, AST_VECTOR_GET(matches, idx));
2903  }
2904 
2905  if (!numoutputline) {
2906  break;
2907  }
2908 
2909  fprintf(stdout, "\n");
2910  }
2911 }
int ast_get_termcols(int fd)
Definition: io.c:373
#define AST_VECTOR_GET(vec, idx)
Get an element from a vector.
Definition: vector.h:678
#define AST_VECTOR_SIZE(vec)
Get the number of elements in a vector.
Definition: vector.h:611
#define max(a, b)
Definition: f2c.h:198

◆ ast_console_puts()

void ast_console_puts ( const char *  string)

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

Definition at line 1314 of file asterisk.c.

References ast_network_puts().

1315 {
1316  /* Send to the root console */
1317  fputs(string, stdout);
1318  fflush(stdout);
1319 
1320  /* Send to any network console clients */
1321  ast_network_puts(string);
1322 }
static void ast_network_puts(const char *string)
write the string to all attached console clients
Definition: asterisk.c:1298

◆ ast_console_puts_mutable()

void ast_console_puts_mutable ( const char *  string,
int  level 
)

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

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

Definition at line 1274 of file asterisk.c.

References ast_console_puts_mutable_full(), and console_print().

Referenced by init_logger_chain(), and make_logchannel().

1275 {
1276  ast_console_puts_mutable_full(string, level, 0);
1277 }
void ast_console_puts_mutable_full(const char *message, int level, int sublevel)
log the string to the console, and all attached console clients
Definition: asterisk.c:1281

◆ ast_console_puts_mutable_full()

void ast_console_puts_mutable_full ( const char *  message,
int  level,
int  sublevel 
)

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

Since
14.0.0
Parameters
messageThe message to write to the console
sublevelIf the log level supports it, the sub-level of the message
levelThe log level of the message

Definition at line 1281 of file asterisk.c.

References ast_network_puts_mutable(), ast_opt_console, AST_PTHREADT_NULL, console_print(), and consolethread.

Referenced by ast_console_puts_mutable(), and logger_print_normal().

1282 {
1283  /* Send to the root console */
1285 
1286  /* Wake up a poll()ing console */
1288  pthread_kill(consolethread, SIGURG);
1289  }
1290 
1291  /* Send to any network console clients */
1292  ast_network_puts_mutable(message, level, sublevel);
1293 }
static int console_print(const char *s)
Definition: asterisk.c:2162
#define ast_opt_console
Definition: options.h:109
#define AST_PTHREADT_NULL
Definition: lock.h:66
static pthread_t consolethread
Definition: asterisk.c:384
static void ast_network_puts_mutable(const char *string, int level, int sublevel)
log the string to all attached network console clients
Definition: asterisk.c:1255

◆ ast_console_toggle_loglevel()

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

enable or disable a logging level to a specified console

enables or disables logging of a specified level to the console fd specifies the index of the console receiving the level change level specifies the index of the logging level being toggled state indicates whether logging will be on or off (0 for off, 1 for on)

Definition at line 1209 of file asterisk.c.

References AST_MAX_CONNECTS, consoles, console::levels, and NUMLOGLEVELS.

Referenced by handle_logger_set_level().

1210 {
1211  int x;
1212 
1213  if (level >= NUMLOGLEVELS) {
1214  level = NUMLOGLEVELS - 1;
1215  }
1216 
1217  for (x = 0;x < AST_MAX_CONNECTS; x++) {
1218  if (fd == consoles[x].fd) {
1219  /*
1220  * Since the logging occurs when levels are false, set to
1221  * flipped iinput because this function accepts 0 as off and 1 as on
1222  */
1223  consoles[x].levels[level] = state ? 0 : 1;
1224  return;
1225  }
1226  }
1227 }
#define AST_MAX_CONNECTS
Definition: asterisk.c:296
#define NUMLOGLEVELS
Definition: logger.h:314
struct console consoles[AST_MAX_CONNECTS]
Definition: asterisk.c:343
int levels[NUMLOGLEVELS]
Definition: asterisk.c:323

◆ ast_console_toggle_mute()

void ast_console_toggle_mute ( int  fd,
int  silent 
)

mute or unmute a console from logging

Definition at line 1232 of file asterisk.c.

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

Referenced by handle_logger_mute().

1233 {
1234  int x;
1235  for (x = 0;x < AST_MAX_CONNECTS; x++) {
1236  if (fd == consoles[x].fd) {
1237  if (consoles[x].mute) {
1238  consoles[x].mute = 0;
1239  if (!silent)
1240  ast_cli(fd, "Console is not muted anymore.\n");
1241  } else {
1242  consoles[x].mute = 1;
1243  if (!silent)
1244  ast_cli(fd, "Console is muted.\n");
1245  }
1246  return;
1247  }
1248  }
1249  ast_cli(fd, "Couldn't find remote console.\n");
1250 }
#define AST_MAX_CONNECTS
Definition: asterisk.c:296
void ast_cli(int fd, const char *fmt,...)
Definition: clicompat.c:6
static int mute
Definition: chan_alsa.c:144
struct console consoles[AST_MAX_CONNECTS]
Definition: asterisk.c:343
int mute
Definition: asterisk.c:320

◆ ast_el_add_history()

static int ast_el_add_history ( const char *  buf)
static

Definition at line 3078 of file asterisk.c.

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

Referenced by consolehandler(), and remoteconsolehandler().

3079 {
3080  HistEvent ev;
3081  char *stripped_buf;
3082 
3083  if (el_hist == NULL || el == NULL) {
3085  }
3086  if (strlen(buf) > (MAX_HISTORY_COMMAND_LENGTH - 1)) {
3087  return 0;
3088  }
3089 
3090  stripped_buf = ast_strip(ast_strdupa(buf));
3091 
3092  /* HISTCONTROL=ignoredups */
3093  if (!history(el_hist, &ev, H_FIRST) && strcmp(ev.str, stripped_buf) == 0) {
3094  return 0;
3095  }
3096 
3097  return history(el_hist, &ev, H_ENTER, stripped_buf);
3098 }
static History * el_hist
Definition: asterisk.c:339
char buf[BUFSIZE]
Definition: eagi_proxy.c:66
static EditLine * el
Definition: asterisk.c:340
#define NULL
Definition: resample.c:96
char * ast_strip(char *s)
Strip leading/trailing whitespace from a string.
Definition: strings.h:219
#define ast_strdupa(s)
duplicate a string in memory from the stack
Definition: astmm.h:300
static int ast_el_initialize(void)
Definition: asterisk.c:3023
#define MAX_HISTORY_COMMAND_LENGTH
Definition: asterisk.c:3076

◆ ast_el_initialize()

static int ast_el_initialize ( void  )
static

Definition at line 3023 of file asterisk.c.

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

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

3024 {
3025  HistEvent ev;
3026  char *editor, *editrc = getenv("EDITRC");
3027 
3028  if (!(editor = getenv("AST_EDITMODE"))) {
3029  if (!(editor = getenv("AST_EDITOR"))) {
3030  editor = "emacs";
3031  }
3032  }
3033 
3034  if (el != NULL)
3035  el_end(el);
3036  if (el_hist != NULL)
3037  history_end(el_hist);
3038 
3039  el = el_init("asterisk", stdin, stdout, stderr);
3040  el_set(el, EL_PROMPT, cli_prompt);
3041 
3042  el_set(el, EL_EDITMODE, 1);
3043  el_set(el, EL_EDITOR, editor);
3044  el_hist = history_init();
3045  if (!el || !el_hist)
3046  return -1;
3047 
3048  /* setup history with 100 entries */
3049  history(el_hist, &ev, H_SETSIZE, 100);
3050 
3051  el_set(el, EL_HIST, history, el_hist);
3052 
3053  el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
3054  /* Bind <tab> to command completion */
3055  el_set(el, EL_BIND, "^I", "ed-complete", NULL);
3056  /* Bind ? to command completion */
3057  el_set(el, EL_BIND, "?", "ed-complete", NULL);
3058  /* Bind ^D to redisplay */
3059  el_set(el, EL_BIND, "^D", "ed-redisplay", NULL);
3060  /* Bind Delete to delete char left */
3061  el_set(el, EL_BIND, "\\e[3~", "ed-delete-next-char", NULL);
3062  /* Bind Home and End to move to line start and end */
3063  el_set(el, EL_BIND, "\\e[1~", "ed-move-to-beg", NULL);
3064  el_set(el, EL_BIND, "\\e[4~", "ed-move-to-end", NULL);
3065  /* Bind C-left and C-right to move by word (not all terminals) */
3066  el_set(el, EL_BIND, "\\eOC", "vi-next-word", NULL);
3067  el_set(el, EL_BIND, "\\eOD", "vi-prev-word", NULL);
3068 
3069  if (editrc) {
3070  el_source(el, editrc);
3071  }
3072 
3073  return 0;
3074 }
static History * el_hist
Definition: asterisk.c:339
static char * cli_complete(EditLine *editline, int ch)
Definition: asterisk.c:2914
static EditLine * el
Definition: asterisk.c:340
static char * cli_prompt(EditLine *editline)
Definition: asterisk.c:2727
#define NULL
Definition: resample.c:96

◆ ast_el_read_char()

static int ast_el_read_char ( EditLine *  editline,
CHAR_T_LIBEDIT cp 
)
static

Definition at line 2626 of file asterisk.c.

References ast_consock, ast_opt_exec, ast_opt_reconnect, ast_poll, ast_tryconnect(), buf, c, CHAR_TO_LIBEDIT, console_print(), EL_BUF_SIZE, errno, max, quit_handler(), send_rasterisk_connect_commands(), SHUTDOWN_FAST, sig_flags, term_quit(), and WELCOME_MESSAGE.

Referenced by ast_remotecontrol(), and asterisk_daemon().

2627 {
2628  int num_read = 0;
2629  int lastpos = 0;
2630  struct pollfd fds[2];
2631  int res;
2632  int max;
2633 #define EL_BUF_SIZE 512
2634  char buf[EL_BUF_SIZE];
2635 
2636  for (;;) {
2637  max = 1;
2638  fds[0].fd = ast_consock;
2639  fds[0].events = POLLIN;
2640  if (!ast_opt_exec) {
2641  fds[1].fd = STDIN_FILENO;
2642  fds[1].events = POLLIN;
2643  max++;
2644  }
2645  res = ast_poll(fds, max, -1);
2646  if (res < 0) {
2647  if (sig_flags.need_quit || sig_flags.need_quit_handler || sig_flags.need_el_end) {
2648  break;
2649  }
2650  if (errno == EINTR) {
2651  continue;
2652  }
2653  fprintf(stderr, "poll failed: %s\n", strerror(errno));
2654  break;
2655  }
2656 
2657  if (!ast_opt_exec && fds[1].revents) {
2658  char c = '\0';
2659 
2660  num_read = read(STDIN_FILENO, &c, 1);
2661  if (num_read < 1) {
2662  break;
2663  }
2664 
2665  *cp = CHAR_TO_LIBEDIT(c);
2666 
2667  return num_read;
2668  }
2669 
2670  if (fds[0].revents) {
2671  res = read(ast_consock, buf, sizeof(buf) - 1);
2672  /* if the remote side disappears exit */
2673  if (res < 1) {
2674  fprintf(stderr, "\nDisconnected from Asterisk server\n");
2675  if (!ast_opt_reconnect) {
2676  quit_handler(0, SHUTDOWN_FAST, 0);
2677  } else {
2678  int tries;
2679  int reconnects_per_second = 20;
2680 
2681  fprintf(stderr, "Attempting to reconnect for 30 seconds\n");
2682  for (tries = 0; tries < 30 * reconnects_per_second; tries++) {
2683  if (ast_tryconnect()) {
2684  fprintf(stderr, "Reconnect succeeded after %.3f seconds\n", 1.0 / reconnects_per_second * tries);
2685  printf("%s", term_quit());
2688  break;
2689  }
2690 
2691  usleep(1000000 / reconnects_per_second);
2692  }
2693  if (tries >= 30 * reconnects_per_second) {
2694  fprintf(stderr, "Failed to reconnect for 30 seconds. Quitting.\n");
2695  quit_handler(0, SHUTDOWN_FAST, 0);
2696  }
2697  }
2698  continue;
2699  }
2700 
2701  buf[res] = '\0';
2702 
2703  /* Write over the CLI prompt */
2704  if (!ast_opt_exec && !lastpos) {
2705  if (write(STDOUT_FILENO, "\r", 5) < 0) {
2706  }
2707  }
2708 
2709  console_print(buf);
2710 
2711  if ((res < EL_BUF_SIZE - 1) && ((buf[res-1] == '\n') || (res >= 2 && buf[res-2] == '\n'))) {
2712  *cp = CHAR_TO_LIBEDIT(CC_REFRESH);
2713 
2714  return 1;
2715  }
2716  lastpos = 1;
2717  }
2718  }
2719 
2720  *cp = CHAR_TO_LIBEDIT('\0');
2721 
2722  return 0;
2723 }
const char * term_quit(void)
Definition: term.c:361
char buf[BUFSIZE]
Definition: eagi_proxy.c:66
static int console_print(const char *s)
Definition: asterisk.c:2162
#define WELCOME_MESSAGE
Welcome message when starting a CLI interface.
Definition: asterisk.c:303
static struct test_val c
static int ast_tryconnect(void)
Definition: asterisk.c:1642
#define ast_opt_reconnect
Definition: options.h:123
static void quit_handler(int num, shutdown_nice_t niceness, int restart)
Definition: asterisk.c:1869
#define EL_BUF_SIZE
#define ast_poll(a, b, c)
Definition: poll-compat.h:88
static void send_rasterisk_connect_commands(void)
Definition: asterisk.c:2590
static struct @329 sig_flags
int errno
static int ast_consock
Definition: asterisk.c:314
#define ast_opt_exec
Definition: options.h:113
#define CHAR_TO_LIBEDIT(c)
Definition: asterisk.c:2620
#define max(a, b)
Definition: f2c.h:198

◆ ast_el_read_default_histfile()

static void ast_el_read_default_histfile ( void  )
static

Definition at line 3121 of file asterisk.c.

References ast_el_read_history(), and ast_strlen_zero.

Referenced by ast_remotecontrol(), and asterisk_daemon().

3122 {
3123  char histfile[80] = "";
3124  const char *home = getenv("HOME");
3125 
3126  if (!ast_strlen_zero(home)) {
3127  snprintf(histfile, sizeof(histfile), "%s/.asterisk_history", home);
3128  ast_el_read_history(histfile);
3129  }
3130 }
static int ast_el_read_history(const char *)
Definition: asterisk.c:3110
#define ast_strlen_zero(a)
Definition: muted.c:73

◆ ast_el_read_history()

static int ast_el_read_history ( const char *  filename)
static

Definition at line 3110 of file asterisk.c.

References ast_el_initialize(), el, el_hist, and NULL.

Referenced by ast_el_read_default_histfile().

3111 {
3112  HistEvent ev;
3113 
3114  if (el_hist == NULL || el == NULL) {
3116  }
3117 
3118  return history(el_hist, &ev, H_LOAD, filename);
3119 }
static History * el_hist
Definition: asterisk.c:339
static EditLine * el
Definition: asterisk.c:340
#define NULL
Definition: resample.c:96
static int ast_el_initialize(void)
Definition: asterisk.c:3023

◆ ast_el_strtoarr()

static struct ast_vector_string* ast_el_strtoarr ( char *  buf)
static

Definition at line 2853 of file asterisk.c.

References ast_calloc, AST_CLI_COMPLETE_EOF, ast_free, ast_strdup, AST_VECTOR_APPEND, AST_VECTOR_CALLBACK_VOID, AST_VECTOR_PTR_FREE, AST_VECTOR_SIZE, NULL, and strsep().

Referenced by cli_complete().

2854 {
2855  char *retstr;
2856  struct ast_vector_string *vec = ast_calloc(1, sizeof(*vec));
2857 
2858  if (!vec) {
2859  return NULL;
2860  }
2861 
2862  while ((retstr = strsep(&buf, " "))) {
2863  if (!strcmp(retstr, AST_CLI_COMPLETE_EOF)) {
2864  break;
2865  }
2866 
2867  retstr = ast_strdup(retstr);
2868  if (!retstr || AST_VECTOR_APPEND(vec, retstr)) {
2869  ast_free(retstr);
2870  goto vector_cleanup;
2871  }
2872  }
2873 
2874  if (!AST_VECTOR_SIZE(vec)) {
2875  goto vector_cleanup;
2876  }
2877 
2878  return vec;
2879 
2880 vector_cleanup:
2882  AST_VECTOR_PTR_FREE(vec);
2883 
2884  return NULL;
2885 }
#define AST_CLI_COMPLETE_EOF
Definition: cli.h:52
char buf[BUFSIZE]
Definition: eagi_proxy.c:66
#define AST_VECTOR_APPEND(vec, elem)
Append an element to a vector, growing the vector if needed.
Definition: vector.h:256
#define ast_strdup(str)
A wrapper for strdup()
Definition: astmm.h:243
#define NULL
Definition: resample.c:96
#define ast_free(a)
Definition: astmm.h:182
#define ast_calloc(num, len)
A wrapper for calloc()
Definition: astmm.h:204
#define AST_VECTOR_PTR_FREE(vec)
Deallocates this vector pointer.
Definition: vector.h:189
char * strsep(char **str, const char *delims)
#define AST_VECTOR_SIZE(vec)
Get the number of elements in a vector.
Definition: vector.h:611
#define AST_VECTOR_CALLBACK_VOID(vec, callback,...)
Execute a callback on every element in a vector disregarding callback return.
Definition: vector.h:861

◆ ast_el_write_default_histfile()

static void ast_el_write_default_histfile ( void  )
static

Definition at line 3132 of file asterisk.c.

References ast_el_write_history(), and ast_strlen_zero.

Referenced by really_quit().

3133 {
3134  char histfile[80] = "";
3135  const char *home = getenv("HOME");
3136 
3137  if (!ast_strlen_zero(home)) {
3138  snprintf(histfile, sizeof(histfile), "%s/.asterisk_history", home);
3139  ast_el_write_history(histfile);
3140  }
3141 }
static int ast_el_write_history(const char *)
Definition: asterisk.c:3100
#define ast_strlen_zero(a)
Definition: muted.c:73

◆ ast_el_write_history()

static int ast_el_write_history ( const char *  filename)
static

Definition at line 3100 of file asterisk.c.

References ast_el_initialize(), el, el_hist, and NULL.

Referenced by ast_el_write_default_histfile().

3101 {
3102  HistEvent ev;
3103 
3104  if (el_hist == NULL || el == NULL)
3106 
3107  return (history(el_hist, &ev, H_SAVE, filename));
3108 }
static History * el_hist
Definition: asterisk.c:339
static EditLine * el
Definition: asterisk.c:340
#define NULL
Definition: resample.c:96
static int ast_el_initialize(void)
Definition: asterisk.c:3023

◆ ast_makesocket()

static int ast_makesocket ( void  )
static

Definition at line 1556 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_sd_get_fd_un(), ast_socket, ast_socket_is_sd, ast_strlen_zero, consoles, errno, console::fd, console::gid, listener(), LOG_WARNING, NULL, console::p, PF_LOCAL, and console::uid.

Referenced by asterisk_daemon().

1557 {
1558  struct sockaddr_un sunaddr;
1559  int res;
1560  int x;
1561  uid_t uid = -1;
1562  gid_t gid = -1;
1563 
1564  for (x = 0; x < AST_MAX_CONNECTS; x++) {
1565  consoles[x].fd = -1;
1566  }
1567 
1568  if (ast_socket_is_sd) {
1570 
1571  goto start_lthread;
1572  }
1573 
1574  unlink(ast_config_AST_SOCKET);
1575  ast_socket = socket(PF_LOCAL, SOCK_STREAM, 0);
1576  if (ast_socket < 0) {
1577  ast_log(LOG_WARNING, "Unable to create control socket: %s\n", strerror(errno));
1578  return -1;
1579  }
1580  memset(&sunaddr, 0, sizeof(sunaddr));
1581  sunaddr.sun_family = AF_LOCAL;
1582  ast_copy_string(sunaddr.sun_path, ast_config_AST_SOCKET, sizeof(sunaddr.sun_path));
1583  res = bind(ast_socket, (struct sockaddr *)&sunaddr, sizeof(sunaddr));
1584  if (res) {
1585  ast_log(LOG_WARNING, "Unable to bind socket to %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
1586  close(ast_socket);
1587  ast_socket = -1;
1588  return -1;
1589  }
1590  res = listen(ast_socket, 2);
1591  if (res < 0) {
1592  ast_log(LOG_WARNING, "Unable to listen on socket %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
1593  close(ast_socket);
1594  ast_socket = -1;
1595  return -1;
1596  }
1597 
1598 start_lthread:
1600  ast_log(LOG_WARNING, "Unable to create listener thread.\n");
1601  close(ast_socket);
1602  return -1;
1603  }
1604 
1605  if (ast_socket_is_sd) {
1606  /* owner/group/permissions are set by systemd, we might not even have access
1607  * to socket file so leave it alone */
1608  return 0;
1609  }
1610 
1612  struct passwd *pw;
1613  if ((pw = getpwnam(ast_config_AST_CTL_OWNER)) == NULL)
1614  ast_log(LOG_WARNING, "Unable to find uid of user %s\n", ast_config_AST_CTL_OWNER);
1615  else
1616  uid = pw->pw_uid;
1617  }
1618 
1620  struct group *grp;
1621  if ((grp = getgrnam(ast_config_AST_CTL_GROUP)) == NULL)
1622  ast_log(LOG_WARNING, "Unable to find gid of group %s\n", ast_config_AST_CTL_GROUP);
1623  else
1624  gid = grp->gr_gid;
1625  }
1626 
1627  if (chown(ast_config_AST_SOCKET, uid, gid) < 0)
1628  ast_log(LOG_WARNING, "Unable to change ownership of %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
1629 
1631  unsigned int p1;
1632  mode_t p;
1633  sscanf(ast_config_AST_CTL_PERMISSIONS, "%30o", &p1);
1634  p = p1;
1635  if ((chmod(ast_config_AST_SOCKET, p)) < 0)
1636  ast_log(LOG_WARNING, "Unable to change file permissions of %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
1637  }
1638 
1639  return 0;
1640 }
#define AST_MAX_CONNECTS
Definition: asterisk.c:296
int ast_sd_get_fd_un(int type, const char *path)
Find a listening AF_LOCAL file descriptor provided by socket activation.
Definition: io.c:454
#define LOG_WARNING
Definition: logger.h:274
#define NULL
Definition: resample.c:96
#define ast_pthread_create_background(a, b, c, d)
Definition: utils.h:507
#define ast_log
Definition: astobj2.c:42
static void * listener(void *unused)
Definition: asterisk.c:1476
const char * ast_config_AST_CTL_GROUP
Definition: options.c:171
static int ast_socket
Definition: asterisk.c:312
struct console consoles[AST_MAX_CONNECTS]
Definition: asterisk.c:343
#define PF_LOCAL
Definition: asterisk.c:293
int errno
#define ast_strlen_zero(a)
Definition: muted.c:73
#define AF_LOCAL
Definition: asterisk.c:292
static pthread_t lthread
Definition: asterisk.c:1324
void ast_copy_string(char *dst, const char *src, size_t size)
Size-limited null-terminating string copy.
Definition: strings.h:401
const char * ast_config_AST_SOCKET
Definition: options.c:164
static int ast_socket_is_sd
Definition: asterisk.c:313
int fd
Definition: asterisk.c:317
const char * ast_config_AST_CTL_PERMISSIONS
Definition: options.c:169
const char * ast_config_AST_CTL_OWNER
Definition: options.c:170

◆ ast_mark()

int64_t ast_mark ( int  i,
int  startstop 
)

Definition at line 835 of file asterisk.c.

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

836 {
837 #if !defined(LOW_MEMORY)
838  if (!prof_data || i < 0 || i > prof_data->entries) /* invalid index */
839  return 0;
840  if (startstop == 1)
841  prof_data->e[i].mark = rdtsc();
842  else {
843  prof_data->e[i].mark = (rdtsc() - prof_data->e[i].mark);
844  if (prof_data->e[i].scale > 1)
845  prof_data->e[i].mark /= prof_data->e[i].scale;
846  prof_data->e[i].value += prof_data->e[i].mark;
847  prof_data->e[i].events++;
848  }
849  return prof_data->e[i].mark;
850 #else /* if defined(LOW_MEMORY) */
851  return 0;
852 #endif
853 }
static struct profile_data * prof_data
Definition: asterisk.c:754
int64_t mark
Definition: asterisk.c:743
uint64_t scale
Definition: asterisk.c:742
int64_t events
Definition: asterisk.c:745
struct profile_entry e[0]
Definition: asterisk.c:751
int64_t value
Definition: asterisk.c:744
static __inline uint64_t rdtsc(void)
Definition: asterisk.c:828

◆ ast_network_puts()

static void ast_network_puts ( const char *  string)
static

write the string to all attached console clients

Definition at line 1298 of file asterisk.c.

References AST_MAX_CONNECTS, consoles, console::fd, fdprint(), and console::p.

Referenced by ast_console_puts().

1299 {
1300  int x;
1301 
1302  for (x = 0; x < AST_MAX_CONNECTS; ++x) {
1303  if (consoles[x].fd < 0) {
1304  continue;
1305  }
1306  fdprint(consoles[x].p[1], string);
1307  }
1308 }
#define AST_MAX_CONNECTS
Definition: asterisk.c:296
struct console consoles[AST_MAX_CONNECTS]
Definition: asterisk.c:343
static int fdprint(int fd, const char *s)
Definition: asterisk.c:1036

◆ ast_network_puts_mutable()

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

log the string to all attached network console clients

Definition at line 1255 of file asterisk.c.

References __LOG_VERBOSE, AST_MAX_CONNECTS, consoles, console::fd, fdprint(), console::levels, console::mute, console::option_verbose, and console::p.

Referenced by ast_console_puts_mutable_full().

1256 {
1257  int x;
1258 
1259  for (x = 0; x < AST_MAX_CONNECTS; ++x) {
1260  if (consoles[x].fd < 0
1261  || consoles[x].mute
1262  || consoles[x].levels[level]
1263  || (level == __LOG_VERBOSE && consoles[x].option_verbose < sublevel)) {
1264  continue;
1265  }
1266  fdprint(consoles[x].p[1], string);
1267  }
1268 }
#define AST_MAX_CONNECTS
Definition: asterisk.c:296
int option_verbose
Definition: options.c:67
static char * levels[NUMLOGLEVELS]
Logging channels used in the Asterisk logging system.
Definition: logger.c:203
static int mute
Definition: chan_alsa.c:144
struct console consoles[AST_MAX_CONNECTS]
Definition: asterisk.c:343
static int fdprint(int fd, const char *s)
Definition: asterisk.c:1036
#define __LOG_VERBOSE
Definition: logger.h:295

◆ ast_pbx_uuid_get()

int ast_pbx_uuid_get ( char *  pbx_uuid,
int  length 
)

Retrieve the PBX UUID.

Parameters
pbx_uuidA buffer of at least AST_UUID_STR_LEN (36 + 1) size to receive the UUID
lengthThe buffer length

Definition at line 934 of file asterisk.c.

References ast_db_get().

Referenced by asterisk_daemon(), and handle_show_settings().

935 {
936  return ast_db_get("pbx", "UUID", pbx_uuid, length);
937 }
int ast_db_get(const char *family, const char *key, char *value, int valuelen)
Get key value specified by family/key.
Definition: main/db.c:412

◆ ast_profile()

int64_t ast_profile ( int  i,
int64_t  delta 
)

Definition at line 794 of file asterisk.c.

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

795 {
796 #if !defined(LOW_MEMORY)
797  if (!prof_data || i < 0 || i > prof_data->entries) /* invalid index */
798  return 0;
799  if (prof_data->e[i].scale > 1)
800  delta /= prof_data->e[i].scale;
801  prof_data->e[i].value += delta;
802  prof_data->e[i].events++;
803  return prof_data->e[i].value;
804 #else /* if defined(LOW_MEMORY) */
805  return 0;
806 #endif
807 }
static struct profile_data * prof_data
Definition: asterisk.c:754
uint64_t scale
Definition: asterisk.c:742
int64_t events
Definition: asterisk.c:745
struct profile_entry e[0]
Definition: asterisk.c:751
int64_t value
Definition: asterisk.c:744

◆ ast_register_atexit()

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

Register a function to be executed before Asterisk exits.

Parameters
funcThe callback function to use.
Return values
0on success.
-1on error.
Note
This function should be rarely used in situations where something must be shutdown to avoid corruption, excessive data loss, or when external programs must be stopped. All other cleanup in the core should use ast_register_cleanup.

Definition at line 1012 of file asterisk.c.

References ast_atexit::func, and register_atexit().

Referenced by asterisk_daemon().

1013 {
1014  return register_atexit(func, 0);
1015 }
static int register_atexit(void(*func)(void), int is_cleanup)
Definition: asterisk.c:993

◆ ast_register_cleanup()

int ast_register_cleanup ( void(*)(void)  func)

Register a function to be executed before Asterisk gracefully exits.

Since
11.9 If Asterisk is immediately shutdown (core stop now, or sending the TERM signal), the callback is not run. When the callbacks are run, they are run in sequence with ast_register_atexit() callbacks, in the reverse order of registration.
Parameters
funcThe callback function to use.
Return values
0on success.
-1on error.

Definition at line 1017 of file asterisk.c.

References ast_atexit::func, and register_atexit().

Referenced by asterisk_daemon().

1018 {
1019  return register_atexit(func, 1);
1020 }
static int register_atexit(void(*func)(void), int is_cleanup)
Definition: asterisk.c:993

◆ ast_register_thread()

void ast_register_thread ( char *  name)

Definition at line 414 of file asterisk.c.

References ast_assert, ast_calloc, ast_get_tid(), AST_RWLIST_INSERT_HEAD, AST_RWLIST_UNLOCK, AST_RWLIST_WRLOCK, multi_thread_safe, and name.

Referenced by dummy_start().

415 {
416  struct thread_list_t *new = ast_calloc(1, sizeof(*new));
417 
418  if (!new)
419  return;
420 
422  new->id = pthread_self();
423  new->lwp = ast_get_tid();
424  new->name = name; /* steal the allocated memory for the thread name */
426  AST_RWLIST_INSERT_HEAD(&thread_list, new, list);
428 }
#define AST_RWLIST_WRLOCK(head)
Write locks a list.
Definition: linkedlists.h:51
static int multi_thread_safe
Definition: asterisk.c:388
#define AST_RWLIST_UNLOCK(head)
Attempts to unlock a read/write based list.
Definition: linkedlists.h:150
#define ast_assert(a)
Definition: utils.h:650
#define AST_RWLIST_INSERT_HEAD
Definition: linkedlists.h:717
int ast_get_tid(void)
Get current thread ID.
Definition: main/utils.c:2375
static const char name[]
Definition: cdr_mysql.c:74
#define ast_calloc(num, len)
A wrapper for calloc()
Definition: astmm.h:204

◆ ast_remotecontrol()

static void ast_remotecontrol ( char *  data)
static

Definition at line 3143 of file asterisk.c.

References __remote_quit_handler(), ast_alloca, ast_consock, ast_el_initialize(), ast_el_read_char(), ast_el_read_default_histfile(), ast_log, ast_opt_exec, ast_poll, ast_strlen_zero, ast_term_init(), ast_verbose(), buf, el, el_hist, errno, hostname, LOG_ERROR, LOG_WARNING, NULL, prefix, remoteconsolehandler(), remotehostname, send_rasterisk_connect_commands(), sig_flags, strsep(), term_end(), tmp(), and version.

Referenced by main().

3144 {
3145  char buf[256] = "";
3146  int res;
3147  char *hostname;
3148  char *cpid;
3149  char *version;
3150  int pid;
3151  char *stringp = NULL;
3152 
3153  char *ebuf;
3154  int num = 0;
3155 
3156  ast_term_init();
3157  printf("%s", term_end());
3158  fflush(stdout);
3159 
3160  memset(&sig_flags, 0, sizeof(sig_flags));
3161  signal(SIGINT, __remote_quit_handler);
3162  signal(SIGTERM, __remote_quit_handler);
3163  signal(SIGHUP, __remote_quit_handler);
3164 
3165  if (read(ast_consock, buf, sizeof(buf) - 1) < 0) {
3166  ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
3167  return;
3168  }
3169  if (data) {
3170  char prefix[] = "cli quit after ";
3171  char *tmp = ast_alloca(strlen(data) + strlen(prefix) + 1);
3172  sprintf(tmp, "%s%s", prefix, data);
3173  if (write(ast_consock, tmp, strlen(tmp) + 1) < 0) {
3174  ast_log(LOG_ERROR, "write() failed: %s\n", strerror(errno));
3175  if (sig_flags.need_quit || sig_flags.need_quit_handler || sig_flags.need_el_end) {
3176  return;
3177  }
3178  }
3179  }
3180  stringp = buf;
3181  hostname = strsep(&stringp, "/");
3182  cpid = strsep(&stringp, "/");
3183  version = strsep(&stringp, "\n");
3184  if (!version)
3185  version = "<Version Unknown>";
3186  stringp = hostname;
3187  strsep(&stringp, ".");
3188  if (cpid)
3189  pid = atoi(cpid);
3190  else
3191  pid = -1;
3192  if (!data) {
3194  }
3195 
3196  if (ast_opt_exec && data) { /* hack to print output then exit if asterisk -rx is used */
3197  int linefull = 1, prev_linefull = 1, prev_line_verbose = 0;
3198  struct pollfd fds;
3199  fds.fd = ast_consock;
3200  fds.events = POLLIN;
3201  fds.revents = 0;
3202 
3203  while (ast_poll(&fds, 1, 60000) > 0) {
3204  char buffer[512] = "", *curline = buffer, *nextline;
3205  int not_written = 1;
3206 
3207  if (sig_flags.need_quit || sig_flags.need_quit_handler || sig_flags.need_el_end) {
3208  break;
3209  }
3210 
3211  if (read(ast_consock, buffer, sizeof(buffer) - 1) <= 0) {
3212  break;
3213  }
3214 
3215  do {
3216  prev_linefull = linefull;
3217  if ((nextline = strchr(curline, '\n'))) {
3218  linefull = 1;
3219  nextline++;
3220  } else {
3221  linefull = 0;
3222  nextline = strchr(curline, '\0');
3223  }
3224 
3225  /* Skip verbose lines */
3226  /* Prev line full? | Line is verbose | Last line verbose? | Print
3227  * TRUE | TRUE* | TRUE | FALSE
3228  * TRUE | TRUE* | FALSE | FALSE
3229  * TRUE | FALSE* | TRUE | TRUE
3230  * TRUE | FALSE* | FALSE | TRUE
3231  * FALSE | TRUE | TRUE* | FALSE
3232  * FALSE | TRUE | FALSE* | TRUE
3233  * FALSE | FALSE | TRUE* | FALSE
3234  * FALSE | FALSE | FALSE* | TRUE
3235  */
3236  if ((!prev_linefull && !prev_line_verbose) || (prev_linefull && *curline > 0)) {
3237  prev_line_verbose = 0;
3238  not_written = 0;
3239  if (write(STDOUT_FILENO, curline, nextline - curline) < 0) {
3240  ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
3241  }
3242  } else {
3243  prev_line_verbose = 1;
3244  }
3245  curline = nextline;
3246  } while (!ast_strlen_zero(curline));
3247 
3248  /* No non-verbose output in 60 seconds. */
3249  if (not_written) {
3250  break;
3251  }
3252  }
3253  return;
3254  }
3255 
3256  ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
3258  if (el_hist == NULL || el == NULL)
3261 
3262  el_set(el, EL_GETCFN, ast_el_read_char);
3263 
3264  for (;;) {
3265  ebuf = (char *)el_gets(el, &num);
3266 
3267  if (sig_flags.need_quit || sig_flags.need_quit_handler || sig_flags.need_el_end) {
3268  break;
3269  }
3270 
3271  if (!ebuf && write(1, "", 1) < 0)
3272  break;
3273 
3274  if (!ast_strlen_zero(ebuf)) {
3275  if (ebuf[strlen(ebuf)-1] == '\n')
3276  ebuf[strlen(ebuf)-1] = '\0';
3277  if (!remoteconsolehandler(ebuf)) {
3278  res = write(ast_consock, ebuf, strlen(ebuf) + 1);
3279  if (res < 1) {
3280  ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
3281  break;
3282  }
3283  }
3284  }
3285  }
3286  printf("\nDisconnected from Asterisk server\n");
3287 }
static History * el_hist
Definition: asterisk.c:339
char buf[BUFSIZE]
Definition: eagi_proxy.c:66
static int ast_el_read_char(EditLine *editline, CHAR_T_LIBEDIT *cp)
Definition: asterisk.c:2626
#define LOG_WARNING
Definition: logger.h:274
static int tmp()
Definition: bt_open.c:389
static void __remote_quit_handler(int num)
Definition: asterisk.c:2110
static void ast_el_read_default_histfile(void)
Definition: asterisk.c:3121
static EditLine * el
Definition: asterisk.c:340
void ast_verbose(const char *fmt,...)
Definition: extconf.c:2207
#define NULL
Definition: resample.c:96
const char * term_end(void)
Definition: term.c:356
#define ast_log
Definition: astobj2.c:42
int ast_term_init(void)
Definition: term.c:92
#define ast_poll(a, b, c)
Definition: poll-compat.h:88
static void send_rasterisk_connect_commands(void)
Definition: asterisk.c:2590
#define ast_alloca(size)
call __builtin_alloca to ensure we get gcc builtin semantics
Definition: astmm.h:290
#define LOG_ERROR
Definition: logger.h:285
static struct @329 sig_flags
int errno
#define ast_strlen_zero(a)
Definition: muted.c:73
static char * remotehostname
Definition: asterisk.c:341
static int ast_consock
Definition: asterisk.c:314
static char version[AST_MAX_EXTENSION]
Definition: chan_ooh323.c:391
#define ast_opt_exec
Definition: options.h:113
char * strsep(char **str, const char *delims)
static int ast_el_initialize(void)
Definition: asterisk.c:3023
static struct ast_str * hostname
Definition: cdr_mysql.c:77
static int remoteconsolehandler(const char *s)
Definition: asterisk.c:2262
static char prefix[MAX_PREFIX]
Definition: http.c:141

◆ ast_replace_sigchld()

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

References ast_mutex_lock, ast_mutex_unlock, safe_system_lock, and safe_system_prev_handler.

Referenced by safe_exec_prep().

1063 {
1064  unsigned int level;
1065 
1067  level = safe_system_level++;
1068 
1069  /* only replace the handler if it has not already been done */
1070  if (level == 0) {
1071  sigaction(SIGCHLD, &null_sig_handler, &safe_system_prev_handler);
1072  }
1073 
1075 }
static ast_mutex_t safe_system_lock
Definition: asterisk.c:1055
static struct sigaction safe_system_prev_handler
Definition: asterisk.c:1060
#define ast_mutex_lock(a)
Definition: lock.h:187
static unsigned int safe_system_level
Keep track of how many threads are currently trying to wait*() on a child process.
Definition: asterisk.c:1059
static struct sigaction null_sig_handler
Definition: asterisk.c:1046
#define ast_mutex_unlock(a)
Definition: lock.h:188

◆ ast_run_atexits()

static void ast_run_atexits ( int  run_cleanups)
static

Definition at line 965 of file asterisk.c.

References ast_free, AST_LIST_LOCK, AST_LIST_REMOVE_HEAD, AST_LIST_UNLOCK, ast_atexit::func, ast_atexit::is_cleanup, and ast_atexit::list.

Referenced by check_init(), and really_quit().

966 {
967  struct ast_atexit *ae;
968 
970  while ((ae = AST_LIST_REMOVE_HEAD(&atexits, list))) {
971  if (ae->func && (!ae->is_cleanup || run_cleanups)) {
972  ae->func();
973  }
974  ast_free(ae);
975  }
977 }
#define AST_LIST_LOCK(head)
Locks a list.
Definition: linkedlists.h:39
#define AST_LIST_UNLOCK(head)
Attempts to unlock a list.
Definition: linkedlists.h:139
struct ast_atexit::@330 list
#define AST_LIST_REMOVE_HEAD(head, field)
Removes and returns the head entry from a list.
Definition: linkedlists.h:832
int is_cleanup
Definition: asterisk.c:330
#define ast_free(a)
Definition: astmm.h:182
void(* func)(void)
Definition: asterisk.c:329

◆ ast_safe_execvp()

int ast_safe_execvp ( int  dualfork,
const char *  file,
char *const  argv[] 
)

Safely spawn an external program while closing file descriptors.

Note
This replaces the execvp call in all Asterisk modules
Parameters
dualforkNon-zero to simulate running the program in the background by forking twice. The option provides similar functionality to the '&' in the OS shell command "cmd &". The option allows Asterisk to run a reaper loop to watch the first fork which immediately exits after spaning the second fork. The actual program is run in the second fork.
fileexecvp(file, argv) file parameter
argvexecvp(file, argv) argv parameter

Definition at line 1180 of file asterisk.c.

References safe_exec_prep(), and safe_exec_wait().

Referenced by run_externnotify().

1181 {
1182  pid_t pid = safe_exec_prep(dualfork);
1183 
1184  if (pid == 0) {
1185  execvp(file, argv);
1186  _exit(1);
1187  /* noreturn from _exit */
1188  }
1189 
1190  return safe_exec_wait(pid);
1191 }
static pid_t safe_exec_prep(int dualfork)
fork and perform other preparations for spawning applications
Definition: asterisk.c:1093
static int safe_exec_wait(pid_t pid)
wait for spawned application to complete and unreplace sigchld
Definition: asterisk.c:1154

◆ ast_safe_system()

int ast_safe_system ( const char *  s)

Safely spawn an OS shell command while closing file descriptors.

Note
This replaces the system call in all Asterisk modules
Parameters
s- OS shell command string to execute.
Warning
Command injection can happen using this call if the passed in string is created using untrusted data from an external source. It is best not to use untrusted data. However, the caller could filter out dangerous characters to avoid command injection.

Definition at line 1193 of file asterisk.c.

References NULL, safe_exec_prep(), and safe_exec_wait().

Referenced by consolehandler(), and remoteconsolehandler().

1194 {
1195  pid_t pid = safe_exec_prep(0);
1196 
1197  if (pid == 0) {
1198  execl("/bin/sh", "/bin/sh", "-c", s, (char *) NULL);
1199  _exit(1);
1200  /* noreturn from _exit */
1201  }
1202 
1203  return safe_exec_wait(pid);
1204 }
#define NULL
Definition: resample.c:96
static pid_t safe_exec_prep(int dualfork)
fork and perform other preparations for spawning applications
Definition: asterisk.c:1093
static int safe_exec_wait(pid_t pid)
wait for spawned application to complete and unreplace sigchld
Definition: asterisk.c:1154

◆ ast_set_priority()

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

References ast_log, ast_verb, LOG_WARNING, sched_setscheduler, and setpriority.

Referenced by app_exec(), asterisk_daemon(), icesencode(), launch_script(), main(), mp3play(), NBScatplay(), safe_exec_prep(), send_waveform_to_fd(), set_priority_all(), spawn_mp3(), and spawn_ras().

1800 {
1801  struct sched_param sched;
1802  memset(&sched, 0, sizeof(sched));
1803 #ifdef __linux__
1804  if (pri) {
1805  sched.sched_priority = 10;
1806  if (sched_setscheduler(0, SCHED_RR, &sched)) {
1807  return -1;
1808  }
1809  } else {
1810  sched.sched_priority = 0;
1811  /* According to the manpage, these parameters can never fail. */
1812  sched_setscheduler(0, SCHED_OTHER, &sched);
1813  }
1814 #else
1815  if (pri) {
1816  if (setpriority(PRIO_PROCESS, 0, -10) == -1) {
1817  ast_log(LOG_WARNING, "Unable to set high priority\n");
1818  return -1;
1819  } else
1820  ast_verb(1, "Set to high priority\n");
1821  } else {
1822  /* According to the manpage, these parameters can never fail. */
1823  setpriority(PRIO_PROCESS, 0, 0);
1824  }
1825 #endif
1826  return 0;
1827 }
#define LOG_WARNING
Definition: logger.h:274
Definition: sched.c:76
#define ast_verb(level,...)
Definition: logger.h:455
#define ast_log
Definition: astobj2.c:42
#define sched_setscheduler
Definition: asterisk.h:49
#define setpriority
Definition: asterisk.h:48

◆ ast_shutdown_final()

int ast_shutdown_final ( void  )
Returns
non-zero if the server is actively shutting down.
Since
13.3.0

The server is releasing resources and unloading modules. It won't be long now.

Definition at line 1829 of file asterisk.c.

References SHUTTING_DOWN_FINAL, and shuttingdown.

Referenced by httpd_process_request(), load_resource(), send_notify(), session_inv_on_media_update(), session_inv_on_redirected(), session_inv_on_rx_offer(), session_inv_on_state_changed(), and session_inv_on_tsx_state_changed().

1830 {
1832 }
static shutdown_nice_t shuttingdown
Definition: asterisk.c:378

◆ ast_shutting_down()

int ast_shutting_down ( void  )

The server is preventing new channel creation in preparation for shutdown and may actively be releasing resources. The shutdown process may be canceled by ast_cancel_shutdown() if it is not too late.

Note
The preparation to shutdown phase can be quite lengthy if we are gracefully shutting down. How long existing calls will last is not up to us.
Returns
non-zero if the server is preparing to or actively shutting down.

Definition at line 1834 of file asterisk.c.

References shutdown_pending.

Referenced by __ast_channel_alloc_ap(), ast_cli_command_full(), ast_unregister_translator(), confbridge_exec(), handle_request_options(), options_on_rx_request(), and process_message().

1835 {
1836  return shutdown_pending;
1837 }
static int shutdown_pending
Definition: asterisk.c:381

◆ ast_tryconnect()

static int ast_tryconnect ( void  )
static

Definition at line 1642 of file asterisk.c.

References AF_LOCAL, ast_config_AST_SOCKET, ast_consock, ast_copy_string(), errno, and PF_LOCAL.

Referenced by ast_el_read_char(), and main().

1643 {
1644  struct sockaddr_un sunaddr;
1645  int res;
1646  ast_consock = socket(PF_LOCAL, SOCK_STREAM, 0);
1647  if (ast_consock < 0) {
1648  fprintf(stderr, "Unable to create socket: %s\n", strerror(errno));
1649  return 0;
1650  }
1651  memset(&sunaddr, 0, sizeof(sunaddr));
1652  sunaddr.sun_family = AF_LOCAL;
1653  ast_copy_string(sunaddr.sun_path, ast_config_AST_SOCKET, sizeof(sunaddr.sun_path));
1654  res = connect(ast_consock, (struct sockaddr *)&sunaddr, sizeof(sunaddr));
1655  if (res) {
1656  close(ast_consock);
1657  ast_consock = -1;
1658  return 0;
1659  } else
1660  return 1;
1661 }
#define PF_LOCAL
Definition: asterisk.c:293
int errno
static int ast_consock
Definition: asterisk.c:314
#define AF_LOCAL
Definition: asterisk.c:292
void ast_copy_string(char *dst, const char *src, size_t size)
Size-limited null-terminating string copy.
Definition: strings.h:401
const char * ast_config_AST_SOCKET
Definition: options.c:164

◆ ast_unregister_atexit()

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

Unregister a function registered with ast_register_atexit().

Parameters
funcThe callback function to unregister.

Definition at line 1022 of file asterisk.c.

References __ast_unregister_atexit(), AST_LIST_LOCK, AST_LIST_UNLOCK, and ast_atexit::func.

Referenced by unload_module().

1023 {
1027 }
static void __ast_unregister_atexit(void(*func)(void))
Definition: asterisk.c:979
#define AST_LIST_LOCK(head)
Locks a list.
Definition: linkedlists.h:39
#define AST_LIST_UNLOCK(head)
Attempts to unlock a list.
Definition: linkedlists.h:139

◆ ast_unregister_thread()

void ast_unregister_thread ( void *  id)

Definition at line 430 of file asterisk.c.

References ast_free, AST_RWLIST_REMOVE_CURRENT, AST_RWLIST_TRAVERSE_SAFE_BEGIN, AST_RWLIST_TRAVERSE_SAFE_END, AST_RWLIST_UNLOCK, and AST_RWLIST_WRLOCK.

Referenced by dummy_start().

431 {
432  struct thread_list_t *x;
433 
436  if ((void *) x->id == id) {
438  break;
439  }
440  }
443  if (x) {
444  ast_free(x->name);
445  ast_free(x);
446  }
447 }
#define AST_RWLIST_WRLOCK(head)
Write locks a list.
Definition: linkedlists.h:51
#define AST_RWLIST_UNLOCK(head)
Attempts to unlock a read/write based list.
Definition: linkedlists.h:150
#define AST_RWLIST_REMOVE_CURRENT
Definition: linkedlists.h:569
#define AST_RWLIST_TRAVERSE_SAFE_BEGIN
Definition: linkedlists.h:544
#define ast_free(a)
Definition: astmm.h:182
#define AST_RWLIST_TRAVERSE_SAFE_END
Definition: linkedlists.h:616

◆ ast_unreplace_sigchld()

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

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

Referenced by safe_exec_wait().

1078 {
1079  unsigned int level;
1080 
1082  level = --safe_system_level;
1083 
1084  /* only restore the handler if we are the last one */
1085  if (level == 0) {
1086  sigaction(SIGCHLD, &safe_system_prev_handler, NULL);
1087  }
1088 
1090 }
static ast_mutex_t safe_system_lock
Definition: asterisk.c:1055
static struct sigaction safe_system_prev_handler
Definition: asterisk.c:1060
#define ast_mutex_lock(a)
Definition: lock.h:187
#define NULL
Definition: resample.c:96
static unsigned int safe_system_level
Keep track of how many threads are currently trying to wait*() on a child process.
Definition: asterisk.c:1059
#define ast_mutex_unlock(a)
Definition: lock.h:188

◆ asterisk_daemon()

static void asterisk_daemon ( int  isroot,
const char *  runuser,
const char *  rungroup 
)
static

Definition at line 3945 of file asterisk.c.

References __quit_handler(), aco_init(), app_init(), ARRAY_LEN, ast_alaw_init(), ast_alertpipe_init(), ast_aoc_cli_init(), ast_autoservice_init(), ast_bridging_init(), ast_bucket_init(), ast_builtins_init(), ast_channels_init(), ast_clear_flag, ast_cli_perms_init(), ast_cli_register_multiple, ast_close_fds_above_n(), ast_codec_builtin_init(), ast_codec_init(), ast_config_AST_PID, ast_config_AST_RUN_DIR, ast_config_AST_SBIN_DIR, ast_copy_string(), ast_db_put(), ast_device_state_engine_init(), ast_dns_system_resolver_init(), ast_el_initialize(), ast_el_read_char(), ast_el_read_default_histfile(), ast_endpoint_init(), ast_endpoint_stasis_init(), ast_fd_init(), ast_file_init(), ast_format_cache_init(), ast_format_init(), ast_image_init(), ast_json_init(), ast_lastreloadtime, ast_local_init(), ast_mainpid, ast_makesocket(), ast_media_cache_init(), ast_msg_init(), ast_named_locks_init(), ast_opt_always_fork, ast_opt_console, AST_OPT_FLAG_FULLY_BOOTED, AST_OPT_FLAG_HIGH_PRIORITY, ast_opt_high_priority, ast_opt_no_fork, ast_options, ast_parking_stasis_init(), ast_pbx_init(), ast_pbx_uuid_get(), ast_pickup_init(), ast_pj_init(), ast_presence_state_engine_init(), ast_process_pending_reloads(), ast_pthread_create_detached, ast_register_atexit(), ast_register_cleanup(), ast_rtp_engine_init(), ast_sd_notify(), ast_security_stasis_init(), ast_set_flag, ast_set_priority(), ast_sorcery_init(), ast_ssl_init(), ast_startuptime, ast_stasis_system_init(), ast_stun_init(), ast_term_init(), ast_test_init(), ast_timing_init(), ast_tps_init(), ast_translate_init(), ast_tvnow(), ast_ulaw_init(), ast_utf8_init(), ast_utils_init(), ast_uuid_generate_str(), ast_uuid_init(), AST_UUID_STR_LEN, ast_verb, ast_xmldoc_load_documentation(), astdb_init(), astobj2_init(), buf, callerid_init(), canary_exit(), canary_filename, canary_pid, canary_thread(), check_init(), COLOR_BRGREEN, COLORIZE, COLORIZE_FMT, consolehandler(), consolethread, devstate_init(), dns_core_init(), dnsmgr_start_refresh(), el, el_hist, errno, has_priority(), hostname, init_logger(), load_astmm_phase_1(), load_astmm_phase_2(), load_modules(), load_pbx(), load_pbx_app(), load_pbx_builtins(), load_pbx_functions_cli(), load_pbx_hangup_handler(), load_pbx_switch(), load_pbx_variables(), logger_queue_start(), main_atexit(), MAXHOSTNAMELEN, mon_sig_flags, monitor_sig_flags(), multi_thread_safe, mwi_init(), NULL, PATH_MAX, print_intro_message(), publish_fully_booted(), quit_handler(), randompool, read_pjproject_startup_options(), register_config_cli(), run_startup_commands(), set_icon(), set_title(), SHUTDOWN_FAST, sig_alert_pipe, sig_flags, stasis_init(), tdd_init(), term_end(), and threadstorage_init().

Referenced by main().

3946 {
3947  FILE *f;
3948  sigset_t sigs;
3949  int num;
3950  char *buf;
3951  char pbx_uuid[AST_UUID_STR_LEN];
3952 
3953  /* Set time as soon as possible */
3955 
3956  /* This needs to remain as high up in the initial start up as possible.
3957  * daemon causes a fork to occur, which has all sorts of unintended
3958  * consequences for things that interact with threads. This call *must*
3959  * occur before anything in Asterisk spawns or manipulates thread related
3960  * primitives. */
3961 #if HAVE_WORKING_FORK
3963 #ifndef HAVE_SBIN_LAUNCHD
3964  if (daemon(1, 0) < 0) {
3965  fprintf(stderr, "daemon() failed: %s\n", strerror(errno));
3966  } else {
3967  ast_mainpid = getpid();
3968  }
3969 #else
3970  fprintf(stderr, "Mac OS X detected. Use 'launchctl load /Library/LaunchDaemon/org.asterisk.asterisk.plist'.\n");
3971 #endif
3972  }
3973 #endif
3974 
3975  /* At this point everything has been forked successfully,
3976  * we have determined that we aren't attempting to connect to
3977  * an Asterisk instance, and that there isn't one already running. */
3978  multi_thread_safe = 1;
3979 
3981 
3982  /* Check whether high prio was succesfully set by us or some
3983  * other incantation. */
3984  if (has_priority()) {
3986  } else {
3988  }
3989 
3990  /* Spawning of astcanary must happen AFTER the call to daemon(3) */
3991  if (ast_opt_high_priority) {
3992  snprintf(canary_filename, sizeof(canary_filename), "%s/alt.asterisk.canary.tweet.tweet.tweet", ast_config_AST_RUN_DIR);
3993 
3994  /* Don't let the canary child kill Asterisk, if it dies immediately */
3995  sigaction(SIGPIPE, &ignore_sig_handler, NULL);
3996 
3997  canary_pid = fork();
3998  if (canary_pid == 0) {
3999  char canary_binary[PATH_MAX], ppid[12];
4000 
4001  /* Reset signal handler */
4002  signal(SIGCHLD, SIG_DFL);
4003  signal(SIGPIPE, SIG_DFL);
4004 
4006  ast_set_priority(0);
4007  snprintf(ppid, sizeof(ppid), "%d", (int) ast_mainpid);
4008 
4009  /* Use the astcanary binary that we installed */
4010  snprintf(canary_binary, sizeof(canary_binary), "%s/astcanary", ast_config_AST_SBIN_DIR);
4011  execl(canary_binary, "astcanary", canary_filename, ppid, (char *)NULL);
4012 
4013  /* Should never happen */
4014  _exit(1);
4015  } else if (canary_pid > 0) {
4016  pthread_t dont_care;
4018  }
4019 
4020  /* Kill the canary when we exit */
4022  }
4023 
4024  /* Blindly write the PID file. */
4025  unlink(ast_config_AST_PID);
4026  f = fopen(ast_config_AST_PID, "w");
4027  if (f) {
4028  fprintf(f, "%ld\n", (long)ast_mainpid);
4029  fclose(f);
4030  } else {
4031  fprintf(stderr, "Unable to open pid file '%s': %s\n", ast_config_AST_PID, strerror(errno));
4032  }
4033 
4034  /* Initialize the terminal. Since all processes have been forked,
4035  * we can now start using the standard log messages.
4036  */
4037  ast_term_init();
4038  printf("%s", term_end());
4039  fflush(stdout);
4040 
4041  print_intro_message(runuser, rungroup);
4042 
4044 
4045  check_init(astobj2_init(), "AO2");
4046  check_init(ast_named_locks_init(), "Named Locks");
4047 
4048  if (ast_opt_console) {
4049  if (el_hist == NULL || el == NULL)
4052  }
4053 
4054 #ifdef AST_XML_DOCS
4055  /* Load XML documentation. */
4057 #endif
4058 
4059  check_init(astdb_init(), "ASTdb");
4060 
4061  ast_uuid_init();
4062 
4063  if (ast_pbx_uuid_get(pbx_uuid, sizeof(pbx_uuid))) {
4064  ast_uuid_generate_str(pbx_uuid, sizeof(pbx_uuid));
4065  ast_db_put("pbx", "UUID", pbx_uuid);
4066  }
4067  ast_verb(0, "PBX UUID: %s\n", pbx_uuid);
4068 
4069  check_init(ast_json_init(), "libjansson");
4070  ast_ulaw_init();
4071  ast_alaw_init();
4072  ast_utf8_init();
4073  tdd_init();
4074  callerid_init();
4076 
4077  check_init(ast_utils_init(), "Utilities");
4078  check_init(ast_tps_init(), "Task Processor Core");
4079  check_init(ast_fd_init(), "File Descriptor Debugging");
4080  check_init(ast_pbx_init(), "ast_pbx_init");
4081  check_init(aco_init(), "Configuration Option Framework");
4082  check_init(stasis_init(), "Stasis");
4083 #ifdef TEST_FRAMEWORK
4084  check_init(ast_test_init(), "Test Framework");
4085 #endif
4086  check_init(ast_translate_init(), "Translator Core");
4087 
4088  ast_aoc_cli_init();
4089 
4090  check_init(ast_sorcery_init(), "Sorcery");
4091  check_init(ast_codec_init(), "Codecs");
4092  check_init(ast_format_init(), "Formats");
4093  check_init(ast_format_cache_init(), "Format Cache");
4094  check_init(ast_codec_builtin_init(), "Built-in Codecs");
4095  check_init(ast_bucket_init(), "Bucket API");
4096  check_init(ast_stasis_system_init(), "Stasis system-level information");
4097  check_init(ast_endpoint_stasis_init(), "Stasis Endpoint");
4098 
4099  ast_makesocket();
4100  /* GCC 4.9 gives a bogus "right-hand operand of comma expression has
4101  * no effect" warning */
4102  (void) sigemptyset(&sigs);
4103  (void) sigaddset(&sigs, SIGHUP);
4104  (void) sigaddset(&sigs, SIGTERM);
4105  (void) sigaddset(&sigs, SIGINT);
4106  (void) sigaddset(&sigs, SIGPIPE);
4107  (void) sigaddset(&sigs, SIGWINCH);
4108  pthread_sigmask(SIG_BLOCK, &sigs, NULL);
4109  sigaction(SIGURG, &urg_handler, NULL);
4110  signal(SIGINT, __quit_handler);
4111  signal(SIGTERM, __quit_handler);
4112  sigaction(SIGHUP, &hup_handler, NULL);
4113  sigaction(SIGPIPE, &ignore_sig_handler, NULL);
4114 
4115  /* ensure that the random number generators are seeded with a different value every time
4116  Asterisk is started
4117  */
4118  srand((unsigned int) getpid() + (unsigned int) time(NULL));
4119  initstate((unsigned int) getpid() * 65536 + (unsigned int) time(NULL), randompool, sizeof(randompool));
4120 
4122 
4123  check_init(init_logger(), "Logger");
4124  check_init(ast_rtp_engine_init(), "RTP Engine");
4125 
4127 
4128  check_init(ast_timing_init(), "Timing");
4129  check_init(ast_ssl_init(), "SSL");
4131  check_init(ast_pj_init(), "Embedded PJProject");
4132  check_init(app_init(), "App Core");
4133  check_init(mwi_init(), "MWI Core");
4134  check_init(devstate_init(), "Device State Core");
4135  check_init(ast_msg_init(), "Messaging API");
4136  check_init(ast_channels_init(), "Channel");
4137  check_init(ast_endpoint_init(), "Endpoints");
4138  check_init(ast_pickup_init(), "Call Pickup");
4139  check_init(ast_bridging_init(), "Bridging");
4140  check_init(ast_parking_stasis_init(), "Parking Core");
4141  check_init(ast_device_state_engine_init(), "Device State Engine");
4142  check_init(ast_presence_state_engine_init(), "Presence State Engine");
4143  check_init(dns_core_init(), "DNS Resolver Core");
4144  check_init(ast_dns_system_resolver_init(), "Default DNS resolver");
4145  check_init(ast_security_stasis_init(), "Security Stasis Topic and Events");
4146  check_init(ast_image_init(), "Image");
4147  check_init(ast_file_init(), "Generic File Format Support");
4148  check_init(load_pbx(), "load_pbx");
4149  check_init(load_pbx_builtins(), "Builtin PBX Applications");
4150  check_init(load_pbx_functions_cli(), "PBX Functions Support");
4151  check_init(load_pbx_variables(), "PBX Variables Support");
4152  check_init(load_pbx_switch(), "PBX Switch Support");
4153  check_init(load_pbx_app(), "PBX Application Support");
4154  check_init(load_pbx_hangup_handler(), "PBX Hangup Handler Support");
4155  check_init(ast_local_init(), "Local Proxy Channel Driver");
4156 
4157  /* We should avoid most config loads before this point as they can't use realtime. */
4158  check_init(load_modules(), "Module");
4159 
4160  /*
4161  * This has to load after the dynamic modules load, as items in the media
4162  * cache can't be constructed from items in the AstDB without their
4163  * bucket backends.
4164  */
4165  check_init(ast_media_cache_init(), "Media Cache");
4166 
4167  /* loads the cli_permissoins.conf file needed to implement cli restrictions. */
4168  ast_cli_perms_init(0);
4169 
4170  ast_stun_init();
4171 
4173 
4174  if (ast_opt_no_fork) {
4175  consolethread = pthread_self();
4176  }
4177 
4179 
4181 
4184 
4185  pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
4186 
4188 
4192 
4194  ast_sd_notify("READY=1");
4195 
4196  ast_verb(0, COLORIZE_FMT "\n", COLORIZE(COLOR_BRGREEN, 0, "Asterisk Ready."));
4197 
4199 
4200  if (ast_opt_console) {
4201  /* Console stuff now... */
4202  /* Register our quit function */
4203  char title[256];
4204  char hostname[MAXHOSTNAMELEN] = "";
4205 
4206  if (gethostname(hostname, sizeof(hostname) - 1)) {
4207  ast_copy_string(hostname, "<Unknown>", sizeof(hostname));
4208  }
4209 
4211 
4212  set_icon("Asterisk");
4213  snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %ld)", hostname, (long)ast_mainpid);
4214  set_title(title);
4215 
4216  el_set(el, EL_GETCFN, ast_el_read_char);
4217 
4218  for (;;) {
4219  if (sig_flags.need_el_end) {
4220  el_end(el);
4221 
4222  return;
4223  }
4224 
4225  if (sig_flags.need_quit || sig_flags.need_quit_handler) {
4226  quit_handler(0, SHUTDOWN_FAST, 0);
4227  break;
4228  }
4229  buf = (char *) el_gets(el, &num);
4230 
4231  if (!buf && write(1, "", 1) < 0)
4232  return; /* quit */
4233 
4234  if (buf) {
4235  if (buf[strlen(buf)-1] == '\n')
4236  buf[strlen(buf)-1] = '\0';
4237 
4238  consolehandler(buf);
4239  }
4240  }
4241  }
4242 
4243  /* Stall until a quit signal is given */
4245 }
int load_pbx_variables(void)
static int sig_alert_pipe[2]
Definition: asterisk.c:396
int ast_utils_init(void)
Definition: main/utils.c:2240
static void * canary_thread(void *unused)
Definition: asterisk.c:3393
int ast_codec_builtin_init(void)
Initialize built-in codecs within the core.
int ast_file_init(void)
Definition: file.c:1982
int stasis_init(void)
Initialize the Stasis subsystem.
Definition: stasis.c:3057
int ast_stasis_system_init(void)
Initialize the stasis system topic and message types.
int ast_pj_init(void)
Definition: libasteriskpj.c:45
void tdd_init(void)
Definition: tdd.c:94
int ast_named_locks_init(void)
Definition: named_locks.c:52
static void canary_exit(void)
Definition: asterisk.c:3422
int ast_pickup_init(void)
Initialize pickup.
Definition: pickup.c:401
static History * el_hist
Definition: asterisk.c:339
#define ARRAY_LEN(a)
Definition: isdn_lib.c:42
void ast_autoservice_init(void)
Definition: autoservice.c:380
static int ast_makesocket(void)
Definition: asterisk.c:1556
int ast_image_init(void)
Initialize image stuff Initializes all the various image stuff. Basically just registers the cli stuf...
Definition: image.c:212
static struct sigaction ignore_sig_handler
Definition: asterisk.c:1051
int aco_init(void)
int ast_translate_init(void)
Initialize the translation matrix and index to format conversion table.
Definition: translate.c:1612
static void check_init(int init_result, const char *name)
Definition: asterisk.c:3932
void ast_builtins_init(void)
initialize the _full_cmd string in * each of the builtins.
Definition: main/cli.c:2160
static struct ast_cli_entry cli_asterisk[]
Definition: asterisk.c:2573
int ast_format_init(void)
Initialize media format support.
Definition: format.c:77
#define AST_UUID_STR_LEN
Definition: uuid.h:27
const char * ast_config_AST_SBIN_DIR
Definition: options.c:160
int ast_media_cache_init(void)
Initialize the media cache.
Definition: media_cache.c:687
#define ast_pthread_create_detached(a, b, c, d)
Definition: utils.h:503
static struct sigaction urg_handler
Definition: asterisk.c:1674
int register_config_cli(void)
Exposed initialization method for core process.
Definition: main/config.c:4066
char buf[BUFSIZE]
Definition: eagi_proxy.c:66
static int ast_el_read_char(EditLine *editline, CHAR_T_LIBEDIT *cp)
Definition: asterisk.c:2626
#define ast_set_flag(p, flag)
Definition: utils.h:70
int mwi_init(void)
Initialize the mwi core.
Definition: mwi.c:502
int ast_endpoint_init(void)
Endpoint support initialization.
void load_astmm_phase_1(void)
Initialize malloc debug phase 1.
Definition: astmm.c:1557
static int multi_thread_safe
Definition: asterisk.c:388
int load_pbx_switch(void)
Definition: pbx_switch.c:125
void ast_close_fds_above_n(int n)
Common routine for child processes, to close all fds prior to exec(2)
Definition: main/app.c:2965
int ast_presence_state_engine_init(void)
int ast_tps_init(void)
int ast_bucket_init(void)
Initialize bucket support.
Definition: bucket.c:953
static void ast_el_read_default_histfile(void)
Definition: asterisk.c:3121
static EditLine * el
Definition: asterisk.c:340
static void read_pjproject_startup_options(void)
Definition: asterisk.c:3334
int ast_bridging_init(void)
Initialize the bridging system.
Definition: bridge.c:5577
int ast_xmldoc_load_documentation(void)
Load XML documentation. Provided by xmldoc.c.
Definition: xmldoc.c:2879
int ast_security_stasis_init(void)
initializes stasis topic/event types for ast_security_topic and ast_security_event_type ...
int ast_endpoint_stasis_init(void)
Initialization function for endpoint stasis support.
#define ast_cli_register_multiple(e, len)
Register multiple commands.
Definition: cli.h:265
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition: time.h:150
int ast_test_init(void)
Definition: test.c:1221
int ast_dns_system_resolver_init(void)
Initializes the resolver.
const char * ast_config_AST_RUN_DIR
Definition: options.c:159
void ast_alaw_init(void)
To init the alaw to slinear conversion stuff, this needs to be run.
Definition: alaw.c:152
#define MAXHOSTNAMELEN
Definition: network.h:69
int ast_format_cache_init(void)
Initialize format cache support within the core.
Definition: format_cache.c:370
struct timeval ast_lastreloadtime
Definition: asterisk.c:337
pid_t ast_mainpid
Definition: asterisk.c:315
#define NULL
Definition: resample.c:96
#define ast_verb(level,...)
Definition: logger.h:455
const char * term_end(void)
Definition: term.c:356
#define ast_opt_console
Definition: options.h:109
int ast_sorcery_init(void)
Initialize the sorcery API.
Definition: sorcery.c:384
#define COLORIZE(fg, bg, str)
Definition: term.h:68
int ast_codec_init(void)
Initialize codec support within the core.
Definition: codec.c:249
static void quit_handler(int num, shutdown_nice_t niceness, int restart)
Definition: asterisk.c:1869
int load_pbx_hangup_handler(void)
struct timeval ast_startuptime
Definition: asterisk.c:336
static pthread_t mon_sig_flags
Definition: asterisk.c:385
void callerid_init(void)
CallerID Initialization.
Definition: callerid.c:115
int ast_term_init(void)
Definition: term.c:92
static void __quit_handler(int num)
Definition: asterisk.c:2100
int ast_sd_notify(const char *state)
a wrapper for sd_notify(): notify systemd of any state changes.
Definition: io.c:392
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 ac...
Definition: asterisk.c:1799
int dns_core_init(void)
Definition: dns_core.c:614
static void set_title(char *text)
Set an X-term or screen title.
Definition: asterisk.c:1723
const char * ast_config_AST_PID
Definition: options.c:163
static struct sigaction hup_handler
Definition: asterisk.c:1697
int ast_utf8_init(void)
Register UTF-8 tests.
Definition: utf8.c:375
#define COLORIZE_FMT
Shortcut macros for coloring a set of text.
Definition: term.h:67
int devstate_init(void)
Initialize the device state core.
Definition: devicestate.c:898
int init_logger(void)
Definition: logger.c:1782
#define COLOR_BRGREEN
Definition: term.h:52
static void publish_fully_booted(void)
Definition: asterisk.c:939
int ast_alertpipe_init(int alert_pipe[2])
Initialize an alert pipe.
Definition: alertpipe.c:38
int ast_aoc_cli_init(void)
enable aoc cli options
Definition: aoc.c:2026
static pthread_t consolethread
Definition: asterisk.c:384
static char canary_filename[128]
Definition: asterisk.c:387
int ast_device_state_engine_init(void)
Initialize the device state engine in separate thread.
Definition: devicestate.c:618
void ast_ulaw_init(void)
Set up mu-law conversion table.
Definition: ulaw.c:173
void ast_uuid_init(void)
Initialize the UUID system.
Definition: uuid.c:194
static void run_startup_commands(void)
Definition: asterisk.c:3432
void ast_stun_init(void)
Initialize the STUN system in Asterisk.
Definition: stun.c:523
static char randompool[256]
Definition: asterisk.c:390
static struct @329 sig_flags
int ast_pbx_uuid_get(char *pbx_uuid, int length)
Retrieve the PBX UUID.
Definition: asterisk.c:934
int ast_parking_stasis_init(void)
initializes the rtp engine arrays
Definition: parking.c:53
int ast_local_init(void)
Initialize the local proxy channel.
Definition: core_local.c:1139
int ast_register_atexit(void(*func)(void))
Register a function to be executed before Asterisk exits.
Definition: asterisk.c:1012
int errno
int astobj2_init(void)
Definition: astobj2.c:1166
int ast_register_cleanup(void(*func)(void))
Register a function to be executed before Asterisk gracefully exits.
Definition: asterisk.c:1017
static void set_icon(char *text)
Definition: asterisk.c:1729
char * ast_uuid_generate_str(char *buf, size_t size)
Generate a UUID string.
Definition: uuid.c:143
int ast_rtp_engine_init(void)
initializes the rtp engine arrays
Definition: rtp_engine.c:3562
static int canary_pid
Definition: asterisk.c:386
#define ast_opt_always_fork
Definition: options.h:126
void logger_queue_start(void)
Start the ast_queue_log() logger.
Definition: logger.c:1766
static void main_atexit(void)
Definition: asterisk.c:3485
#define ast_clear_flag(p, flag)
Definition: utils.h:77
int ast_ssl_init(void)
void load_astmm_phase_2(void)
Initialize malloc debug phase 2.
Definition: astmm.c:1561
int ast_pbx_init(void)
Definition: pbx.c:8963
struct ast_flags ast_options
Definition: options.c:61
int load_pbx_app(void)
Definition: pbx_app.c:511
void threadstorage_init(void)
Definition: threadstorage.c:35
static int ast_el_initialize(void)
Definition: asterisk.c:3023
void ast_copy_string(char *dst, const char *src, size_t size)
Size-limited null-terminating string copy.
Definition: strings.h:401
int ast_json_init(void)
Initialize the JSON library.
Definition: json.c:705
void dnsmgr_start_refresh(void)
Definition: dnsmgr.c:302
static struct ast_str * hostname
Definition: cdr_mysql.c:77
int load_modules(void)
Definition: loader.c:2336
static void consolehandler(const char *s)
Definition: asterisk.c:2244
static int has_priority(void)
Check whether we were set to high(er) priority.
Definition: asterisk.c:1736
int ast_db_put(const char *family, const char *key, const char *value)
Store value addressed by family/key.
Definition: main/db.c:327
#define PATH_MAX
Definition: asterisk.h:40
int ast_timing_init(void)
Definition: timing.c:289
int load_pbx_functions_cli(void)
int ast_fd_init(void)
Definition: astfd.c:370
int ast_channels_init(void)
Definition: channel.c:7948
static struct ast_cli_entry cli_asterisk_shutdown[]
Shutdown Asterisk CLI commands.
Definition: asterisk.c:2564
int load_pbx_builtins(void)
#define ast_opt_no_fork
Definition: options.h:107
int ast_msg_init(void)
Definition: message.c:1693
static void print_intro_message(const char *runuser, const char *rungroup)
Definition: asterisk.c:3472
int load_pbx(void)
Definition: pbx.c:8441
void ast_process_pending_reloads(void)
Process reload requests received during startup.
Definition: loader.c:1405
int astdb_init(void)
Definition: main/db.c:1082
static void * monitor_sig_flags(void *unused)
Definition: asterisk.c:3368
int ast_cli_perms_init(int reload)
Definition: main/cli.c:2032
int app_init(void)
Initialize the application core.
Definition: main/app.c:3128
#define ast_opt_high_priority
Definition: options.h:110

◆ can_safely_quit()

static int can_safely_quit ( shutdown_nice_t  niceness,
int  restart 
)
static

Definition at line 1921 of file asterisk.c.

References ast_begin_shutdown(), ast_cdr_engine_term(), ast_msg_shutdown(), ast_mutex_lock, ast_mutex_unlock, ast_opt_console, ast_softhangup_all(), ast_verb, ast_verbose(), NOT_SHUTTING_DOWN, safe_system_lock, SHUTDOWN_NICE, SHUTDOWN_NORMAL, SHUTDOWN_REALLY_NICE, SHUTDOWN_TIMEOUT, SHUTTING_DOWN, SHUTTING_DOWN_FINAL, shuttingdown, and wait_for_channels_to_die().

Referenced by ast_begin_shutdown(), and quit_handler().

1922 {
1923  int waited = 0;
1924 
1925  /* Check if someone else isn't already doing this. */
1927  if (shuttingdown != NOT_SHUTTING_DOWN && niceness >= shuttingdown) {
1928  /* Already in progress and other request was less nice. */
1930  ast_verbose("Ignoring asterisk %s request, already in progress.\n", restart ? "restart" : "shutdown");
1931  return 0;
1932  }
1933  shuttingdown = niceness;
1935 
1936  /* Try to get as many CDRs as possible submitted to the backend engines
1937  * (if in batch mode). really_quit happens to call it again when running
1938  * the atexit handlers, otherwise this would be a bit early. */
1940 
1941  /*
1942  * Shutdown the message queue for the technology agnostic message channel.
1943  * This has to occur before we pause shutdown pending ast_undestroyed_channels.
1944  *
1945  * XXX This is not reversed on shutdown cancel.
1946  */
1947  ast_msg_shutdown();
1948 
1949  if (niceness == SHUTDOWN_NORMAL) {
1950  /* Begin shutdown routine, hanging up active channels */
1952  if (ast_opt_console) {
1953  ast_verb(0, "Beginning asterisk %s....\n", restart ? "restart" : "shutdown");
1954  }
1956  waited |= wait_for_channels_to_die(niceness, SHUTDOWN_TIMEOUT);
1957  } else if (niceness >= SHUTDOWN_NICE) {
1958  if (niceness != SHUTDOWN_REALLY_NICE) {
1960  }
1961  if (ast_opt_console) {
1962  ast_verb(0, "Waiting for inactivity to perform %s...\n", restart ? "restart" : "halt");
1963  }
1964  waited |= wait_for_channels_to_die(niceness, -1);
1965  }
1966 
1967  /* Re-acquire lock and check if someone changed the niceness, in which
1968  * case someone else has taken over the shutdown.
1969  */
1971  if (shuttingdown != niceness) {
1973  ast_verb(0, "Asterisk %s cancelled.\n", restart ? "restart" : "shutdown");
1974  }
1976  return 0;
1977  }
1978 
1979  if (niceness >= SHUTDOWN_REALLY_NICE) {
1982 
1983  /* No more Mr. Nice guy. We are committed to shutting down now. */
1987 
1989  }
1992 
1993  if (niceness >= SHUTDOWN_NORMAL && waited) {
1994  /*
1995  * We were not idle. Give things in progress a chance to
1996  * recognize the final shutdown phase.
1997  */
1998  sleep(1);
1999  }
2000  return 1;
2001 }
static ast_mutex_t safe_system_lock
Definition: asterisk.c:1055
static int wait_for_channels_to_die(shutdown_nice_t niceness, int seconds)
Definition: asterisk.c:1891
#define ast_mutex_lock(a)
Definition: lock.h:187
void ast_verbose(const char *fmt,...)
Definition: extconf.c:2207
#define ast_verb(level,...)
Definition: logger.h:455
#define ast_opt_console
Definition: options.h:109
void ast_softhangup_all(void)
Soft hangup all active channels.
Definition: channel.c:489
static shutdown_nice_t shuttingdown
Definition: asterisk.c:378
void ast_cdr_engine_term(void)
Definition: cdr.c:4577
static void ast_begin_shutdown(void)
Definition: asterisk.c:1857
#define SHUTDOWN_TIMEOUT
Definition: asterisk.c:1878
void ast_msg_shutdown(void)
Definition: message.c:1652
#define ast_mutex_unlock(a)
Definition: lock.h:188

◆ canary_exit()

static void canary_exit ( void  )
static

Definition at line 3422 of file asterisk.c.

References canary_pid, and status.

Referenced by asterisk_daemon().

3423 {
3424  if (canary_pid > 0) {
3425  int status;
3426  kill(canary_pid, SIGKILL);
3427  waitpid(canary_pid, &status, 0);
3428  }
3429 }
static int canary_pid
Definition: asterisk.c:386
jack_status_t status
Definition: app_jack.c:146

◆ canary_thread()

static void* canary_thread ( void *  unused)
static

Definition at line 3393 of file asterisk.c.

References ast_log, ast_tvnow(), canary_filename, LOG_WARNING, NULL, and set_priority_all().

Referenced by asterisk_daemon().

3394 {
3395  struct stat canary_stat;
3396  struct timeval now;
3397 
3398  /* Give the canary time to sing */
3399  sleep(120);
3400 
3401  for (;;) {
3402  now = ast_tvnow();
3403  if (stat(canary_filename, &canary_stat) || now.tv_sec > canary_stat.st_mtime + 60) {
3405  "The canary is no more. He has ceased to be! "
3406  "He's expired and gone to meet his maker! "
3407  "He's a stiff! Bereft of life, he rests in peace. "
3408  "His metabolic processes are now history! He's off the twig! "
3409  "He's kicked the bucket. He's shuffled off his mortal coil, "
3410  "run down the curtain, and joined the bleeding choir invisible!! "
3411  "THIS is an EX-CANARY. (Reducing priority)\n");
3412  set_priority_all(0);
3413  pthread_exit(NULL);
3414  }
3415 
3416  /* Check the canary once a minute */
3417  sleep(60);
3418  }
3419 }
#define LOG_WARNING
Definition: logger.h:274
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition: time.h:150
#define NULL
Definition: resample.c:96
#define ast_log
Definition: astobj2.c:42
static char canary_filename[128]
Definition: asterisk.c:387
static int set_priority_all(int pri)
Set priority on all known threads.
Definition: asterisk.c:1756

◆ check_init()

static void check_init ( int  init_result,
const char *  name 
)
inlinestatic

Definition at line 3932 of file asterisk.c.

References ast_is_logger_initialized(), ast_log, ast_run_atexits(), LOG_ERROR, and term_quit().

Referenced by asterisk_daemon().

3933 {
3934  if (init_result) {
3935  if (ast_is_logger_initialized()) {
3936  ast_log(LOG_ERROR, "%s initialization failed. ASTERISK EXITING!\n%s", name, term_quit());
3937  } else {
3938  fprintf(stderr, "%s initialization failed. ASTERISK EXITING!\n%s", name, term_quit());
3939  }
3940  ast_run_atexits(0);
3941  exit(init_result == -2 ? 2 : 1);
3942  }
3943 }
const char * term_quit(void)
Definition: term.c:361
#define ast_log
Definition: astobj2.c:42
#define LOG_ERROR
Definition: logger.h:285
int ast_is_logger_initialized(void)
Test if logger is initialized.
Definition: logger.c:1753
static const char name[]
Definition: cdr_mysql.c:74
static void ast_run_atexits(int run_cleanups)
Definition: asterisk.c:965

◆ cli_complete()

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

Definition at line 2914 of file asterisk.c.

References ast_asprintf, AST_CLI_COMPLETE_EOF, ast_cli_completion_vector(), ast_cli_display_match_list(), ast_consock, ast_el_strtoarr(), ast_free, ast_opt_remote, ast_realloc, ast_strlen_zero, AST_VECTOR_CALLBACK_VOID, AST_VECTOR_GET, AST_VECTOR_PTR_FREE, AST_VECTOR_SIZE, CMD_MATCHESARRAY, fdsend(), if(), len(), and retval.

Referenced by ast_el_initialize().

2915 {
2916  int len = 0;
2917  char *ptr;
2918  struct ast_vector_string *matches;
2919  int retval = CC_ERROR;
2920  char savechr;
2921  int res;
2922 
2923  LineInfo *lf = (LineInfo *)el_line(editline);
2924 
2925  savechr = *(char *)lf->cursor;
2926  *(char *)lf->cursor = '\0';
2927  ptr = (char *)lf->cursor;
2928  if (ptr) {
2929  while (ptr > lf->buffer) {
2930  if (isspace(*ptr)) {
2931  ptr++;
2932  break;
2933  }
2934  ptr--;
2935  }
2936  }
2937 
2938  len = lf->cursor - ptr;
2939 
2940  if (ast_opt_remote) {
2941 #define CMD_MATCHESARRAY "_COMMAND MATCHESARRAY \"%s\" \"%s\""
2942  char *mbuf;
2943  char *new_mbuf;
2944  int mlen = 0;
2945  int maxmbuf = ast_asprintf(&mbuf, CMD_MATCHESARRAY, lf->buffer, ptr);
2946 
2947  if (maxmbuf == -1) {
2948  *((char *) lf->cursor) = savechr;
2949 
2950  return (char *)(CC_ERROR);
2951  }
2952 
2953  fdsend(ast_consock, mbuf);
2954  res = 0;
2955  mlen = 0;
2956  mbuf[0] = '\0';
2957 
2958  while (!strstr(mbuf, AST_CLI_COMPLETE_EOF) && res != -1) {
2959  if (mlen + 1024 > maxmbuf) {
2960  /* Expand buffer to the next 1024 byte increment plus a NULL terminator. */
2961  maxmbuf = mlen + 1024;
2962  new_mbuf = ast_realloc(mbuf, maxmbuf + 1);
2963  if (!new_mbuf) {
2964  ast_free(mbuf);
2965  *((char *) lf->cursor) = savechr;
2966 
2967  return (char *)(CC_ERROR);
2968  }
2969  mbuf = new_mbuf;
2970  }
2971  /* Only read 1024 bytes at a time */
2972  res = read(ast_consock, mbuf + mlen, 1024);
2973  if (res > 0) {
2974  mlen += res;
2975  mbuf[mlen] = '\0';
2976  }
2977  }
2978  mbuf[mlen] = '\0';
2979 
2980  matches = ast_el_strtoarr(mbuf);
2981  ast_free(mbuf);
2982  } else {
2983  matches = ast_cli_completion_vector((char *)lf->buffer, ptr);
2984  }
2985 
2986  if (matches) {
2987  int i;
2988  int maxlen, match_len;
2989  const char *best_match = AST_VECTOR_GET(matches, 0);
2990 
2991  if (!ast_strlen_zero(best_match)) {
2992  el_deletestr(editline, (int) len);
2993  el_insertstr(editline, best_match);
2994  retval = CC_REFRESH;
2995  }
2996 
2997  if (AST_VECTOR_SIZE(matches) == 2) {
2998  /* Found an exact match */
2999  el_insertstr(editline, " ");
3000  retval = CC_REFRESH;
3001  } else {
3002  /* Must be more than one match */
3003  for (i = 1, maxlen = 0; i < AST_VECTOR_SIZE(matches); i++) {
3004  match_len = strlen(AST_VECTOR_GET(matches, i));
3005  if (match_len > maxlen) {
3006  maxlen = match_len;
3007  }
3008  }
3009 
3010  fprintf(stdout, "\n");
3011  ast_cli_display_match_list(matches, maxlen);
3012  retval = CC_REDISPLAY;
3013  }
3015  AST_VECTOR_PTR_FREE(matches);
3016  }
3017 
3018  *((char *) lf->cursor) = savechr;
3019 
3020  return (char *)(long)retval;
3021 }
#define ast_realloc(p, len)
A wrapper for realloc()
Definition: astmm.h:228
static struct ast_vector_string * ast_el_strtoarr(char *buf)
Definition: asterisk.c:2853
#define AST_CLI_COMPLETE_EOF
Definition: cli.h:52
if(!yyg->yy_init)
Definition: ast_expr2f.c:868
static void ast_cli_display_match_list(struct ast_vector_string *matches, int max)
Definition: asterisk.c:2887
#define ast_asprintf(ret, fmt,...)
A wrapper for asprintf()
Definition: astmm.h:269
struct ast_vector_string * ast_cli_completion_vector(const char *text, const char *word)
Generates a vector of strings for CLI completion.
Definition: main/cli.c:2682
static int fdsend(int fd, const char *s)
Definition: asterisk.c:1030
#define ast_opt_remote
Definition: options.h:112
static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
#define ast_strlen_zero(a)
Definition: muted.c:73
static int ast_consock
Definition: asterisk.c:314
#define ast_free(a)
Definition: astmm.h:182
#define AST_VECTOR_PTR_FREE(vec)
Deallocates this vector pointer.
Definition: vector.h:189
#define AST_VECTOR_GET(vec, idx)
Get an element from a vector.
Definition: vector.h:678
static ENTRY retval
Definition: hsearch.c:50
#define CMD_MATCHESARRAY
#define AST_VECTOR_SIZE(vec)
Get the number of elements in a vector.
Definition: vector.h:611
#define AST_VECTOR_CALLBACK_VOID(vec, callback,...)
Execute a callback on every element in a vector disregarding callback return.
Definition: vector.h:861

◆ cli_prompt()

static char* cli_prompt ( EditLine *  editline)
static

Definition at line 2727 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_term_color_code(), ast_tvnow(), ASTERISK_PROMPT, COLOR_BLACK, COLOR_WHITE, getloadavg(), hostname, MAXHOSTNAMELEN, NULL, remotehostname, console::t, and tmp().

Referenced by ast_el_initialize().

2728 {
2729  char tmp[100];
2730  char *pfmt;
2731  int color_used = 0;
2732  static int cli_prompt_changes = 0;
2733  struct passwd *pw;
2734  struct group *gr;
2735 
2736  if (prompt == NULL) {
2737  prompt = ast_str_create(100);
2738  } else if (!cli_prompt_changes) {
2739  return ast_str_buffer(prompt);
2740  } else {
2742  }
2743 
2744  if ((pfmt = getenv("ASTERISK_PROMPT"))) {
2745  char *t = pfmt;
2746  struct timeval ts = ast_tvnow();
2747  while (*t != '\0') {
2748  if (*t == '%') {
2749  char hostname[MAXHOSTNAMELEN] = "";
2750  int i, which;
2751  struct ast_tm tm = { 0, };
2752  int fgcolor = COLOR_WHITE, bgcolor = COLOR_BLACK;
2753 
2754  t++;
2755  switch (*t) {
2756  case 'C': /* color */
2757  t++;
2758  if (sscanf(t, "%30d;%30d%n", &fgcolor, &bgcolor, &i) == 2) {
2759  ast_term_color_code(&prompt, fgcolor, bgcolor);
2760  t += i - 1;
2761  } else if (sscanf(t, "%30d%n", &fgcolor, &i) == 1) {
2762  ast_term_color_code(&prompt, fgcolor, 0);
2763  t += i - 1;
2764  }
2765 
2766  /* If the color has been reset correctly, then there's no need to reset it later */
2767  color_used = ((fgcolor == COLOR_WHITE) && (bgcolor == COLOR_BLACK)) ? 0 : 1;
2768  break;
2769  case 'd': /* date */
2770  if (ast_localtime(&ts, &tm, NULL)) {
2771  ast_strftime(tmp, sizeof(tmp), "%Y-%m-%d", &tm);
2772  ast_str_append(&prompt, 0, "%s", tmp);
2773  cli_prompt_changes++;
2774  }
2775  break;
2776  case 'g': /* group */
2777  if ((gr = getgrgid(getgid()))) {
2778  ast_str_append(&prompt, 0, "%s", gr->gr_name);
2779  }
2780  break;
2781  case 'h': /* hostname */
2782  if (!gethostname(hostname, sizeof(hostname) - 1)) {
2783  ast_str_append(&prompt, 0, "%s", hostname);
2784  } else {
2785  ast_str_append(&prompt, 0, "%s", "localhost");
2786  }
2787  break;
2788  case 'H': /* short hostname */
2789  if (!gethostname(hostname, sizeof(hostname) - 1)) {
2790  char *dotptr;
2791  if ((dotptr = strchr(hostname, '.'))) {
2792  *dotptr = '\0';
2793  }
2794  ast_str_append(&prompt, 0, "%s", hostname);
2795  } else {
2796  ast_str_append(&prompt, 0, "%s", "localhost");
2797  }
2798  break;
2799 #ifdef HAVE_GETLOADAVG
2800  case 'l': /* load avg */
2801  t++;
2802  if (sscanf(t, "%30d", &which) == 1 && which > 0 && which <= 3) {
2803  double list[3];
2804  getloadavg(list, 3);
2805  ast_str_append(&prompt, 0, "%.2f", list[which - 1]);
2806  cli_prompt_changes++;
2807  }
2808  break;
2809 #endif
2810  case 's': /* Asterisk system name (from asterisk.conf) */
2812  break;
2813  case 't': /* time */
2814  if (ast_localtime(&ts, &tm, NULL)) {
2815  ast_strftime(tmp, sizeof(tmp), "%H:%M:%S", &tm);
2816  ast_str_append(&prompt, 0, "%s", tmp);
2817  cli_prompt_changes++;
2818  }
2819  break;
2820  case 'u': /* username */
2821  if ((pw = getpwuid(getuid()))) {
2822  ast_str_append(&prompt, 0, "%s", pw->pw_name);
2823  }
2824  break;
2825  case '#': /* process console or remote? */
2826  ast_str_append(&prompt, 0, "%c", ast_opt_remote ? '>' : '#');
2827  break;
2828  case '%': /* literal % */
2829  ast_str_append(&prompt, 0, "%c", '%');
2830  break;
2831  case '\0': /* % is last character - prevent bug */
2832  t--;
2833  break;
2834  }
2835  } else {
2836  ast_str_append(&prompt, 0, "%c", *t);
2837  }
2838  t++;
2839  }
2840  if (color_used) {
2841  /* Force colors back to normal at end */
2842  ast_term_color_code(&prompt, 0, 0);
2843  }
2844  } else {
2845  ast_str_set(&prompt, 0, "%s%s",
2847  ASTERISK_PROMPT);
2848  }
2849 
2850  return ast_str_buffer(prompt);
2851 }
char * ast_str_buffer(const struct ast_str *buf)
Returns the string buffer within the ast_str buf.
Definition: strings.h:714
static int tmp()
Definition: bt_open.c:389
struct ast_tm * ast_localtime(const struct timeval *timep, struct ast_tm *p_tm, const char *zone)
Timezone-independent version of localtime_r(3).
Definition: localtime.c:1739
int ast_term_color_code(struct ast_str **str, int fgcolor, int bgcolor)
Append a color sequence to an ast_str.
Definition: term.c:245
#define COLOR_WHITE
Definition: term.h:61
int ast_str_append(struct ast_str **buf, ssize_t max_len, const char *fmt,...)
Append to a thread local dynamic string.
Definition: strings.h:1091
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition: time.h:150
#define MAXHOSTNAMELEN
Definition: network.h:69
#define NULL
Definition: resample.c:96
const char * ast_config_AST_SYSTEM_NAME
Definition: options.c:167
int ast_str_set(struct ast_str **buf, ssize_t max_len, const char *fmt,...)
Set a dynamic string using variable arguments.
Definition: strings.h:1065
#define COLOR_BLACK
Definition: term.h:47
#define ast_opt_remote
Definition: options.h:112
static char * remotehostname
Definition: asterisk.c:341
int ast_strftime(char *buf, size_t len, const char *format, const struct ast_tm *tm)
Special version of strftime(3) that handles fractions of a second. Takes the same arguments as strfti...
Definition: localtime.c:2524
void ast_str_reset(struct ast_str *buf)
Reset the content of a dynamic string. Useful before a series of ast_str_append.
Definition: strings.h:653
static struct ast_str * hostname
Definition: cdr_mysql.c:77
int getloadavg(double *list, int nelem)
static struct ast_str * prompt
Definition: asterisk.c:2725
#define ASTERISK_PROMPT
Definition: asterisk.c:2554
#define ast_str_create(init_len)
Create a malloc&#39;ed dynamic length string.
Definition: strings.h:620

◆ console_print()

static int console_print ( const char *  s)
static

Definition at line 2162 of file asterisk.c.

References ast_strlen_zero, ast_threadstorage_get(), c, console_state, console::option_verbose, prefix, set_header(), VERBOSE_HASMAGIC, console_state_data::verbose_line_level, and VERBOSE_MAGIC2LEVEL.

Referenced by ast_console_puts_mutable(), ast_console_puts_mutable_full(), and ast_el_read_char().

2163 {
2164  struct console_state_data *state =
2165  ast_threadstorage_get(&console_state, sizeof(*state));
2166 
2167  char prefix[80];
2168  const char *c;
2169  int num, res = 0;
2170  unsigned int newline;
2171 
2172  do {
2173  if (VERBOSE_HASMAGIC(s)) {
2174 
2175  /* always use the given line's level, otherwise
2176  we'll use the last line's level */
2178 
2179  /* move past magic */
2180  s++;
2181 
2182  set_header(prefix, sizeof(prefix), state->verbose_line_level);
2183  } else {
2184  *prefix = '\0';
2185  }
2186  c = s;
2187 
2188  /* for a given line separate on verbose magic, newline, and eol */
2189  if ((s = strchr(c, '\n'))) {
2190  ++s;
2191  newline = 1;
2192  } else {
2193  s = strchr(c, '\0');
2194  newline = 0;
2195  }
2196 
2197  /* check if we should write this line after calculating begin/end
2198  so we process the case of a higher level line embedded within
2199  two lower level lines */
2200  if (state->verbose_line_level > option_verbose) {
2201  continue;
2202  }
2203 
2204  if (!ast_strlen_zero(prefix)) {
2205  fputs(prefix, stdout);
2206  }
2207 
2208  num = s - c;
2209  if (fwrite(c, sizeof(char), num, stdout) < num) {
2210  break;
2211  }
2212 
2213  if (!res) {
2214  /* if at least some info has been written
2215  we'll want to return true */
2216  res = 1;
2217  }
2218  } while (*s);
2219 
2220  if (newline) {
2221  /* if ending on a newline then reset last level to zero
2222  since what follows may be not be logging output */
2223  state->verbose_line_level = 0;
2224  }
2225 
2226  if (res) {
2227  fflush(stdout);
2228  }
2229 
2230  return res;
2231 }
void * ast_threadstorage_get(struct ast_threadstorage *ts, size_t init_size)
Retrieve thread storage.
int option_verbose
Definition: options.c:67
static struct test_val c
static struct ast_threadstorage console_state
Definition: asterisk.c:2160
#define VERBOSE_HASMAGIC(x)
Definition: logger.h:193
#define ast_strlen_zero(a)
Definition: muted.c:73
#define VERBOSE_MAGIC2LEVEL(x)
Definition: logger.h:192
static void set_header(char *outbuf, int maxout, char level)
Definition: asterisk.c:2115
static char prefix[MAX_PREFIX]
Definition: http.c:141

◆ console_state_init()

static int console_state_init ( void *  ptr)
static

Definition at line 2153 of file asterisk.c.

References console_state_data::verbose_line_level.

2154 {
2155  struct console_state_data *state = ptr;
2156  state->verbose_line_level = 0;
2157  return 0;
2158 }

◆ consolehandler()

static void consolehandler ( const char *  s)
static

Definition at line 2244 of file asterisk.c.

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

Referenced by asterisk_daemon().

2245 {
2246  printf("%s", term_end());
2247  fflush(stdout);
2248 
2249  /* Called when readline data is available */
2250  if (!ast_all_zeros(s))
2251  ast_el_add_history(s);
2252  /* The real handler for bang */
2253  if (s[0] == '!') {
2254  if (s[1])
2255  ast_safe_system(s+1);
2256  else
2257  ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
2258  } else
2259  ast_cli_command(STDOUT_FILENO, s);
2260 }
static int ast_all_zeros(const char *s)
Definition: asterisk.c:2233
static int ast_el_add_history(const char *)
Definition: asterisk.c:3078
const char * term_end(void)
Definition: term.c:356
ast_cli_command
calling arguments for new-style handlers.
Definition: cli.h:151
int ast_safe_system(const char *s)
Safely spawn an OS shell command while closing file descriptors.
Definition: asterisk.c:1193

◆ env_init()

static void env_init ( void  )
static

Definition at line 3460 of file asterisk.c.

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

Referenced by main().

3461 {
3462  setenv("AST_SYSTEMNAME", ast_config_AST_SYSTEM_NAME, 1);
3463  setenv("AST_BUILD_HOST", ast_build_hostname, 1);
3464  setenv("AST_BUILD_DATE", ast_build_date, 1);
3465  setenv("AST_BUILD_KERNEL", ast_build_kernel, 1);
3466  setenv("AST_BUILD_MACHINE", ast_build_machine, 1);
3467  setenv("AST_BUILD_OS", ast_build_os, 1);
3468  setenv("AST_BUILD_USER", ast_build_user, 1);
3469  setenv("AST_VERSION", ast_get_version(), 1);
3470 }
const char * ast_build_user
Definition: buildinfo.c:34
const char * ast_get_version(void)
Retrieve the Asterisk version string.
const char * ast_build_date
Definition: buildinfo.c:33
const char * ast_build_os
Definition: buildinfo.c:32
const char * ast_build_hostname
Definition: buildinfo.c:29
const char * ast_build_kernel
Definition: buildinfo.c:30
const char * ast_config_AST_SYSTEM_NAME
Definition: options.c:167
const char * ast_build_machine
Definition: buildinfo.c:31
int setenv(const char *name, const char *value, int overwrite)

◆ fdprint()

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

Definition at line 1036 of file asterisk.c.

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

1037 {
1038  return write(fd, s, strlen(s));
1039 }

◆ fdsend()

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

Definition at line 1030 of file asterisk.c.

Referenced by cli_complete(), and send_rasterisk_connect_commands().

1031 {
1032  return write(fd, s, strlen(s) + 1);
1033 }

◆ handle_abort_shutdown()

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

Definition at line 2436 of file asterisk.c.

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

2437 {
2438  switch (cmd) {
2439  case CLI_INIT:
2440  e->command = "core abort shutdown";
2441  e->usage =
2442  "Usage: core abort shutdown\n"
2443  " Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
2444  " call operations.\n";
2446  return NULL;
2447  case CLI_GENERATE:
2448  return NULL;
2449  }
2450 
2451  if (a->argc != e->args)
2452  return CLI_SHOWUSAGE;
2453 
2455 
2456  return CLI_SUCCESS;
2457 }
const int argc
Definition: cli.h:160
Definition: cli.h:152
int ast_cancel_shutdown(void)
Cancel an existing shutdown and return to normal operation.
Definition: asterisk.c:1839
#define NULL
Definition: resample.c:96
int args
This gets set in ast_cli_register()
Definition: cli.h:185
int ast_cli_allow_at_shutdown(struct ast_cli_entry *e)
Definition: main/cli.c:2977
#define CLI_SHOWUSAGE
Definition: cli.h:45
char * command
Definition: cli.h:186
const char * usage
Definition: cli.h:177
#define CLI_SUCCESS
Definition: cli.h:44

◆ handle_bang()

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

Definition at line 2459 of file asterisk.c.

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

2460 {
2461  switch (cmd) {
2462  case CLI_INIT:
2463  e->command = "!";
2464  e->usage =
2465  "Usage: !<command>\n"
2466  " Executes a given shell command\n";
2467  return NULL;
2468  case CLI_GENERATE:
2469  return NULL;
2470  }
2471 
2472  return CLI_SUCCESS;
2473 }
Definition: cli.h:152
#define NULL
Definition: resample.c:96
char * command
Definition: cli.h:186
const char * usage
Definition: cli.h:177
#define CLI_SUCCESS
Definition: cli.h:44

◆ handle_clear_profile()

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

Definition at line 904 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, max, min, profile_entry::name, NULL, ast_cli_entry::usage, and profile_entry::value.

905 {
906  int i, min, max;
907  const char *search = NULL;
908  switch (cmd) {
909  case CLI_INIT:
910  e->command = "core clear profile";
911  e->usage = "Usage: core clear profile\n"
912  " clear profile information";
913  return NULL;
914  case CLI_GENERATE:
915  return NULL;
916  }
917 
918  if (prof_data == NULL)
919  return 0;
920 
922  for (i= min; i < max; i++) {
923  if (!search || strstr(prof_data->e[i].name, search)) {
924  prof_data->e[i].value = 0;
925  prof_data->e[i].events = 0;
926  }
927  }
928  return CLI_SUCCESS;
929 }
const char * name
Definition: asterisk.c:741
Definition: cli.h:152
static struct profile_data * prof_data
Definition: asterisk.c:754
#define NULL
Definition: resample.c:96
int64_t events
Definition: asterisk.c:745
struct profile_entry e[0]
Definition: asterisk.c:751
#define DEFINE_PROFILE_MIN_MAX_VALUES
Definition: asterisk.c:856
char * command
Definition: cli.h:186
int64_t value
Definition: asterisk.c:744
const char * usage
Definition: cli.h:177
#define CLI_SUCCESS
Definition: cli.h:44
#define min(a, b)
Definition: f2c.h:197
#define max(a, b)
Definition: f2c.h:198

◆ handle_restart_gracefully()

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

Definition at line 2394 of file asterisk.c.

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

2395 {
2396  switch (cmd) {
2397  case CLI_INIT:
2398  e->command = "core restart gracefully";
2399  e->usage =
2400  "Usage: core restart gracefully\n"
2401  " Causes Asterisk to stop accepting new calls and exec() itself performing a cold\n"
2402  " restart when all active calls have ended.\n";
2404  return NULL;
2405  case CLI_GENERATE:
2406  return NULL;
2407  }
2408 
2409  if (a->argc != e->args)
2410  return CLI_SHOWUSAGE;
2411  quit_handler(0, SHUTDOWN_NICE, 1 /* restart */);
2412  return CLI_SUCCESS;
2413 }
const int argc
Definition: cli.h:160
Definition: cli.h:152
#define NULL
Definition: resample.c:96
int args
This gets set in ast_cli_register()
Definition: cli.h:185
static void quit_handler(int num, shutdown_nice_t niceness, int restart)
Definition: asterisk.c:1869
int ast_cli_allow_at_shutdown(struct ast_cli_entry *e)
Definition: main/cli.c:2977
#define CLI_SHOWUSAGE
Definition: cli.h:45
char * command
Definition: cli.h:186
const char * usage
Definition: cli.h:177
#define CLI_SUCCESS
Definition: cli.h:44

◆ handle_restart_now()

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

Definition at line 2373 of file asterisk.c.

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

2374 {
2375  switch (cmd) {
2376  case CLI_INIT:
2377  e->command = "core restart now";
2378  e->usage =
2379  "Usage: core restart now\n"
2380  " Causes Asterisk to hangup all calls and exec() itself performing a cold\n"
2381  " restart.\n";
2383  return NULL;
2384  case CLI_GENERATE:
2385  return NULL;
2386  }
2387 
2388  if (a->argc != e->args)
2389  return CLI_SHOWUSAGE;
2390  quit_handler(0, SHUTDOWN_NORMAL, 1 /* restart */);
2391  return CLI_SUCCESS;
2392 }
const int argc
Definition: cli.h:160
Definition: cli.h:152
#define NULL
Definition: resample.c:96
int args
This gets set in ast_cli_register()
Definition: cli.h:185
static void quit_handler(int num, shutdown_nice_t niceness, int restart)
Definition: asterisk.c:1869
int ast_cli_allow_at_shutdown(struct ast_cli_entry *e)
Definition: main/cli.c:2977
#define CLI_SHOWUSAGE
Definition: cli.h:45
char * command
Definition: cli.h:186
const char * usage
Definition: cli.h:177
#define CLI_SUCCESS
Definition: cli.h:44

◆ handle_restart_when_convenient()

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

Definition at line 2415 of file asterisk.c.

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

2416 {
2417  switch (cmd) {
2418  case CLI_INIT:
2419  e->command = "core restart when convenient";
2420  e->usage =
2421  "Usage: core restart when convenient\n"
2422  " Causes Asterisk to perform a cold restart when all active calls have ended.\n";
2424  return NULL;
2425  case CLI_GENERATE:
2426  return NULL;
2427  }
2428 
2429  if (a->argc != e->args)
2430  return CLI_SHOWUSAGE;
2431  ast_cli(a->fd, "Waiting for inactivity to perform restart\n");
2432  quit_handler(0, SHUTDOWN_REALLY_NICE, 1 /* restart */);
2433  return CLI_SUCCESS;
2434 }
const int argc
Definition: cli.h:160
Definition: cli.h:152
#define NULL
Definition: resample.c:96
void ast_cli(int fd, const char *fmt,...)
Definition: clicompat.c:6
int args
This gets set in ast_cli_register()
Definition: cli.h:185
static void quit_handler(int num, shutdown_nice_t niceness, int restart)
Definition: asterisk.c:1869
const int fd
Definition: cli.h:159
int ast_cli_allow_at_shutdown(struct ast_cli_entry *e)
Definition: main/cli.c:2977
#define CLI_SHOWUSAGE
Definition: cli.h:45
char * command
Definition: cli.h:186
const char * usage
Definition: cli.h:177
#define CLI_SUCCESS
Definition: cli.h:44

◆ handle_show_profile()

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

Definition at line 869 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, max, profile_data::max_size, min, profile_entry::name, NULL, profile_entry::scale, ast_cli_entry::usage, and profile_entry::value.

870 {
871  int i, min, max;
872  const char *search = NULL;
873  switch (cmd) {
874  case CLI_INIT:
875  e->command = "core show profile";
876  e->usage = "Usage: core show profile\n"
877  " show profile information";
878  return NULL;
879  case CLI_GENERATE:
880  return NULL;
881  }
882 
883  if (prof_data == NULL)
884  return 0;
885 
887  ast_cli(a->fd, "profile values (%d, allocated %d)\n-------------------\n",
889  ast_cli(a->fd, "%6s %8s %10s %12s %12s %s\n", "ID", "Scale", "Events",
890  "Value", "Average", "Name");
891  for (i = min; i < max; i++) {
892  struct profile_entry *entry = &prof_data->e[i];
893  if (!search || strstr(entry->name, search))
894  ast_cli(a->fd, "%6d: [%8ld] %10ld %12lld %12lld %s\n",
895  i,
896  (long)entry->scale,
897  (long)entry->events, (long long)entry->value,
898  (long long)(entry->events ? entry->value / entry->events : entry->value),
899  entry->name);
900  }
901  return CLI_SUCCESS;
902 }
const char * name
Definition: asterisk.c:741
Definition: cli.h:152
static struct profile_data * prof_data
Definition: asterisk.c:754
#define NULL
Definition: resample.c:96
void ast_cli(int fd, const char *fmt,...)
Definition: clicompat.c:6
int max_size
Definition: asterisk.c:750
uint64_t scale
Definition: asterisk.c:742
int64_t events
Definition: asterisk.c:745
const int fd
Definition: cli.h:159
struct profile_entry e[0]
Definition: asterisk.c:751
#define DEFINE_PROFILE_MIN_MAX_VALUES
Definition: asterisk.c:856
char * command
Definition: cli.h:186
int64_t value
Definition: asterisk.c:744
const char * usage
Definition: cli.h:177
#define CLI_SUCCESS
Definition: cli.h:44
Definition: asterisk.c:740
Definition: search.h:40
#define min(a, b)
Definition: f2c.h:197
#define max(a, b)
Definition: f2c.h:198

◆ handle_show_settings()

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

References ast_active_channels(), ast_build_date, ast_build_kernel, ast_build_machine, ast_build_os, ast_build_user, ast_cdr_is_enabled(), ast_cli(), ast_config_AST_AGI_DIR, ast_config_AST_CONFIG_DIR, ast_config_AST_CONFIG_FILE, ast_config_AST_DATA_DIR, ast_config_AST_DB, ast_config_AST_KEY_DIR, ast_config_AST_LOG_DIR, ast_config_AST_MODULE_DIR, ast_config_AST_PID, ast_config_AST_RUN_DIR, ast_config_AST_RUN_GROUP, ast_config_AST_RUN_USER, ast_config_AST_SPOOL_DIR, ast_config_AST_SYSTEM_NAME, ast_config_AST_VAR_DIR, ast_defaultlanguage, ast_eid_default, ast_eid_to_str(), ast_get_build_opts(), ast_get_version(), ast_language_is_prefix, ast_lastreloadtime, ast_localtime(), ast_opt_cache_media_frames, AST_OPT_FLAG_EXEC_INCLUDES, AST_OPT_FLAG_GENERIC_PLC, AST_OPT_FLAG_GENERIC_PLC_ON_EQUAL_CODECS, AST_OPT_FLAG_TRANSCODE_VIA_SLIN, AST_OPT_FLAG_TRANSMIT_SILENCE, ast_opt_hide_messaging_ami_events, ast_option_maxcalls, ast_option_maxfiles, ast_option_maxload, ast_option_rtpptdynamic, ast_option_rtpusedynamic, ast_options, ast_pbx_uuid_get(), ast_realtime_enabled(), AST_RTP_MAX_PT, AST_RTP_PT_FIRST_DYNAMIC, AST_RTP_PT_LAST_REASSIGN, ast_startuptime, ast_strftime(), ast_test_flag, AST_UUID_STR_LEN, ast_verb_console_get(), buf, check_manager_enabled(), check_webmanager_enabled(), CLI_GENERATE, CLI_INIT, CLI_SUCCESS, ast_cli_entry::command, errno, ast_cli_args::fd, NULL, option_debug, option_dtmfminduration, option_minmemfree, option_trace, console::option_verbose, S_OR, and ast_cli_entry::usage.

451 {
452  char buf[BUFSIZ];
453  struct ast_tm tm;
454  char eid_str[128];
455  struct rlimit limits;
456  char pbx_uuid[AST_UUID_STR_LEN];
457 
458  switch (cmd) {
459  case CLI_INIT:
460  e->command = "core show settings";
461  e->usage = "Usage: core show settings\n"
462  " Show core misc settings";
463  return NULL;
464  case CLI_GENERATE:
465  return NULL;
466  }
467 
468  ast_eid_to_str(eid_str, sizeof(eid_str), &ast_eid_default);
469  ast_pbx_uuid_get(pbx_uuid, sizeof(pbx_uuid));
470 
471  ast_cli(a->fd, "\nPBX Core settings\n");
472  ast_cli(a->fd, "-----------------\n");
473  ast_cli(a->fd, " Version: %s\n", ast_get_version());
474  ast_cli(a->fd, " Build Options: %s\n", S_OR(ast_get_build_opts(), "(none)"));
476  ast_cli(a->fd, " Maximum calls: %d (Current %d)\n", ast_option_maxcalls, ast_active_channels());
477  else
478  ast_cli(a->fd, " Maximum calls: Not set\n");
479 
480  if (getrlimit(RLIMIT_NOFILE, &limits)) {
481  ast_cli(a->fd, " Maximum open file handles: Error because of %s\n", strerror(errno));
482  } else if (limits.rlim_cur == RLIM_INFINITY) {
483  ast_cli(a->fd, " Maximum open file handles: Unlimited\n");
484  } else if (limits.rlim_cur < ast_option_maxfiles) {
485  ast_cli(a->fd, " Maximum open file handles: %d (is) %d (requested)\n", (int) limits.rlim_cur, ast_option_maxfiles);
486  } else {
487  ast_cli(a->fd, " Maximum open file handles: %d\n", (int) limits.rlim_cur);
488  }
489 
490  ast_cli(a->fd, " Root console verbosity: %d\n", option_verbose);
491  ast_cli(a->fd, " Current console verbosity: %d\n", ast_verb_console_get());
492  ast_cli(a->fd, " Debug level: %d\n", option_debug);
493  ast_cli(a->fd, " Trace level: %d\n", option_trace);
494  ast_cli(a->fd, " Maximum load average: %lf\n", ast_option_maxload);
495 #if defined(HAVE_SYSINFO)
496  ast_cli(a->fd, " Minimum free memory: %ld MB\n", option_minmemfree);
497 #endif
498  if (ast_localtime(&ast_startuptime, &tm, NULL)) {
499  ast_strftime(buf, sizeof(buf), "%H:%M:%S", &tm);
500  ast_cli(a->fd, " Startup time: %s\n", buf);
501  }
502  if (ast_localtime(&ast_lastreloadtime, &tm, NULL)) {
503  ast_strftime(buf, sizeof(buf), "%H:%M:%S", &tm);
504  ast_cli(a->fd, " Last reload time: %s\n", buf);
505  }
506  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);
507  ast_cli(a->fd, " System name: %s\n", ast_config_AST_SYSTEM_NAME);
508  ast_cli(a->fd, " Entity ID: %s\n", eid_str);
509  ast_cli(a->fd, " PBX UUID: %s\n", pbx_uuid);
510  ast_cli(a->fd, " Default language: %s\n", ast_defaultlanguage);
511  ast_cli(a->fd, " Language prefix: %s\n", ast_language_is_prefix ? "Enabled" : "Disabled");
512  ast_cli(a->fd, " User name and group: %s/%s\n", ast_config_AST_RUN_USER, ast_config_AST_RUN_GROUP);
513  ast_cli(a->fd, " Executable includes: %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_EXEC_INCLUDES) ? "Enabled" : "Disabled");
514  ast_cli(a->fd, " Transcode via SLIN: %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_TRANSCODE_VIA_SLIN) ? "Enabled" : "Disabled");
515  ast_cli(a->fd, " Transmit silence during rec: %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_TRANSMIT_SILENCE) ? "Enabled" : "Disabled");
516  ast_cli(a->fd, " Generic PLC: %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_GENERIC_PLC) ? "Enabled" : "Disabled");
517  ast_cli(a->fd, " Generic PLC on equal codecs: %s\n", ast_test_flag(&ast_options, AST_OPT_FLAG_GENERIC_PLC_ON_EQUAL_CODECS) ? "Enabled" : "Disabled");
518  ast_cli(a->fd, " Hide Msg Chan AMI events: %s\n", ast_opt_hide_messaging_ami_events ? "Enabled" : "Disabled");
519  ast_cli(a->fd, " Min DTMF duration:: %u\n", option_dtmfminduration);
520 #if !defined(LOW_MEMORY)
521  ast_cli(a->fd, " Cache media frames: %s\n", ast_opt_cache_media_frames ? "Enabled" : "Disabled");
522 #endif
523  ast_cli(a->fd, " RTP use dynamic payloads: %u\n", ast_option_rtpusedynamic);
524 
526  ast_cli(a->fd, " RTP dynamic payload types: %u,%u-%u\n",
530  ast_cli(a->fd, " RTP dynamic payload types: %u-%u,%u-%u\n",
533  } else {
534  ast_cli(a->fd, " RTP dynamic payload types: %u-%u\n",
536  }
537 
538  ast_cli(a->fd, "\n* Subsystems\n");
539  ast_cli(a->fd, " -------------\n");
540  ast_cli(a->fd, " Manager (AMI): %s\n", check_manager_enabled() ? "Enabled" : "Disabled");
541  ast_cli(a->fd, " Web Manager (AMI/HTTP): %s\n", check_webmanager_enabled() ? "Enabled" : "Disabled");
542  ast_cli(a->fd, " Call data records: %s\n", ast_cdr_is_enabled() ? "Enabled" : "Disabled");
543  ast_cli(a->fd, " Realtime Architecture (ARA): %s\n", ast_realtime_enabled() ? "Enabled" : "Disabled");
544 
545  /*! \todo we could check musiconhold, voicemail, smdi, adsi, queues */
546 
547  ast_cli(a->fd, "\n* Directories\n");
548  ast_cli(a->fd, " -------------\n");
549  ast_cli(a->fd, " Configuration file: %s\n", ast_config_AST_CONFIG_FILE);
550  ast_cli(a->fd, " Configuration directory: %s\n", ast_config_AST_CONFIG_DIR);
551  ast_cli(a->fd, " Module directory: %s\n", ast_config_AST_MODULE_DIR);
552  ast_cli(a->fd, " Spool directory: %s\n", ast_config_AST_SPOOL_DIR);
553  ast_cli(a->fd, " Log directory: %s\n", ast_config_AST_LOG_DIR);
554  ast_cli(a->fd, " Run/Sockets directory: %s\n", ast_config_AST_RUN_DIR);
555  ast_cli(a->fd, " PID file: %s\n", ast_config_AST_PID);
556  ast_cli(a->fd, " VarLib directory: %s\n", ast_config_AST_VAR_DIR);
557  ast_cli(a->fd, " Data directory: %s\n", ast_config_AST_DATA_DIR);
558  ast_cli(a->fd, " ASTDB: %s\n", ast_config_AST_DB);
559  ast_cli(a->fd, " IAX2 Keys directory: %s\n", ast_config_AST_KEY_DIR);
560  ast_cli(a->fd, " AGI Scripts directory: %s\n", ast_config_AST_AGI_DIR);
561  ast_cli(a->fd, "\n\n");
562  return CLI_SUCCESS;
563 }
const char * ast_config_AST_KEY_DIR
Definition: options.c:158
int ast_option_maxfiles
Definition: options.c:81
const char * ast_build_user
Definition: buildinfo.c:34
unsigned int option_dtmfminduration
Definition: options.c:83
#define AST_UUID_STR_LEN
Definition: uuid.h:27
const char * ast_config_AST_DB
Definition: options.c:162
char * ast_eid_to_str(char *s, int maxlen, struct ast_eid *eid)
Convert an EID to a string.
Definition: main/utils.c:2458
#define ast_test_flag(p, flag)
Definition: utils.h:63
int option_debug
Definition: options.c:69
const char * ast_config_AST_MODULE_DIR
Definition: options.c:150
char buf[BUFSIZE]
Definition: eagi_proxy.c:66
const char * ast_get_version(void)
Retrieve the Asterisk version string.
int ast_verb_console_get(void)
Get this thread&#39;s console verbosity level.
Definition: logger.c:2231
struct ast_tm * ast_localtime(const struct timeval *timep, struct ast_tm *p_tm, const char *zone)
Timezone-independent version of localtime_r(3).
Definition: localtime.c:1739
const char * ast_build_date
Definition: buildinfo.c:33
const char * ast_get_build_opts(void)
const char * ast_build_os
Definition: buildinfo.c:32
Definition: cli.h:152
int option_verbose
Definition: options.c:67
const char * ast_config_AST_RUN_DIR
Definition: options.c:159
double ast_option_maxload
Definition: options.c:77
const char * ast_config_AST_RUN_USER
Definition: options.c:165
struct timeval ast_lastreloadtime
Definition: asterisk.c:337
#define AST_RTP_PT_FIRST_DYNAMIC
Definition: rtp_engine.h:91
#define NULL
Definition: resample.c:96
int check_manager_enabled(void)
Check if AMI is enabled.
Definition: manager.c:1949
void ast_cli(int fd, const char *fmt,...)
Definition: clicompat.c:6
int ast_option_maxcalls
Definition: options.c:79
const char * ast_build_kernel
Definition: buildinfo.c:30
int ast_realtime_enabled(void)
Check if there&#39;s any realtime engines loaded.
Definition: main/config.c:3377
const char * ast_config_AST_SYSTEM_NAME
Definition: options.c:167
int ast_cdr_is_enabled(void)
Return TRUE if CDR subsystem is enabled.
Definition: cdr.c:2861
const char * ast_config_AST_RUN_GROUP
Definition: options.c:166
const char * ast_build_machine
Definition: buildinfo.c:31
const char * ast_config_AST_CONFIG_FILE
Definition: options.c:149
struct timeval ast_startuptime
Definition: asterisk.c:336
#define AST_RTP_MAX_PT
Definition: rtp_engine.h:82
#define ast_opt_hide_messaging_ami_events
Definition: options.h:137
long option_minmemfree
Definition: options.c:86
#define ast_opt_cache_media_frames
Definition: options.h:121
const char * ast_config_AST_AGI_DIR
Definition: options.c:157
const int fd
Definition: cli.h:159
const char * ast_config_AST_PID
Definition: options.c:163
int ast_language_is_prefix
The following variable controls the layout of localized sound files. If 0, use the historical layout ...
Definition: file.c:67
char ast_defaultlanguage[]
Definition: options.c:98
const char * ast_config_AST_DATA_DIR
Definition: options.c:155
const char * ast_config_AST_CONFIG_DIR
Definition: options.c:148
int ast_pbx_uuid_get(char *pbx_uuid, int length)
Retrieve the PBX UUID.
Definition: asterisk.c:934
int errno
const char * ast_config_AST_LOG_DIR
Definition: options.c:156
char * command
Definition: cli.h:186
const char * ast_config_AST_SPOOL_DIR
Definition: options.c:151
int ast_strftime(char *buf, size_t len, const char *format, const struct ast_tm *tm)
Special version of strftime(3) that handles fractions of a second. Takes the same arguments as strfti...
Definition: localtime.c:2524
int check_webmanager_enabled(void)
Check if AMI/HTTP is enabled.
Definition: manager.c:1954
const char * usage
Definition: cli.h:177
struct ast_eid ast_eid_default
Global EID.
Definition: options.c:93
#define CLI_SUCCESS
Definition: cli.h:44
struct ast_flags ast_options
Definition: options.c:61
#define S_OR(a, b)
returns the equivalent of logic or for strings: first one if not empty, otherwise second one...
Definition: strings.h:79
#define AST_RTP_PT_LAST_REASSIGN
Definition: rtp_engine.h:94
int ast_option_rtpusedynamic
Definition: options.c:88
const char * ast_config_AST_VAR_DIR
Definition: options.c:154
int ast_active_channels(void)
returns number of active/allocated channels
Definition: channel.c:495
unsigned int ast_option_rtpptdynamic
Definition: options.c:89
int option_trace
Definition: options.c:71

◆ handle_show_sysinfo()

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

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

632 {
633  uint64_t physmem, freeram;
634 #if defined(HAVE_SYSINFO) || defined(HAVE_SWAPCTL)
635  int totalswap = 0;
636  uint64_t freeswap = 0;
637 #endif
638  int nprocs = 0;
639  long uptime = 0;
640 #if defined(HAVE_SYSINFO)
641  struct sysinfo sys_info;
642 #elif defined(HAVE_SYSCTL)
643  static int pageshift;
644  struct vmtotal vmtotal;
645  struct timeval boottime;
646  time_t now;
647  int mib[2], pagesize;
648 #if defined(HAVE_SWAPCTL)
649  int usedswap = 0;
650 #endif
651  size_t len;
652 #endif
653 
654  switch (cmd) {
655  case CLI_INIT:
656  e->command = "core show sysinfo";
657  e->usage =
658  "Usage: core show sysinfo\n"
659  " List current system information.\n";
660  return NULL;
661  case CLI_GENERATE:
662  return NULL;
663  }
664 
665 #if defined(HAVE_SYSINFO)
666  sysinfo(&sys_info);
667  uptime = sys_info.uptime / 3600;
668  physmem = sys_info.totalram * sys_info.mem_unit;
669  freeram = (sys_info.freeram * sys_info.mem_unit) / 1024;
670  totalswap = (sys_info.totalswap * sys_info.mem_unit) / 1024;
671  freeswap = (sys_info.freeswap * sys_info.mem_unit) / 1024;
672  nprocs = sys_info.procs;
673 #elif defined(HAVE_SYSCTL)
674  /* calculate the uptime by looking at boottime */
675  time(&now);
676  mib[0] = CTL_KERN;
677  mib[1] = KERN_BOOTTIME;
678  len = sizeof(boottime);
679  if (sysctl(mib, 2, &boottime, &len, NULL, 0) != -1) {
680  uptime = now - boottime.tv_sec;
681  }
682  uptime = uptime/3600;
683  /* grab total physical memory */
684  mib[0] = CTL_HW;
685 #if defined(HW_PHYSMEM64)
686  mib[1] = HW_PHYSMEM64;
687 #else
688  mib[1] = HW_PHYSMEM;
689 #endif
690  len = sizeof(physmem);
691  sysctl(mib, 2, &physmem, &len, NULL, 0);
692 
693  pagesize = getpagesize();
694  pageshift = 0;
695  while (pagesize > 1) {
696  pageshift++;
697  pagesize >>= 1;
698  }
699 
700  /* we only need the amount of log(2)1024 for our conversion */
701  pageshift -= 10;
702 
703  /* grab vm totals */
704  mib[0] = CTL_VM;
705  mib[1] = VM_METER;
706  len = sizeof(vmtotal);
707  sysctl(mib, 2, &vmtotal, &len, NULL, 0);
708  freeram = (vmtotal.t_free << pageshift);
709  /* generate swap usage and totals */
710 #if defined(HAVE_SWAPCTL)
711  swapmode(&usedswap, &totalswap);
712  freeswap = (totalswap - usedswap);
713 #endif
714  /* grab number of processes */
715 #if defined(__OpenBSD__)
716  mib[0] = CTL_KERN;
717  mib[1] = KERN_NPROCS;
718  len = sizeof(nprocs);
719  sysctl(mib, 2, &nprocs, &len, NULL, 0);
720 #endif
721 #endif
722 
723  ast_cli(a->fd, "\nSystem Statistics\n");
724  ast_cli(a->fd, "-----------------\n");
725  ast_cli(a->fd, " System Uptime: %ld hours\n", uptime);
726  ast_cli(a->fd, " Total RAM: %" PRIu64 " KiB\n", physmem / 1024);
727  ast_cli(a->fd, " Free RAM: %" PRIu64 " KiB\n", freeram);
728 #if defined(HAVE_SYSINFO)
729  ast_cli(a->fd, " Buffer RAM: %" PRIu64 " KiB\n", ((uint64_t) sys_info.bufferram * sys_info.mem_unit) / 1024);
730 #endif
731 #if defined(HAVE_SYSINFO) || defined(HAVE_SWAPCTL)
732  ast_cli(a->fd, " Total Swap Space: %d KiB\n", totalswap);
733  ast_cli(a->fd, " Free Swap Space: %" PRIu64 " KiB\n\n", freeswap);
734 #endif
735  ast_cli(a->fd, " Number of Processes: %d \n\n", nprocs);
736  return CLI_SUCCESS;
737 }
Definition: cli.h:152
#define NULL
Definition: resample.c:96
void ast_cli(int fd, const char *fmt,...)
Definition: clicompat.c:6
const int fd
Definition: cli.h:159
static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
char * command
Definition: cli.h:186
const char * usage
Definition: cli.h:177
#define CLI_SUCCESS
Definition: cli.h:44

◆ handle_show_threads()

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

Definition at line 565 of file asterisk.c.

References ast_calloc, ast_cli(), ast_free, AST_RWLIST_RDLOCK, AST_RWLIST_TRAVERSE, AST_RWLIST_UNLOCK, CLI_GENERATE, CLI_INIT, CLI_SUCCESS, ast_cli_entry::command, ast_cli_args::fd, NULL, total, and ast_cli_entry::usage.

566 {
567  int count = 0;
568  struct thread_list_t *cur;
569  switch (cmd) {
570  case CLI_INIT:
571  e->command = "core show threads";
572  e->usage =
573  "Usage: core show threads\n"
574  " List threads currently active in the system.\n";
575  return NULL;
576  case CLI_GENERATE:
577  return NULL;
578  }
579 
581  AST_RWLIST_TRAVERSE(&thread_list, cur, list) {
582  ast_cli(a->fd, "%p %d %s\n", (void *)cur->id, cur->lwp, cur->name);
583  count++;
584  }
586  ast_cli(a->fd, "%d threads listed.\n", count);
587  return CLI_SUCCESS;
588 }
#define AST_RWLIST_UNLOCK(head)
Attempts to unlock a read/write based list.
Definition: linkedlists.h:150
Definition: cli.h:152
#define NULL
Definition: resample.c:96
void ast_cli(int fd, const char *fmt,...)
Definition: clicompat.c:6
#define AST_RWLIST_RDLOCK(head)
Read locks a list.
Definition: linkedlists.h:77
const int fd
Definition: cli.h:159
#define AST_RWLIST_TRAVERSE
Definition: linkedlists.h:493
char * command
Definition: cli.h:186
const char * usage
Definition: cli.h:177
#define CLI_SUCCESS
Definition: cli.h:44

◆ handle_stop_gracefully()

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

Definition at line 2331 of file asterisk.c.

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

2332 {
2333  switch (cmd) {
2334  case CLI_INIT:
2335  e->command = "core stop gracefully";
2336  e->usage =
2337  "Usage: core stop gracefully\n"
2338  " Causes Asterisk to not accept new calls, and exit when all\n"
2339  " active calls have terminated normally.\n";
2341  return NULL;
2342  case CLI_GENERATE:
2343  return NULL;
2344  }
2345 
2346  if (a->argc != e->args)
2347  return CLI_SHOWUSAGE;
2348  quit_handler(0, SHUTDOWN_NICE, 0 /* no restart */);
2349  return CLI_SUCCESS;
2350 }
const int argc
Definition: cli.h:160
Definition: cli.h:152
#define NULL
Definition: resample.c:96
int args
This gets set in ast_cli_register()
Definition: cli.h:185
static void quit_handler(int num, shutdown_nice_t niceness, int restart)
Definition: asterisk.c:1869
int ast_cli_allow_at_shutdown(struct ast_cli_entry *e)
Definition: main/cli.c:2977
#define CLI_SHOWUSAGE
Definition: cli.h:45
char * command
Definition: cli.h:186
const char * usage
Definition: cli.h:177
#define CLI_SUCCESS
Definition: cli.h:44

◆ handle_stop_now()

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

Definition at line 2311 of file asterisk.c.

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

2312 {
2313  switch (cmd) {
2314  case CLI_INIT:
2315  e->command = "core stop now";
2316  e->usage =
2317  "Usage: core stop now\n"
2318  " Shuts down a running Asterisk immediately, hanging up all active calls .\n";
2320  return NULL;
2321  case CLI_GENERATE:
2322  return NULL;
2323  }
2324 
2325  if (a->argc != e->args)
2326  return CLI_SHOWUSAGE;
2327  quit_handler(0, SHUTDOWN_NORMAL, 0 /* not restart */);
2328  return CLI_SUCCESS;
2329 }
const int argc
Definition: cli.h:160
Definition: cli.h:152
#define NULL
Definition: resample.c:96
int args
This gets set in ast_cli_register()
Definition: cli.h:185
static void quit_handler(int num, shutdown_nice_t niceness, int restart)
Definition: asterisk.c:1869
int ast_cli_allow_at_shutdown(struct ast_cli_entry *e)
Definition: main/cli.c:2977
#define CLI_SHOWUSAGE
Definition: cli.h:45
char * command
Definition: cli.h:186
const char * usage
Definition: cli.h:177
#define CLI_SUCCESS
Definition: cli.h:44

◆ handle_stop_when_convenient()

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

Definition at line 2352 of file asterisk.c.

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

2353 {
2354  switch (cmd) {
2355  case CLI_INIT:
2356  e->command = "core stop when convenient";
2357  e->usage =
2358  "Usage: core stop when convenient\n"
2359  " Causes Asterisk to perform a shutdown when all active calls have ended.\n";
2361  return NULL;
2362  case CLI_GENERATE:
2363  return NULL;
2364  }
2365 
2366  if (a->argc != e->args)
2367  return CLI_SHOWUSAGE;
2368  ast_cli(a->fd, "Waiting for inactivity to perform halt\n");
2369  quit_handler(0, SHUTDOWN_REALLY_NICE, 0 /* don't restart */);
2370  return CLI_SUCCESS;
2371 }
const int argc
Definition: cli.h:160
Definition: cli.h:152
#define NULL
Definition: resample.c:96
void ast_cli(int fd, const char *fmt,...)
Definition: clicompat.c:6
int args
This gets set in ast_cli_register()
Definition: cli.h:185
static void quit_handler(int num, shutdown_nice_t niceness, int restart)
Definition: asterisk.c:1869
const int fd
Definition: cli.h:159
int ast_cli_allow_at_shutdown(struct ast_cli_entry *e)
Definition: main/cli.c:2977
#define CLI_SHOWUSAGE
Definition: cli.h:45
char * command
Definition: cli.h:186
const char * usage
Definition: cli.h:177
#define CLI_SUCCESS
Definition: cli.h:44

◆ handle_version()

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

Definition at line 2290 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, NULL, and ast_cli_entry::usage.

2291 {
2292  switch (cmd) {
2293  case CLI_INIT:
2294  e->command = "core show version";
2295  e->usage =
2296  "Usage: core show version\n"
2297  " Shows Asterisk version information.\n";
2298  return NULL;
2299  case CLI_GENERATE:
2300  return NULL;
2301  }
2302 
2303  if (a->argc != 3)
2304  return CLI_SHOWUSAGE;
2305  ast_cli(a->fd, "Asterisk %s built by %s @ %s on a %s running %s on %s\n",
2308  return CLI_SUCCESS;
2309 }
const char * ast_build_user
Definition: buildinfo.c:34
const char * ast_get_version(void)
Retrieve the Asterisk version string.
const int argc
Definition: cli.h:160
const char * ast_build_date
Definition: buildinfo.c:33
const char * ast_build_os
Definition: buildinfo.c:32
Definition: cli.h:152
#define NULL
Definition: resample.c:96
void ast_cli(int fd, const char *fmt,...)
Definition: clicompat.c:6
const char * ast_build_hostname
Definition: buildinfo.c:29
const char * ast_build_machine
Definition: buildinfo.c:31
const int fd
Definition: cli.h:159
#define CLI_SHOWUSAGE
Definition: cli.h:45
char * command
Definition: cli.h:186
const char * usage
Definition: cli.h:177
#define CLI_SUCCESS
Definition: cli.h:44

◆ has_priority()

static int has_priority ( void  )
static

Check whether we were set to high(er) priority.

Definition at line 1736 of file asterisk.c.

Referenced by ast_ari_validate_dialplan_cep(), and asterisk_daemon().

1737 {
1738  /* Neither of these calls should fail with these arguments. */
1739 #ifdef __linux__
1740  /* For SCHED_OTHER, SCHED_BATCH and SCHED_IDLE, this will return
1741  * 0. For the realtime priorities SCHED_RR and SCHED_FIFO, it
1742  * will return something >= 1. */
1743  return sched_getscheduler(0);
1744 #else
1745  /* getpriority() can return a value in -20..19 (or even -INF..20)
1746  * where negative numbers are high priority. We don't bother
1747  * checking errno. If the query fails and it returns -1, we'll
1748  * assume that we're running at high prio; a safe assumption
1749  * that will enable the resource starvation monitor (canary)
1750  * just in case. */
1751  return (getpriority(PRIO_PROCESS, 0) < 0);
1752 #endif
1753 }

◆ listener()

static void* listener ( void *  unused)
static

Definition at line 1476 of file asterisk.c.

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

Referenced by __allocate_taskprocessor(), ast_makesocket(), ast_taskprocessor_get(), ast_taskprocessor_listener_alloc(), AST_TEST_DEFINE(), default_tps_processing_function(), and taskprocessor_listener_dtor().

1477 {
1478  struct sockaddr_un sunaddr;
1479  int s;
1480  socklen_t len;
1481  int x;
1482  int poll_result;
1483  struct pollfd fds[1];
1484 
1485  for (;;) {
1486  if (ast_socket < 0) {
1487  return NULL;
1488  }
1489  fds[0].fd = ast_socket;
1490  fds[0].events = POLLIN;
1491  poll_result = ast_poll(fds, 1, -1);
1492  pthread_testcancel();
1493  if (poll_result < 0) {
1494  if (errno != EINTR) {
1495  ast_log(LOG_WARNING, "poll returned error: %s\n", strerror(errno));
1496  }
1497  continue;
1498  }
1499  len = sizeof(sunaddr);
1500  s = accept(ast_socket, (struct sockaddr *)&sunaddr, &len);
1501  if (s < 0) {
1502  if (errno != EINTR)
1503  ast_log(LOG_WARNING, "Accept returned %d: %s\n", s, strerror(errno));
1504  } else {
1505 #if defined(SO_PASSCRED)
1506  int sckopt = 1;
1507  /* turn on socket credentials passing. */
1508  if (setsockopt(s, SOL_SOCKET, SO_PASSCRED, &sckopt, sizeof(sckopt)) < 0) {
1509  ast_log(LOG_WARNING, "Unable to turn on socket credentials passing\n");
1510  close(s);
1511  } else
1512 #endif
1513  {
1514  for (x = 0; x < AST_MAX_CONNECTS; x++) {
1515  if (consoles[x].fd >= 0) {
1516  continue;
1517  }
1518  if (socketpair(AF_LOCAL, SOCK_STREAM, 0, consoles[x].p)) {
1519  ast_log(LOG_ERROR, "Unable to create pipe: %s\n", strerror(errno));
1520  fdprint(s, "Server failed to create pipe\n");
1521  close(s);
1522  break;
1523  }
1524  ast_fd_set_flags(consoles[x].p[1], O_NONBLOCK);
1525  consoles[x].mute = 1; /* Default is muted, we will un-mute if necessary */
1526  /* Default uid and gid to -2, so then in cli.c/cli_has_permissions() we will be able
1527  to know if the user didn't send the credentials. */
1528  consoles[x].uid = -2;
1529  consoles[x].gid = -2;
1530  /* Server default of remote console verbosity level is OFF. */
1531  consoles[x].option_verbose = 0;
1532  consoles[x].fd = s;
1534  consoles[x].fd = -1;
1535  ast_log(LOG_ERROR, "Unable to spawn thread to handle connection: %s\n", strerror(errno));
1536  close(consoles[x].p[0]);
1537  close(consoles[x].p[1]);
1538  fdprint(s, "Server failed to spawn thread\n");
1539  close(s);
1540  }
1541  break;
1542  }
1543  if (x >= AST_MAX_CONNECTS) {
1544  fdprint(s, "No more connections allowed\n");
1545  ast_log(LOG_WARNING, "No more connections allowed\n");
1546  close(s);
1547  } else if ((consoles[x].fd > -1) && (!ast_opt_hide_connect)) {
1548  ast_verb(3, "Remote UNIX connection\n");
1549  }
1550  }
1551  }
1552  }
1553  return NULL;
1554 }
#define AST_MAX_CONNECTS
Definition: asterisk.c:296
int option_verbose
Definition: asterisk.c:325
#define LOG_WARNING
Definition: logger.h:274
int uid
Definition: asterisk.c:321
#define NULL
Definition: resample.c:96
#define ast_pthread_create_detached_background(a, b, c, d)
Definition: utils.h:512
#define ast_verb(level,...)
Definition: logger.h:455
int gid
Definition: asterisk.c:322
#define ast_fd_set_flags(fd, flags)
Set flags on the given file descriptor.
Definition: utils.h:949
#define ast_log
Definition: astobj2.c:42
#define ast_poll(a, b, c)
Definition: poll-compat.h:88
static int ast_socket
Definition: asterisk.c:312
struct console consoles[AST_MAX_CONNECTS]
Definition: asterisk.c:343
int mute
Definition: asterisk.c:320
#define LOG_ERROR
Definition: logger.h:285
static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
int errno
static void * netconsole(void *vconsole)
Definition: asterisk.c:1386
#define AF_LOCAL
Definition: asterisk.c:292
static int fdprint(int fd, const char *s)
Definition: asterisk.c:1036
int fd
Definition: asterisk.c:317
#define ast_opt_hide_connect
Definition: options.h:132

◆ main()

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

Check for options

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

Definition at line 3490 of file asterisk.c.

References _argv, ARRAY_LEN, ast_clear_flag, ast_config_AST_RUN_DIR, ast_config_AST_RUN_GROUP, ast_config_AST_RUN_USER, ast_config_AST_SOCKET, ast_FD_SETSIZE, ast_FDMAX, ast_free, ast_language_is_prefix, ast_log, ast_mainpid, ast_opt_always_fork, ast_opt_console, ast_opt_dump_core, ast_opt_exec, AST_OPT_FLAG_ALWAYS_FORK, AST_OPT_FLAG_CACHE_RECORD_FILES, AST_OPT_FLAG_CONSOLE, AST_OPT_FLAG_DUMP_CORE, AST_OPT_FLAG_EXEC, AST_OPT_FLAG_EXEC_INCLUDES, AST_OPT_FLAG_FORCE_BLACK_BACKGROUND, AST_OPT_FLAG_HIGH_PRIORITY, AST_OPT_FLAG_INIT_KEYS, AST_OPT_FLAG_LIGHT_BACKGROUND, AST_OPT_FLAG_MUTE, AST_OPT_FLAG_NO_COLOR, AST_OPT_FLAG_NO_FORK, 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_option_maxcalls, ast_option_maxload, ast_options, ast_remotecontrol(), ast_sd_get_fd_un(), ast_select(), ast_set_flag, ast_set_priority(), ast_socket_is_sd, ast_strdup, ast_strlen_zero, ast_term_init(), ast_test_flag, ast_tryconnect(), ast_verb_sys_level, asterisk_daemon(), c, env_init(), errno, console::fd, FD_SET, FD_ZERO, load_asterisk_conf(), LOG_WARNING, multi_thread_safe, NULL, option_debug, option_minmemfree, console::option_verbose, PATH_MAX, print_intro_message(), quit_handler(), RAII_VAR, set_asterisk_conf_path(), set_socket_path(), show_cli_help(), show_version(), SHUTDOWN_FAST, term_end(), and term_quit().

3491 {
3492  int c;
3493  int x;
3494  int isroot = 1, rundir_exists = 0;
3495  RAII_VAR(char *, runuser, NULL, ast_free);
3496  RAII_VAR(char *, rungroup, NULL, ast_free);
3497  RAII_VAR(char *, xarg, NULL, ast_free);
3498  struct rlimit l;
3499  static const char *getopt_settings = "BC:cde:FfG:ghIiL:M:mnpqRrs:TtU:VvWXx:";
3500 
3501  /* Remember original args for restart */
3502  if (argc > ARRAY_LEN(_argv) - 1) {
3503  fprintf(stderr, "Truncating argument size to %d\n", (int)ARRAY_LEN(_argv) - 1);
3504  argc = ARRAY_LEN(_argv) - 1;
3505  }
3506  for (x = 0; x < argc; x++)
3507  _argv[x] = argv[x];
3508  _argv[x] = NULL;
3509 
3510  if (geteuid() != 0)
3511  isroot = 0;
3512 
3513  /* if the progname is rasterisk consider it a remote console */
3514  if (argv[0] && (strstr(argv[0], "rasterisk")) != NULL) {
3516  }
3517  ast_mainpid = getpid();
3518 
3519  /* Process command-line options that effect asterisk.conf load. */
3520  while ((c = getopt(argc, argv, getopt_settings)) != -1) {
3521  switch (c) {
3522  case 'X':
3524  break;
3525  case 'C':
3526  set_asterisk_conf_path(optarg);
3527  break;
3528  case 'd':
3529  option_debug++;
3530  break;
3531  case 'h':
3532  show_cli_help();
3533  exit(0);
3534  case 'R':
3535  case 'r':
3536  case 'x':
3537  /* ast_opt_remote is checked during config load. This is only part of what
3538  * these options do, see the second loop for the rest of the actions. */
3540  break;
3541  case 'V':
3542  show_version();
3543  exit(0);
3544  case 'v':
3545  option_verbose++;
3546  break;
3547  case '?':
3548  exit(1);
3549  }
3550  }
3551 
3552  /* Initialize env so it is available if #exec is used in asterisk.conf. */
3553  env_init();
3554 
3556 
3557  /* Update env to include any systemname that was set. */
3558  env_init();
3559 
3560  /*! \brief Check for options
3561  *
3562  * \todo Document these options
3563  */
3564  optind = 1;
3565  while ((c = getopt(argc, argv, getopt_settings)) != -1) {
3566  /*!\note Please keep the ordering here to alphabetical, capital letters
3567  * first. This will make it easier in the future to select unused
3568  * option flags for new features. */
3569  switch (c) {
3570  case 'B': /* Force black background */
3573  break;
3574  case 'X':
3575  /* The command-line -X option enables #exec for asterisk.conf only. */
3576  break;
3577  case 'C':
3578  /* already processed. */
3579  break;
3580  case 'c':
3582  break;
3583  case 'd':
3584  /* already processed. */
3585  break;
3586 #if defined(HAVE_SYSINFO)
3587  case 'e':
3588  if ((sscanf(&optarg[1], "%30ld", &option_minmemfree) != 1) || (option_minmemfree < 0)) {
3589  option_minmemfree = 0;
3590  }
3591  break;
3592 #endif
3593 #if HAVE_WORKING_FORK
3594  case 'F':
3595  ast_set_flag(&ast