00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042
00043
00044
00045
00046
00047
00048
00049
00050
00051
00052
00053 #include "asterisk.h"
00054
00055 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
00056
00057 #undef sched_setscheduler
00058 #undef setpriority
00059 #include <unistd.h>
00060 #include <stdlib.h>
00061 #include <sys/time.h>
00062 #include <fcntl.h>
00063 #include <stdio.h>
00064 #include <signal.h>
00065 #include <sched.h>
00066 #include <sys/socket.h>
00067 #include <sys/un.h>
00068 #include <sys/wait.h>
00069 #include <string.h>
00070 #include <errno.h>
00071 #include <ctype.h>
00072 #include <sys/resource.h>
00073 #include <grp.h>
00074 #include <pwd.h>
00075 #include <sys/stat.h>
00076
00077 #if defined(HAVE_ZAPTEL) || defined (HAVE_DAHDI)
00078 #include <sys/ioctl.h>
00079 #include "asterisk/dahdi_compat.h"
00080 #endif
00081
00082 #ifdef linux
00083 #include <sys/prctl.h>
00084 #ifdef HAVE_CAP
00085 #include <sys/capability.h>
00086 #endif
00087 #endif
00088 #include <regex.h>
00089
00090 #if defined(__FreeBSD__) || defined( __NetBSD__ ) || defined(SOLARIS)
00091 #include <netdb.h>
00092 #if defined(SOLARIS)
00093 int daemon(int, int);
00094 #endif
00095 #endif
00096
00097 #include "asterisk/logger.h"
00098 #include "asterisk/options.h"
00099 #include "asterisk/cli.h"
00100 #include "asterisk/channel.h"
00101 #include "asterisk/ulaw.h"
00102 #include "asterisk/alaw.h"
00103 #include "asterisk/callerid.h"
00104 #include "asterisk/image.h"
00105 #include "asterisk/tdd.h"
00106 #include "asterisk/term.h"
00107 #include "asterisk/manager.h"
00108 #include "asterisk/cdr.h"
00109 #include "asterisk/pbx.h"
00110 #include "asterisk/enum.h"
00111 #include "asterisk/rtp.h"
00112 #include "asterisk/http.h"
00113 #include "asterisk/udptl.h"
00114 #include "asterisk/app.h"
00115 #include "asterisk/lock.h"
00116 #include "asterisk/utils.h"
00117 #include "asterisk/file.h"
00118 #include "asterisk/io.h"
00119 #include "asterisk/lock.h"
00120 #include "editline/histedit.h"
00121 #include "asterisk/config.h"
00122 #include "asterisk/version.h"
00123 #include "asterisk/linkedlists.h"
00124 #include "asterisk/devicestate.h"
00125 #include "asterisk/module.h"
00126
00127 #include "asterisk/doxyref.h"
00128
00129 #include "../defaults.h"
00130
00131 #ifndef AF_LOCAL
00132 #define AF_LOCAL AF_UNIX
00133 #define PF_LOCAL PF_UNIX
00134 #endif
00135
00136 #define AST_MAX_CONNECTS 128
00137 #define NUM_MSGS 64
00138
00139
00140 #define WELCOME_MESSAGE \
00141 ast_verbose("Asterisk " ASTERISK_VERSION ", Copyright (C) 1999 - 2008 Digium, Inc. and others.\n"); \
00142 ast_verbose("Created by Mark Spencer <markster@digium.com>\n"); \
00143 ast_verbose("Asterisk comes with ABSOLUTELY NO WARRANTY; type 'core show warranty' for details.\n"); \
00144 ast_verbose("This is free software, with components licensed under the GNU General Public\n"); \
00145 ast_verbose("License version 2 and other licenses; you are welcome to redistribute it under\n"); \
00146 ast_verbose("certain conditions. Type 'core show license' for details.\n"); \
00147 ast_verbose("=========================================================================\n")
00148
00149
00150
00151
00152
00153
00154
00155
00156 struct ast_flags ast_options = { AST_DEFAULT_OPTIONS };
00157
00158 int option_verbose;
00159 int option_debug;
00160
00161 double option_maxload;
00162 int option_maxcalls;
00163
00164
00165
00166 char record_cache_dir[AST_CACHE_DIR_LEN] = AST_TMP_DIR;
00167 char debug_filename[AST_FILENAME_MAX] = "";
00168 #ifdef HAVE_ZAPTEL
00169 static char _dahdi_chan_name[AST_CHANNEL_NAME] = "Zap";
00170 static size_t _dahdi_chan_name_len = 3;
00171 static enum dahdi_chan_modes _dahdi_chan_mode = CHAN_ZAP_MODE;
00172 #else
00173 static char _dahdi_chan_name[AST_CHANNEL_NAME] = "DAHDI";
00174 static size_t _dahdi_chan_name_len = 5;
00175 static enum dahdi_chan_modes _dahdi_chan_mode = CHAN_DAHDI_PLUS_ZAP_MODE;
00176 #endif
00177 const char *dahdi_chan_name;
00178 const size_t *dahdi_chan_name_len;
00179 const enum dahdi_chan_modes *dahdi_chan_mode;
00180
00181 static int ast_socket = -1;
00182 static int ast_consock = -1;
00183 pid_t ast_mainpid;
00184 struct console {
00185 int fd;
00186 int p[2];
00187 pthread_t t;
00188 int mute;
00189 };
00190
00191 struct ast_atexit {
00192 void (*func)(void);
00193 AST_LIST_ENTRY(ast_atexit) list;
00194 };
00195
00196 static AST_LIST_HEAD_STATIC(atexits, ast_atexit);
00197
00198 time_t ast_startuptime;
00199 time_t ast_lastreloadtime;
00200
00201 static History *el_hist;
00202 static EditLine *el;
00203 static char *remotehostname;
00204
00205 struct console consoles[AST_MAX_CONNECTS];
00206
00207 char defaultlanguage[MAX_LANGUAGE] = DEFAULT_LANGUAGE;
00208
00209 static int ast_el_add_history(char *);
00210 static int ast_el_read_history(char *);
00211 static int ast_el_write_history(char *);
00212
00213 char ast_config_AST_CONFIG_DIR[PATH_MAX];
00214 char ast_config_AST_CONFIG_FILE[PATH_MAX];
00215 char ast_config_AST_MODULE_DIR[PATH_MAX];
00216 char ast_config_AST_SPOOL_DIR[PATH_MAX];
00217 char ast_config_AST_MONITOR_DIR[PATH_MAX];
00218 char ast_config_AST_VAR_DIR[PATH_MAX];
00219 char ast_config_AST_DATA_DIR[PATH_MAX];
00220 char ast_config_AST_LOG_DIR[PATH_MAX];
00221 char ast_config_AST_AGI_DIR[PATH_MAX];
00222 char ast_config_AST_DB[PATH_MAX];
00223 char ast_config_AST_KEY_DIR[PATH_MAX];
00224 char ast_config_AST_PID[PATH_MAX];
00225 char ast_config_AST_SOCKET[PATH_MAX];
00226 char ast_config_AST_RUN_DIR[PATH_MAX];
00227 char ast_config_AST_RUN_USER[PATH_MAX];
00228 char ast_config_AST_RUN_GROUP[PATH_MAX];
00229 char ast_config_AST_CTL_PERMISSIONS[PATH_MAX];
00230 char ast_config_AST_CTL_OWNER[PATH_MAX] = "\0";
00231 char ast_config_AST_CTL_GROUP[PATH_MAX] = "\0";
00232 char ast_config_AST_CTL[PATH_MAX] = "asterisk.ctl";
00233 char ast_config_AST_SYSTEM_NAME[20] = "";
00234
00235 extern const char *ast_build_hostname;
00236 extern const char *ast_build_kernel;
00237 extern const char *ast_build_machine;
00238 extern const char *ast_build_os;
00239 extern const char *ast_build_date;
00240 extern const char *ast_build_user;
00241
00242 static char *_argv[256];
00243 static int shuttingdown;
00244 static int restartnow;
00245 static pthread_t consolethread = AST_PTHREADT_NULL;
00246
00247 static char randompool[256];
00248
00249 static int sig_alert_pipe[2] = { -1, -1 };
00250 static struct {
00251 unsigned int need_reload:1;
00252 unsigned int need_quit:1;
00253 } sig_flags;
00254
00255 #if !defined(LOW_MEMORY)
00256 struct file_version {
00257 AST_LIST_ENTRY(file_version) list;
00258 const char *file;
00259 char *version;
00260 };
00261
00262 static AST_LIST_HEAD_STATIC(file_versions, file_version);
00263
00264 void ast_register_file_version(const char *file, const char *version)
00265 {
00266 struct file_version *new;
00267 char *work;
00268 size_t version_length;
00269
00270 work = ast_strdupa(version);
00271 work = ast_strip(ast_strip_quoted(work, "$", "$"));
00272 version_length = strlen(work) + 1;
00273
00274 if (!(new = ast_calloc(1, sizeof(*new) + version_length)))
00275 return;
00276
00277 new->file = file;
00278 new->version = (char *) new + sizeof(*new);
00279 memcpy(new->version, work, version_length);
00280 AST_LIST_LOCK(&file_versions);
00281 AST_LIST_INSERT_HEAD(&file_versions, new, list);
00282 AST_LIST_UNLOCK(&file_versions);
00283 }
00284
00285 void ast_unregister_file_version(const char *file)
00286 {
00287 struct file_version *find;
00288
00289 AST_LIST_LOCK(&file_versions);
00290 AST_LIST_TRAVERSE_SAFE_BEGIN(&file_versions, find, list) {
00291 if (!strcasecmp(find->file, file)) {
00292 AST_LIST_REMOVE_CURRENT(&file_versions, list);
00293 break;
00294 }
00295 }
00296 AST_LIST_TRAVERSE_SAFE_END;
00297 AST_LIST_UNLOCK(&file_versions);
00298 if (find)
00299 free(find);
00300 }
00301
00302 struct thread_list_t {
00303 AST_LIST_ENTRY(thread_list_t) list;
00304 char *name;
00305 pthread_t id;
00306 };
00307
00308 static AST_LIST_HEAD_STATIC(thread_list, thread_list_t);
00309
00310 static char show_threads_help[] =
00311 "Usage: core show threads\n"
00312 " List threads currently active in the system.\n";
00313
00314 void ast_register_thread(char *name)
00315 {
00316 struct thread_list_t *new = ast_calloc(1, sizeof(*new));
00317
00318 if (!new)
00319 return;
00320 new->id = pthread_self();
00321 new->name = name;
00322 AST_LIST_LOCK(&thread_list);
00323 AST_LIST_INSERT_HEAD(&thread_list, new, list);
00324 AST_LIST_UNLOCK(&thread_list);
00325 }
00326
00327 void ast_unregister_thread(void *id)
00328 {
00329 struct thread_list_t *x;
00330
00331 AST_LIST_LOCK(&thread_list);
00332 AST_LIST_TRAVERSE_SAFE_BEGIN(&thread_list, x, list) {
00333 if ((void *) x->id == id) {
00334 AST_LIST_REMOVE_CURRENT(&thread_list, list);
00335 break;
00336 }
00337 }
00338 AST_LIST_TRAVERSE_SAFE_END;
00339 AST_LIST_UNLOCK(&thread_list);
00340 if (x) {
00341 free(x->name);
00342 free(x);
00343 }
00344 }
00345
00346 static int handle_show_threads(int fd, int argc, char *argv[])
00347 {
00348 int count = 0;
00349 struct thread_list_t *cur;
00350
00351 AST_LIST_LOCK(&thread_list);
00352 AST_LIST_TRAVERSE(&thread_list, cur, list) {
00353 ast_cli(fd, "%p %s\n", (void *)cur->id, cur->name);
00354 count++;
00355 }
00356 AST_LIST_UNLOCK(&thread_list);
00357 ast_cli(fd, "%d threads listed.\n", count);
00358 return 0;
00359 }
00360
00361 struct profile_entry {
00362 const char *name;
00363 uint64_t scale;
00364 int64_t mark;
00365 int64_t value;
00366 int64_t events;
00367 };
00368
00369 struct profile_data {
00370 int entries;
00371 int max_size;
00372 struct profile_entry e[0];
00373 };
00374
00375 static struct profile_data *prof_data;
00376
00377
00378
00379
00380 int ast_add_profile(const char *name, uint64_t scale)
00381 {
00382 int l = sizeof(struct profile_data);
00383 int n = 10;
00384
00385 if (prof_data == NULL) {
00386 prof_data = ast_calloc(1, l + n*sizeof(struct profile_entry));
00387 if (prof_data == NULL)
00388 return -1;
00389 prof_data->entries = 0;
00390 prof_data->max_size = n;
00391 }
00392 if (prof_data->entries >= prof_data->max_size) {
00393 void *p;
00394 n = prof_data->max_size + 20;
00395 p = ast_realloc(prof_data, l + n*sizeof(struct profile_entry));
00396 if (p == NULL)
00397 return -1;
00398 prof_data = p;
00399 prof_data->max_size = n;
00400 }
00401 n = prof_data->entries++;
00402 prof_data->e[n].name = ast_strdup(name);
00403 prof_data->e[n].value = 0;
00404 prof_data->e[n].events = 0;
00405 prof_data->e[n].mark = 0;
00406 prof_data->e[n].scale = scale;
00407 return n;
00408 }
00409
00410 int64_t ast_profile(int i, int64_t delta)
00411 {
00412 if (!prof_data || i < 0 || i > prof_data->entries)
00413 return 0;
00414 if (prof_data->e[i].scale > 1)
00415 delta /= prof_data->e[i].scale;
00416 prof_data->e[i].value += delta;
00417 prof_data->e[i].events++;
00418 return prof_data->e[i].value;
00419 }
00420
00421
00422
00423
00424 #if defined ( __i686__) && (defined(__FreeBSD__) || defined(linux))
00425 #if defined(__FreeBSD__)
00426 #include <machine/cpufunc.h>
00427 #elif defined(linux)
00428 static __inline uint64_t
00429 rdtsc(void)
00430 {
00431 uint64_t rv;
00432
00433 __asm __volatile(".byte 0x0f, 0x31" : "=A" (rv));
00434 return (rv);
00435 }
00436 #endif
00437 #else
00438 static __inline uint64_t
00439 rdtsc(void)
00440 {
00441 return 0;
00442 }
00443 #endif
00444
00445 int64_t ast_mark(int i, int startstop)
00446 {
00447 if (!prof_data || i < 0 || i > prof_data->entries)
00448 return 0;
00449 if (startstop == 1)
00450 prof_data->e[i].mark = rdtsc();
00451 else {
00452 prof_data->e[i].mark = (rdtsc() - prof_data->e[i].mark);
00453 if (prof_data->e[i].scale > 1)
00454 prof_data->e[i].mark /= prof_data->e[i].scale;
00455 prof_data->e[i].value += prof_data->e[i].mark;
00456 prof_data->e[i].events++;
00457 }
00458 return prof_data->e[i].mark;
00459 }
00460
00461 static int handle_show_profile_deprecated(int fd, int argc, char *argv[])
00462 {
00463 int i, min, max;
00464 char *search = NULL;
00465
00466 if (prof_data == NULL)
00467 return 0;
00468
00469 min = 0;
00470 max = prof_data->entries;
00471 if (argc >= 3) {
00472 if (isdigit(argv[2][0])) {
00473 min = atoi(argv[2]);
00474 if (argc == 4 && strcmp(argv[3], "-"))
00475 max = atoi(argv[3]);
00476 } else
00477 search = argv[2];
00478 }
00479 if (max > prof_data->entries)
00480 max = prof_data->entries;
00481 if (!strcmp(argv[0], "clear")) {
00482 for (i= min; i < max; i++) {
00483 if (!search || strstr(prof_data->e[i].name, search)) {
00484 prof_data->e[i].value = 0;
00485 prof_data->e[i].events = 0;
00486 }
00487 }
00488 return 0;
00489 }
00490 ast_cli(fd, "profile values (%d, allocated %d)\n-------------------\n",
00491 prof_data->entries, prof_data->max_size);
00492 ast_cli(fd, "%6s %8s %10s %12s %12s %s\n", "ID", "Scale", "Events",
00493 "Value", "Average", "Name");
00494 for (i = min; i < max; i++) {
00495 struct profile_entry *e = &prof_data->e[i];
00496 if (!search || strstr(prof_data->e[i].name, search))
00497 ast_cli(fd, "%6d: [%8ld] %10ld %12lld %12lld %s\n",
00498 i,
00499 (long)e->scale,
00500 (long)e->events, (long long)e->value,
00501 (long long)(e->events ? e->value / e->events : e->value),
00502 e->name);
00503 }
00504 return 0;
00505 }
00506
00507 static int handle_show_profile(int fd, int argc, char *argv[])
00508 {
00509 int i, min, max;
00510 char *search = NULL;
00511
00512 if (prof_data == NULL)
00513 return 0;
00514
00515 min = 0;
00516 max = prof_data->entries;
00517 if (argc > 3) {
00518 if (isdigit(argv[3][0])) {
00519 min = atoi(argv[3]);
00520 if (argc == 5 && strcmp(argv[4], "-"))
00521 max = atoi(argv[4]);
00522 } else
00523 search = argv[3];
00524 }
00525 if (max > prof_data->entries)
00526 max = prof_data->entries;
00527 if (!strcmp(argv[1], "clear")) {
00528 for (i= min; i < max; i++) {
00529 if (!search || strstr(prof_data->e[i].name, search)) {
00530 prof_data->e[i].value = 0;
00531 prof_data->e[i].events = 0;
00532 }
00533 }
00534 return 0;
00535 }
00536 ast_cli(fd, "profile values (%d, allocated %d)\n-------------------\n",
00537 prof_data->entries, prof_data->max_size);
00538 ast_cli(fd, "%6s %8s %10s %12s %12s %s\n", "ID", "Scale", "Events",
00539 "Value", "Average", "Name");
00540 for (i = min; i < max; i++) {
00541 struct profile_entry *e = &prof_data->e[i];
00542 if (!search || strstr(prof_data->e[i].name, search))
00543 ast_cli(fd, "%6d: [%8ld] %10ld %12lld %12lld %s\n",
00544 i,
00545 (long)e->scale,
00546 (long)e->events, (long long)e->value,
00547 (long long)(e->events ? e->value / e->events : e->value),
00548 e->name);
00549 }
00550 return 0;
00551 }
00552
00553 static char show_version_files_help[] =
00554 "Usage: core show file version [like <pattern>]\n"
00555 " Lists the revision numbers of the files used to build this copy of Asterisk.\n"
00556 " Optional regular expression pattern is used to filter the file list.\n";
00557
00558
00559 static int handle_show_version_files_deprecated(int fd, int argc, char *argv[])
00560 {
00561 #define FORMAT "%-25.25s %-40.40s\n"
00562 struct file_version *iterator;
00563 regex_t regexbuf;
00564 int havepattern = 0;
00565 int havename = 0;
00566 int count_files = 0;
00567
00568 switch (argc) {
00569 case 5:
00570 if (!strcasecmp(argv[3], "like")) {
00571 if (regcomp(®exbuf, argv[4], REG_EXTENDED | REG_NOSUB))
00572 return RESULT_SHOWUSAGE;
00573 havepattern = 1;
00574 } else
00575 return RESULT_SHOWUSAGE;
00576 break;
00577 case 4:
00578 havename = 1;
00579 break;
00580 case 3:
00581 break;
00582 default:
00583 return RESULT_SHOWUSAGE;
00584 }
00585
00586 ast_cli(fd, FORMAT, "File", "Revision");
00587 ast_cli(fd, FORMAT, "----", "--------");
00588 AST_LIST_LOCK(&file_versions);
00589 AST_LIST_TRAVERSE(&file_versions, iterator, list) {
00590 if (havename && strcasecmp(iterator->file, argv[3]))
00591 continue;
00592
00593 if (havepattern && regexec(®exbuf, iterator->file, 0, NULL, 0))
00594 continue;
00595
00596 ast_cli(fd, FORMAT, iterator->file, iterator->version);
00597 count_files++;
00598 if (havename)
00599 break;
00600 }
00601 AST_LIST_UNLOCK(&file_versions);
00602 if (!havename) {
00603 ast_cli(fd, "%d files listed.\n", count_files);
00604 }
00605
00606 if (havepattern)
00607 regfree(®exbuf);
00608
00609 return RESULT_SUCCESS;
00610 #undef FORMAT
00611 }
00612
00613 static int handle_show_version_files(int fd, int argc, char *argv[])
00614 {
00615 #define FORMAT "%-25.25s %-40.40s\n"
00616 struct file_version *iterator;
00617 regex_t regexbuf;
00618 int havepattern = 0;
00619 int havename = 0;
00620 int count_files = 0;
00621
00622 switch (argc) {
00623 case 6:
00624 if (!strcasecmp(argv[4], "like")) {
00625 if (regcomp(®exbuf, argv[5], REG_EXTENDED | REG_NOSUB))
00626 return RESULT_SHOWUSAGE;
00627 havepattern = 1;
00628 } else
00629 return RESULT_SHOWUSAGE;
00630 break;
00631 case 5:
00632 havename = 1;
00633 break;
00634 case 4:
00635 break;
00636 default:
00637 return RESULT_SHOWUSAGE;
00638 }
00639
00640 ast_cli(fd, FORMAT, "File", "Revision");
00641 ast_cli(fd, FORMAT, "----", "--------");
00642 AST_LIST_LOCK(&file_versions);
00643 AST_LIST_TRAVERSE(&file_versions, iterator, list) {
00644 if (havename && strcasecmp(iterator->file, argv[4]))
00645 continue;
00646
00647 if (havepattern && regexec(®exbuf, iterator->file, 0, NULL, 0))
00648 continue;
00649
00650 ast_cli(fd, FORMAT, iterator->file, iterator->version);
00651 count_files++;
00652 if (havename)
00653 break;
00654 }
00655 AST_LIST_UNLOCK(&file_versions);
00656 if (!havename) {
00657 ast_cli(fd, "%d files listed.\n", count_files);
00658 }
00659
00660 if (havepattern)
00661 regfree(®exbuf);
00662
00663 return RESULT_SUCCESS;
00664 #undef FORMAT
00665 }
00666
00667 static char *complete_show_version_files_deprecated(const char *line, const char *word, int pos, int state)
00668 {
00669 struct file_version *find;
00670 int which = 0;
00671 char *ret = NULL;
00672 int matchlen = strlen(word);
00673
00674 if (pos != 3)
00675 return NULL;
00676
00677 AST_LIST_LOCK(&file_versions);
00678 AST_LIST_TRAVERSE(&file_versions, find, list) {
00679 if (!strncasecmp(word, find->file, matchlen) && ++which > state) {
00680 ret = ast_strdup(find->file);
00681 break;
00682 }
00683 }
00684 AST_LIST_UNLOCK(&file_versions);
00685
00686 return ret;
00687 }
00688
00689 static char *complete_show_version_files(const char *line, const char *word, int pos, int state)
00690 {
00691 struct file_version *find;
00692 int which = 0;
00693 char *ret = NULL;
00694 int matchlen = strlen(word);
00695
00696 if (pos != 4)
00697 return NULL;
00698
00699 AST_LIST_LOCK(&file_versions);
00700 AST_LIST_TRAVERSE(&file_versions, find, list) {
00701 if (!strncasecmp(word, find->file, matchlen) && ++which > state) {
00702 ret = ast_strdup(find->file);
00703 break;
00704 }
00705 }
00706 AST_LIST_UNLOCK(&file_versions);
00707
00708 return ret;
00709 }
00710
00711 #endif
00712
00713 int ast_register_atexit(void (*func)(void))
00714 {
00715 struct ast_atexit *ae;
00716
00717 if (!(ae = ast_calloc(1, sizeof(*ae))))
00718 return -1;
00719
00720 ae->func = func;
00721
00722 ast_unregister_atexit(func);
00723
00724 AST_LIST_LOCK(&atexits);
00725 AST_LIST_INSERT_HEAD(&atexits, ae, list);
00726 AST_LIST_UNLOCK(&atexits);
00727
00728 return 0;
00729 }
00730
00731 void ast_unregister_atexit(void (*func)(void))
00732 {
00733 struct ast_atexit *ae = NULL;
00734
00735 AST_LIST_LOCK(&atexits);
00736 AST_LIST_TRAVERSE_SAFE_BEGIN(&atexits, ae, list) {
00737 if (ae->func == func) {
00738 AST_LIST_REMOVE_CURRENT(&atexits, list);
00739 break;
00740 }
00741 }
00742 AST_LIST_TRAVERSE_SAFE_END
00743 AST_LIST_UNLOCK(&atexits);
00744
00745 if (ae)
00746 free(ae);
00747 }
00748
00749
00750 static int fdsend(int fd, const char *s)
00751 {
00752 return write(fd, s, strlen(s) + 1);
00753 }
00754
00755
00756 static int fdprint(int fd, const char *s)
00757 {
00758 return write(fd, s, strlen(s));
00759 }
00760
00761
00762 static void null_sig_handler(int signal)
00763 {
00764
00765 }
00766
00767 AST_MUTEX_DEFINE_STATIC(safe_system_lock);
00768
00769
00770 static unsigned int safe_system_level = 0;
00771 static void *safe_system_prev_handler;
00772
00773 void ast_replace_sigchld(void)
00774 {
00775 unsigned int level;
00776
00777 ast_mutex_lock(&safe_system_lock);
00778 level = safe_system_level++;
00779
00780
00781 if (level == 0)
00782 safe_system_prev_handler = signal(SIGCHLD, null_sig_handler);
00783
00784 ast_mutex_unlock(&safe_system_lock);
00785 }
00786
00787 void ast_unreplace_sigchld(void)
00788 {
00789 unsigned int level;
00790
00791 ast_mutex_lock(&safe_system_lock);
00792 level = --safe_system_level;
00793
00794
00795 if (level == 0)
00796 signal(SIGCHLD, safe_system_prev_handler);
00797
00798 ast_mutex_unlock(&safe_system_lock);
00799 }
00800
00801 int ast_safe_system(const char *s)
00802 {
00803 pid_t pid;
00804 #ifdef HAVE_WORKING_FORK
00805 int x;
00806 #endif
00807 int res;
00808 struct rusage rusage;
00809 int status;
00810
00811 #if defined(HAVE_WORKING_FORK) || defined(HAVE_WORKING_VFORK)
00812 ast_replace_sigchld();
00813
00814 #ifdef HAVE_WORKING_FORK
00815 pid = fork();
00816 #else
00817 pid = vfork();
00818 #endif
00819
00820 if (pid == 0) {
00821 #ifdef HAVE_WORKING_FORK
00822 if (ast_opt_high_priority)
00823 ast_set_priority(0);
00824
00825 for (x = STDERR_FILENO + 1; x < 4096; x++)
00826 close(x);
00827 #endif
00828 execl("/bin/sh", "/bin/sh", "-c", s, (char *) NULL);
00829 _exit(1);
00830 } else if (pid > 0) {
00831 for(;;) {
00832 res = wait4(pid, &status, 0, &rusage);
00833 if (res > -1) {
00834 res = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
00835 break;
00836 } else if (errno != EINTR)
00837 break;
00838 }
00839 } else {
00840 ast_log(LOG_WARNING, "Fork failed: %s\n", strerror(errno));
00841 res = -1;
00842 }
00843
00844 ast_unreplace_sigchld();
00845 #else
00846 res = -1;
00847 #endif
00848
00849 return res;
00850 }
00851
00852
00853
00854
00855 void ast_console_toggle_mute(int fd, int silent) {
00856 int x;
00857 for (x = 0;x < AST_MAX_CONNECTS; x++) {
00858 if (fd == consoles[x].fd) {
00859 if (consoles[x].mute) {
00860 consoles[x].mute = 0;
00861 if (!silent)
00862 ast_cli(fd, "Console is not muted anymore.\n");
00863 } else {
00864 consoles[x].mute = 1;
00865 if (!silent)
00866 ast_cli(fd, "Console is muted.\n");
00867 }
00868 return;
00869 }
00870 }
00871 ast_cli(fd, "Couldn't find remote console.\n");
00872 }
00873
00874
00875
00876
00877 static void ast_network_puts_mutable(const char *string)
00878 {
00879 int x;
00880 for (x = 0;x < AST_MAX_CONNECTS; x++) {
00881 if (consoles[x].mute)
00882 continue;
00883 if (consoles[x].fd > -1)
00884 fdprint(consoles[x].p[1], string);
00885 }
00886 }
00887
00888
00889
00890
00891
00892 void ast_console_puts_mutable(const char *string)
00893 {
00894 fputs(string, stdout);
00895 fflush(stdout);
00896 ast_network_puts_mutable(string);
00897 }
00898
00899
00900
00901
00902 static void ast_network_puts(const char *string)
00903 {
00904 int x;
00905 for (x=0; x < AST_MAX_CONNECTS; x++) {
00906 if (consoles[x].fd > -1)
00907 fdprint(consoles[x].p[1], string);
00908 }
00909 }
00910
00911
00912
00913
00914
00915 void ast_console_puts(const char *string)
00916 {
00917 fputs(string, stdout);
00918 fflush(stdout);
00919 ast_network_puts(string);
00920 }
00921
00922 static void network_verboser(const char *s)
00923 {
00924 ast_network_puts_mutable(s);
00925 }
00926
00927 static pthread_t lthread;
00928
00929 static void *netconsole(void *vconsole)
00930 {
00931 struct console *con = vconsole;
00932 char hostname[MAXHOSTNAMELEN] = "";
00933 char tmp[512];
00934 int res;
00935 struct pollfd fds[2];
00936
00937 if (gethostname(hostname, sizeof(hostname)-1))
00938 ast_copy_string(hostname, "<Unknown>", sizeof(hostname));
00939 snprintf(tmp, sizeof(tmp), "%s/%ld/%s\n", hostname, (long)ast_mainpid, ASTERISK_VERSION);
00940 fdprint(con->fd, tmp);
00941 for(;;) {
00942 fds[0].fd = con->fd;
00943 fds[0].events = POLLIN;
00944 fds[0].revents = 0;
00945 fds[1].fd = con->p[0];
00946 fds[1].events = POLLIN;
00947 fds[1].revents = 0;
00948
00949 res = poll(fds, 2, -1);
00950 if (res < 0) {
00951 if (errno != EINTR)
00952 ast_log(LOG_WARNING, "poll returned < 0: %s\n", strerror(errno));
00953 continue;
00954 }
00955 if (fds[0].revents) {
00956 res = read(con->fd, tmp, sizeof(tmp));
00957 if (res < 1) {
00958 break;
00959 }
00960 tmp[res] = 0;
00961 ast_cli_command_multiple(con->fd, res, tmp);
00962 }
00963 if (fds[1].revents) {
00964 res = read(con->p[0], tmp, sizeof(tmp));
00965 if (res < 1) {
00966 ast_log(LOG_ERROR, "read returned %d\n", res);
00967 break;
00968 }
00969 res = write(con->fd, tmp, res);
00970 if (res < 1)
00971 break;
00972 }
00973 }
00974 if (option_verbose > 2)
00975 ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection disconnected\n");
00976 close(con->fd);
00977 close(con->p[0]);
00978 close(con->p[1]);
00979 con->fd = -1;
00980
00981 return NULL;
00982 }
00983
00984 static void *listener(void *unused)
00985 {
00986 struct sockaddr_un sunaddr;
00987 int s;
00988 socklen_t len;
00989 int x;
00990 int flags;
00991 struct pollfd fds[1];
00992 pthread_attr_t attr;
00993 pthread_attr_init(&attr);
00994 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
00995 for (;;) {
00996 if (ast_socket < 0)
00997 return NULL;
00998 fds[0].fd = ast_socket;
00999 fds[0].events = POLLIN;
01000 s = poll(fds, 1, -1);
01001 pthread_testcancel();
01002 if (s < 0) {
01003 if (errno != EINTR)
01004 ast_log(LOG_WARNING, "poll returned error: %s\n", strerror(errno));
01005 continue;
01006 }
01007 len = sizeof(sunaddr);
01008 s = accept(ast_socket, (struct sockaddr *)&sunaddr, &len);
01009 if (s < 0) {
01010 if (errno != EINTR)
01011 ast_log(LOG_WARNING, "Accept returned %d: %s\n", s, strerror(errno));
01012 } else {
01013 for (x = 0; x < AST_MAX_CONNECTS; x++) {
01014 if (consoles[x].fd < 0) {
01015 if (socketpair(AF_LOCAL, SOCK_STREAM, 0, consoles[x].p)) {
01016 ast_log(LOG_ERROR, "Unable to create pipe: %s\n", strerror(errno));
01017 consoles[x].fd = -1;
01018 fdprint(s, "Server failed to create pipe\n");
01019 close(s);
01020 break;
01021 }
01022 flags = fcntl(consoles[x].p[1], F_GETFL);
01023 fcntl(consoles[x].p[1], F_SETFL, flags | O_NONBLOCK);
01024 consoles[x].fd = s;
01025 consoles[x].mute = 1;
01026 if (ast_pthread_create_background(&consoles[x].t, &attr, netconsole, &consoles[x])) {
01027 ast_log(LOG_ERROR, "Unable to spawn thread to handle connection: %s\n", strerror(errno));
01028 close(consoles[x].p[0]);
01029 close(consoles[x].p[1]);
01030 consoles[x].fd = -1;
01031 fdprint(s, "Server failed to spawn thread\n");
01032 close(s);
01033 }
01034 break;
01035 }
01036 }
01037 if (x >= AST_MAX_CONNECTS) {
01038 fdprint(s, "No more connections allowed\n");
01039 ast_log(LOG_WARNING, "No more connections allowed\n");
01040 close(s);
01041 } else if (consoles[x].fd > -1) {
01042 if (option_verbose > 2)
01043 ast_verbose(VERBOSE_PREFIX_3 "Remote UNIX connection\n");
01044 }
01045 }
01046 }
01047 return NULL;
01048 }
01049
01050 static int ast_makesocket(void)
01051 {
01052 struct sockaddr_un sunaddr;
01053 int res;
01054 int x;
01055 uid_t uid = -1;
01056 gid_t gid = -1;
01057
01058 for (x = 0; x < AST_MAX_CONNECTS; x++)
01059 consoles[x].fd = -1;
01060 unlink(ast_config_AST_SOCKET);
01061 ast_socket = socket(PF_LOCAL, SOCK_STREAM, 0);
01062 if (ast_socket < 0) {
01063 ast_log(LOG_WARNING, "Unable to create control socket: %s\n", strerror(errno));
01064 return -1;
01065 }
01066 memset(&sunaddr, 0, sizeof(sunaddr));
01067 sunaddr.sun_family = AF_LOCAL;
01068 ast_copy_string(sunaddr.sun_path, ast_config_AST_SOCKET, sizeof(sunaddr.sun_path));
01069 res = bind(ast_socket, (struct sockaddr *)&sunaddr, sizeof(sunaddr));
01070 if (res) {
01071 ast_log(LOG_WARNING, "Unable to bind socket to %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
01072 close(ast_socket);
01073 ast_socket = -1;
01074 return -1;
01075 }
01076 res = listen(ast_socket, 2);
01077 if (res < 0) {
01078 ast_log(LOG_WARNING, "Unable to listen on socket %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
01079 close(ast_socket);
01080 ast_socket = -1;
01081 return -1;
01082 }
01083 ast_register_verbose(network_verboser);
01084 ast_pthread_create_background(<hread, NULL, listener, NULL);
01085
01086 if (!ast_strlen_zero(ast_config_AST_CTL_OWNER)) {
01087 struct passwd *pw;
01088 if ((pw = getpwnam(ast_config_AST_CTL_OWNER)) == NULL) {
01089 ast_log(LOG_WARNING, "Unable to find uid of user %s\n", ast_config_AST_CTL_OWNER);
01090 } else {
01091 uid = pw->pw_uid;
01092 }
01093 }
01094
01095 if (!ast_strlen_zero(ast_config_AST_CTL_GROUP)) {
01096 struct group *grp;
01097 if ((grp = getgrnam(ast_config_AST_CTL_GROUP)) == NULL) {
01098 ast_log(LOG_WARNING, "Unable to find gid of group %s\n", ast_config_AST_CTL_GROUP);
01099 } else {
01100 gid = grp->gr_gid;
01101 }
01102 }
01103
01104 if (chown(ast_config_AST_SOCKET, uid, gid) < 0)
01105 ast_log(LOG_WARNING, "Unable to change ownership of %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
01106
01107 if (!ast_strlen_zero(ast_config_AST_CTL_PERMISSIONS)) {
01108 int p1;
01109 mode_t p;
01110 sscanf(ast_config_AST_CTL_PERMISSIONS, "%o", &p1);
01111 p = p1;
01112 if ((chmod(ast_config_AST_SOCKET, p)) < 0)
01113 ast_log(LOG_WARNING, "Unable to change file permissions of %s: %s\n", ast_config_AST_SOCKET, strerror(errno));
01114 }
01115
01116 return 0;
01117 }
01118
01119 static int ast_tryconnect(void)
01120 {
01121 struct sockaddr_un sunaddr;
01122 int res;
01123 ast_consock = socket(PF_LOCAL, SOCK_STREAM, 0);
01124 if (ast_consock < 0) {
01125 ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
01126 return 0;
01127 }
01128 memset(&sunaddr, 0, sizeof(sunaddr));
01129 sunaddr.sun_family = AF_LOCAL;
01130 ast_copy_string(sunaddr.sun_path, (char *)ast_config_AST_SOCKET, sizeof(sunaddr.sun_path));
01131 res = connect(ast_consock, (struct sockaddr *)&sunaddr, sizeof(sunaddr));
01132 if (res) {
01133 close(ast_consock);
01134 ast_consock = -1;
01135 return 0;
01136 } else
01137 return 1;
01138 }
01139
01140
01141
01142
01143
01144
01145
01146 static void urg_handler(int num)
01147 {
01148 signal(num, urg_handler);
01149 return;
01150 }
01151
01152 static void hup_handler(int num)
01153 {
01154 int a = 0;
01155 if (option_verbose > 1)
01156 printf("Received HUP signal -- Reloading configs\n");
01157 if (restartnow)
01158 execvp(_argv[0], _argv);
01159 sig_flags.need_reload = 1;
01160 if (sig_alert_pipe[1] != -1) {
01161 if (write(sig_alert_pipe[1], &a, sizeof(a)) < 0) {
01162 fprintf(stderr, "hup_handler: write() failed: %s\n", strerror(errno));
01163 }
01164 }
01165 signal(num, hup_handler);
01166 }
01167
01168 static void child_handler(int sig)
01169 {
01170
01171 int n, status;
01172
01173
01174
01175
01176 for (n = 0; wait4(-1, &status, WNOHANG, NULL) > 0; n++)
01177 ;
01178 if (n == 0 && option_debug)
01179 printf("Huh? Child handler, but nobody there?\n");
01180 signal(sig, child_handler);
01181 }
01182
01183
01184 static void set_ulimit(int value)
01185 {
01186 struct rlimit l = {0, 0};
01187
01188 if (value <= 0) {
01189 ast_log(LOG_WARNING, "Unable to change max files open to invalid value %i\n",value);
01190 return;
01191 }
01192
01193 l.rlim_cur = value;
01194 l.rlim_max = value;
01195
01196 if (setrlimit(RLIMIT_NOFILE, &l)) {
01197 ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n",strerror(errno));
01198 return;
01199 }
01200
01201 ast_log(LOG_NOTICE, "Setting max files open to %d\n",value);
01202
01203 return;
01204 }
01205
01206
01207 static void set_title(char *text)
01208 {
01209 if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
01210 fprintf(stdout, "\033]2;%s\007", text);
01211 }
01212
01213 static void set_icon(char *text)
01214 {
01215 if (getenv("TERM") && strstr(getenv("TERM"), "xterm"))
01216 fprintf(stdout, "\033]1;%s\007", text);
01217 }
01218
01219
01220
01221 int ast_set_priority(int pri)
01222 {
01223 struct sched_param sched;
01224 memset(&sched, 0, sizeof(sched));
01225 #ifdef __linux__
01226 if (pri) {
01227 sched.sched_priority = 10;
01228 if (sched_setscheduler(0, SCHED_RR, &sched)) {
01229 ast_log(LOG_WARNING, "Unable to set high priority\n");
01230 return -1;
01231 } else
01232 if (option_verbose)
01233 ast_verbose("Set to realtime thread\n");
01234 } else {
01235 sched.sched_priority = 0;
01236
01237 sched_setscheduler(0, SCHED_OTHER, &sched);
01238 }
01239 #else
01240 if (pri) {
01241 if (setpriority(PRIO_PROCESS, 0, -10) == -1) {
01242 ast_log(LOG_WARNING, "Unable to set high priority\n");
01243 return -1;
01244 } else
01245 if (option_verbose)
01246 ast_verbose("Set to high priority\n");
01247 } else {
01248
01249 setpriority(PRIO_PROCESS, 0, 0);
01250 }
01251 #endif
01252 return 0;
01253 }
01254
01255 static void ast_run_atexits(void)
01256 {
01257 struct ast_atexit *ae;
01258 AST_LIST_LOCK(&atexits);
01259 AST_LIST_TRAVERSE(&atexits, ae, list) {
01260 if (ae->func)
01261 ae->func();
01262 }
01263 AST_LIST_UNLOCK(&atexits);
01264 }
01265
01266 static void quit_handler(int num, int nice, int safeshutdown, int restart)
01267 {
01268 char filename[80] = "";
01269 time_t s,e;
01270 int x;
01271
01272 ast_cdr_engine_term();
01273 if (safeshutdown) {
01274 shuttingdown = 1;
01275 if (!nice) {
01276
01277 ast_begin_shutdown(1);
01278 if (option_verbose && ast_opt_console)
01279 ast_verbose("Beginning asterisk %s....\n", restart ? "restart" : "shutdown");
01280 time(&s);
01281 for (;;) {
01282 time(&e);
01283
01284 if ((e - s) > 15)
01285 break;
01286 if (!ast_active_channels())
01287 break;
01288 if (!shuttingdown)
01289 break;
01290
01291 usleep(100000);
01292 }
01293 } else {
01294 if (nice < 2)
01295 ast_begin_shutdown(0);
01296 if (option_verbose && ast_opt_console)
01297 ast_verbose("Waiting for inactivity to perform %s...\n", restart ? "restart" : "halt");
01298 for (;;) {
01299 if (!ast_active_channels())
01300 break;
01301 if (!shuttingdown)
01302 break;
01303 sleep(1);
01304 }
01305 }
01306
01307 if (!shuttingdown) {
01308 if (option_verbose && ast_opt_console)
01309 ast_verbose("Asterisk %s cancelled.\n", restart ? "restart" : "shutdown");
01310 return;
01311 }
01312
01313 if (nice)
01314 ast_module_shutdown();
01315 }
01316 if (ast_opt_console || ast_opt_remote) {
01317 if (getenv("HOME"))
01318 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
01319 if (!ast_strlen_zero(filename))
01320 ast_el_write_history(filename);
01321 if (el != NULL)
01322 el_end(el);
01323 if (el_hist != NULL)
01324 history_end(el_hist);
01325 }
01326 if (option_verbose)
01327 ast_verbose("Executing last minute cleanups\n");
01328 ast_run_atexits();
01329
01330 if (option_verbose && ast_opt_console)
01331 ast_verbose("Asterisk %s ending (%d).\n", ast_active_channels() ? "uncleanly" : "cleanly", num);
01332 if (option_debug)
01333 ast_log(LOG_DEBUG, "Asterisk ending (%d).\n", num);
01334 manager_event(EVENT_FLAG_SYSTEM, "Shutdown", "Shutdown: %s\r\nRestart: %s\r\n", ast_active_channels() ? "Uncleanly" : "Cleanly", restart ? "True" : "False");
01335 if (ast_socket > -1) {
01336 pthread_cancel(lthread);
01337 close(ast_socket);
01338 ast_socket = -1;
01339 unlink(ast_config_AST_SOCKET);
01340 }
01341 if (ast_consock > -1)
01342 close(ast_consock);
01343 if (!ast_opt_remote)
01344 unlink(ast_config_AST_PID);
01345 printf("%s", term_quit());
01346 if (restart) {
01347 if (option_verbose || ast_opt_console)
01348 ast_verbose("Preparing for Asterisk restart...\n");
01349
01350 for (x=3; x < 32768; x++) {
01351 fcntl(x, F_SETFD, FD_CLOEXEC);
01352 }
01353 if (option_verbose || ast_opt_console)
01354 ast_verbose("Asterisk is now restarting...\n");
01355 restartnow = 1;
01356
01357
01358 close_logger();
01359
01360
01361
01362 if ((consolethread != AST_PTHREADT_NULL) && (consolethread != pthread_self())) {
01363 pthread_kill(consolethread, SIGHUP);
01364
01365 sleep(2);
01366 } else
01367 execvp(_argv[0], _argv);
01368
01369 } else {
01370
01371 close_logger();
01372 }
01373 exit(0);
01374 }
01375
01376 static void __quit_handler(int num)
01377 {
01378 int a = 0;
01379 sig_flags.need_quit = 1;
01380 if (sig_alert_pipe[1] != -1) {
01381 if (write(sig_alert_pipe[1], &a, sizeof(a)) < 0) {
01382 fprintf(stderr, "hup_handler: write() failed: %s\n", strerror(errno));
01383 }
01384 }
01385
01386
01387 }
01388
01389 static void __remote_quit_handler(int num)
01390 {
01391 sig_flags.need_quit = 1;
01392 }
01393
01394 static const char *fix_header(char *outbuf, int maxout, const char *s, char *cmp)
01395 {
01396 const char *c;
01397
01398
01399 if (*s == 127) {
01400 s++;
01401 }
01402
01403 if (!strncmp(s, cmp, strlen(cmp))) {
01404 c = s + strlen(cmp);
01405 term_color(outbuf, cmp, COLOR_GRAY, 0, maxout);
01406 return c;
01407 }
01408 return NULL;
01409 }
01410
01411 static void console_verboser(const char *s)
01412 {
01413 char tmp[80];
01414 const char *c = NULL;
01415
01416 if ((c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_4)) ||
01417 (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_3)) ||
01418 (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_2)) ||
01419 (c = fix_header(tmp, sizeof(tmp), s, VERBOSE_PREFIX_1))) {
01420 fputs(tmp, stdout);
01421 fputs(c, stdout);
01422 } else {
01423 if (*s == 127) {
01424 s++;
01425 }
01426 fputs(s, stdout);
01427 }
01428
01429 fflush(stdout);
01430
01431
01432 if (ast_opt_console && consolethread != AST_PTHREADT_NULL)
01433 pthread_kill(consolethread, SIGURG);
01434 }
01435
01436 static int ast_all_zeros(char *s)
01437 {
01438 while (*s) {
01439 if (*s > 32)
01440 return 0;
01441 s++;
01442 }
01443 return 1;
01444 }
01445
01446 static void consolehandler(char *s)
01447 {
01448 printf("%s", term_end());
01449 fflush(stdout);
01450
01451
01452 if (!ast_all_zeros(s))
01453 ast_el_add_history(s);
01454
01455 if (s[0] == '!') {
01456 if (s[1])
01457 ast_safe_system(s+1);
01458 else
01459 ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
01460 } else
01461 ast_cli_command(STDOUT_FILENO, s);
01462 }
01463
01464 static int remoteconsolehandler(char *s)
01465 {
01466 int ret = 0;
01467
01468
01469 if (!ast_all_zeros(s))
01470 ast_el_add_history(s);
01471
01472 if (s[0] == '!') {
01473 if (s[1])
01474 ast_safe_system(s+1);
01475 else
01476 ast_safe_system(getenv("SHELL") ? getenv("SHELL") : "/bin/sh");
01477 ret = 1;
01478 }
01479 if ((strncasecmp(s, "quit", 4) == 0 || strncasecmp(s, "exit", 4) == 0) &&
01480 (s[4] == '\0' || isspace(s[4]))) {
01481 quit_handler(0, 0, 0, 0);
01482 ret = 1;
01483 }
01484
01485 return ret;
01486 }
01487
01488 static char abort_halt_help[] =
01489 "Usage: abort shutdown\n"
01490 " Causes Asterisk to abort an executing shutdown or restart, and resume normal\n"
01491 " call operations.\n";
01492
01493 static char shutdown_now_help[] =
01494 "Usage: stop now\n"
01495 " Shuts down a running Asterisk immediately, hanging up all active calls .\n";
01496
01497 static char shutdown_gracefully_help[] =
01498 "Usage: stop gracefully\n"
01499 " Causes Asterisk to not accept new calls, and exit when all\n"
01500 " active calls have terminated normally.\n";
01501
01502 static char shutdown_when_convenient_help[] =
01503 "Usage: stop when convenient\n"
01504 " Causes Asterisk to perform a shutdown when all active calls have ended.\n";
01505
01506 static char restart_now_help[] =
01507 "Usage: restart now\n"
01508 " Causes Asterisk to hangup all calls and exec() itself performing a cold\n"
01509 " restart.\n";
01510
01511 static char restart_gracefully_help[] =
01512 "Usage: restart gracefully\n"
01513 " Causes Asterisk to stop accepting new calls and exec() itself performing a cold\n"
01514 " restart when all active calls have ended.\n";
01515
01516 static char restart_when_convenient_help[] =
01517 "Usage: restart when convenient\n"
01518 " Causes Asterisk to perform a cold restart when all active calls have ended.\n";
01519
01520 static char bang_help[] =
01521 "Usage: !<command>\n"
01522 " Executes a given shell command\n";
01523
01524 static char show_warranty_help[] =
01525 "Usage: core show warranty\n"
01526 " Shows the warranty (if any) for this copy of Asterisk.\n";
01527
01528 static char show_license_help[] =
01529 "Usage: core show license\n"
01530 " Shows the license(s) for this copy of Asterisk.\n";
01531
01532 static char version_help[] =
01533 "Usage: core show version\n"
01534 " Shows Asterisk version information.\n";
01535
01536 static int handle_version_deprecated(int fd, int argc, char *argv[])
01537 {
01538 if (argc != 2)
01539 return RESULT_SHOWUSAGE;
01540 ast_cli(fd, "Asterisk %s built by %s @ %s on a %s running %s on %s\n",
01541 ASTERISK_VERSION, ast_build_user, ast_build_hostname,
01542 ast_build_machine, ast_build_os, ast_build_date);
01543 return RESULT_SUCCESS;
01544 }
01545
01546 static int handle_version(int fd, int argc, char *argv[])
01547 {
01548 if (argc != 3)
01549 return RESULT_SHOWUSAGE;
01550 ast_cli(fd, "Asterisk %s built by %s @ %s on a %s running %s on %s\n",
01551 ASTERISK_VERSION, ast_build_user, ast_build_hostname,
01552 ast_build_machine, ast_build_os, ast_build_date);
01553 return RESULT_SUCCESS;
01554 }
01555
01556 #if 0
01557 static int handle_quit(int fd, int argc, char *argv[])
01558 {
01559 if (argc != 1)
01560 return RESULT_SHOWUSAGE;
01561 quit_handler(0, 0, 1, 0);
01562 return RESULT_SUCCESS;
01563 }
01564 #endif
01565
01566 static int handle_shutdown_now(int fd, int argc, char *argv[])
01567 {
01568 if (argc != 2)
01569 return RESULT_SHOWUSAGE;
01570 quit_handler(0, 0 , 1 , 0 );
01571 return RESULT_SUCCESS;
01572 }
01573
01574 static int handle_shutdown_gracefully(int fd, int argc, char *argv[])
01575 {
01576 if (argc != 2)
01577 return RESULT_SHOWUSAGE;
01578 quit_handler(0, 1 , 1 , 0 );
01579 return RESULT_SUCCESS;
01580 }
01581
01582 static int handle_shutdown_when_convenient(int fd, int argc, char *argv[])
01583 {
01584 if (argc != 3)
01585 return RESULT_SHOWUSAGE;
01586 ast_cli(fd, "Waiting for inactivity to perform halt\n");
01587 quit_handler(0, 2 , 1 , 0 );
01588 return RESULT_SUCCESS;
01589 }
01590
01591 static int handle_restart_now(int fd, int argc, char *argv[])
01592 {
01593 if (argc != 2)
01594 return RESULT_SHOWUSAGE;
01595 quit_handler(0, 0 , 1 , 1 );
01596 return RESULT_SUCCESS;
01597 }
01598
01599 static int handle_restart_gracefully(int fd, int argc, char *argv[])
01600 {
01601 if (argc != 2)
01602 return RESULT_SHOWUSAGE;
01603 quit_handler(0, 1 , 1 , 1 );
01604 return RESULT_SUCCESS;
01605 }
01606
01607 static int handle_restart_when_convenient(int fd, int argc, char *argv[])
01608 {
01609 if (argc != 3)
01610 return RESULT_SHOWUSAGE;
01611 ast_cli(fd, "Waiting for inactivity to perform restart\n");
01612 quit_handler(0, 2 , 1 , 1 );
01613 return RESULT_SUCCESS;
01614 }
01615
01616 static int handle_abort_halt(int fd, int argc, char *argv[])
01617 {
01618 if (argc != 2)
01619 return RESULT_SHOWUSAGE;
01620 ast_cancel_shutdown();
01621 shuttingdown = 0;
01622 return RESULT_SUCCESS;
01623 }
01624
01625 static int handle_bang(int fd, int argc, char *argv[])
01626 {
01627 return RESULT_SUCCESS;
01628 }
01629 static const char *warranty_lines[] = {
01630 "\n",
01631 " NO WARRANTY\n",
01632 "\n",
01633 "BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\n",
01634 "FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN\n",
01635 "OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\n",
01636 "PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\n",
01637 "OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n",
01638 "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS\n",
01639 "TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE\n",
01640 "PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\n",
01641 "REPAIR OR CORRECTION.\n",
01642 "\n",
01643 "IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\n",
01644 "WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\n",
01645 "REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\n",
01646 "INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\n",
01647 "OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\n",
01648 "TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\n",
01649 "YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\n",
01650 "PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\n",
01651 "POSSIBILITY OF SUCH DAMAGES.\n",
01652 };
01653
01654 static int show_warranty(int fd, int argc, char *argv[])
01655 {
01656 int x;
01657
01658 for (x = 0; x < ARRAY_LEN(warranty_lines); x++)
01659 ast_cli(fd, "%s", (char *) warranty_lines[x]);
01660
01661 return RESULT_SUCCESS;
01662 }
01663
01664 static const char *license_lines[] = {
01665 "\n",
01666 "This program is free software; you can redistribute it and/or modify\n",
01667 "it under the terms of the GNU General Public License version 2 as\n",
01668 "published by the Free Software Foundation.\n",
01669 "\n",
01670 "This program also contains components licensed under other licenses.\n",
01671 "They include:\n",
01672 "\n",
01673 "This program is distributed in the hope that it will be useful,\n",
01674 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n",
01675 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n",
01676 "GNU General Public License for more details.\n",
01677 "\n",
01678 "You should have received a copy of the GNU General Public License\n",
01679 "along with this program; if not, write to the Free Software\n",
01680 "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n",
01681 };
01682
01683 static int show_license(int fd, int argc, char *argv[])
01684 {
01685 int x;
01686
01687 for (x = 0; x < ARRAY_LEN(license_lines); x++)
01688 ast_cli(fd, "%s", (char *) license_lines[x]);
01689
01690 return RESULT_SUCCESS;
01691 }
01692
01693 #define ASTERISK_PROMPT "*CLI> "
01694
01695 #define ASTERISK_PROMPT2 "%s*CLI> "
01696
01697 static struct ast_cli_entry cli_show_version_deprecated = {
01698 { "show", "version", NULL },
01699 handle_version_deprecated, "Display version info",
01700 version_help };
01701
01702 #if !defined(LOW_MEMORY)
01703 static struct ast_cli_entry cli_show_version_files_deprecated = {
01704 { "show", "version", "files", NULL },
01705 handle_show_version_files_deprecated, NULL,
01706 NULL, complete_show_version_files_deprecated };
01707
01708 static struct ast_cli_entry cli_show_profile_deprecated = {
01709 { "show", "profile", NULL },
01710 handle_show_profile_deprecated, NULL,
01711 NULL };
01712
01713 static struct ast_cli_entry cli_clear_profile_deprecated = {
01714 { "clear", "profile", NULL },
01715 handle_show_profile_deprecated, NULL,
01716 NULL };
01717 #endif
01718
01719 static struct ast_cli_entry cli_asterisk[] = {
01720 { { "abort", "halt", NULL },
01721 handle_abort_halt, "Cancel a running halt",
01722 abort_halt_help },
01723
01724 { { "stop", "now", NULL },
01725 handle_shutdown_now, "Shut down Asterisk immediately",
01726 shutdown_now_help },
01727
01728 { { "stop", "gracefully", NULL },
01729 handle_shutdown_gracefully, "Gracefully shut down Asterisk",
01730 shutdown_gracefully_help },
01731
01732 { { "stop", "when", "convenient", NULL },
01733 handle_shutdown_when_convenient, "Shut down Asterisk at empty call volume",
01734 shutdown_when_convenient_help },
01735
01736 { { "restart", "now", NULL },
01737 handle_restart_now, "Restart Asterisk immediately", restart_now_help },
01738
01739 { { "restart", "gracefully", NULL },
01740 handle_restart_gracefully, "Restart Asterisk gracefully",
01741 restart_gracefully_help },
01742
01743 { { "restart", "when", "convenient", NULL },
01744 handle_restart_when_convenient, "Restart Asterisk at empty call volume",
01745 restart_when_convenient_help },
01746
01747 { { "core", "show", "warranty", NULL },
01748 show_warranty, "Show the warranty (if any) for this copy of Asterisk",
01749 show_warranty_help },
01750
01751 { { "core", "show", "license", NULL },
01752 show_license, "Show the license(s) for this copy of Asterisk",
01753 show_license_help },
01754
01755 { { "core", "show", "version", NULL },
01756 handle_version, "Display version info",
01757 version_help, NULL, &cli_show_version_deprecated },
01758
01759 { { "!", NULL },
01760 handle_bang, "Execute a shell command",
01761 bang_help },
01762
01763 #if !defined(LOW_MEMORY)
01764 { { "core", "show", "file", "version", NULL },
01765 handle_show_version_files, "List versions of files used to build Asterisk",
01766 show_version_files_help, complete_show_version_files, &cli_show_version_files_deprecated },
01767
01768 { { "core", "show", "threads", NULL },
01769 handle_show_threads, "Show running threads",
01770 show_threads_help },
01771
01772 { { "core", "show", "profile", NULL },
01773 handle_show_profile, "Display profiling info",
01774 NULL, NULL, &cli_show_profile_deprecated },
01775
01776 { { "core", "clear", "profile", NULL },
01777 handle_show_profile, "Clear profiling info",
01778 NULL, NULL, &cli_clear_profile_deprecated },
01779 #endif
01780 };
01781
01782 static int ast_el_read_char(EditLine *el, char *cp)
01783 {
01784 int num_read = 0;
01785 int lastpos = 0;
01786 struct pollfd fds[2];
01787 int res;
01788 int max;
01789 #define EL_BUF_SIZE 512
01790 char buf[EL_BUF_SIZE];
01791
01792 for (;;) {
01793 max = 1;
01794 fds[0].fd = ast_consock;
01795 fds[0].events = POLLIN;
01796 if (!ast_opt_exec) {
01797 fds[1].fd = STDIN_FILENO;
01798 fds[1].events = POLLIN;
01799 max++;
01800 }
01801 res = poll(fds, max, -1);
01802 if (res < 0) {
01803 if (sig_flags.need_quit)
01804 break;
01805 if (errno == EINTR)
01806 continue;
01807 ast_log(LOG_ERROR, "poll failed: %s\n", strerror(errno));
01808 break;
01809 }
01810
01811 if (!ast_opt_exec && fds[1].revents) {
01812 num_read = read(STDIN_FILENO, cp, 1);
01813 if (num_read < 1) {
01814 break;
01815 } else
01816 return (num_read);
01817 }
01818 if (fds[0].revents) {
01819 char *tmp;
01820 res = read(ast_consock, buf, sizeof(buf) - 1);
01821
01822 if (res < 1) {
01823 fprintf(stderr, "\nDisconnected from Asterisk server\n");
01824 if (!ast_opt_reconnect) {
01825 quit_handler(0, 0, 0, 0);
01826 } else {
01827 int tries;
01828 int reconnects_per_second = 20;
01829 fprintf(stderr, "Attempting to reconnect for 30 seconds\n");
01830 for (tries=0; tries < 30 * reconnects_per_second; tries++) {
01831 if (ast_tryconnect()) {
01832 fprintf(stderr, "Reconnect succeeded after %.3f seconds\n", 1.0 / reconnects_per_second * tries);
01833 printf("%s", term_quit());
01834 WELCOME_MESSAGE;
01835 if (!ast_opt_mute)
01836 fdsend(ast_consock, "logger mute silent");
01837 else
01838 printf("log and verbose output currently muted ('logger mute' to unmute)\n");
01839 break;
01840 } else {
01841 usleep(1000000 / reconnects_per_second);
01842 }
01843 }
01844 if (tries >= 30 * reconnects_per_second) {
01845 fprintf(stderr, "Failed to reconnect for 30 seconds. Quitting.\n");
01846 quit_handler(0, 0, 0, 0);
01847 }
01848 }
01849 }
01850
01851 buf[res] = '\0';
01852
01853
01854 for (tmp = buf; *tmp; tmp++) {
01855 if (*tmp == 127) {
01856 memmove(tmp, tmp + 1, strlen(tmp));
01857 tmp--;
01858 }
01859 }
01860
01861
01862 if (!ast_opt_exec && !lastpos) {
01863 if (write(STDOUT_FILENO, "\r", 1) < 0) {
01864 }
01865 }
01866 if (write(STDOUT_FILENO, buf, res) < 0) {
01867 }
01868 if ((res < EL_BUF_SIZE - 1) && ((buf[res-1] == '\n') || (buf[res-2] == '\n'))) {
01869 *cp = CC_REFRESH;
01870 return(1);
01871 } else {
01872 lastpos = 1;
01873 }
01874 }
01875 }
01876
01877 *cp = '\0';
01878 return (0);
01879 }
01880
01881 static char *cli_prompt(EditLine *el)
01882 {
01883 static char prompt[200];
01884 char *pfmt;
01885 int color_used = 0;
01886 char term_code[20];
01887
01888 if ((pfmt = getenv("ASTERISK_PROMPT"))) {
01889 char *t = pfmt, *p = prompt;
01890 memset(prompt, 0, sizeof(prompt));
01891 while (*t != '\0' && *p < sizeof(prompt)) {
01892 if (*t == '%') {
01893 char hostname[MAXHOSTNAMELEN]="";
01894 int i;
01895 time_t ts;
01896 struct tm tm;
01897 #ifdef linux
01898 FILE *LOADAVG;
01899 #endif
01900 int fgcolor = COLOR_WHITE, bgcolor = COLOR_BLACK;
01901
01902 t++;
01903 switch (*t) {
01904 case 'C':
01905 t++;
01906 if (sscanf(t, "%d;%d%n", &fgcolor, &bgcolor, &i) == 2) {
01907 strncat(p, term_color_code(term_code, fgcolor, bgcolor, sizeof(term_code)),sizeof(prompt) - strlen(prompt) - 1);
01908 t += i - 1;
01909 } else if (sscanf(t, "%d%n", &fgcolor, &i) == 1) {
01910 strncat(p, term_color_code(term_code, fgcolor, 0, sizeof(term_code)),sizeof(prompt) - strlen(prompt) - 1);
01911 t += i - 1;
01912 }
01913
01914
01915 if ((fgcolor == COLOR_WHITE) && (bgcolor == COLOR_BLACK)) {
01916 color_used = 0;
01917 } else {
01918 color_used = 1;
01919 }
01920 break;
01921 case 'd':
01922 memset(&tm, 0, sizeof(tm));
01923 time(&ts);
01924 if (ast_localtime(&ts, &tm, NULL)) {
01925 strftime(p, sizeof(prompt) - strlen(prompt), "%Y-%m-%d", &tm);
01926 }
01927 break;
01928 case 'h':
01929 if (!gethostname(hostname, sizeof(hostname) - 1)) {
01930 strncat(p, hostname, sizeof(prompt) - strlen(prompt) - 1);
01931 } else {
01932 strncat(p, "localhost", sizeof(prompt) - strlen(prompt) - 1);
01933 }
01934 break;
01935 case 'H':
01936 if (!gethostname(hostname, sizeof(hostname) - 1)) {
01937 for (i = 0; i < sizeof(hostname); i++) {
01938 if (hostname[i] == '.') {
01939 hostname[i] = '\0';
01940 break;
01941 }
01942 }
01943 strncat(p, hostname, sizeof(prompt) - strlen(prompt) - 1);
01944 } else {
01945 strncat(p, "localhost", sizeof(prompt) - strlen(prompt) - 1);
01946 }
01947 break;
01948 #ifdef linux
01949 case 'l':
01950 t++;
01951 if ((LOADAVG = fopen("/proc/loadavg", "r"))) {
01952 float avg1, avg2, avg3;
01953 int actproc, totproc, npid, which;
01954
01955 if (fscanf(LOADAVG, "%f %f %f %d/%d %d",
01956 &avg1, &avg2, &avg3, &actproc, &totproc, &npid) != 6) {
01957 ast_log(LOG_WARNING, "parsing /proc/loadavg failed\n");
01958 fclose(LOADAVG);
01959 break;
01960 }
01961 if (sscanf(t, "%d", &which) == 1) {
01962 switch (which) {
01963 case 1:
01964 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg1);
01965 break;
01966 case 2:
01967 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg2);
01968 break;
01969 case 3:
01970 snprintf(p, sizeof(prompt) - strlen(prompt), "%.2f", avg3);
01971 break;
01972 case 4:
01973 snprintf(p, sizeof(prompt) - strlen(prompt), "%d/%d", actproc, totproc);
01974 break;
01975 case 5:
01976 snprintf(p, sizeof(prompt) - strlen(prompt), "%d", npid);
01977 break;
01978 }
01979 }
01980 fclose(LOADAVG);
01981 }
01982 break;
01983 #endif
01984 case 's':
01985 strncat(p, ast_config_AST_SYSTEM_NAME, sizeof(prompt) - strlen(prompt) - 1);
01986 break;
01987 case 't':
01988 memset(&tm, 0, sizeof(tm));
01989 time(&ts);
01990 if (ast_localtime(&ts, &tm, NULL)) {
01991 strftime(p, sizeof(prompt) - strlen(prompt), "%H:%M:%S", &tm);
01992 }
01993 break;
01994 case '#':
01995 if (!ast_opt_remote) {
01996 strncat(p, "#", sizeof(prompt) - strlen(prompt) - 1);
01997 } else {
01998 strncat(p, ">", sizeof(prompt) - strlen(prompt) - 1);
01999 }
02000 break;
02001 case '%':
02002 strncat(p, "%", sizeof(prompt) - strlen(prompt) - 1);
02003 break;
02004 case '\0':
02005 t--;
02006 break;
02007 }
02008 while (*p != '\0') {
02009 p++;
02010 }
02011 t++;
02012 } else {
02013 *p = *t;
02014 p++;
02015 t++;
02016 }
02017 }
02018 if (color_used) {
02019
02020 term_color_code(term_code, COLOR_WHITE, COLOR_BLACK, sizeof(term_code));
02021 if (strlen(term_code) > sizeof(prompt) - strlen(prompt) - 1) {
02022 ast_copy_string(prompt + sizeof(prompt) - strlen(term_code) - 1, term_code, strlen(term_code) + 1);
02023 } else {
02024
02025 strncat(p, term_code, sizeof(term_code));
02026 }
02027 }
02028 } else if (remotehostname)
02029 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT2, remotehostname);
02030 else
02031 snprintf(prompt, sizeof(prompt), ASTERISK_PROMPT);
02032
02033 return(prompt);
02034 }
02035
02036 static char **ast_el_strtoarr(char *buf)
02037 {
02038 char **match_list = NULL, *retstr;
02039 size_t match_list_len;
02040 int matches = 0;
02041
02042 match_list_len = 1;
02043 while ( (retstr = strsep(&buf, " ")) != NULL) {
02044
02045 if (!strcmp(retstr, AST_CLI_COMPLETE_EOF))
02046 break;
02047 if (matches + 1 >= match_list_len) {
02048 match_list_len <<= 1;
02049 if (!(match_list = ast_realloc(match_list, match_list_len * sizeof(char *)))) {
02050
02051 }
02052 }
02053
02054 match_list[matches++] = strdup(retstr);
02055 }
02056
02057 if (!match_list)
02058 return (char **) NULL;
02059
02060 if (matches >= match_list_len) {
02061 if (!(match_list = ast_realloc(match_list, (match_list_len + 1) * sizeof(char *)))) {
02062
02063 }
02064 }
02065
02066 match_list[matches] = (char *) NULL;
02067
02068 return match_list;
02069 }
02070
02071 static int ast_el_sort_compare(const void *i1, const void *i2)
02072 {
02073 char *s1, *s2;
02074
02075 s1 = ((char **)i1)[0];
02076 s2 = ((char **)i2)[0];
02077
02078 return strcasecmp(s1, s2);
02079 }
02080
02081 static int ast_cli_display_match_list(char **matches, int len, int max)
02082 {
02083 int i, idx, limit, count;
02084 int screenwidth = 0;
02085 int numoutput = 0, numoutputline = 0;
02086
02087 screenwidth = ast_get_termcols(STDOUT_FILENO);
02088
02089
02090 limit = screenwidth / (max + 2);
02091 if (limit == 0)
02092 limit = 1;
02093
02094
02095 count = len / limit;
02096 if (count * limit < len)
02097 count++;
02098
02099 idx = 1;
02100
02101 qsort(&matches[0], (size_t)(len), sizeof(char *), ast_el_sort_compare);
02102
02103 for (; count > 0; count--) {
02104 numoutputline = 0;
02105 for (i=0; i < limit && matches[idx]; i++, idx++) {
02106
02107
02108 if ( (matches[idx+1] != NULL && strcmp(matches[idx], matches[idx+1]) == 0 ) ) {
02109 i--;
02110 free(matches[idx]);
02111 matches[idx] = NULL;
02112 continue;
02113 }
02114
02115 numoutput++;
02116 numoutputline++;
02117 fprintf(stdout, "%-*s ", max, matches[idx]);
02118 free(matches[idx]);
02119 matches[idx] = NULL;
02120 }
02121 if (numoutputline > 0)
02122 fprintf(stdout, "\n");
02123 }
02124
02125 return numoutput;
02126 }
02127
02128
02129 static char *cli_complete(EditLine *el, int ch)
02130 {
02131 int len = 0;
02132 char *ptr;
02133 int nummatches = 0;
02134 char **matches;
02135 int retval = CC_ERROR;
02136 char buf[2048];
02137 int res;
02138
02139 LineInfo *lf = (LineInfo *)el_line(el);
02140
02141 *(char *)lf->cursor = '\0';
02142 ptr = (char *)lf->cursor;
02143 if (ptr) {
02144 while (ptr > lf->buffer) {
02145 if (isspace(*ptr)) {
02146 ptr++;
02147 break;
02148 }
02149 ptr--;
02150 }
02151 }
02152
02153 len = lf->cursor - ptr;
02154
02155 if (ast_opt_remote) {
02156 snprintf(buf, sizeof(buf),"_COMMAND NUMMATCHES \"%s\" \"%s\"", lf->buffer, ptr);
02157 fdsend(ast_consock, buf);
02158 res = read(ast_consock, buf, sizeof(buf));
02159 buf[res] = '\0';
02160 nummatches = atoi(buf);
02161
02162 if (nummatches > 0) {
02163 char *mbuf;
02164 int mlen = 0, maxmbuf = 2048;
02165
02166 if (!(mbuf = ast_malloc(maxmbuf)))
02167 return (char *)(CC_ERROR);
02168 snprintf(buf, sizeof(buf),"_COMMAND MATCHESARRAY \"%s\" \"%s\"", lf->buffer, ptr);
02169 fdsend(ast_consock, buf);
02170 res = 0;
02171 mbuf[0] = '\0';
02172 while (!strstr(mbuf, AST_CLI_COMPLETE_EOF) && res != -1) {
02173 if (mlen + 1024 > maxmbuf) {
02174
02175 maxmbuf += 1024;
02176 if (!(mbuf = ast_realloc(mbuf, maxmbuf)))
02177 return (char *)(CC_ERROR);
02178 }
02179
02180 res = read(ast_consock, mbuf + mlen, 1024);
02181 if (res > 0)
02182 mlen += res;
02183 }
02184 mbuf[mlen] = '\0';
02185
02186 matches = ast_el_strtoarr(mbuf);
02187 free(mbuf);
02188 } else
02189 matches = (char **) NULL;
02190 } else {
02191 char **p, *oldbuf=NULL;
02192 nummatches = 0;
02193 matches = ast_cli_completion_matches((char *)lf->buffer,ptr);
02194 for (p = matches; p && *p; p++) {
02195 if (!oldbuf || strcmp(*p,oldbuf))
02196 nummatches++;
02197 oldbuf = *p;
02198 }
02199 }
02200
02201 if (matches) {
02202 int i;
02203 int matches_num, maxlen, match_len;
02204
02205 if (matches[0][0] != '\0') {
02206 el_deletestr(el, (int) len);
02207 el_insertstr(el, matches[0]);
02208 retval = CC_REFRESH;
02209 }
02210
02211 if (nummatches == 1) {
02212
02213 el_insertstr(el, " ");
02214 retval = CC_REFRESH;
02215 } else {
02216
02217 for (i=1, maxlen=0; matches[i]; i++) {
02218 match_len = strlen(matches[i]);
02219 if (match_len > maxlen)
02220 maxlen = match_len;
02221 }
02222 matches_num = i - 1;
02223 if (matches_num >1) {
02224 fprintf(stdout, "\n");
02225 ast_cli_display_match_list(matches, nummatches, maxlen);
02226 retval = CC_REDISPLAY;
02227 } else {
02228 el_insertstr(el," ");
02229 retval = CC_REFRESH;
02230 }
02231 }
02232 for (i = 0; matches[i]; i++)
02233 free(matches[i]);
02234 free(matches);
02235 }
02236
02237 return (char *)(long)retval;
02238 }
02239
02240 static int ast_el_initialize(void)
02241 {
02242 HistEvent ev;
02243 char *editor = getenv("AST_EDITOR");
02244
02245 if (el != NULL)
02246 el_end(el);
02247 if (el_hist != NULL)
02248 history_end(el_hist);
02249
02250 el = el_init("asterisk", stdin, stdout, stderr);
02251 el_set(el, EL_PROMPT, cli_prompt);
02252
02253 el_set(el, EL_EDITMODE, 1);
02254 el_set(el, EL_EDITOR, editor ? editor : "emacs");
02255 el_hist = history_init();
02256 if (!el || !el_hist)
02257 return -1;
02258
02259
02260 history(el_hist, &ev, H_SETSIZE, 100);
02261
02262 el_set(el, EL_HIST, history, el_hist);
02263
02264 el_set(el, EL_ADDFN, "ed-complete", "Complete argument", cli_complete);
02265
02266 el_set(el, EL_BIND, "^I", "ed-complete", NULL);
02267
02268 el_set(el, EL_BIND, "?", "ed-complete", NULL);
02269
02270 el_set(el, EL_BIND, "^D", "ed-redisplay", NULL);
02271
02272 return 0;
02273 }
02274
02275 static int ast_el_add_history(char *buf)
02276 {
02277 HistEvent ev;
02278
02279 if (el_hist == NULL || el == NULL)
02280 ast_el_initialize();
02281 if (strlen(buf) > 256)
02282 return 0;
02283 return (history(el_hist, &ev, H_ENTER, buf));
02284 }
02285
02286 static int ast_el_write_history(char *filename)
02287 {
02288 HistEvent ev;
02289
02290 if (el_hist == NULL || el == NULL)
02291 ast_el_initialize();
02292
02293 return (history(el_hist, &ev, H_SAVE, filename));
02294 }
02295
02296 static int ast_el_read_history(char *filename)
02297 {
02298 char buf[256];
02299 FILE *f;
02300 int ret = -1;
02301
02302 if (el_hist == NULL || el == NULL)
02303 ast_el_initialize();
02304
02305 if ((f = fopen(filename, "r")) == NULL)
02306 return ret;
02307
02308 while (!feof(f)) {
02309 if (!fgets(buf, sizeof(buf), f)) {
02310 continue;
02311 }
02312 if (!strcmp(buf, "_HiStOrY_V2_\n"))
02313 continue;
02314 if (ast_all_zeros(buf))
02315 continue;
02316 if ((ret = ast_el_add_history(buf)) == -1)
02317 break;
02318 }
02319 fclose(f);
02320
02321 return ret;
02322 }
02323
02324 static void ast_remotecontrol(char *data)
02325 {
02326 char buf[80];
02327 int res;
02328 char filename[80] = "";
02329 char *hostname;
02330 char *cpid;
02331 char *version;
02332 int pid;
02333 char tmp[80];
02334 char *stringp = NULL;
02335
02336 char *ebuf;
02337 int num = 0;
02338
02339 memset(&sig_flags, 0, sizeof(sig_flags));
02340 signal(SIGINT, __remote_quit_handler);
02341 signal(SIGTERM, __remote_quit_handler);
02342 signal(SIGHUP, __remote_quit_handler);
02343
02344 if (read(ast_consock, buf, sizeof(buf)) < 0) {
02345 ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
02346 return;
02347 }
02348 if (data) {
02349 if (write(ast_consock, data, strlen(data) + 1) < 0) {
02350 ast_log(LOG_ERROR, "write() failed: %s\n", strerror(errno));
02351 if (sig_flags.need_quit == 1) {
02352 return;
02353 }
02354 }
02355 }
02356 stringp = buf;
02357 hostname = strsep(&stringp, "/");
02358 cpid = strsep(&stringp, "/");
02359 version = strsep(&stringp, "\n");
02360 if (!version)
02361 version = "<Version Unknown>";
02362 stringp = hostname;
02363 strsep(&stringp, ".");
02364 if (cpid)
02365 pid = atoi(cpid);
02366 else
02367 pid = -1;
02368 if (!data) {
02369 snprintf(tmp, sizeof(tmp), "core set verbose atleast %d", option_verbose);
02370 fdsend(ast_consock, tmp);
02371 snprintf(tmp, sizeof(tmp), "core set debug atleast %d", option_debug);
02372 fdsend(ast_consock, tmp);
02373 if (!ast_opt_mute)
02374 fdsend(ast_consock, "logger mute silent");
02375 else
02376 printf("log and verbose output currently muted ('logger mute' to unmute)\n");
02377 }
02378 ast_verbose("Connected to Asterisk %s currently running on %s (pid = %d)\n", version, hostname, pid);
02379 remotehostname = hostname;
02380 if (getenv("HOME"))
02381 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
02382 if (el_hist == NULL || el == NULL)
02383 ast_el_initialize();
02384
02385 el_set(el, EL_GETCFN, ast_el_read_char);
02386
02387 if (!ast_strlen_zero(filename))
02388 ast_el_read_history(filename);
02389
02390 if (ast_opt_exec && data) {
02391 struct pollfd fds;
02392 fds.fd = ast_consock;
02393 fds.events = POLLIN;
02394 fds.revents = 0;
02395 while (poll(&fds, 1, 500) > 0) {
02396 char buf[512] = "", *curline = buf, *nextline;
02397 int not_written = 1;
02398
02399 if (sig_flags.need_quit == 1) {
02400 break;
02401 }
02402
02403 if (read(ast_consock, buf, sizeof(buf) - 1) <= 0) {
02404 break;
02405 }
02406
02407 do {
02408 if ((nextline = strchr(curline, '\n'))) {
02409 nextline++;
02410 } else {
02411 nextline = strchr(curline, '\0');
02412 }
02413
02414
02415 if (*curline != 127) {
02416 not_written = 0;
02417 if (write(STDOUT_FILENO, curline, nextline - curline) < 0) {
02418 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
02419 }
02420 }
02421 curline = nextline;
02422 } while (!ast_strlen_zero(curline));
02423
02424
02425 if (not_written) {
02426 break;
02427 }
02428 }
02429 return;
02430 }
02431 for (;;) {
02432 ebuf = (char *)el_gets(el, &num);
02433
02434 if (sig_flags.need_quit == 1) {
02435 break;
02436 }
02437
02438 if (!ebuf && write(1, "", 1) < 0)
02439 break;
02440
02441 if (!ast_strlen_zero(ebuf)) {
02442 if (ebuf[strlen(ebuf)-1] == '\n')
02443 ebuf[strlen(ebuf)-1] = '\0';
02444 if (!remoteconsolehandler(ebuf)) {
02445
02446 char *tmp;
02447 for (tmp = ebuf; *tmp; tmp++) {
02448 if (*tmp == 127) {
02449 memmove(tmp, tmp + 1, strlen(tmp));
02450 tmp--;
02451 }
02452 }
02453 res = write(ast_consock, ebuf, strlen(ebuf) + 1);
02454 if (res < 1) {
02455 ast_log(LOG_WARNING, "Unable to write: %s\n", strerror(errno));
02456 break;
02457 }
02458 }
02459 }
02460 }
02461 printf("\nDisconnected from Asterisk server\n");
02462 }
02463
02464 static int show_version(void)
02465 {
02466 printf("Asterisk " ASTERISK_VERSION "\n");
02467 return 0;
02468 }
02469
02470 static int show_cli_help(void) {
02471 printf("Asterisk " ASTERISK_VERSION ", Copyright (C) 1999 - 2008, Digium, Inc. and others.\n");
02472 printf("Usage: asterisk [OPTIONS]\n");
02473 printf("Valid Options:\n");
02474 printf(" -V Display version number and exit\n");
02475 printf(" -C <configfile> Use an alternate configuration file\n");
02476 printf(" -G <group> Run as a group other than the caller\n");
02477 printf(" -U <user> Run as a user other than the caller\n");
02478 printf(" -c Provide console CLI\n");
02479 printf(" -d Enable extra debugging\n");
02480 #if HAVE_WORKING_FORK
02481 printf(" -f Do not fork\n");
02482 printf(" -F Always fork\n");
02483 #endif
02484 printf(" -g Dump core in case of a crash\n");
02485 printf(" -h This help screen\n");
02486 printf(" -i Initialize crypto keys at startup\n");
02487 printf(" -I Enable internal timing if %s timer is available\n", dahdi_chan_name);
02488 printf(" -L <load> Limit the maximum load average before rejecting new calls\n");
02489 printf(" -M <value> Limit the maximum number of calls to the specified value\n");
02490 printf(" -m Mute debugging and console output on the console\n");
02491 printf(" -n Disable console colorization\n");
02492 printf(" -p Run as pseudo-realtime thread\n");
02493 printf(" -q Quiet mode (suppress output)\n");
02494 printf(" -r Connect to Asterisk on this machine\n");
02495 printf(" -R Same as -r, except attempt to reconnect if disconnected\n");
02496 printf(" -t Record soundfiles in /var/tmp and move them where they\n");
02497 printf(" belong after they are done\n");
02498 printf(" -T Display the time in [Mmm dd hh:mm:ss] format for each line\n");
02499 printf(" of output to the CLI\n");
02500 printf(" -v Increase verbosity (multiple v's = more verbose)\n");
02501 printf(" -x <cmd> Execute command <cmd> (only valid with -r)\n");
02502 printf("\n");
02503 return 0;
02504 }
02505
02506 static void ast_readconfig(void)
02507 {
02508 struct ast_config *cfg;
02509 struct ast_variable *v;
02510 char *config = AST_CONFIG_FILE;
02511
02512 if (ast_opt_override_config) {
02513 cfg = ast_config_load(ast_config_AST_CONFIG_FILE);
02514 if (!cfg)
02515 ast_log(LOG_WARNING, "Unable to open specified master config file '%s', using built-in defaults\n", ast_config_AST_CONFIG_FILE);
02516 } else {
02517 cfg = ast_config_load(config);
02518 }
02519
02520
02521 ast_copy_string(ast_config_AST_CONFIG_DIR, AST_CONFIG_DIR, sizeof(ast_config_AST_CONFIG_DIR));
02522 ast_copy_string(ast_config_AST_SPOOL_DIR, AST_SPOOL_DIR, sizeof(ast_config_AST_SPOOL_DIR));
02523 ast_copy_string(ast_config_AST_MODULE_DIR, AST_MODULE_DIR, sizeof(ast_config_AST_MODULE_DIR));
02524 snprintf(ast_config_AST_MONITOR_DIR, sizeof(ast_config_AST_MONITOR_DIR) - 1, "%s/monitor", ast_config_AST_SPOOL_DIR);
02525 ast_copy_string(ast_config_AST_VAR_DIR, AST_VAR_DIR, sizeof(ast_config_AST_VAR_DIR));
02526 ast_copy_string(ast_config_AST_DATA_DIR, AST_DATA_DIR, sizeof(ast_config_AST_DATA_DIR));
02527 ast_copy_string(ast_config_AST_LOG_DIR, AST_LOG_DIR, sizeof(ast_config_AST_LOG_DIR));
02528 ast_copy_string(ast_config_AST_AGI_DIR, AST_AGI_DIR, sizeof(ast_config_AST_AGI_DIR));
02529 ast_copy_string(ast_config_AST_DB, AST_DB, sizeof(ast_config_AST_DB));
02530 ast_copy_string(ast_config_AST_KEY_DIR, AST_KEY_DIR, sizeof(ast_config_AST_KEY_DIR));
02531 ast_copy_string(ast_config_AST_PID, AST_PID, sizeof(ast_config_AST_PID));
02532 ast_copy_string(ast_config_AST_SOCKET, AST_SOCKET, sizeof(ast_config_AST_SOCKET));
02533 ast_copy_string(ast_config_AST_RUN_DIR, AST_RUN_DIR, sizeof(ast_config_AST_RUN_DIR));
02534
02535
02536 if (!cfg) {
02537 return;
02538 }
02539
02540 for (v = ast_variable_browse(cfg, "files"); v; v = v->next) {
02541 if (!strcasecmp(v->name, "astctlpermissions")) {
02542 ast_copy_string(ast_config_AST_CTL_PERMISSIONS, v->value, sizeof(ast_config_AST_CTL_PERMISSIONS));
02543 } else if (!strcasecmp(v->name, "astctlowner")) {
02544 ast_copy_string(ast_config_AST_CTL_OWNER, v->value, sizeof(ast_config_AST_CTL_OWNER));
02545 } else if (!strcasecmp(v->name, "astctlgroup")) {
02546 ast_copy_string(ast_config_AST_CTL_GROUP, v->value, sizeof(ast_config_AST_CTL_GROUP));
02547 } else if (!strcasecmp(v->name, "astctl")) {
02548 ast_copy_string(ast_config_AST_CTL, v->value, sizeof(ast_config_AST_CTL));
02549 }
02550 }
02551
02552 for (v = ast_variable_browse(cfg, "directories"); v; v = v->next) {
02553 if (!strcasecmp(v->name, "astetcdir")) {
02554 ast_copy_string(ast_config_AST_CONFIG_DIR, v->value, sizeof(ast_config_AST_CONFIG_DIR));
02555 } else if (!strcasecmp(v->name, "astspooldir")) {
02556 ast_copy_string(ast_config_AST_SPOOL_DIR, v->value, sizeof(ast_config_AST_SPOOL_DIR));
02557 snprintf(ast_config_AST_MONITOR_DIR, sizeof(ast_config_AST_MONITOR_DIR) - 1, "%s/monitor", v->value);
02558 } else if (!strcasecmp(v->name, "astvarlibdir")) {
02559 ast_copy_string(ast_config_AST_VAR_DIR, v->value, sizeof(ast_config_AST_VAR_DIR));
02560 snprintf(ast_config_AST_DB, sizeof(ast_config_AST_DB), "%s/astdb", v->value);
02561 } else if (!strcasecmp(v->name, "astdatadir")) {
02562 ast_copy_string(ast_config_AST_DATA_DIR, v->value, sizeof(ast_config_AST_DATA_DIR));
02563 snprintf(ast_config_AST_KEY_DIR, sizeof(ast_config_AST_KEY_DIR), "%s/keys", v->value);
02564 } else if (!strcasecmp(v->name, "astlogdir")) {
02565 ast_copy_string(ast_config_AST_LOG_DIR, v->value, sizeof(ast_config_AST_LOG_DIR));
02566 } else if (!strcasecmp(v->name, "astagidir")) {
02567 ast_copy_string(ast_config_AST_AGI_DIR, v->value, sizeof(ast_config_AST_AGI_DIR));
02568 } else if (!strcasecmp(v->name, "astrundir")) {
02569 snprintf(ast_config_AST_PID, sizeof(ast_config_AST_PID), "%s/%s", v->value, "asterisk.pid");
02570 snprintf(ast_config_AST_SOCKET, sizeof(ast_config_AST_SOCKET), "%s/%s", v->value, ast_config_AST_CTL);
02571 ast_copy_string(ast_config_AST_RUN_DIR, v->value, sizeof(ast_config_AST_RUN_DIR));
02572 } else if (!strcasecmp(v->name, "astmoddir")) {
02573 ast_copy_string(ast_config_AST_MODULE_DIR, v->value, sizeof(ast_config_AST_MODULE_DIR));
02574 }
02575 }
02576
02577 for (v = ast_variable_browse(cfg, "options"); v; v = v->next) {
02578
02579 if (!strcasecmp(v->name, "verbose")) {
02580 option_verbose = atoi(v->value);
02581
02582 } else if (!strcasecmp(v->name, "timestamp")) {
02583 ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_TIMESTAMP);
02584
02585 } else if (!strcasecmp(v->name, "execincludes")) {
02586 ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_EXEC_INCLUDES);
02587
02588 } else if (!strcasecmp(v->name, "debug")) {
02589 option_debug = 0;
02590 if (sscanf(v->value, "%d", &option_debug) != 1) {
02591 option_debug = ast_true(v->value);
02592 }
02593 #if HAVE_WORKING_FORK
02594
02595 } else if (!strcasecmp(v->name, "nofork")) {
02596 ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_NO_FORK);
02597
02598 } else if (!strcasecmp(v->name, "alwaysfork")) {
02599 ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_ALWAYS_FORK);
02600 #endif
02601
02602 } else if (!strcasecmp(v->name, "quiet")) {
02603 ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_QUIET);
02604
02605 } else if (!strcasecmp(v->name, "console")) {
02606 ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_CONSOLE);
02607
02608 } else if (!strcasecmp(v->name, "highpriority")) {
02609 ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_HIGH_PRIORITY);
02610
02611 } else if (!strcasecmp(v->name, "initcrypto")) {
02612 ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_INIT_KEYS);
02613
02614 } else if (!strcasecmp(v->name, "nocolor")) {
02615 ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_NO_COLOR);
02616
02617 } else if (!strcasecmp(v->name, "dontwarn")) {
02618 ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_DONT_WARN);
02619
02620 } else if (!strcasecmp(v->name, "dumpcore")) {
02621 ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_DUMP_CORE);
02622
02623 } else if (!strcasecmp(v->name, "cache_record_files")) {
02624 ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_CACHE_RECORD_FILES);
02625
02626 } else if (!strcasecmp(v->name, "record_cache_dir")) {
02627 ast_copy_string(record_cache_dir, v->value, AST_CACHE_DIR_LEN);
02628
02629 } else if (!strcasecmp(v->name, "transcode_via_sln")) {
02630 ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_TRANSCODE_VIA_SLIN);
02631
02632 } else if (!strcasecmp(v->name, "transmit_silence_during_record") || !strcasecmp(v->name, "transmit_silence")) {
02633 ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_TRANSMIT_SILENCE);
02634
02635 } else if (!strcasecmp(v->name, "internal_timing")) {
02636 ast_set2_flag(&ast_options, ast_true(v->value), AST_OPT_FLAG_INTERNAL_TIMING);
02637 } else if (!strcasecmp(v->name, "maxcalls")) {
02638 if ((sscanf(v->value, "%d", &option_maxcalls) != 1) || (option_maxcalls < 0)) {
02639 option_maxcalls = 0;
02640 }
02641 } else if (!strcasecmp(v->name, "maxload")) {
02642 double test[1];
02643
02644 if (getloadavg(test, 1) == -1) {
02645 ast_log(LOG_ERROR, "Cannot obtain load average on this system. 'maxload' option disabled.\n");
02646 option_maxload = 0.0;
02647 } else if ((sscanf(v->value, "%lf", &option_maxload) != 1) || (option_maxload < 0.0)) {
02648 option_maxload = 0.0;
02649 }
02650
02651 } else if (!strcasecmp(v->name, "maxfiles")) {
02652 set_ulimit(atoi(v->value));
02653
02654 } else if (!strcasecmp(v->name, "runuser")) {
02655 ast_copy_string(ast_config_AST_RUN_USER, v->value, sizeof(ast_config_AST_RUN_USER));
02656
02657 } else if (!strcasecmp(v->name, "rungroup")) {
02658 ast_copy_string(ast_config_AST_RUN_GROUP, v->value, sizeof(ast_config_AST_RUN_GROUP));
02659 } else if (!strcasecmp(v->name, "systemname")) {
02660 ast_copy_string(ast_config_AST_SYSTEM_NAME, v->value, sizeof(ast_config_AST_SYSTEM_NAME));
02661 } else if (!strcasecmp(v->name, "languageprefix")) {
02662 ast_language_is_prefix = ast_true(v->value);
02663 } else if (!strcasecmp(v->name, "dahdichanname")) {
02664 #ifdef HAVE_ZAPTEL
02665 if (ast_true(v->value)) {
02666 strcpy(_dahdi_chan_name, "DAHDI");
02667 _dahdi_chan_name_len = 5;
02668 _dahdi_chan_mode = CHAN_DAHDI_PLUS_ZAP_MODE;
02669 }
02670 #else
02671 if (ast_false(v->value)) {
02672 strcpy(_dahdi_chan_name, "Zap");
02673 _dahdi_chan_name_len = 3;
02674 _dahdi_chan_mode = CHAN_ZAP_MODE;
02675 }
02676 #endif
02677 }
02678 }
02679 ast_config_destroy(cfg);
02680 }
02681
02682 static void *monitor_sig_flags(void *unused)
02683 {
02684 for (;;) {
02685 struct pollfd p = { sig_alert_pipe[0], POLLIN, 0 };
02686 int a;
02687 poll(&p, 1, -1);
02688 if (sig_flags.need_reload) {
02689 sig_flags.need_reload = 0;
02690 ast_module_reload(NULL);
02691 }
02692 if (sig_flags.need_quit) {
02693 sig_flags.need_quit = 0;
02694 quit_handler(0, 0, 1, 0);
02695 }
02696 if (read(sig_alert_pipe[0], &a, sizeof(a)) != sizeof(a)) {
02697 }
02698 }
02699
02700 return NULL;
02701 }
02702
02703 int main(int argc, char *argv[])
02704 {
02705 int c;
02706 char filename[80] = "";
02707 char hostname[MAXHOSTNAMELEN] = "";
02708 char tmp[80];
02709 char * xarg = NULL;
02710 int x;
02711 FILE *f;
02712 sigset_t sigs;
02713 int num;
02714 int isroot = 1;
02715 char *buf;
02716 char *runuser = NULL, *rungroup = NULL;
02717
02718
02719 if (argc > sizeof(_argv) / sizeof(_argv[0]) - 1) {
02720 fprintf(stderr, "Truncating argument size to %d\n", (int)(sizeof(_argv) / sizeof(_argv[0])) - 1);
02721 argc = sizeof(_argv) / sizeof(_argv[0]) - 1;
02722 }
02723 for (x=0; x<argc; x++)
02724 _argv[x] = argv[x];
02725 _argv[x] = NULL;
02726
02727 if (geteuid() != 0)
02728 isroot = 0;
02729
02730
02731 if (argv[0] && (strstr(argv[0], "rasterisk")) != NULL) {
02732 ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK | AST_OPT_FLAG_REMOTE);
02733 }
02734 if (gethostname(hostname, sizeof(hostname)-1))
02735 ast_copy_string(hostname, "<Unknown>", sizeof(hostname));
02736 ast_mainpid = getpid();
02737 ast_ulaw_init();
02738 ast_alaw_init();
02739 callerid_init();
02740 ast_builtins_init();
02741 ast_utils_init();
02742 tdd_init();
02743
02744 if (getenv("HOME"))
02745 snprintf(filename, sizeof(filename), "%s/.asterisk_history", getenv("HOME"));
02746
02747 while ((c = getopt(argc, argv, "mtThfFdvVqprRgciInx:U:G:C:L:M:")) != -1) {
02748 switch (c) {
02749 #if HAVE_WORKING_FORK
02750 case 'F':
02751 ast_set_flag(&ast_options, AST_OPT_FLAG_ALWAYS_FORK);
02752 break;
02753 case 'f':
02754 ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK);
02755 break;
02756 #endif
02757 case 'd':
02758 option_debug++;
02759 ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK);
02760 break;
02761 case 'c':
02762 ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK | AST_OPT_FLAG_CONSOLE);
02763 break;
02764 case 'n':
02765 ast_set_flag(&ast_options, AST_OPT_FLAG_NO_COLOR);
02766 break;
02767 case 'r':
02768 ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK | AST_OPT_FLAG_REMOTE);
02769 break;
02770 case 'R':
02771 ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK | AST_OPT_FLAG_REMOTE | AST_OPT_FLAG_RECONNECT);
02772 break;
02773 case 'p':
02774 ast_set_flag(&ast_options, AST_OPT_FLAG_HIGH_PRIORITY);
02775 break;
02776 case 'v':
02777 option_verbose++;
02778 ast_set_flag(&ast_options, AST_OPT_FLAG_NO_FORK);
02779 break;
02780 case 'm':
02781 ast_set_flag(&ast_options, AST_OPT_FLAG_MUTE);
02782 break;
02783 case 'M':
02784 if ((sscanf(optarg, "%d", &option_maxcalls) != 1) || (option_maxcalls < 0))
02785 option_maxcalls = 0;
02786 break;
02787 case 'L':
02788 if ((sscanf(optarg, "%lf", &option_maxload) != 1) || (option_maxload < 0.0))
02789 option_maxload = 0.0;
02790 break;
02791 case 'q':
02792 ast_set_flag(&ast_options, AST_OPT_FLAG_QUIET);
02793 break;
02794 case 't':
02795 ast_set_flag(&ast_options, AST_OPT_FLAG_CACHE_RECORD_FILES);
02796 break;
02797 case 'T':
02798 ast_set_flag(&ast_options, AST_OPT_FLAG_TIMESTAMP);
02799 break;
02800 case 'x':
02801 ast_set_flag(&ast_options, AST_OPT_FLAG_EXEC);
02802 xarg = ast_strdupa(optarg);
02803 break;
02804 case 'C':
02805 ast_copy_string(ast_config_AST_CONFIG_FILE, optarg, sizeof(ast_config_AST_CONFIG_FILE));
02806 ast_set_flag(&ast_options, AST_OPT_FLAG_OVERRIDE_CONFIG);
02807 break;
02808 case 'I':
02809 ast_set_flag(&ast_options, AST_OPT_FLAG_INTERNAL_TIMING);
02810 break;
02811 case 'i':
02812 ast_set_flag(&ast_options, AST_OPT_FLAG_INIT_KEYS);
02813 break;
02814 case 'g':
02815 ast_set_flag(&ast_options, AST_OPT_FLAG_DUMP_CORE);
02816 break;
02817 case 'h':
02818 show_cli_help();
02819 exit(0);
02820 case 'V':
02821 show_version();
02822 exit(0);
02823 case 'U':
02824 runuser = ast_strdupa(optarg);
02825 break;
02826 case 'G':
02827 rungroup = ast_strdupa(optarg);
02828 break;
02829 case '?':
02830 exit(1);
02831 }
02832 }
02833
02834 if (ast_opt_console || option_verbose || (ast_opt_remote && !ast_opt_exec)) {
02835 ast_register_verbose(console_verboser);
02836 WELCOME_MESSAGE;
02837 }
02838
02839 if (ast_opt_console && !option_verbose)
02840 ast_verbose("[ Booting...\n");
02841
02842
02843
02844
02845 if (ast_opt_remote) {
02846 strcpy(argv[0], "rasterisk");
02847 for (x = 1; x < argc; x++) {
02848 argv[x] = argv[0] + 10;
02849 }
02850 }
02851
02852 if (ast_opt_console && !option_verbose) {
02853 ast_verbose("[ Reading Master Configuration ]\n");
02854 }
02855
02856 ast_readconfig();
02857
02858 if (ast_opt_always_fork && (ast_opt_remote || ast_opt_console)) {
02859 ast_log(LOG_WARNING, "'alwaysfork' is not compatible with console or remote console mode; ignored\n");
02860 ast_clear_flag(&ast_options, AST_OPT_FLAG_ALWAYS_FORK);
02861 }
02862
02863 if (ast_opt_dump_core) {
02864 struct rlimit l;
02865 memset(&l, 0, sizeof(l));
02866 l.rlim_cur = RLIM_INFINITY;
02867 l.rlim_max = RLIM_INFINITY;
02868 if (setrlimit(RLIMIT_CORE, &l)) {
02869 ast_log(LOG_WARNING, "Unable to disable core size resource limit: %s\n", strerror(errno));
02870 }
02871 }
02872
02873 if ((!rungroup) && !ast_strlen_zero(ast_config_AST_RUN_GROUP))
02874 rungroup = ast_config_AST_RUN_GROUP;
02875 if ((!runuser) && !ast_strlen_zero(ast_config_AST_RUN_USER))
02876 runuser = ast_config_AST_RUN_USER;
02877
02878 #ifndef __CYGWIN__
02879
02880 if (isroot)
02881 ast_set_priority(ast_opt_high_priority);
02882
02883 if (isroot && rungroup) {
02884 struct group *gr;
02885 gr = getgrnam(rungroup);
02886 if (!gr) {
02887 ast_log(LOG_WARNING, "No such group '%s'!\n", rungroup);
02888 exit(1);
02889 }
02890 if (setgid(gr->gr_gid)) {
02891 ast_log(LOG_WARNING, "Unable to setgid to %d (%s)\n", (int)gr->gr_gid, rungroup);
02892 exit(1);
02893 }
02894 if (setgroups(0, NULL)) {
02895 ast_log(LOG_WARNING, "Unable to drop unneeded groups\n");
02896 exit(1);
02897 }
02898 if (option_verbose)
02899 ast_verbose("Running as group '%s'\n", rungroup);
02900 }
02901
02902 if (runuser && !ast_test_flag(&ast_options, AST_OPT_FLAG_REMOTE)) {
02903 #ifdef HAVE_CAP
02904 int has_cap = 1;
02905 #endif
02906 struct passwd *pw;
02907 pw = getpwnam(runuser);
02908 if (!pw) {
02909 ast_log(LOG_WARNING, "No such user '%s'!\n", runuser);
02910 exit(1);
02911 }
02912 #ifdef HAVE_CAP
02913 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0)) {
02914 ast_log(LOG_WARNING, "Unable to keep capabilities.\n");
02915 has_cap = 0;
02916 }
02917 #endif
02918 if (!isroot && pw->pw_uid != geteuid()) {
02919 ast_log(LOG_ERROR, "Asterisk started as nonroot, but runuser '%s' requested.\n", runuser);
02920 exit(1);
02921 }
02922 if (!rungroup) {
02923 if (setgid(pw->pw_gid)) {
02924 ast_log(LOG_WARNING, "Unable to setgid to %d!\n", (int)pw->pw_gid);
02925 exit(1);
02926 }
02927 if (isroot && initgroups(pw->pw_name, pw->pw_gid)) {
02928 ast_log(LOG_WARNING, "Unable to init groups for '%s'\n", runuser);
02929 exit(1);
02930 }
02931 }
02932 if (setuid(pw->pw_uid)) {
02933 ast_log(LOG_WARNING, "Unable to setuid to %d (%s)\n", (int)pw->pw_uid, runuser);
02934 exit(1);
02935 }
02936 if (option_verbose)
02937 ast_verbose("Running as user '%s'\n", runuser);
02938 #ifdef HAVE_CAP
02939 if (has_cap) {
02940 cap_t cap;
02941
02942 cap = cap_from_text("cap_net_admin=ep");
02943
02944 if (cap_set_proc(cap))
02945 ast_log(LOG_WARNING, "Unable to install capabilities.\n");
02946
02947 if (cap_free(cap))
02948 ast_log(LOG_WARNING, "Unable to drop capabilities.\n");
02949 }
02950 #endif
02951 }
02952
02953 #endif
02954
02955 #ifdef linux
02956 if (geteuid() && ast_opt_dump_core) {
02957 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) < 0) {
02958 ast_log(LOG_WARNING, "Unable to set the process for core dumps after changing to a non-root user. %s\n", strerror(errno));
02959 }
02960 }
02961 #endif
02962
02963 ast_term_init();
02964 printf("%s", term_end());
02965 fflush(stdout);
02966
02967 if (ast_opt_console && !option_verbose)
02968 ast_verbose("[ Initializing Custom Configuration Options ]\n");
02969
02970 register_config_cli();
02971 read_config_maps();
02972
02973 if (ast_opt_console) {
02974 if (el_hist == NULL || el == NULL)
02975 ast_el_initialize();
02976
02977 if (!ast_strlen_zero(filename))
02978 ast_el_read_history(filename);
02979 }
02980
02981 if (ast_tryconnect()) {
02982
02983 if (ast_opt_remote) {
02984 if (ast_opt_exec) {
02985 ast_remotecontrol(xarg);
02986 quit_handler(0, 0, 0, 0);
02987 exit(0);
02988 }
02989 printf("%s", term_quit());
02990 ast_remotecontrol(NULL);
02991 quit_handler(0, 0, 0, 0);
02992 exit(0);
02993 } else {
02994 ast_log(LOG_ERROR, "Asterisk already running on %s. Use 'asterisk -r' to connect.\n", ast_config_AST_SOCKET);
02995 printf("%s", term_quit());
02996 exit(1);
02997 }
02998 } else if (ast_opt_remote || ast_opt_exec) {
02999 ast_log(LOG_ERROR, "Unable to connect to remote asterisk (does %s exist?)\n", ast_config_AST_SOCKET);
03000 printf("%s", term_quit());
03001 exit(1);
03002 }
03003
03004 unlink(ast_config_AST_PID);
03005 f = fopen(ast_config_AST_PID, "w");
03006 if (f) {
03007 fprintf(f, "%ld\n", (long)getpid());
03008 fclose(f);
03009 } else
03010 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", ast_config_AST_PID, strerror(errno));
03011
03012 #if HAVE_WORKING_FORK
03013 if (ast_opt_always_fork || !ast_opt_no_fork) {
03014 #ifndef HAVE_SBIN_LAUNCHD
03015 if (daemon(1, 0) < 0) {
03016 ast_log(LOG_ERROR, "daemon() failed: %s\n", strerror(errno));
03017 }
03018 ast_mainpid = getpid();
03019
03020 unlink(ast_config_AST_PID);
03021 f = fopen(ast_config_AST_PID, "w");
03022 if (f) {
03023 fprintf(f, "%ld\n", (long)ast_mainpid);
03024 fclose(f);
03025 } else
03026 ast_log(LOG_WARNING, "Unable to open pid file '%s': %s\n", ast_config_AST_PID, strerror(errno));
03027 #else
03028 ast_log(LOG_WARNING, "Mac OS X detected. Use '/sbin/launchd -d' to launch with the nofork option.\n");
03029 #endif
03030 }
03031 #endif
03032
03033 ast_makesocket();
03034 sigemptyset(&sigs);
03035 sigaddset(&sigs, SIGHUP);
03036 sigaddset(&sigs, SIGTERM);
03037 sigaddset(&sigs, SIGINT);
03038 sigaddset(&sigs, SIGPIPE);
03039 sigaddset(&sigs, SIGWINCH);
03040 pthread_sigmask(SIG_BLOCK, &sigs, NULL);
03041 signal(SIGURG, urg_handler);
03042 signal(SIGINT, __quit_handler);
03043 signal(SIGTERM, __quit_handler);
03044 signal(SIGHUP, hup_handler);
03045 signal(SIGCHLD, child_handler);
03046 signal(SIGPIPE, SIG_IGN);
03047
03048
03049
03050
03051 srand((unsigned int) getpid() + (unsigned int) time(NULL));
03052 initstate((unsigned int) getpid() * 65536 + (unsigned int) time(NULL), randompool, sizeof(randompool));
03053
03054 if (init_logger()) {
03055 printf("%s", term_quit());
03056 exit(1);
03057 }
03058
03059 dahdi_chan_name = _dahdi_chan_name;
03060 dahdi_chan_name_len = &_dahdi_chan_name_len;
03061 dahdi_chan_mode = &_dahdi_chan_mode;
03062
03063 #ifdef HAVE_ZAPTEL
03064 {
03065 int fd;
03066 int x = 160;
03067 fd = open("/dev/zap/timer", O_RDWR);
03068 if (fd >= 0) {
03069 if (ioctl(fd, DAHDI_TIMERCONFIG, &x)) {
03070 ast_log(LOG_ERROR, "You have Zaptel built and drivers loaded, but the Zaptel timer test failed to set ZT_TIMERCONFIG to %d.\n", x);
03071 exit(1);
03072 }
03073 if ((x = ast_wait_for_input(fd, 300)) < 0) {
03074 ast_log(LOG_ERROR, "You have Zaptel built and drivers loaded, but the Zaptel timer could not be polled during the Zaptel timer test.\n");
03075 exit(1);
03076 }
03077 if (!x) {
03078 const char zaptel_timer_error[] = {
03079 "Asterisk has detected a problem with your Zaptel configuration and will shutdown for your protection. You have options:"
03080 "\n\t1. You only have to compile Zaptel support into Asterisk if you need it. One option is to recompile without Zaptel support."
03081 "\n\t2. You only have to load Zaptel drivers if you want to take advantage of Zaptel services. One option is to unload zaptel modules if you don't need them."
03082 "\n\t3. If you need Zaptel services, you must correctly configure Zaptel."
03083 };
03084 ast_log(LOG_ERROR, "%s\n", zaptel_timer_error);
03085 exit(1);
03086 }
03087 close(fd);
03088 }
03089 }
03090 #elif defined(HAVE_DAHDI)
03091 {
03092 int fd;
03093 int x = 160;
03094 fd = open("/dev/dahdi/timer", O_RDWR);
03095 if (fd >= 0) {
03096 if (ioctl(fd, DAHDI_TIMERCONFIG, &x)) {
03097 ast_log(LOG_ERROR, "You have DAHDI built and drivers loaded, but the DAHDI timer test failed to set DAHDI_TIMERCONFIG to %d.\n", x);
03098 exit(1);
03099 }
03100 if ((x = ast_wait_for_input(fd, 300)) < 0) {
03101 ast_log(LOG_ERROR, "You have DAHDI built and drivers loaded, but the DAHDI timer could not be polled during the DAHDI timer test.\n");
03102 exit(1);
03103 }
03104 if (!x) {
03105 const char dahdi_timer_error[] = {
03106 "Asterisk has detected a problem with your DAHDI configuration and will shutdown for your protection. You have options:"
03107 "\n\t1. You only have to compile DAHDI support into Asterisk if you need it. One option is to recompile without DAHDI support."
03108 "\n\t2. You only have to load DAHDI drivers if you want to take advantage of DAHDI services. One option is to unload DAHDI modules if you don't need them."
03109 "\n\t3. If you need DAHDI services, you must correctly configure DAHDI."
03110 };
03111 ast_log(LOG_ERROR, "%s\n", dahdi_timer_error);
03112 exit(1);
03113 }
03114 close(fd);
03115 }
03116 }
03117
03118 #endif
03119 threadstorage_init();
03120
03121 astobj2_init();
03122
03123 ast_autoservice_init();
03124
03125 if (load_modules(1)) {
03126 printf("%s", term_quit());
03127 exit(1);
03128 }
03129
03130 if (dnsmgr_init()) {
03131 printf("%s", term_quit());
03132 exit(1);
03133 }
03134
03135 ast_http_init();
03136
03137 ast_channels_init();
03138
03139 if (ast_cdr_engine_init()) {
03140 printf("%s", term_quit());
03141 exit(1);
03142 }
03143
03144 if (ast_device_state_engine_init()) {
03145 printf("%s", term_quit());
03146 exit(1);
03147 }
03148
03149 ast_rtp_init();
03150
03151 ast_udptl_init();
03152
03153 if (ast_image_init()) {
03154 printf("%s", term_quit());
03155 exit(1);
03156 }
03157
03158 if (ast_file_init()) {
03159 printf("%s", term_quit());
03160 exit(1);
03161 }
03162
03163 if (load_pbx()) {
03164 printf("%s", term_quit());
03165 exit(1);
03166 }
03167
03168 if (init_framer()) {
03169 printf("%s", term_quit());
03170 exit(1);
03171 }
03172
03173 if (astdb_init()) {
03174 printf("%s", term_quit());
03175 exit(1);
03176 }
03177
03178 if (ast_enum_init()) {
03179 printf("%s", term_quit());
03180 exit(1);
03181 }
03182
03183 if (load_modules(0)) {
03184 printf("%s", term_quit());
03185 exit(1);
03186 }
03187
03188
03189
03190
03191
03192 if (init_manager()) {
03193 printf("%s", term_quit());
03194 exit(1);
03195 }
03196
03197 dnsmgr_start_refresh();
03198
03199
03200
03201 if (ast_opt_console && !option_verbose)
03202 ast_verbose(" ]\n");
03203 if (option_verbose || ast_opt_console)
03204 ast_verbose("%s", term_color(tmp, "Asterisk Ready.\n", COLOR_BRWHITE, COLOR_BLACK, sizeof(tmp)));
03205 if (ast_opt_no_fork)
03206 consolethread = pthread_self();
03207
03208 if (pipe(sig_alert_pipe))
03209 sig_alert_pipe[0] = sig_alert_pipe[1] = -1;
03210
03211 ast_set_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED);
03212 pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
03213
03214 #ifdef __AST_DEBUG_MALLOC
03215 __ast_mm_init();
03216 #endif
03217
03218 time(&ast_startuptime);
03219 ast_cli_register_multiple(cli_asterisk, sizeof(cli_asterisk) / sizeof(struct ast_cli_entry));
03220
03221 if (ast_opt_console) {
03222
03223
03224 char title[256];
03225 pthread_attr_t attr;
03226 pthread_t dont_care;
03227
03228 pthread_attr_init(&attr);
03229 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
03230 ast_pthread_create(&dont_care, &attr, monitor_sig_flags, NULL);
03231 pthread_attr_destroy(&attr);
03232
03233 set_icon("Asterisk");
03234 snprintf(title, sizeof(title), "Asterisk Console on '%s' (pid %ld)", hostname, (long)ast_mainpid);
03235 set_title(title);
03236
03237 for (;;) {
03238 buf = (char *)el_gets(el, &num);
03239
03240 if (!buf && write(1, "", 1) < 0)
03241 goto lostterm;
03242
03243 if (buf) {
03244 if (buf[strlen(buf)-1] == '\n')
03245 buf[strlen(buf)-1] = '\0';
03246
03247 consolehandler((char *)buf);
03248 } else if (ast_opt_remote && (write(STDOUT_FILENO, "\nUse EXIT or QUIT to exit the asterisk console\n",
03249 strlen("\nUse EXIT or QUIT to exit the asterisk console\n")) < 0)) {
03250
03251 int fd;
03252 fd = open("/dev/null", O_RDWR);
03253 if (fd > -1) {
03254 dup2(fd, STDOUT_FILENO);
03255 dup2(fd, STDIN_FILENO);
03256 } else
03257 ast_log(LOG_WARNING, "Failed to open /dev/null to recover from dead console. Bad things will happen!\n");
03258 break;
03259 }
03260 }
03261 }
03262
03263 monitor_sig_flags(NULL);
03264
03265 lostterm:
03266 return 0;
03267 }