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 #include "asterisk.h"
00045
00046 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 301594 $")
00047
00048 #include "asterisk/_private.h"
00049 #include "asterisk/paths.h"
00050 #include <ctype.h>
00051 #include <sys/time.h>
00052 #include <signal.h>
00053 #include <sys/mman.h>
00054
00055 #include "asterisk/channel.h"
00056 #include "asterisk/file.h"
00057 #include "asterisk/manager.h"
00058 #include "asterisk/module.h"
00059 #include "asterisk/config.h"
00060 #include "asterisk/callerid.h"
00061 #include "asterisk/lock.h"
00062 #include "asterisk/cli.h"
00063 #include "asterisk/app.h"
00064 #include "asterisk/pbx.h"
00065 #include "asterisk/md5.h"
00066 #include "asterisk/acl.h"
00067 #include "asterisk/utils.h"
00068 #include "asterisk/tcptls.h"
00069 #include "asterisk/http.h"
00070 #include "asterisk/ast_version.h"
00071 #include "asterisk/threadstorage.h"
00072 #include "asterisk/linkedlists.h"
00073 #include "asterisk/version.h"
00074 #include "asterisk/term.h"
00075 #include "asterisk/astobj2.h"
00076 #include "asterisk/features.h"
00077
00078 enum error_type {
00079 UNKNOWN_ACTION = 1,
00080 UNKNOWN_CATEGORY,
00081 UNSPECIFIED_CATEGORY,
00082 UNSPECIFIED_ARGUMENT,
00083 FAILURE_ALLOCATION,
00084 FAILURE_NEWCAT,
00085 FAILURE_DELCAT,
00086 FAILURE_EMPTYCAT,
00087 FAILURE_UPDATE,
00088 FAILURE_DELETE,
00089 FAILURE_APPEND
00090 };
00091
00092
00093
00094
00095
00096
00097
00098
00099
00100
00101
00102
00103
00104
00105
00106
00107
00108
00109
00110
00111
00112 struct eventqent {
00113 int usecount;
00114 int category;
00115 unsigned int seq;
00116 struct timeval tv;
00117 AST_RWLIST_ENTRY(eventqent) eq_next;
00118 char eventdata[1];
00119 };
00120
00121 static AST_RWLIST_HEAD_STATIC(all_events, eventqent);
00122
00123 static const int DEFAULT_ENABLED = 0;
00124 static const int DEFAULT_WEBENABLED = 0;
00125 static const int DEFAULT_BLOCKSOCKETS = 0;
00126 static const int DEFAULT_DISPLAYCONNECTS = 1;
00127 static const int DEFAULT_TIMESTAMPEVENTS = 0;
00128 static const int DEFAULT_HTTPTIMEOUT = 60;
00129 static const int DEFAULT_BROKENEVENTSACTION = 0;
00130
00131 static int displayconnects;
00132 static int allowmultiplelogin = 1;
00133 static int timestampevents;
00134 static int httptimeout;
00135 static int broken_events_action;
00136 static int manager_enabled = 0;
00137 static int webmanager_enabled = 0;
00138
00139 static int block_sockets;
00140 static int num_sessions;
00141
00142 static int manager_debug;
00143
00144
00145
00146
00147
00148
00149
00150
00151
00152
00153 #define MAX_BLACKLIST_CMD_LEN 2
00154 static struct {
00155 char *words[AST_MAX_CMD_LEN];
00156 } command_blacklist[] = {
00157 {{ "module", "load", NULL }},
00158 {{ "module", "unload", NULL }},
00159 {{ "restart", "gracefully", NULL }},
00160 };
00161
00162
00163
00164
00165
00166
00167
00168
00169
00170
00171
00172
00173
00174
00175
00176
00177
00178
00179
00180
00181
00182
00183
00184
00185
00186
00187
00188
00189
00190
00191
00192
00193
00194 struct mansession_session {
00195 ast_mutex_t __lock;
00196
00197 struct sockaddr_in sin;
00198 FILE *f;
00199 int fd;
00200 int inuse;
00201 int needdestroy;
00202 pthread_t waiting_thread;
00203 uint32_t managerid;
00204 time_t sessionstart;
00205 time_t sessiontimeout;
00206 char username[80];
00207 char challenge[10];
00208 int authenticated;
00209 int readperm;
00210 int writeperm;
00211 char inbuf[1025];
00212
00213 int inlen;
00214 int send_events;
00215 struct eventqent *last_ev;
00216 int writetimeout;
00217 int pending_event;
00218 AST_LIST_HEAD_NOLOCK(mansession_datastores, ast_datastore) datastores;
00219 AST_LIST_ENTRY(mansession_session) list;
00220 };
00221
00222
00223
00224
00225
00226
00227 struct mansession {
00228 struct mansession_session *session;
00229 FILE *f;
00230 int fd;
00231 };
00232
00233 static AST_LIST_HEAD_STATIC(sessions, mansession_session);
00234
00235
00236
00237
00238
00239
00240
00241 struct ast_manager_user {
00242 char username[80];
00243 char *secret;
00244 struct ast_ha *ha;
00245 int readperm;
00246 int writeperm;
00247 int writetimeout;
00248 int displayconnects;
00249 int keep;
00250 AST_RWLIST_ENTRY(ast_manager_user) list;
00251 };
00252
00253
00254 static AST_RWLIST_HEAD_STATIC(users, ast_manager_user);
00255
00256
00257 static AST_RWLIST_HEAD_STATIC(actions, manager_action);
00258
00259
00260 static AST_RWLIST_HEAD_STATIC(manager_hooks, manager_custom_hook);
00261
00262
00263 void ast_manager_register_hook(struct manager_custom_hook *hook)
00264 {
00265 AST_RWLIST_WRLOCK(&manager_hooks);
00266 AST_RWLIST_INSERT_TAIL(&manager_hooks, hook, list);
00267 AST_RWLIST_UNLOCK(&manager_hooks);
00268 return;
00269 }
00270
00271
00272 void ast_manager_unregister_hook(struct manager_custom_hook *hook)
00273 {
00274 AST_RWLIST_WRLOCK(&manager_hooks);
00275 AST_RWLIST_REMOVE(&manager_hooks, hook, list);
00276 AST_RWLIST_UNLOCK(&manager_hooks);
00277 return;
00278 }
00279
00280
00281
00282
00283
00284
00285
00286 #if 0
00287 static time_t __deb(time_t start, const char *msg)
00288 {
00289 time_t now = time(NULL);
00290 ast_verbose("%4d th %p %s\n", (int)(now % 3600), pthread_self(), msg);
00291 if (start != 0 && now - start > 5)
00292 ast_verbose("+++ WOW, %s took %d seconds\n", msg, (int)(now - start));
00293 return now;
00294 }
00295
00296 static void LOCK_EVENTS(void)
00297 {
00298 time_t start = __deb(0, "about to lock events");
00299 AST_LIST_LOCK(&all_events);
00300 __deb(start, "done lock events");
00301 }
00302
00303 static void UNLOCK_EVENTS(void)
00304 {
00305 __deb(0, "about to unlock events");
00306 AST_LIST_UNLOCK(&all_events);
00307 }
00308
00309 static void LOCK_SESS(void)
00310 {
00311 time_t start = __deb(0, "about to lock sessions");
00312 AST_LIST_LOCK(&sessions);
00313 __deb(start, "done lock sessions");
00314 }
00315
00316 static void UNLOCK_SESS(void)
00317 {
00318 __deb(0, "about to unlock sessions");
00319 AST_LIST_UNLOCK(&sessions);
00320 }
00321 #endif
00322
00323 int check_manager_enabled()
00324 {
00325 return manager_enabled;
00326 }
00327
00328 int check_webmanager_enabled()
00329 {
00330 return (webmanager_enabled && manager_enabled);
00331 }
00332
00333
00334
00335
00336
00337 static struct eventqent *grab_last(void)
00338 {
00339 struct eventqent *ret;
00340
00341 AST_RWLIST_RDLOCK(&all_events);
00342 ret = AST_RWLIST_LAST(&all_events);
00343
00344
00345
00346 if (ret) {
00347 ast_atomic_fetchadd_int(&ret->usecount, 1);
00348 }
00349 AST_RWLIST_UNLOCK(&all_events);
00350 return ret;
00351 }
00352
00353
00354
00355
00356
00357 static void purge_events(void)
00358 {
00359 struct eventqent *ev;
00360 struct timeval now = ast_tvnow();
00361
00362 AST_RWLIST_WRLOCK(&all_events);
00363 while ( (ev = AST_RWLIST_FIRST(&all_events)) &&
00364 ev->usecount == 0 && AST_RWLIST_NEXT(ev, eq_next)) {
00365 AST_RWLIST_REMOVE_HEAD(&all_events, eq_next);
00366 ast_free(ev);
00367 }
00368
00369 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&all_events, ev, eq_next) {
00370
00371 if (!AST_RWLIST_NEXT(ev, eq_next)) {
00372 break;
00373 }
00374
00375
00376 if (ev->usecount == 0 && ast_tvdiff_sec(now, ev->tv) > (httptimeout > 3600 ? 3600 : httptimeout) * 2.5) {
00377 AST_RWLIST_REMOVE_CURRENT(eq_next);
00378 ast_free(ev);
00379 }
00380 }
00381 AST_RWLIST_TRAVERSE_SAFE_END;
00382 AST_RWLIST_UNLOCK(&all_events);
00383 }
00384
00385
00386
00387
00388
00389 static struct permalias {
00390 int num;
00391 char *label;
00392 } perms[] = {
00393 { EVENT_FLAG_SYSTEM, "system" },
00394 { EVENT_FLAG_CALL, "call" },
00395 { EVENT_FLAG_LOG, "log" },
00396 { EVENT_FLAG_VERBOSE, "verbose" },
00397 { EVENT_FLAG_COMMAND, "command" },
00398 { EVENT_FLAG_AGENT, "agent" },
00399 { EVENT_FLAG_USER, "user" },
00400 { EVENT_FLAG_CONFIG, "config" },
00401 { EVENT_FLAG_DTMF, "dtmf" },
00402 { EVENT_FLAG_REPORTING, "reporting" },
00403 { EVENT_FLAG_CDR, "cdr" },
00404 { EVENT_FLAG_DIALPLAN, "dialplan" },
00405 { EVENT_FLAG_ORIGINATE, "originate" },
00406 { EVENT_FLAG_AGI, "agi" },
00407 { INT_MAX, "all" },
00408 { 0, "none" },
00409 };
00410
00411
00412 static char *authority_to_str(int authority, struct ast_str **res)
00413 {
00414 int i;
00415 char *sep = "";
00416
00417 ast_str_reset(*res);
00418 for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
00419 if (authority & perms[i].num) {
00420 ast_str_append(res, 0, "%s%s", sep, perms[i].label);
00421 sep = ",";
00422 }
00423 }
00424
00425 if (ast_str_strlen(*res) == 0)
00426 ast_str_append(res, 0, "<none>");
00427
00428 return ast_str_buffer(*res);
00429 }
00430
00431
00432
00433
00434
00435
00436 static int ast_instring(const char *bigstr, const char *smallstr, const char delim)
00437 {
00438 const char *val = bigstr, *next;
00439
00440 do {
00441 if ((next = strchr(val, delim))) {
00442 if (!strncmp(val, smallstr, (next - val)))
00443 return 1;
00444 else
00445 continue;
00446 } else
00447 return !strcmp(smallstr, val);
00448 } while (*(val = (next + 1)));
00449
00450 return 0;
00451 }
00452
00453 static int get_perm(const char *instr)
00454 {
00455 int x = 0, ret = 0;
00456
00457 if (!instr)
00458 return 0;
00459
00460 for (x = 0; x < ARRAY_LEN(perms); x++) {
00461 if (ast_instring(instr, perms[x].label, ','))
00462 ret |= perms[x].num;
00463 }
00464
00465 return ret;
00466 }
00467
00468
00469
00470
00471
00472 static int strings_to_mask(const char *string)
00473 {
00474 const char *p;
00475
00476 if (ast_strlen_zero(string))
00477 return -1;
00478
00479 for (p = string; *p; p++)
00480 if (*p < '0' || *p > '9')
00481 break;
00482 if (!*p)
00483 return atoi(string);
00484 if (ast_false(string))
00485 return 0;
00486 if (ast_true(string)) {
00487 int x, ret = 0;
00488 for (x = 0; x < ARRAY_LEN(perms); x++)
00489 ret |= perms[x].num;
00490 return ret;
00491 }
00492 return get_perm(string);
00493 }
00494
00495 static int check_manager_session_inuse(const char *name)
00496 {
00497 struct mansession_session *session = NULL;
00498
00499 AST_LIST_LOCK(&sessions);
00500 AST_LIST_TRAVERSE(&sessions, session, list) {
00501 if (!strcasecmp(session->username, name))
00502 break;
00503 }
00504 AST_LIST_UNLOCK(&sessions);
00505
00506 return session ? 1 : 0;
00507 }
00508
00509
00510
00511
00512
00513
00514 static struct ast_manager_user *get_manager_by_name_locked(const char *name)
00515 {
00516 struct ast_manager_user *user = NULL;
00517
00518 AST_RWLIST_TRAVERSE(&users, user, list)
00519 if (!strcasecmp(user->username, name))
00520 break;
00521 return user;
00522 }
00523
00524
00525
00526
00527
00528 static int manager_displayconnects (struct mansession_session *session)
00529 {
00530 struct ast_manager_user *user = NULL;
00531 int ret = 0;
00532
00533 AST_RWLIST_RDLOCK(&users);
00534 if ((user = get_manager_by_name_locked (session->username)))
00535 ret = user->displayconnects;
00536 AST_RWLIST_UNLOCK(&users);
00537
00538 return ret;
00539 }
00540
00541 static char *handle_showmancmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00542 {
00543 struct manager_action *cur;
00544 struct ast_str *authority;
00545 int num, l, which;
00546 char *ret = NULL;
00547 switch (cmd) {
00548 case CLI_INIT:
00549 e->command = "manager show command";
00550 e->usage =
00551 "Usage: manager show command <actionname> [<actionname> [<actionname> [...]]]\n"
00552 " Shows the detailed description for a specific Asterisk manager interface command.\n";
00553 return NULL;
00554 case CLI_GENERATE:
00555 l = strlen(a->word);
00556 which = 0;
00557 AST_RWLIST_RDLOCK(&actions);
00558 AST_RWLIST_TRAVERSE(&actions, cur, list) {
00559 if (!strncasecmp(a->word, cur->action, l) && ++which > a->n) {
00560 ret = ast_strdup(cur->action);
00561 break;
00562 }
00563 }
00564 AST_RWLIST_UNLOCK(&actions);
00565 return ret;
00566 }
00567 authority = ast_str_alloca(80);
00568 if (a->argc < 4) {
00569 return CLI_SHOWUSAGE;
00570 }
00571
00572 AST_RWLIST_RDLOCK(&actions);
00573 AST_RWLIST_TRAVERSE(&actions, cur, list) {
00574 for (num = 3; num < a->argc; num++) {
00575 if (!strcasecmp(cur->action, a->argv[num])) {
00576 ast_cli(a->fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n",
00577 cur->action, cur->synopsis,
00578 authority_to_str(cur->authority, &authority),
00579 S_OR(cur->description, ""));
00580 }
00581 }
00582 }
00583 AST_RWLIST_UNLOCK(&actions);
00584
00585 return CLI_SUCCESS;
00586 }
00587
00588 static char *handle_mandebug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00589 {
00590 switch (cmd) {
00591 case CLI_INIT:
00592 e->command = "manager set debug [on|off]";
00593 e->usage = "Usage: manager set debug [on|off]\n Show, enable, disable debugging of the manager code.\n";
00594 return NULL;
00595 case CLI_GENERATE:
00596 return NULL;
00597 }
00598 if (a->argc == 3)
00599 ast_cli(a->fd, "manager debug is %s\n", manager_debug? "on" : "off");
00600 else if (a->argc == 4) {
00601 if (!strcasecmp(a->argv[3], "on"))
00602 manager_debug = 1;
00603 else if (!strcasecmp(a->argv[3], "off"))
00604 manager_debug = 0;
00605 else
00606 return CLI_SHOWUSAGE;
00607 }
00608 return CLI_SUCCESS;
00609 }
00610
00611 static char *handle_showmanager(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00612 {
00613 struct ast_manager_user *user = NULL;
00614 int l, which;
00615 char *ret = NULL;
00616 struct ast_str *rauthority = ast_str_alloca(128);
00617 struct ast_str *wauthority = ast_str_alloca(128);
00618
00619 switch (cmd) {
00620 case CLI_INIT:
00621 e->command = "manager show user";
00622 e->usage =
00623 " Usage: manager show user <user>\n"
00624 " Display all information related to the manager user specified.\n";
00625 return NULL;
00626 case CLI_GENERATE:
00627 l = strlen(a->word);
00628 which = 0;
00629 if (a->pos != 3)
00630 return NULL;
00631 AST_RWLIST_RDLOCK(&users);
00632 AST_RWLIST_TRAVERSE(&users, user, list) {
00633 if ( !strncasecmp(a->word, user->username, l) && ++which > a->n ) {
00634 ret = ast_strdup(user->username);
00635 break;
00636 }
00637 }
00638 AST_RWLIST_UNLOCK(&users);
00639 return ret;
00640 }
00641
00642 if (a->argc != 4)
00643 return CLI_SHOWUSAGE;
00644
00645 AST_RWLIST_RDLOCK(&users);
00646
00647 if (!(user = get_manager_by_name_locked(a->argv[3]))) {
00648 ast_cli(a->fd, "There is no manager called %s\n", a->argv[3]);
00649 AST_RWLIST_UNLOCK(&users);
00650 return CLI_SUCCESS;
00651 }
00652
00653 ast_cli(a->fd, "\n");
00654 ast_cli(a->fd,
00655 " username: %s\n"
00656 " secret: %s\n"
00657 " acl: %s\n"
00658 " read perm: %s\n"
00659 " write perm: %s\n"
00660 "displayconnects: %s\n",
00661 (user->username ? user->username : "(N/A)"),
00662 (user->secret ? "<Set>" : "(N/A)"),
00663 (user->ha ? "yes" : "no"),
00664 authority_to_str(user->readperm, &rauthority),
00665 authority_to_str(user->writeperm, &wauthority),
00666 (user->displayconnects ? "yes" : "no"));
00667
00668 AST_RWLIST_UNLOCK(&users);
00669
00670 return CLI_SUCCESS;
00671 }
00672
00673
00674 static char *handle_showmanagers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00675 {
00676 struct ast_manager_user *user = NULL;
00677 int count_amu = 0;
00678 switch (cmd) {
00679 case CLI_INIT:
00680 e->command = "manager show users";
00681 e->usage =
00682 "Usage: manager show users\n"
00683 " Prints a listing of all managers that are currently configured on that\n"
00684 " system.\n";
00685 return NULL;
00686 case CLI_GENERATE:
00687 return NULL;
00688 }
00689 if (a->argc != 3)
00690 return CLI_SHOWUSAGE;
00691
00692 AST_RWLIST_RDLOCK(&users);
00693
00694
00695 if (AST_RWLIST_EMPTY(&users)) {
00696 ast_cli(a->fd, "There are no manager users.\n");
00697 AST_RWLIST_UNLOCK(&users);
00698 return CLI_SUCCESS;
00699 }
00700
00701 ast_cli(a->fd, "\nusername\n--------\n");
00702
00703 AST_RWLIST_TRAVERSE(&users, user, list) {
00704 ast_cli(a->fd, "%s\n", user->username);
00705 count_amu++;
00706 }
00707
00708 AST_RWLIST_UNLOCK(&users);
00709
00710 ast_cli(a->fd, "-------------------\n");
00711 ast_cli(a->fd, "%d manager users configured.\n", count_amu);
00712
00713 return CLI_SUCCESS;
00714 }
00715
00716
00717
00718 static char *handle_showmancmds(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00719 {
00720 struct manager_action *cur;
00721 struct ast_str *authority;
00722 #define HSMC_FORMAT " %-15.15s %-15.15s %-55.55s\n"
00723 switch (cmd) {
00724 case CLI_INIT:
00725 e->command = "manager show commands";
00726 e->usage =
00727 "Usage: manager show commands\n"
00728 " Prints a listing of all the available Asterisk manager interface commands.\n";
00729 return NULL;
00730 case CLI_GENERATE:
00731 return NULL;
00732 }
00733 authority = ast_str_alloca(80);
00734 ast_cli(a->fd, HSMC_FORMAT, "Action", "Privilege", "Synopsis");
00735 ast_cli(a->fd, HSMC_FORMAT, "------", "---------", "--------");
00736
00737 AST_RWLIST_RDLOCK(&actions);
00738 AST_RWLIST_TRAVERSE(&actions, cur, list)
00739 ast_cli(a->fd, HSMC_FORMAT, cur->action, authority_to_str(cur->authority, &authority), cur->synopsis);
00740 AST_RWLIST_UNLOCK(&actions);
00741
00742 return CLI_SUCCESS;
00743 }
00744
00745
00746 static char *handle_showmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00747 {
00748 struct mansession_session *session;
00749 time_t now = time(NULL);
00750 #define HSMCONN_FORMAT1 " %-15.15s %-15.15s %-10.10s %-10.10s %-8.8s %-8.8s %-5.5s %-5.5s\n"
00751 #define HSMCONN_FORMAT2 " %-15.15s %-15.15s %-10d %-10d %-8d %-8d %-5.5d %-5.5d\n"
00752 int count = 0;
00753 switch (cmd) {
00754 case CLI_INIT:
00755 e->command = "manager show connected";
00756 e->usage =
00757 "Usage: manager show connected\n"
00758 " Prints a listing of the users that are currently connected to the\n"
00759 "Asterisk manager interface.\n";
00760 return NULL;
00761 case CLI_GENERATE:
00762 return NULL;
00763 }
00764
00765 ast_cli(a->fd, HSMCONN_FORMAT1, "Username", "IP Address", "Start", "Elapsed", "FileDes", "HttpCnt", "Read", "Write");
00766
00767 AST_LIST_LOCK(&sessions);
00768 AST_LIST_TRAVERSE(&sessions, session, list) {
00769 ast_cli(a->fd, HSMCONN_FORMAT2, session->username, ast_inet_ntoa(session->sin.sin_addr), (int)(session->sessionstart), (int)(now - session->sessionstart), session->fd, session->inuse, session->readperm, session->writeperm);
00770 count++;
00771 }
00772 AST_LIST_UNLOCK(&sessions);
00773
00774 ast_cli(a->fd, "%d users connected.\n", count);
00775
00776 return CLI_SUCCESS;
00777 }
00778
00779
00780
00781 static char *handle_showmaneventq(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00782 {
00783 struct eventqent *s;
00784 switch (cmd) {
00785 case CLI_INIT:
00786 e->command = "manager show eventq";
00787 e->usage =
00788 "Usage: manager show eventq\n"
00789 " Prints a listing of all events pending in the Asterisk manger\n"
00790 "event queue.\n";
00791 return NULL;
00792 case CLI_GENERATE:
00793 return NULL;
00794 }
00795 AST_RWLIST_RDLOCK(&all_events);
00796 AST_RWLIST_TRAVERSE(&all_events, s, eq_next) {
00797 ast_cli(a->fd, "Usecount: %d\n", s->usecount);
00798 ast_cli(a->fd, "Category: %d\n", s->category);
00799 ast_cli(a->fd, "Event:\n%s", s->eventdata);
00800 }
00801 AST_RWLIST_UNLOCK(&all_events);
00802
00803 return CLI_SUCCESS;
00804 }
00805
00806
00807 static char *handle_manager_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00808 {
00809 switch (cmd) {
00810 case CLI_INIT:
00811 e->command = "manager reload";
00812 e->usage =
00813 "Usage: manager reload\n"
00814 " Reloads the manager configuration.\n";
00815 return NULL;
00816 case CLI_GENERATE:
00817 return NULL;
00818 }
00819 if (a->argc > 2)
00820 return CLI_SHOWUSAGE;
00821 reload_manager();
00822 return CLI_SUCCESS;
00823 }
00824
00825
00826 static struct ast_cli_entry cli_manager[] = {
00827 AST_CLI_DEFINE(handle_showmancmd, "Show a manager interface command"),
00828 AST_CLI_DEFINE(handle_showmancmds, "List manager interface commands"),
00829 AST_CLI_DEFINE(handle_showmanconn, "List connected manager interface users"),
00830 AST_CLI_DEFINE(handle_showmaneventq, "List manager interface queued events"),
00831 AST_CLI_DEFINE(handle_showmanagers, "List configured manager users"),
00832 AST_CLI_DEFINE(handle_showmanager, "Display information on a specific manager user"),
00833 AST_CLI_DEFINE(handle_mandebug, "Show, enable, disable debugging of the manager code"),
00834 AST_CLI_DEFINE(handle_manager_reload, "Reload manager configurations"),
00835 };
00836
00837 static struct eventqent *advance_event(struct eventqent *e)
00838 {
00839 struct eventqent *next;
00840
00841 AST_RWLIST_RDLOCK(&all_events);
00842 if ((next = AST_RWLIST_NEXT(e, eq_next))) {
00843 ast_atomic_fetchadd_int(&next->usecount, 1);
00844 ast_atomic_fetchadd_int(&e->usecount, -1);
00845 }
00846 AST_RWLIST_UNLOCK(&all_events);
00847 return next;
00848 }
00849
00850
00851
00852
00853 static void free_session(struct mansession_session *session)
00854 {
00855 struct eventqent *eqe = session->last_ev;
00856 struct ast_datastore *datastore;
00857
00858
00859 while ((datastore = AST_LIST_REMOVE_HEAD(&session->datastores, entry))) {
00860
00861 ast_datastore_free(datastore);
00862 }
00863
00864 if (session->f != NULL)
00865 fclose(session->f);
00866 ast_mutex_destroy(&session->__lock);
00867 ast_free(session);
00868 if (eqe) {
00869 ast_atomic_fetchadd_int(&eqe->usecount, -1);
00870 }
00871 }
00872
00873 static void destroy_session(struct mansession_session *session)
00874 {
00875 AST_LIST_LOCK(&sessions);
00876 AST_LIST_REMOVE(&sessions, session, list);
00877 ast_atomic_fetchadd_int(&num_sessions, -1);
00878 free_session(session);
00879 AST_LIST_UNLOCK(&sessions);
00880 }
00881
00882
00883
00884
00885
00886
00887
00888 #define GET_HEADER_FIRST_MATCH 0
00889 #define GET_HEADER_LAST_MATCH 1
00890 #define GET_HEADER_SKIP_EMPTY 2
00891 static const char *__astman_get_header(const struct message *m, char *var, int mode)
00892 {
00893 int x, l = strlen(var);
00894 const char *result = "";
00895
00896 for (x = 0; x < m->hdrcount; x++) {
00897 const char *h = m->headers[x];
00898 if (!strncasecmp(var, h, l) && h[l] == ':' && h[l+1] == ' ') {
00899 const char *value = h + l + 2;
00900
00901 if (mode & GET_HEADER_SKIP_EMPTY && ast_strlen_zero(value))
00902 continue;
00903 if (mode & GET_HEADER_LAST_MATCH)
00904 result = value;
00905 else
00906 return value;
00907 }
00908 }
00909
00910 return "";
00911 }
00912
00913
00914
00915
00916
00917
00918 const char *astman_get_header(const struct message *m, char *var)
00919 {
00920 return __astman_get_header(m, var, GET_HEADER_FIRST_MATCH);
00921 }
00922
00923
00924 struct ast_variable *astman_get_variables(const struct message *m)
00925 {
00926 int varlen, x, y;
00927 struct ast_variable *head = NULL, *cur;
00928
00929 AST_DECLARE_APP_ARGS(args,
00930 AST_APP_ARG(vars)[32];
00931 );
00932
00933 varlen = strlen("Variable: ");
00934
00935 for (x = 0; x < m->hdrcount; x++) {
00936 char *parse, *var, *val;
00937
00938 if (strncasecmp("Variable: ", m->headers[x], varlen))
00939 continue;
00940 parse = ast_strdupa(m->headers[x] + varlen);
00941
00942 AST_STANDARD_APP_ARGS(args, parse);
00943 if (!args.argc)
00944 continue;
00945 for (y = 0; y < args.argc; y++) {
00946 if (!args.vars[y])
00947 continue;
00948 var = val = ast_strdupa(args.vars[y]);
00949 strsep(&val, "=");
00950 if (!val || ast_strlen_zero(var))
00951 continue;
00952 cur = ast_variable_new(var, val, "");
00953 cur->next = head;
00954 head = cur;
00955 }
00956 }
00957
00958 return head;
00959 }
00960
00961
00962
00963
00964
00965 static int send_string(struct mansession *s, char *string)
00966 {
00967 if (s->f) {
00968 return ast_careful_fwrite(s->f, s->fd, string, strlen(string), s->session->writetimeout);
00969 } else {
00970 return ast_careful_fwrite(s->session->f, s->session->fd, string, strlen(string), s->session->writetimeout);
00971 }
00972 }
00973
00974
00975
00976
00977
00978
00979
00980
00981 AST_THREADSTORAGE(astman_append_buf);
00982 AST_THREADSTORAGE(userevent_buf);
00983
00984
00985 #define ASTMAN_APPEND_BUF_INITSIZE 256
00986
00987
00988
00989
00990 void astman_append(struct mansession *s, const char *fmt, ...)
00991 {
00992 va_list ap;
00993 struct ast_str *buf;
00994
00995 if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE)))
00996 return;
00997
00998 va_start(ap, fmt);
00999 ast_str_set_va(&buf, 0, fmt, ap);
01000 va_end(ap);
01001
01002 if (s->f != NULL || s->session->f != NULL) {
01003 send_string(s, ast_str_buffer(buf));
01004 } else {
01005 ast_verbose("fd == -1 in astman_append, should not happen\n");
01006 }
01007 }
01008
01009
01010
01011
01012
01013
01014
01015
01016
01017
01018
01019
01020
01021
01022
01023
01024
01025 #define MSG_MOREDATA ((char *)astman_send_response)
01026 static void astman_send_response_full(struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
01027 {
01028 const char *id = astman_get_header(m, "ActionID");
01029
01030 astman_append(s, "Response: %s\r\n", resp);
01031 if (!ast_strlen_zero(id))
01032 astman_append(s, "ActionID: %s\r\n", id);
01033 if (listflag)
01034 astman_append(s, "EventList: %s\r\n", listflag);
01035 if (msg == MSG_MOREDATA)
01036 return;
01037 else if (msg)
01038 astman_append(s, "Message: %s\r\n\r\n", msg);
01039 else
01040 astman_append(s, "\r\n");
01041 }
01042
01043 void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
01044 {
01045 astman_send_response_full(s, m, resp, msg, NULL);
01046 }
01047
01048 void astman_send_error(struct mansession *s, const struct message *m, char *error)
01049 {
01050 astman_send_response_full(s, m, "Error", error, NULL);
01051 }
01052
01053 void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
01054 {
01055 astman_send_response_full(s, m, "Success", msg, NULL);
01056 }
01057
01058 static void astman_start_ack(struct mansession *s, const struct message *m)
01059 {
01060 astman_send_response_full(s, m, "Success", MSG_MOREDATA, NULL);
01061 }
01062
01063 void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
01064 {
01065 astman_send_response_full(s, m, "Success", msg, listflag);
01066 }
01067
01068
01069
01070
01071
01072
01073 static int set_eventmask(struct mansession *s, const char *eventmask)
01074 {
01075 int maskint = strings_to_mask(eventmask);
01076
01077 ast_mutex_lock(&s->session->__lock);
01078 if (maskint >= 0)
01079 s->session->send_events = maskint;
01080 ast_mutex_unlock(&s->session->__lock);
01081
01082 return maskint;
01083 }
01084
01085
01086
01087
01088
01089
01090
01091
01092 static int authenticate(struct mansession *s, const struct message *m)
01093 {
01094 const char *username = astman_get_header(m, "Username");
01095 const char *password = astman_get_header(m, "Secret");
01096 int error = -1;
01097 struct ast_manager_user *user = NULL;
01098
01099 if (ast_strlen_zero(username))
01100 return -1;
01101
01102
01103 AST_RWLIST_WRLOCK(&users);
01104
01105 if (!(user = get_manager_by_name_locked(username))) {
01106 ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_inet_ntoa(s->session->sin.sin_addr), username);
01107 } else if (user->ha && !ast_apply_ha(user->ha, &(s->session->sin))) {
01108 ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_inet_ntoa(s->session->sin.sin_addr), username);
01109 } else if (!strcasecmp(astman_get_header(m, "AuthType"), "MD5")) {
01110 const char *key = astman_get_header(m, "Key");
01111 if (!ast_strlen_zero(key) && !ast_strlen_zero(s->session->challenge) && user->secret) {
01112 int x;
01113 int len = 0;
01114 char md5key[256] = "";
01115 struct MD5Context md5;
01116 unsigned char digest[16];
01117
01118 MD5Init(&md5);
01119 MD5Update(&md5, (unsigned char *) s->session->challenge, strlen(s->session->challenge));
01120 MD5Update(&md5, (unsigned char *) user->secret, strlen(user->secret));
01121 MD5Final(digest, &md5);
01122 for (x = 0; x < 16; x++)
01123 len += sprintf(md5key + len, "%2.2x", digest[x]);
01124 if (!strcmp(md5key, key))
01125 error = 0;
01126 } else {
01127 ast_debug(1, "MD5 authentication is not possible. challenge: '%s'\n",
01128 S_OR(s->session->challenge, ""));
01129 }
01130 } else if (password && user->secret && !strcmp(password, user->secret))
01131 error = 0;
01132
01133 if (error) {
01134 ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_inet_ntoa(s->session->sin.sin_addr), username);
01135 AST_RWLIST_UNLOCK(&users);
01136 return -1;
01137 }
01138
01139
01140
01141 ast_copy_string(s->session->username, username, sizeof(s->session->username));
01142 s->session->readperm = user->readperm;
01143 s->session->writeperm = user->writeperm;
01144 s->session->writetimeout = user->writetimeout;
01145 s->session->sessionstart = time(NULL);
01146 set_eventmask(s, astman_get_header(m, "Events"));
01147
01148 AST_RWLIST_UNLOCK(&users);
01149 return 0;
01150 }
01151
01152
01153 static char mandescr_ping[] =
01154 "Description: A 'Ping' action will ellicit a 'Pong' response. Used to keep the\n"
01155 " manager connection open.\n"
01156 "Variables: NONE\n";
01157
01158 static int action_ping(struct mansession *s, const struct message *m)
01159 {
01160 const char *actionid = astman_get_header(m, "ActionID");
01161
01162 astman_append(s, "Response: Success\r\n");
01163 if (!ast_strlen_zero(actionid)){
01164 astman_append(s, "ActionID: %s\r\n", actionid);
01165 }
01166 astman_append(s, "Ping: Pong\r\n\r\n");
01167 return 0;
01168 }
01169
01170 static char mandescr_getconfig[] =
01171 "Description: A 'GetConfig' action will dump the contents of a configuration\n"
01172 "file by category and contents or optionally by specified category only.\n"
01173 "Variables: (Names marked with * are required)\n"
01174 " *Filename: Configuration filename (e.g. foo.conf)\n"
01175 " Category: Category in configuration file\n";
01176
01177 static int action_getconfig(struct mansession *s, const struct message *m)
01178 {
01179 struct ast_config *cfg;
01180 const char *fn = astman_get_header(m, "Filename");
01181 const char *category = astman_get_header(m, "Category");
01182 int catcount = 0;
01183 int lineno = 0;
01184 char *cur_category = NULL;
01185 struct ast_variable *v;
01186 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
01187
01188 if (ast_strlen_zero(fn)) {
01189 astman_send_error(s, m, "Filename not specified");
01190 return 0;
01191 }
01192 cfg = ast_config_load2(fn, "manager", config_flags);
01193 if (cfg == CONFIG_STATUS_FILEMISSING) {
01194 astman_send_error(s, m, "Config file not found");
01195 return 0;
01196 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
01197 astman_send_error(s, m, "Config file has invalid format");
01198 return 0;
01199 }
01200
01201 astman_start_ack(s, m);
01202 while ((cur_category = ast_category_browse(cfg, cur_category))) {
01203 if (ast_strlen_zero(category) || (!ast_strlen_zero(category) && !strcmp(category, cur_category))) {
01204 lineno = 0;
01205 astman_append(s, "Category-%06d: %s\r\n", catcount, cur_category);
01206 for (v = ast_variable_browse(cfg, cur_category); v; v = v->next)
01207 astman_append(s, "Line-%06d-%06d: %s=%s\r\n", catcount, lineno++, v->name, v->value);
01208 catcount++;
01209 }
01210 }
01211 if (!ast_strlen_zero(category) && catcount == 0)
01212 astman_append(s, "No categories found\r\n");
01213 ast_config_destroy(cfg);
01214 astman_append(s, "\r\n");
01215
01216 return 0;
01217 }
01218
01219 static char mandescr_listcategories[] =
01220 "Description: A 'ListCategories' action will dump the categories in\n"
01221 "a given file.\n"
01222 "Variables:\n"
01223 " Filename: Configuration filename (e.g. foo.conf)\n";
01224
01225 static int action_listcategories(struct mansession *s, const struct message *m)
01226 {
01227 struct ast_config *cfg;
01228 const char *fn = astman_get_header(m, "Filename");
01229 char *category = NULL;
01230 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
01231 int catcount = 0;
01232
01233 if (ast_strlen_zero(fn)) {
01234 astman_send_error(s, m, "Filename not specified");
01235 return 0;
01236 }
01237 if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
01238 astman_send_error(s, m, "Config file not found");
01239 return 0;
01240 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
01241 astman_send_error(s, m, "Config file has invalid format");
01242 return 0;
01243 }
01244 astman_start_ack(s, m);
01245 while ((category = ast_category_browse(cfg, category))) {
01246 astman_append(s, "Category-%06d: %s\r\n", catcount, category);
01247 catcount++;
01248 }
01249 if (catcount == 0)
01250 astman_append(s, "Error: no categories found\r\n");
01251 ast_config_destroy(cfg);
01252 astman_append(s, "\r\n");
01253
01254 return 0;
01255 }
01256
01257
01258
01259
01260
01261 static void json_escape(char *out, const char *in)
01262 {
01263 for (; *in; in++) {
01264 if (*in == '\\' || *in == '\"')
01265 *out++ = '\\';
01266 *out++ = *in;
01267 }
01268 *out = '\0';
01269 }
01270
01271 static char mandescr_getconfigjson[] =
01272 "Description: A 'GetConfigJSON' action will dump the contents of a configuration\n"
01273 "file by category and contents in JSON format. This only makes sense to be used\n"
01274 "using rawman over the HTTP interface.\n"
01275 "Variables:\n"
01276 " Filename: Configuration filename (e.g. foo.conf)\n";
01277
01278 static int action_getconfigjson(struct mansession *s, const struct message *m)
01279 {
01280 struct ast_config *cfg;
01281 const char *fn = astman_get_header(m, "Filename");
01282 char *category = NULL;
01283 struct ast_variable *v;
01284 int comma1 = 0;
01285 char *buf = NULL;
01286 unsigned int buf_len = 0;
01287 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
01288
01289 if (ast_strlen_zero(fn)) {
01290 astman_send_error(s, m, "Filename not specified");
01291 return 0;
01292 }
01293
01294 if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
01295 astman_send_error(s, m, "Config file not found");
01296 return 0;
01297 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
01298 astman_send_error(s, m, "Config file has invalid format");
01299 return 0;
01300 }
01301
01302 buf_len = 512;
01303 buf = alloca(buf_len);
01304
01305 astman_start_ack(s, m);
01306 astman_append(s, "JSON: {");
01307 while ((category = ast_category_browse(cfg, category))) {
01308 int comma2 = 0;
01309 if (buf_len < 2 * strlen(category) + 1) {
01310 buf_len *= 2;
01311 buf = alloca(buf_len);
01312 }
01313 json_escape(buf, category);
01314 astman_append(s, "%s\"%s\":[", comma1 ? "," : "", buf);
01315 if (!comma1)
01316 comma1 = 1;
01317 for (v = ast_variable_browse(cfg, category); v; v = v->next) {
01318 if (comma2)
01319 astman_append(s, ",");
01320 if (buf_len < 2 * strlen(v->name) + 1) {
01321 buf_len *= 2;
01322 buf = alloca(buf_len);
01323 }
01324 json_escape(buf, v->name);
01325 astman_append(s, "\"%s", buf);
01326 if (buf_len < 2 * strlen(v->value) + 1) {
01327 buf_len *= 2;
01328 buf = alloca(buf_len);
01329 }
01330 json_escape(buf, v->value);
01331 astman_append(s, "%s\"", buf);
01332 if (!comma2)
01333 comma2 = 1;
01334 }
01335 astman_append(s, "]");
01336 }
01337 astman_append(s, "}\r\n\r\n");
01338
01339 ast_config_destroy(cfg);
01340
01341 return 0;
01342 }
01343
01344
01345 static enum error_type handle_updates(struct mansession *s, const struct message *m, struct ast_config *cfg, const char *dfn)
01346 {
01347 int x;
01348 char hdr[40];
01349 const char *action, *cat, *var, *value, *match, *line;
01350 struct ast_category *category;
01351 struct ast_variable *v;
01352 struct ast_str *str1 = ast_str_create(16), *str2 = ast_str_create(16);
01353 enum error_type result = 0;
01354
01355 for (x = 0; x < 100000; x++) {
01356 unsigned int object = 0;
01357
01358 snprintf(hdr, sizeof(hdr), "Action-%06d", x);
01359 action = astman_get_header(m, hdr);
01360 if (ast_strlen_zero(action))
01361 break;
01362
01363 snprintf(hdr, sizeof(hdr), "Cat-%06d", x);
01364 cat = astman_get_header(m, hdr);
01365 if (ast_strlen_zero(cat)) {
01366 result = UNSPECIFIED_CATEGORY;
01367 break;
01368 }
01369
01370 snprintf(hdr, sizeof(hdr), "Var-%06d", x);
01371 var = astman_get_header(m, hdr);
01372
01373 snprintf(hdr, sizeof(hdr), "Value-%06d", x);
01374 value = astman_get_header(m, hdr);
01375
01376 if (!ast_strlen_zero(value) && *value == '>') {
01377 object = 1;
01378 value++;
01379 }
01380
01381 snprintf(hdr, sizeof(hdr), "Match-%06d", x);
01382 match = astman_get_header(m, hdr);
01383
01384 snprintf(hdr, sizeof(hdr), "Line-%06d", x);
01385 line = astman_get_header(m, hdr);
01386
01387 if (!strcasecmp(action, "newcat")) {
01388 if (ast_category_get(cfg,cat)) {
01389 result = FAILURE_NEWCAT;
01390 break;
01391 }
01392 if (!(category = ast_category_new(cat, dfn, -1))) {
01393 result = FAILURE_ALLOCATION;
01394 break;
01395 }
01396 if (ast_strlen_zero(match)) {
01397 ast_category_append(cfg, category);
01398 } else
01399 ast_category_insert(cfg, category, match);
01400 } else if (!strcasecmp(action, "renamecat")) {
01401 if (ast_strlen_zero(value)) {
01402 result = UNSPECIFIED_ARGUMENT;
01403 break;
01404 }
01405 if (!(category = ast_category_get(cfg, cat))) {
01406 result = UNKNOWN_CATEGORY;
01407 break;
01408 }
01409 ast_category_rename(category, value);
01410 } else if (!strcasecmp(action, "delcat")) {
01411 if (ast_category_delete(cfg, cat)) {
01412 result = FAILURE_DELCAT;
01413 break;
01414 }
01415 } else if (!strcasecmp(action, "emptycat")) {
01416 if (ast_category_empty(cfg, cat)) {
01417 result = FAILURE_EMPTYCAT;
01418 break;
01419 }
01420 } else if (!strcasecmp(action, "update")) {
01421 if (ast_strlen_zero(var)) {
01422 result = UNSPECIFIED_ARGUMENT;
01423 break;
01424 }
01425 if (!(category = ast_category_get(cfg,cat))) {
01426 result = UNKNOWN_CATEGORY;
01427 break;
01428 }
01429 if (ast_variable_update(category, var, value, match, object)) {
01430 result = FAILURE_UPDATE;
01431 break;
01432 }
01433 } else if (!strcasecmp(action, "delete")) {
01434 if ((ast_strlen_zero(var) && ast_strlen_zero(line))) {
01435 result = UNSPECIFIED_ARGUMENT;
01436 break;
01437 }
01438 if (!(category = ast_category_get(cfg, cat))) {
01439 result = UNKNOWN_CATEGORY;
01440 break;
01441 }
01442 if (ast_variable_delete(category, var, match, line)) {
01443 result = FAILURE_DELETE;
01444 break;
01445 }
01446 } else if (!strcasecmp(action, "append")) {
01447 if (ast_strlen_zero(var)) {
01448 result = UNSPECIFIED_ARGUMENT;
01449 break;
01450 }
01451 if (!(category = ast_category_get(cfg, cat))) {
01452 result = UNKNOWN_CATEGORY;
01453 break;
01454 }
01455 if (!(v = ast_variable_new(var, value, dfn))) {
01456 result = FAILURE_ALLOCATION;
01457 break;
01458 }
01459 if (object || (match && !strcasecmp(match, "object")))
01460 v->object = 1;
01461 ast_variable_append(category, v);
01462 } else if (!strcasecmp(action, "insert")) {
01463 if (ast_strlen_zero(var) || ast_strlen_zero(line)) {
01464 result = UNSPECIFIED_ARGUMENT;
01465 break;
01466 }
01467 if (!(category = ast_category_get(cfg, cat))) {
01468 result = UNKNOWN_CATEGORY;
01469 break;
01470 }
01471 if (!(v = ast_variable_new(var, value, dfn))) {
01472 result = FAILURE_ALLOCATION;
01473 break;
01474 }
01475 ast_variable_insert(category, v, line);
01476 }
01477 else {
01478 ast_log(LOG_WARNING, "Action-%06d: %s not handled\n", x, action);
01479 result = UNKNOWN_ACTION;
01480 break;
01481 }
01482 }
01483 ast_free(str1);
01484 ast_free(str2);
01485 return result;
01486 }
01487
01488 static char mandescr_updateconfig[] =
01489 "Description: A 'UpdateConfig' action will modify, create, or delete\n"
01490 "configuration elements in Asterisk configuration files.\n"
01491 "Variables (X's represent 6 digit number beginning with 000000):\n"
01492 " SrcFilename: Configuration filename to read(e.g. foo.conf)\n"
01493 " DstFilename: Configuration filename to write(e.g. foo.conf)\n"
01494 " Reload: Whether or not a reload should take place (or name of specific module)\n"
01495 " Action-XXXXXX: Action to Take (NewCat,RenameCat,DelCat,EmptyCat,Update,Delete,Append,Insert)\n"
01496 " Cat-XXXXXX: Category to operate on\n"
01497 " Var-XXXXXX: Variable to work on\n"
01498 " Value-XXXXXX: Value to work on\n"
01499 " Match-XXXXXX: Extra match required to match line\n"
01500 " Line-XXXXXX: Line in category to operate on (used with delete and insert actions)\n";
01501
01502 static int action_updateconfig(struct mansession *s, const struct message *m)
01503 {
01504 struct ast_config *cfg;
01505 const char *sfn = astman_get_header(m, "SrcFilename");
01506 const char *dfn = astman_get_header(m, "DstFilename");
01507 int res;
01508 const char *rld = astman_get_header(m, "Reload");
01509 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
01510 enum error_type result;
01511
01512 if (ast_strlen_zero(sfn) || ast_strlen_zero(dfn)) {
01513 astman_send_error(s, m, "Filename not specified");
01514 return 0;
01515 }
01516 if (!(cfg = ast_config_load2(sfn, "manager", config_flags))) {
01517 astman_send_error(s, m, "Config file not found");
01518 return 0;
01519 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
01520 astman_send_error(s, m, "Config file has invalid format");
01521 return 0;
01522 }
01523 result = handle_updates(s, m, cfg, dfn);
01524 if (!result) {
01525 ast_include_rename(cfg, sfn, dfn);
01526 res = ast_config_text_file_save(dfn, cfg, "Manager");
01527 ast_config_destroy(cfg);
01528 if (res) {
01529 astman_send_error(s, m, "Save of config failed");
01530 return 0;
01531 }
01532 astman_send_ack(s, m, NULL);
01533 if (!ast_strlen_zero(rld)) {
01534 if (ast_true(rld))
01535 rld = NULL;
01536 ast_module_reload(rld);
01537 }
01538 } else {
01539 ast_config_destroy(cfg);
01540 switch(result) {
01541 case UNKNOWN_ACTION:
01542 astman_send_error(s, m, "Unknown action command");
01543 break;
01544 case UNKNOWN_CATEGORY:
01545 astman_send_error(s, m, "Given category does not exist");
01546 break;
01547 case UNSPECIFIED_CATEGORY:
01548 astman_send_error(s, m, "Category not specified");
01549 break;
01550 case UNSPECIFIED_ARGUMENT:
01551 astman_send_error(s, m, "Problem with category, value, or line (if required)");
01552 break;
01553 case FAILURE_ALLOCATION:
01554 astman_send_error(s, m, "Memory allocation failure, this should not happen");
01555 break;
01556 case FAILURE_NEWCAT:
01557 astman_send_error(s, m, "Create category did not complete successfully");
01558 break;
01559 case FAILURE_DELCAT:
01560 astman_send_error(s, m, "Delete category did not complete successfully");
01561 break;
01562 case FAILURE_EMPTYCAT:
01563 astman_send_error(s, m, "Empty category did not complete successfully");
01564 break;
01565 case FAILURE_UPDATE:
01566 astman_send_error(s, m, "Update did not complete successfully");
01567 break;
01568 case FAILURE_DELETE:
01569 astman_send_error(s, m, "Delete did not complete successfully");
01570 break;
01571 case FAILURE_APPEND:
01572 astman_send_error(s, m, "Append did not complete successfully");
01573 break;
01574 }
01575 }
01576 return 0;
01577 }
01578
01579 static char mandescr_createconfig[] =
01580 "Description: A 'CreateConfig' action will create an empty file in the\n"
01581 "configuration directory. This action is intended to be used before an\n"
01582 "UpdateConfig action.\n"
01583 "Variables\n"
01584 " Filename: The configuration filename to create (e.g. foo.conf)\n";
01585
01586 static int action_createconfig(struct mansession *s, const struct message *m)
01587 {
01588 int fd;
01589 const char *fn = astman_get_header(m, "Filename");
01590 struct ast_str *filepath = ast_str_alloca(PATH_MAX);
01591 ast_str_set(&filepath, 0, "%s/", ast_config_AST_CONFIG_DIR);
01592 ast_str_append(&filepath, 0, "%s", fn);
01593
01594 if ((fd = open(ast_str_buffer(filepath), O_CREAT | O_EXCL, AST_FILE_MODE)) != -1) {
01595 close(fd);
01596 astman_send_ack(s, m, "New configuration file created successfully");
01597 } else {
01598 astman_send_error(s, m, strerror(errno));
01599 }
01600
01601 return 0;
01602 }
01603
01604
01605 static char mandescr_waitevent[] =
01606 "Description: A 'WaitEvent' action will ellicit a 'Success' response. Whenever\n"
01607 "a manager event is queued. Once WaitEvent has been called on an HTTP manager\n"
01608 "session, events will be generated and queued.\n"
01609 "Variables: \n"
01610 " Timeout: Maximum time (in seconds) to wait for events, -1 means forever.\n";
01611
01612 static int action_waitevent(struct mansession *s, const struct message *m)
01613 {
01614 const char *timeouts = astman_get_header(m, "Timeout");
01615 int timeout = -1;
01616 int x;
01617 int needexit = 0;
01618 const char *id = astman_get_header(m, "ActionID");
01619 char idText[256];
01620
01621 if (!ast_strlen_zero(id))
01622 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
01623 else
01624 idText[0] = '\0';
01625
01626 if (!ast_strlen_zero(timeouts)) {
01627 sscanf(timeouts, "%30i", &timeout);
01628 if (timeout < -1)
01629 timeout = -1;
01630
01631 }
01632
01633 ast_mutex_lock(&s->session->__lock);
01634 if (s->session->waiting_thread != AST_PTHREADT_NULL)
01635 pthread_kill(s->session->waiting_thread, SIGURG);
01636
01637 if (s->session->managerid) {
01638
01639
01640
01641
01642
01643 time_t now = time(NULL);
01644 int max = s->session->sessiontimeout - now - 10;
01645
01646 if (max < 0)
01647 max = 0;
01648 if (timeout < 0 || timeout > max)
01649 timeout = max;
01650 if (!s->session->send_events)
01651 s->session->send_events = -1;
01652 }
01653 ast_mutex_unlock(&s->session->__lock);
01654
01655
01656 s->session->waiting_thread = pthread_self();
01657 ast_debug(1, "Starting waiting for an event!\n");
01658
01659 for (x = 0; x < timeout || timeout < 0; x++) {
01660 ast_mutex_lock(&s->session->__lock);
01661 if (AST_RWLIST_NEXT(s->session->last_ev, eq_next)) {
01662 needexit = 1;
01663 }
01664
01665
01666
01667
01668 if (s->session->waiting_thread != pthread_self())
01669 needexit = 1;
01670 if (s->session->needdestroy)
01671 needexit = 1;
01672 ast_mutex_unlock(&s->session->__lock);
01673 if (needexit)
01674 break;
01675 if (s->session->managerid == 0) {
01676 if (ast_wait_for_input(s->session->fd, 1000))
01677 break;
01678 } else {
01679 sleep(1);
01680 }
01681 }
01682 ast_debug(1, "Finished waiting for an event!\n");
01683 ast_mutex_lock(&s->session->__lock);
01684 if (s->session->waiting_thread == pthread_self()) {
01685 struct eventqent *eqe = s->session->last_ev;
01686 astman_send_response(s, m, "Success", "Waiting for Event completed.");
01687 while ((eqe = advance_event(eqe))) {
01688 if (((s->session->readperm & eqe->category) == eqe->category) &&
01689 ((s->session->send_events & eqe->category) == eqe->category)) {
01690 astman_append(s, "%s", eqe->eventdata);
01691 }
01692 s->session->last_ev = eqe;
01693 }
01694 astman_append(s,
01695 "Event: WaitEventComplete\r\n"
01696 "%s"
01697 "\r\n", idText);
01698 s->session->waiting_thread = AST_PTHREADT_NULL;
01699 } else {
01700 ast_debug(1, "Abandoning event request!\n");
01701 }
01702 ast_mutex_unlock(&s->session->__lock);
01703 return 0;
01704 }
01705
01706 static char mandescr_listcommands[] =
01707 "Description: Returns the action name and synopsis for every\n"
01708 " action that is available to the user\n"
01709 "Variables: NONE\n";
01710
01711
01712 static int action_listcommands(struct mansession *s, const struct message *m)
01713 {
01714 struct manager_action *cur;
01715 struct ast_str *temp = ast_str_alloca(BUFSIZ);
01716
01717 astman_start_ack(s, m);
01718 AST_RWLIST_TRAVERSE(&actions, cur, list) {
01719 if (s->session->writeperm & cur->authority || cur->authority == 0)
01720 astman_append(s, "%s: %s (Priv: %s)\r\n",
01721 cur->action, cur->synopsis, authority_to_str(cur->authority, &temp));
01722 }
01723 astman_append(s, "\r\n");
01724
01725 return 0;
01726 }
01727
01728 static char mandescr_events[] =
01729 "Description: Enable/Disable sending of events to this manager\n"
01730 " client.\n"
01731 "Variables:\n"
01732 " EventMask: 'on' if all events should be sent,\n"
01733 " 'off' if no events should be sent,\n"
01734 " 'system,call,log' to select which flags events should have to be sent.\n";
01735
01736 static int action_events(struct mansession *s, const struct message *m)
01737 {
01738 const char *mask = astman_get_header(m, "EventMask");
01739 int res, x;
01740
01741 res = set_eventmask(s, mask);
01742 if (broken_events_action) {
01743
01744
01745
01746 if (res > 0) {
01747 for (x = 0; x < ARRAY_LEN(perms); x++) {
01748 if (!strcasecmp(perms[x].label, "all") && res == perms[x].num) {
01749 return 0;
01750 }
01751 }
01752 astman_append(s, "Response: Success\r\n"
01753 "Events: On\r\n\r\n");
01754 } else if (res == 0)
01755 astman_append(s, "Response: Success\r\n"
01756 "Events: Off\r\n\r\n");
01757 return 0;
01758 }
01759
01760 if (res > 0)
01761 astman_append(s, "Response: Success\r\n"
01762 "Events: On\r\n\r\n");
01763 else if (res == 0)
01764 astman_append(s, "Response: Success\r\n"
01765 "Events: Off\r\n\r\n");
01766 else
01767 astman_send_error(s, m, "Invalid event mask");
01768
01769 return 0;
01770 }
01771
01772 static char mandescr_logoff[] =
01773 "Description: Logoff this manager session\n"
01774 "Variables: NONE\n";
01775
01776 static int action_logoff(struct mansession *s, const struct message *m)
01777 {
01778 astman_send_response(s, m, "Goodbye", "Thanks for all the fish.");
01779 return -1;
01780 }
01781
01782 static int action_login(struct mansession *s, const struct message *m)
01783 {
01784 if (authenticate(s, m)) {
01785 sleep(1);
01786 astman_send_error(s, m, "Authentication failed");
01787 return -1;
01788 }
01789 s->session->authenticated = 1;
01790 if (manager_displayconnects(s->session))
01791 ast_verb(2, "%sManager '%s' logged on from %s\n", (s->session->managerid ? "HTTP " : ""), s->session->username, ast_inet_ntoa(s->session->sin.sin_addr));
01792 ast_log(LOG_EVENT, "%sManager '%s' logged on from %s\n", (s->session->managerid ? "HTTP " : ""), s->session->username, ast_inet_ntoa(s->session->sin.sin_addr));
01793 astman_send_ack(s, m, "Authentication accepted");
01794 if (ast_opt_send_fullybooted && ast_test_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED)) {
01795 manager_event(EVENT_FLAG_SYSTEM, "FullyBooted", "Status: Fully Booted\r\n");
01796 }
01797 return 0;
01798 }
01799
01800 static int action_challenge(struct mansession *s, const struct message *m)
01801 {
01802 const char *authtype = astman_get_header(m, "AuthType");
01803
01804 if (!strcasecmp(authtype, "MD5")) {
01805 if (ast_strlen_zero(s->session->challenge))
01806 snprintf(s->session->challenge, sizeof(s->session->challenge), "%ld", ast_random());
01807 ast_mutex_lock(&s->session->__lock);
01808 astman_start_ack(s, m);
01809 astman_append(s, "Challenge: %s\r\n\r\n", s->session->challenge);
01810 ast_mutex_unlock(&s->session->__lock);
01811 } else {
01812 astman_send_error(s, m, "Must specify AuthType");
01813 }
01814 return 0;
01815 }
01816
01817 static char mandescr_hangup[] =
01818 "Description: Hangup a channel\n"
01819 "Variables: \n"
01820 " Channel: The channel name to be hungup\n";
01821
01822 static int action_hangup(struct mansession *s, const struct message *m)
01823 {
01824 struct ast_channel *c = NULL;
01825 const char *name = astman_get_header(m, "Channel");
01826 if (ast_strlen_zero(name)) {
01827 astman_send_error(s, m, "No channel specified");
01828 return 0;
01829 }
01830 c = ast_get_channel_by_name_locked(name);
01831 if (!c) {
01832 astman_send_error(s, m, "No such channel");
01833 return 0;
01834 }
01835 ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
01836 ast_channel_unlock(c);
01837 astman_send_ack(s, m, "Channel Hungup");
01838 return 0;
01839 }
01840
01841 static char mandescr_setvar[] =
01842 "Description: Set a global or local channel variable.\n"
01843 "Variables: (Names marked with * are required)\n"
01844 " Channel: Channel to set variable for\n"
01845 " *Variable: Variable name\n"
01846 " *Value: Value\n";
01847
01848 static int action_setvar(struct mansession *s, const struct message *m)
01849 {
01850 struct ast_channel *c = NULL;
01851 const char *name = astman_get_header(m, "Channel");
01852 const char *varname = astman_get_header(m, "Variable");
01853 const char *varval = astman_get_header(m, "Value");
01854 int res = 0;
01855
01856 if (ast_strlen_zero(varname)) {
01857 astman_send_error(s, m, "No variable specified");
01858 return 0;
01859 }
01860
01861 if (!ast_strlen_zero(name)) {
01862 c = ast_get_channel_by_name_locked(name);
01863 if (!c) {
01864 astman_send_error(s, m, "No such channel");
01865 return 0;
01866 }
01867 }
01868 if (varname[strlen(varname)-1] == ')') {
01869 char *function = ast_strdupa(varname);
01870 res = ast_func_write(c, function, varval);
01871 } else {
01872 pbx_builtin_setvar_helper(c, varname, S_OR(varval, ""));
01873 }
01874
01875 if (c)
01876 ast_channel_unlock(c);
01877 if (res == 0) {
01878 astman_send_ack(s, m, "Variable Set");
01879 } else {
01880 astman_send_error(s, m, "Variable not set");
01881 }
01882 return 0;
01883 }
01884
01885 static char mandescr_getvar[] =
01886 "Description: Get the value of a global or local channel variable.\n"
01887 "Variables: (Names marked with * are required)\n"
01888 " Channel: Channel to read variable from\n"
01889 " *Variable: Variable name\n"
01890 " ActionID: Optional Action id for message matching.\n";
01891
01892 static int action_getvar(struct mansession *s, const struct message *m)
01893 {
01894 struct ast_channel *c = NULL;
01895 const char *name = astman_get_header(m, "Channel");
01896 const char *varname = astman_get_header(m, "Variable");
01897 char *varval;
01898 char workspace[1024] = "";
01899
01900 if (ast_strlen_zero(varname)) {
01901 astman_send_error(s, m, "No variable specified");
01902 return 0;
01903 }
01904
01905 if (!ast_strlen_zero(name)) {
01906 c = ast_get_channel_by_name_locked(name);
01907 if (!c) {
01908 astman_send_error(s, m, "No such channel");
01909 return 0;
01910 }
01911 }
01912
01913 if (varname[strlen(varname) - 1] == ')') {
01914 if (!c) {
01915 c = ast_channel_alloc(0, 0, "", "", "", "", "", 0, "Bogus/manager");
01916 if (c) {
01917 ast_func_read(c, (char *) varname, workspace, sizeof(workspace));
01918 ast_channel_free(c);
01919 c = NULL;
01920 } else
01921 ast_log(LOG_ERROR, "Unable to allocate bogus channel for variable substitution. Function results may be blank.\n");
01922 } else
01923 ast_func_read(c, (char *) varname, workspace, sizeof(workspace));
01924 varval = workspace;
01925 } else {
01926 pbx_retrieve_variable(c, varname, &varval, workspace, sizeof(workspace), NULL);
01927 }
01928
01929 if (c)
01930 ast_channel_unlock(c);
01931 astman_start_ack(s, m);
01932 astman_append(s, "Variable: %s\r\nValue: %s\r\n\r\n", varname, S_OR(varval, ""));
01933
01934 return 0;
01935 }
01936
01937 static char mandescr_status[] =
01938 "Description: Lists channel status along with requested channel vars.\n"
01939 "Variables: (Names marked with * are required)\n"
01940 " *Channel: Name of the channel to query for status\n"
01941 " Variables: Comma ',' separated list of variables to include\n"
01942 " ActionID: Optional ID for this transaction\n"
01943 "Will return the status information of each channel along with the\n"
01944 "value for the specified channel variables.\n";
01945
01946
01947
01948
01949 static int action_status(struct mansession *s, const struct message *m)
01950 {
01951 const char *name = astman_get_header(m, "Channel");
01952 const char *cvariables = astman_get_header(m, "Variables");
01953 char *variables = ast_strdupa(S_OR(cvariables, ""));
01954 struct ast_channel *c;
01955 char bridge[256];
01956 struct timeval now = ast_tvnow();
01957 long elapsed_seconds = 0;
01958 int channels = 0;
01959 int all = ast_strlen_zero(name);
01960 const char *id = astman_get_header(m, "ActionID");
01961 char idText[256];
01962 AST_DECLARE_APP_ARGS(vars,
01963 AST_APP_ARG(name)[100];
01964 );
01965 struct ast_str *str = ast_str_create(1000);
01966
01967 if (!ast_strlen_zero(id))
01968 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
01969 else
01970 idText[0] = '\0';
01971
01972 if (all)
01973 c = ast_channel_walk_locked(NULL);
01974 else {
01975 c = ast_get_channel_by_name_locked(name);
01976 if (!c) {
01977 astman_send_error(s, m, "No such channel");
01978 ast_free(str);
01979 return 0;
01980 }
01981 }
01982 astman_send_ack(s, m, "Channel status will follow");
01983
01984 if (!ast_strlen_zero(cvariables)) {
01985 AST_STANDARD_APP_ARGS(vars, variables);
01986 }
01987
01988
01989 while (c) {
01990 if (!ast_strlen_zero(cvariables)) {
01991 int i;
01992 ast_str_reset(str);
01993 for (i = 0; i < vars.argc; i++) {
01994 char valbuf[512], *ret = NULL;
01995
01996 if (vars.name[i][strlen(vars.name[i]) - 1] == ')') {
01997 if (ast_func_read(c, vars.name[i], valbuf, sizeof(valbuf)) < 0) {
01998 valbuf[0] = '\0';
01999 }
02000 ret = valbuf;
02001 } else {
02002 pbx_retrieve_variable(c, vars.name[i], &ret, valbuf, sizeof(valbuf), NULL);
02003 }
02004
02005 ast_str_append(&str, 0, "Variable: %s=%s\r\n", vars.name[i], ret);
02006 }
02007 }
02008
02009 channels++;
02010 if (c->_bridge)
02011 snprintf(bridge, sizeof(bridge), "BridgedChannel: %s\r\nBridgedUniqueid: %s\r\n", c->_bridge->name, c->_bridge->uniqueid);
02012 else
02013 bridge[0] = '\0';
02014 if (c->pbx) {
02015 if (c->cdr) {
02016 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
02017 }
02018 astman_append(s,
02019 "Event: Status\r\n"
02020 "Privilege: Call\r\n"
02021 "Channel: %s\r\n"
02022 "CallerIDNum: %s\r\n"
02023 "CallerIDName: %s\r\n"
02024 "Accountcode: %s\r\n"
02025 "ChannelState: %d\r\n"
02026 "ChannelStateDesc: %s\r\n"
02027 "Context: %s\r\n"
02028 "Extension: %s\r\n"
02029 "Priority: %d\r\n"
02030 "Seconds: %ld\r\n"
02031 "%s"
02032 "Uniqueid: %s\r\n"
02033 "%s"
02034 "%s"
02035 "\r\n",
02036 c->name,
02037 S_OR(c->cid.cid_num, ""),
02038 S_OR(c->cid.cid_name, ""),
02039 c->accountcode,
02040 c->_state,
02041 ast_state2str(c->_state), c->context,
02042 c->exten, c->priority, (long)elapsed_seconds, bridge, c->uniqueid, ast_str_buffer(str), idText);
02043 } else {
02044 astman_append(s,
02045 "Event: Status\r\n"
02046 "Privilege: Call\r\n"
02047 "Channel: %s\r\n"
02048 "CallerIDNum: %s\r\n"
02049 "CallerIDName: %s\r\n"
02050 "Account: %s\r\n"
02051 "State: %s\r\n"
02052 "%s"
02053 "Uniqueid: %s\r\n"
02054 "%s"
02055 "%s"
02056 "\r\n",
02057 c->name,
02058 S_OR(c->cid.cid_num, "<unknown>"),
02059 S_OR(c->cid.cid_name, "<unknown>"),
02060 c->accountcode,
02061 ast_state2str(c->_state), bridge, c->uniqueid, ast_str_buffer(str), idText);
02062 }
02063 ast_channel_unlock(c);
02064 if (!all)
02065 break;
02066 c = ast_channel_walk_locked(c);
02067 }
02068 astman_append(s,
02069 "Event: StatusComplete\r\n"
02070 "%s"
02071 "Items: %d\r\n"
02072 "\r\n", idText, channels);
02073 ast_free(str);
02074 return 0;
02075 }
02076
02077 static char mandescr_sendtext[] =
02078 "Description: Sends A Text Message while in a call.\n"
02079 "Variables: (Names marked with * are required)\n"
02080 " *Channel: Channel to send message to\n"
02081 " *Message: Message to send\n"
02082 " ActionID: Optional Action id for message matching.\n";
02083
02084 static int action_sendtext(struct mansession *s, const struct message *m)
02085 {
02086 struct ast_channel *c = NULL;
02087 const char *name = astman_get_header(m, "Channel");
02088 const char *textmsg = astman_get_header(m, "Message");
02089 int res = 0;
02090
02091 if (ast_strlen_zero(name)) {
02092 astman_send_error(s, m, "No channel specified");
02093 return 0;
02094 }
02095
02096 if (ast_strlen_zero(textmsg)) {
02097 astman_send_error(s, m, "No Message specified");
02098 return 0;
02099 }
02100
02101 c = ast_get_channel_by_name_locked(name);
02102 if (!c) {
02103 astman_send_error(s, m, "No such channel");
02104 return 0;
02105 }
02106
02107 res = ast_sendtext(c, textmsg);
02108 ast_channel_unlock(c);
02109
02110 if (res > 0)
02111 astman_send_ack(s, m, "Success");
02112 else
02113 astman_send_error(s, m, "Failure");
02114
02115 return res;
02116 }
02117
02118 static char mandescr_redirect[] =
02119 "Description: Redirect (transfer) a call.\n"
02120 "Variables: (Names marked with * are required)\n"
02121 " *Channel: Channel to redirect\n"
02122 " ExtraChannel: Second call leg to transfer (optional)\n"
02123 " *Exten: Extension to transfer to\n"
02124 " *Context: Context to transfer to\n"
02125 " *Priority: Priority to transfer to\n"
02126 " ActionID: Optional Action id for message matching.\n";
02127
02128
02129 static int action_redirect(struct mansession *s, const struct message *m)
02130 {
02131 const char *name = astman_get_header(m, "Channel");
02132 const char *name2 = astman_get_header(m, "ExtraChannel");
02133 const char *exten = astman_get_header(m, "Exten");
02134 const char *context = astman_get_header(m, "Context");
02135 const char *priority = astman_get_header(m, "Priority");
02136 struct ast_channel *chan, *chan2 = NULL;
02137 int pi = 0;
02138 int res;
02139
02140 if (ast_strlen_zero(name)) {
02141 astman_send_error(s, m, "Channel not specified");
02142 return 0;
02143 }
02144 if (!ast_strlen_zero(priority) && (sscanf(priority, "%30d", &pi) != 1)) {
02145 if ((pi = ast_findlabel_extension(NULL, context, exten, priority, NULL)) < 1) {
02146 astman_send_error(s, m, "Invalid priority");
02147 return 0;
02148 }
02149 }
02150
02151 chan = ast_get_channel_by_name_locked(name);
02152 if (!chan) {
02153 char buf[256];
02154 snprintf(buf, sizeof(buf), "Channel does not exist: %s", name);
02155 astman_send_error(s, m, buf);
02156 return 0;
02157 }
02158 if (ast_check_hangup(chan)) {
02159 astman_send_error(s, m, "Redirect failed, channel not up.");
02160 ast_channel_unlock(chan);
02161 return 0;
02162 }
02163 if (!ast_strlen_zero(name2))
02164 chan2 = ast_get_channel_by_name_locked(name2);
02165 if (chan2 && ast_check_hangup(chan2)) {
02166 astman_send_error(s, m, "Redirect failed, extra channel not up.");
02167 ast_channel_unlock(chan);
02168 ast_channel_unlock(chan2);
02169 return 0;
02170 }
02171 if (chan->pbx) {
02172 ast_channel_lock(chan);
02173 ast_set_flag(chan, AST_FLAG_BRIDGE_HANGUP_DONT);
02174 ast_channel_unlock(chan);
02175 }
02176 res = ast_async_goto(chan, context, exten, pi);
02177 if (!res) {
02178 if (!ast_strlen_zero(name2)) {
02179 if (chan2) {
02180 if (chan2->pbx) {
02181 ast_channel_lock(chan2);
02182 ast_set_flag(chan2, AST_FLAG_BRIDGE_HANGUP_DONT);
02183 ast_channel_unlock(chan2);
02184 }
02185 res = ast_async_goto(chan2, context, exten, pi);
02186 } else {
02187 res = -1;
02188 }
02189 if (!res)
02190 astman_send_ack(s, m, "Dual Redirect successful");
02191 else
02192 astman_send_error(s, m, "Secondary redirect failed");
02193 } else
02194 astman_send_ack(s, m, "Redirect successful");
02195 } else
02196 astman_send_error(s, m, "Redirect failed");
02197 if (chan)
02198 ast_channel_unlock(chan);
02199 if (chan2)
02200 ast_channel_unlock(chan2);
02201 return 0;
02202 }
02203
02204 static char mandescr_atxfer[] =
02205 "Description: Attended transfer.\n"
02206 "Variables: (Names marked with * are required)\n"
02207 " *Channel: Transferer's channel\n"
02208 " *Exten: Extension to transfer to\n"
02209 " *Context: Context to transfer to\n"
02210 " *Priority: Priority to transfer to\n"
02211 " ActionID: Optional Action id for message matching.\n";
02212
02213 static int action_atxfer(struct mansession *s, const struct message *m)
02214 {
02215 const char *name = astman_get_header(m, "Channel");
02216 const char *exten = astman_get_header(m, "Exten");
02217 const char *context = astman_get_header(m, "Context");
02218 struct ast_channel *chan = NULL;
02219 struct ast_call_feature *atxfer_feature = NULL;
02220 char *feature_code = NULL;
02221
02222 if (ast_strlen_zero(name)) {
02223 astman_send_error(s, m, "No channel specified");
02224 return 0;
02225 }
02226 if (ast_strlen_zero(exten)) {
02227 astman_send_error(s, m, "No extension specified");
02228 return 0;
02229 }
02230
02231 if (!(atxfer_feature = ast_find_call_feature("atxfer"))) {
02232 astman_send_error(s, m, "No attended transfer feature found");
02233 return 0;
02234 }
02235
02236 if (!(chan = ast_get_channel_by_name_locked(name))) {
02237 astman_send_error(s, m, "Channel specified does not exist");
02238 return 0;
02239 }
02240
02241 if (!ast_strlen_zero(context)) {
02242 pbx_builtin_setvar_helper(chan, "TRANSFER_CONTEXT", context);
02243 }
02244
02245 for (feature_code = atxfer_feature->exten; feature_code && *feature_code; ++feature_code) {
02246 struct ast_frame f = {AST_FRAME_DTMF, *feature_code};
02247 ast_queue_frame(chan, &f);
02248 }
02249
02250 for (feature_code = (char *)exten; feature_code && *feature_code; ++feature_code) {
02251 struct ast_frame f = {AST_FRAME_DTMF, *feature_code};
02252 ast_queue_frame(chan, &f);
02253 }
02254
02255 astman_send_ack(s, m, "Atxfer successfully queued");
02256 ast_channel_unlock(chan);
02257
02258 return 0;
02259 }
02260
02261 static int check_blacklist(const char *cmd)
02262 {
02263 char *cmd_copy, *cur_cmd;
02264 char *cmd_words[MAX_BLACKLIST_CMD_LEN] = { NULL, };
02265 int i;
02266
02267 cmd_copy = ast_strdupa(cmd);
02268 for (i = 0; i < MAX_BLACKLIST_CMD_LEN && (cur_cmd = strsep(&cmd_copy, " ")); i++) {
02269 cur_cmd = ast_strip(cur_cmd);
02270 if (ast_strlen_zero(cur_cmd)) {
02271 i--;
02272 continue;
02273 }
02274
02275 cmd_words[i] = cur_cmd;
02276 }
02277
02278 for (i = 0; i < ARRAY_LEN(command_blacklist); i++) {
02279 int j, match = 1;
02280
02281 for (j = 0; command_blacklist[i].words[j]; j++) {
02282 if (ast_strlen_zero(cmd_words[j]) || strcasecmp(cmd_words[j], command_blacklist[i].words[j])) {
02283 match = 0;
02284 break;
02285 }
02286 }
02287
02288 if (match) {
02289 return 1;
02290 }
02291 }
02292
02293 return 0;
02294 }
02295
02296 static char mandescr_command[] =
02297 "Description: Run a CLI command.\n"
02298 "Variables: (Names marked with * are required)\n"
02299 " *Command: Asterisk CLI command to run\n"
02300 " ActionID: Optional Action id for message matching.\n";
02301
02302
02303 static int action_command(struct mansession *s, const struct message *m)
02304 {
02305 const char *cmd = astman_get_header(m, "Command");
02306 const char *id = astman_get_header(m, "ActionID");
02307 char *buf, *final_buf;
02308 char template[] = "/tmp/ast-ami-XXXXXX";
02309 int fd;
02310 off_t l;
02311
02312 if (ast_strlen_zero(cmd)) {
02313 astman_send_error(s, m, "No command provided");
02314 return 0;
02315 }
02316
02317 if (check_blacklist(cmd)) {
02318 astman_send_error(s, m, "Command blacklisted");
02319 return 0;
02320 }
02321
02322 fd = mkstemp(template);
02323
02324 astman_append(s, "Response: Follows\r\nPrivilege: Command\r\n");
02325 if (!ast_strlen_zero(id))
02326 astman_append(s, "ActionID: %s\r\n", id);
02327
02328 ast_cli_command(fd, cmd);
02329 l = lseek(fd, 0, SEEK_END);
02330
02331
02332 buf = ast_calloc(1, l + 1);
02333 final_buf = ast_calloc(1, l + 1);
02334 if (buf) {
02335 lseek(fd, 0, SEEK_SET);
02336 if (read(fd, buf, l) < 0) {
02337 ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
02338 }
02339 buf[l] = '\0';
02340 if (final_buf) {
02341 term_strip(final_buf, buf, l);
02342 final_buf[l] = '\0';
02343 }
02344 astman_append(s, "%s", S_OR(final_buf, buf));
02345 ast_free(buf);
02346 }
02347 close(fd);
02348 unlink(template);
02349 astman_append(s, "--END COMMAND--\r\n\r\n");
02350 if (final_buf)
02351 ast_free(final_buf);
02352 return 0;
02353 }
02354
02355
02356 struct fast_originate_helper {
02357 char tech[AST_MAX_EXTENSION];
02358
02359 char data[512];
02360 int timeout;
02361 int format;
02362 char app[AST_MAX_APP];
02363 char appdata[AST_MAX_EXTENSION];
02364 char cid_name[AST_MAX_EXTENSION];
02365 char cid_num[AST_MAX_EXTENSION];
02366 char context[AST_MAX_CONTEXT];
02367 char exten[AST_MAX_EXTENSION];
02368 char idtext[AST_MAX_EXTENSION];
02369 char account[AST_MAX_ACCOUNT_CODE];
02370 int priority;
02371 struct ast_variable *vars;
02372 };
02373
02374 static void *fast_originate(void *data)
02375 {
02376 struct fast_originate_helper *in = data;
02377 int res;
02378 int reason = 0;
02379 struct ast_channel *chan = NULL;
02380 char requested_channel[AST_CHANNEL_NAME];
02381
02382 if (!ast_strlen_zero(in->app)) {
02383 res = ast_pbx_outgoing_app(in->tech, in->format, in->data, in->timeout, in->app, in->appdata, &reason, 1,
02384 S_OR(in->cid_num, NULL),
02385 S_OR(in->cid_name, NULL),
02386 in->vars, in->account, &chan);
02387 } else {
02388 res = ast_pbx_outgoing_exten(in->tech, in->format, in->data, in->timeout, in->context, in->exten, in->priority, &reason, 1,
02389 S_OR(in->cid_num, NULL),
02390 S_OR(in->cid_name, NULL),
02391 in->vars, in->account, &chan);
02392 }
02393
02394 if (!chan)
02395 snprintf(requested_channel, AST_CHANNEL_NAME, "%s/%s", in->tech, in->data);
02396
02397 manager_event(EVENT_FLAG_CALL, "OriginateResponse",
02398 "%s%s"
02399 "Response: %s\r\n"
02400 "Channel: %s\r\n"
02401 "Context: %s\r\n"
02402 "Exten: %s\r\n"
02403 "Reason: %d\r\n"
02404 "Uniqueid: %s\r\n"
02405 "CallerIDNum: %s\r\n"
02406 "CallerIDName: %s\r\n",
02407 in->idtext, ast_strlen_zero(in->idtext) ? "" : "\r\n", res ? "Failure" : "Success",
02408 chan ? chan->name : requested_channel, in->context, in->exten, reason,
02409 chan ? chan->uniqueid : "<null>",
02410 S_OR(in->cid_num, "<unknown>"),
02411 S_OR(in->cid_name, "<unknown>")
02412 );
02413
02414
02415 if (chan)
02416 ast_channel_unlock(chan);
02417 ast_free(in);
02418 return NULL;
02419 }
02420
02421 static char mandescr_originate[] =
02422 "Description: Generates an outgoing call to a Extension/Context/Priority or\n"
02423 " Application/Data\n"
02424 "Variables: (Names marked with * are required)\n"
02425 " *Channel: Channel name to call\n"
02426 " Exten: Extension to use (requires 'Context' and 'Priority')\n"
02427 " Context: Context to use (requires 'Exten' and 'Priority')\n"
02428 " Priority: Priority to use (requires 'Exten' and 'Context')\n"
02429 " Application: Application to use\n"
02430 " Data: Data to use (requires 'Application')\n"
02431 " Timeout: How long to wait for call to be answered (in ms. Default: 30000)\n"
02432 " CallerID: Caller ID to be set on the outgoing channel\n"
02433 " Variable: Channel variable to set, multiple Variable: headers are allowed\n"
02434 " Codecs: Comma-separated list of codecs to use for the new channels\n"
02435 " Account: Account code\n"
02436 " Async: Set to 'true' for fast origination\n";
02437
02438 static int action_originate(struct mansession *s, const struct message *m)
02439 {
02440 const char *name = astman_get_header(m, "Channel");
02441 const char *exten = astman_get_header(m, "Exten");
02442 const char *context = astman_get_header(m, "Context");
02443 const char *priority = astman_get_header(m, "Priority");
02444 const char *timeout = astman_get_header(m, "Timeout");
02445 const char *callerid = astman_get_header(m, "CallerID");
02446 const char *account = astman_get_header(m, "Account");
02447 const char *app = astman_get_header(m, "Application");
02448 const char *appdata = astman_get_header(m, "Data");
02449 const char *async = astman_get_header(m, "Async");
02450 const char *id = astman_get_header(m, "ActionID");
02451 const char *codecs = astman_get_header(m, "Codecs");
02452 struct ast_variable *vars;
02453 char *tech, *data;
02454 char *l = NULL, *n = NULL;
02455 int pi = 0;
02456 int res;
02457 int to = 30000;
02458 int reason = 0;
02459 char tmp[256];
02460 char tmp2[256];
02461 int format = AST_FORMAT_SLINEAR;
02462
02463 pthread_t th;
02464 if (ast_strlen_zero(name)) {
02465 astman_send_error(s, m, "Channel not specified");
02466 return 0;
02467 }
02468 if (!ast_strlen_zero(priority) && (sscanf(priority, "%30d", &pi) != 1)) {
02469 if ((pi = ast_findlabel_extension(NULL, context, exten, priority, NULL)) < 1) {
02470 astman_send_error(s, m, "Invalid priority");
02471 return 0;
02472 }
02473 }
02474 if (!ast_strlen_zero(timeout) && (sscanf(timeout, "%30d", &to) != 1)) {
02475 astman_send_error(s, m, "Invalid timeout");
02476 return 0;
02477 }
02478 ast_copy_string(tmp, name, sizeof(tmp));
02479 tech = tmp;
02480 data = strchr(tmp, '/');
02481 if (!data) {
02482 astman_send_error(s, m, "Invalid channel");
02483 return 0;
02484 }
02485 *data++ = '\0';
02486 ast_copy_string(tmp2, callerid, sizeof(tmp2));
02487 ast_callerid_parse(tmp2, &n, &l);
02488 if (n) {
02489 if (ast_strlen_zero(n))
02490 n = NULL;
02491 }
02492 if (l) {
02493 ast_shrink_phone_number(l);
02494 if (ast_strlen_zero(l))
02495 l = NULL;
02496 }
02497 if (!ast_strlen_zero(codecs)) {
02498 format = 0;
02499 ast_parse_allow_disallow(NULL, &format, codecs, 1);
02500 }
02501
02502 vars = astman_get_variables(m);
02503
02504 if (ast_true(async)) {
02505 struct fast_originate_helper *fast = ast_calloc(1, sizeof(*fast));
02506 if (!fast) {
02507 res = -1;
02508 } else {
02509 if (!ast_strlen_zero(id))
02510 snprintf(fast->idtext, sizeof(fast->idtext), "ActionID: %s", id);
02511 ast_copy_string(fast->tech, tech, sizeof(fast->tech));
02512 ast_copy_string(fast->data, data, sizeof(fast->data));
02513 ast_copy_string(fast->app, app, sizeof(fast->app));
02514 ast_copy_string(fast->appdata, appdata, sizeof(fast->appdata));
02515 if (l)
02516 ast_copy_string(fast->cid_num, l, sizeof(fast->cid_num));
02517 if (n)
02518 ast_copy_string(fast->cid_name, n, sizeof(fast->cid_name));
02519 fast->vars = vars;
02520 ast_copy_string(fast->context, context, sizeof(fast->context));
02521 ast_copy_string(fast->exten, exten, sizeof(fast->exten));
02522 ast_copy_string(fast->account, account, sizeof(fast->account));
02523 fast->format = format;
02524 fast->timeout = to;
02525 fast->priority = pi;
02526 if (ast_pthread_create_detached(&th, NULL, fast_originate, fast)) {
02527 ast_free(fast);
02528 res = -1;
02529 } else {
02530 res = 0;
02531 }
02532 }
02533 } else if (!ast_strlen_zero(app)) {
02534
02535 if (!(s->session->writeperm & EVENT_FLAG_SYSTEM)
02536 && (
02537 strcasestr(app, "system") ||
02538
02539 strcasestr(app, "exec") ||
02540
02541 strcasestr(app, "agi") ||
02542
02543 strstr(appdata, "SHELL") ||
02544 strstr(appdata, "EVAL")
02545 )) {
02546 astman_send_error(s, m, "Originate with certain 'Application' arguments requires the additional System privilege, which you do not have.");
02547 return 0;
02548 }
02549 res = ast_pbx_outgoing_app(tech, format, data, to, app, appdata, &reason, 1, l, n, vars, account, NULL);
02550 } else {
02551 if (exten && context && pi)
02552 res = ast_pbx_outgoing_exten(tech, format, data, to, context, exten, pi, &reason, 1, l, n, vars, account, NULL);
02553 else {
02554 astman_send_error(s, m, "Originate with 'Exten' requires 'Context' and 'Priority'");
02555 if (vars) {
02556 ast_variables_destroy(vars);
02557 }
02558 return 0;
02559 }
02560 }
02561 if (!res)
02562 astman_send_ack(s, m, "Originate successfully queued");
02563 else
02564 astman_send_error(s, m, "Originate failed");
02565 return 0;
02566 }
02567
02568
02569
02570 static char mandescr_mailboxstatus[] =
02571 "Description: Checks a voicemail account for status.\n"
02572 "Variables: (Names marked with * are required)\n"
02573 " *Mailbox: Full mailbox ID <mailbox>@<vm-context>\n"
02574 " ActionID: Optional ActionID for message matching.\n"
02575 "Returns number of messages.\n"
02576 " Message: Mailbox Status\n"
02577 " Mailbox: <mailboxid>\n"
02578 " Waiting: <count>\n"
02579 "\n";
02580
02581 static int action_mailboxstatus(struct mansession *s, const struct message *m)
02582 {
02583 const char *mailbox = astman_get_header(m, "Mailbox");
02584 int ret;
02585
02586 if (ast_strlen_zero(mailbox)) {
02587 astman_send_error(s, m, "Mailbox not specified");
02588 return 0;
02589 }
02590 ret = ast_app_has_voicemail(mailbox, NULL);
02591 astman_start_ack(s, m);
02592 astman_append(s, "Message: Mailbox Status\r\n"
02593 "Mailbox: %s\r\n"
02594 "Waiting: %d\r\n\r\n", mailbox, ret);
02595 return 0;
02596 }
02597
02598 static char mandescr_mailboxcount[] =
02599 "Description: Checks a voicemail account for new messages.\n"
02600 "Variables: (Names marked with * are required)\n"
02601 " *Mailbox: Full mailbox ID <mailbox>@<vm-context>\n"
02602 " ActionID: Optional ActionID for message matching.\n"
02603 "Returns number of urgent, new and old messages.\n"
02604 " Message: Mailbox Message Count\n"
02605 " Mailbox: <mailboxid>\n"
02606 " UrgentMessages: <count>\n"
02607 " NewMessages: <count>\n"
02608 " OldMessages: <count>\n"
02609 "\n";
02610 static int action_mailboxcount(struct mansession *s, const struct message *m)
02611 {
02612 const char *mailbox = astman_get_header(m, "Mailbox");
02613 int newmsgs = 0, oldmsgs = 0, urgentmsgs = 0;;
02614
02615 if (ast_strlen_zero(mailbox)) {
02616 astman_send_error(s, m, "Mailbox not specified");
02617 return 0;
02618 }
02619 ast_app_inboxcount2(mailbox, &urgentmsgs, &newmsgs, &oldmsgs);
02620 astman_start_ack(s, m);
02621 astman_append(s, "Message: Mailbox Message Count\r\n"
02622 "Mailbox: %s\r\n"
02623 "UrgMessages: %d\r\n"
02624 "NewMessages: %d\r\n"
02625 "OldMessages: %d\r\n"
02626 "\r\n",
02627 mailbox, urgentmsgs, newmsgs, oldmsgs);
02628 return 0;
02629 }
02630
02631 static char mandescr_extensionstate[] =
02632 "Description: Report the extension state for given extension.\n"
02633 " If the extension has a hint, will use devicestate to check\n"
02634 " the status of the device connected to the extension.\n"
02635 "Variables: (Names marked with * are required)\n"
02636 " *Exten: Extension to check state on\n"
02637 " *Context: Context for extension\n"
02638 " ActionId: Optional ID for this transaction\n"
02639 "Will return an \"Extension Status\" message.\n"
02640 "The response will include the hint for the extension and the status.\n";
02641
02642 static int action_extensionstate(struct mansession *s, const struct message *m)
02643 {
02644 const char *exten = astman_get_header(m, "Exten");
02645 const char *context = astman_get_header(m, "Context");
02646 char hint[256] = "";
02647 int status;
02648 if (ast_strlen_zero(exten)) {
02649 astman_send_error(s, m, "Extension not specified");
02650 return 0;
02651 }
02652 if (ast_strlen_zero(context))
02653 context = "default";
02654 status = ast_extension_state(NULL, context, exten);
02655 ast_get_hint(hint, sizeof(hint) - 1, NULL, 0, NULL, context, exten);
02656 astman_start_ack(s, m);
02657 astman_append(s, "Message: Extension Status\r\n"
02658 "Exten: %s\r\n"
02659 "Context: %s\r\n"
02660 "Hint: %s\r\n"
02661 "Status: %d\r\n\r\n",
02662 exten, context, hint, status);
02663 return 0;
02664 }
02665
02666 static char mandescr_timeout[] =
02667 "Description: Hangup a channel after a certain time.\n"
02668 "Variables: (Names marked with * are required)\n"
02669 " *Channel: Channel name to hangup\n"
02670 " *Timeout: Maximum duration of the call (sec)\n"
02671 "Acknowledges set time with 'Timeout Set' message\n";
02672
02673 static int action_timeout(struct mansession *s, const struct message *m)
02674 {
02675 struct ast_channel *c;
02676 const char *name = astman_get_header(m, "Channel");
02677 double timeout = atof(astman_get_header(m, "Timeout"));
02678 struct timeval when = { timeout, 0 };
02679
02680 if (ast_strlen_zero(name)) {
02681 astman_send_error(s, m, "No channel specified");
02682 return 0;
02683 }
02684 if (!timeout || timeout < 0) {
02685 astman_send_error(s, m, "No timeout specified");
02686 return 0;
02687 }
02688 c = ast_get_channel_by_name_locked(name);
02689 if (!c) {
02690 astman_send_error(s, m, "No such channel");
02691 return 0;
02692 }
02693
02694 when.tv_usec = (timeout - when.tv_sec) * 1000000.0;
02695 ast_channel_setwhentohangup_tv(c, when);
02696 ast_channel_unlock(c);
02697 astman_send_ack(s, m, "Timeout Set");
02698 return 0;
02699 }
02700
02701
02702
02703
02704
02705
02706 static int process_events(struct mansession *s)
02707 {
02708 int ret = 0;
02709
02710 ast_mutex_lock(&s->session->__lock);
02711 if (s->session->f != NULL) {
02712 struct eventqent *eqe = s->session->last_ev;
02713
02714 while ((eqe = advance_event(eqe))) {
02715 if (!ret && s->session->authenticated &&
02716 (s->session->readperm & eqe->category) == eqe->category &&
02717 (s->session->send_events & eqe->category) == eqe->category) {
02718 if (send_string(s, eqe->eventdata) < 0)
02719 ret = -1;
02720 }
02721 s->session->last_ev = eqe;
02722 }
02723 }
02724 ast_mutex_unlock(&s->session->__lock);
02725 return ret;
02726 }
02727
02728 static char mandescr_userevent[] =
02729 "Description: Send an event to manager sessions.\n"
02730 "Variables: (Names marked with * are required)\n"
02731 " *UserEvent: EventStringToSend\n"
02732 " Header1: Content1\n"
02733 " HeaderN: ContentN\n";
02734
02735 static int action_userevent(struct mansession *s, const struct message *m)
02736 {
02737 const char *event = astman_get_header(m, "UserEvent");
02738 struct ast_str *body = ast_str_thread_get(&userevent_buf, 16);
02739 int x;
02740
02741 ast_str_reset(body);
02742
02743 for (x = 0; x < m->hdrcount; x++) {
02744 if (strncasecmp("UserEvent:", m->headers[x], strlen("UserEvent:"))) {
02745 ast_str_append(&body, 0, "%s\r\n", m->headers[x]);
02746 }
02747 }
02748
02749 astman_send_ack(s, m, "Event Sent");
02750 manager_event(EVENT_FLAG_USER, "UserEvent", "UserEvent: %s\r\n%s", event, ast_str_buffer(body));
02751 return 0;
02752 }
02753
02754 static char mandescr_coresettings[] =
02755 "Description: Query for Core PBX settings.\n"
02756 "Variables: (Names marked with * are optional)\n"
02757 " *ActionID: ActionID of this transaction\n";
02758
02759
02760 static int action_coresettings(struct mansession *s, const struct message *m)
02761 {
02762 const char *actionid = astman_get_header(m, "ActionID");
02763 char idText[150];
02764
02765 if (!ast_strlen_zero(actionid))
02766 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", actionid);
02767 else
02768 idText[0] = '\0';
02769
02770 astman_append(s, "Response: Success\r\n"
02771 "%s"
02772 "AMIversion: %s\r\n"
02773 "AsteriskVersion: %s\r\n"
02774 "SystemName: %s\r\n"
02775 "CoreMaxCalls: %d\r\n"
02776 "CoreMaxLoadAvg: %f\r\n"
02777 "CoreRunUser: %s\r\n"
02778 "CoreRunGroup: %s\r\n"
02779 "CoreMaxFilehandles: %d\r\n"
02780 "CoreRealTimeEnabled: %s\r\n"
02781 "CoreCDRenabled: %s\r\n"
02782 "CoreHTTPenabled: %s\r\n"
02783 "\r\n",
02784 idText,
02785 AMI_VERSION,
02786 ast_get_version(),
02787 ast_config_AST_SYSTEM_NAME,
02788 option_maxcalls,
02789 option_maxload,
02790 ast_config_AST_RUN_USER,
02791 ast_config_AST_RUN_GROUP,
02792 option_maxfiles,
02793 ast_realtime_enabled() ? "Yes" : "No",
02794 check_cdr_enabled() ? "Yes" : "No",
02795 check_webmanager_enabled() ? "Yes" : "No"
02796 );
02797 return 0;
02798 }
02799
02800 static char mandescr_corestatus[] =
02801 "Description: Query for Core PBX status.\n"
02802 "Variables: (Names marked with * are optional)\n"
02803 " *ActionID: ActionID of this transaction\n";
02804
02805
02806 static int action_corestatus(struct mansession *s, const struct message *m)
02807 {
02808 const char *actionid = astman_get_header(m, "ActionID");
02809 char idText[150];
02810 char startuptime[150];
02811 char reloadtime[150];
02812 struct ast_tm tm;
02813
02814 if (!ast_strlen_zero(actionid))
02815 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", actionid);
02816 else
02817 idText[0] = '\0';
02818
02819 ast_localtime(&ast_startuptime, &tm, NULL);
02820 ast_strftime(startuptime, sizeof(startuptime), "%H:%M:%S", &tm);
02821 ast_localtime(&ast_lastreloadtime, &tm, NULL);
02822 ast_strftime(reloadtime, sizeof(reloadtime), "%H:%M:%S", &tm);
02823
02824 astman_append(s, "Response: Success\r\n"
02825 "%s"
02826 "CoreStartupTime: %s\r\n"
02827 "CoreReloadTime: %s\r\n"
02828 "CoreCurrentCalls: %d\r\n"
02829 "\r\n",
02830 idText,
02831 startuptime,
02832 reloadtime,
02833 ast_active_channels()
02834 );
02835 return 0;
02836 }
02837
02838 static char mandescr_reload[] =
02839 "Description: Send a reload event.\n"
02840 "Variables: (Names marked with * are optional)\n"
02841 " *ActionID: ActionID of this transaction\n"
02842 " *Module: Name of the module to reload\n";
02843
02844
02845 static int action_reload(struct mansession *s, const struct message *m)
02846 {
02847 const char *module = astman_get_header(m, "Module");
02848 int res = ast_module_reload(S_OR(module, NULL));
02849
02850 if (res == 2)
02851 astman_send_ack(s, m, "Module Reloaded");
02852 else
02853 astman_send_error(s, m, s == 0 ? "No such module" : "Module does not support reload");
02854 return 0;
02855 }
02856
02857 static char mandescr_coreshowchannels[] =
02858 "Description: List currently defined channels and some information\n"
02859 " about them.\n"
02860 "Variables:\n"
02861 " ActionID: Optional Action id for message matching.\n";
02862
02863
02864
02865 static int action_coreshowchannels(struct mansession *s, const struct message *m)
02866 {
02867 const char *actionid = astman_get_header(m, "ActionID");
02868 char idText[256];
02869 struct ast_channel *c = NULL;
02870 int numchans = 0;
02871 int duration, durh, durm, durs;
02872
02873 if (!ast_strlen_zero(actionid))
02874 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", actionid);
02875 else
02876 idText[0] = '\0';
02877
02878 astman_send_listack(s, m, "Channels will follow", "start");
02879
02880 while ((c = ast_channel_walk_locked(c)) != NULL) {
02881 struct ast_channel *bc = ast_bridged_channel(c);
02882 char durbuf[10] = "";
02883
02884 if (c->cdr && !ast_tvzero(c->cdr->start)) {
02885 duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
02886 durh = duration / 3600;
02887 durm = (duration % 3600) / 60;
02888 durs = duration % 60;
02889 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
02890 }
02891
02892 astman_append(s,
02893 "Event: CoreShowChannel\r\n"
02894 "%s"
02895 "Channel: %s\r\n"
02896 "UniqueID: %s\r\n"
02897 "Context: %s\r\n"
02898 "Extension: %s\r\n"
02899 "Priority: %d\r\n"
02900 "ChannelState: %d\r\n"
02901 "ChannelStateDesc: %s\r\n"
02902 "Application: %s\r\n"
02903 "ApplicationData: %s\r\n"
02904 "CallerIDnum: %s\r\n"
02905 "Duration: %s\r\n"
02906 "AccountCode: %s\r\n"
02907 "BridgedChannel: %s\r\n"
02908 "BridgedUniqueID: %s\r\n"
02909 "\r\n", idText, c->name, c->uniqueid, c->context, c->exten, c->priority, c->_state,
02910 ast_state2str(c->_state), c->appl ? c->appl : "", c->data ? S_OR(c->data, "") : "",
02911 S_OR(c->cid.cid_num, ""), durbuf, S_OR(c->accountcode, ""), bc ? bc->name : "", bc ? bc->uniqueid : "");
02912 ast_channel_unlock(c);
02913 numchans++;
02914 }
02915
02916 astman_append(s,
02917 "Event: CoreShowChannelsComplete\r\n"
02918 "EventList: Complete\r\n"
02919 "ListItems: %d\r\n"
02920 "%s"
02921 "\r\n", numchans, idText);
02922
02923 return 0;
02924 }
02925
02926 static char mandescr_modulecheck[] =
02927 "Description: Checks if Asterisk module is loaded\n"
02928 "Variables: \n"
02929 " ActionID: <id> Action ID for this transaction. Will be returned.\n"
02930 " Module: <name> Asterisk module name (not including extension)\n"
02931 "\n"
02932 "Will return Success/Failure\n"
02933 "For success returns, the module revision number is included.\n";
02934
02935
02936 static int manager_modulecheck(struct mansession *s, const struct message *m)
02937 {
02938 int res;
02939 const char *module = astman_get_header(m, "Module");
02940 const char *id = astman_get_header(m, "ActionID");
02941 char idText[256];
02942 #if !defined(LOW_MEMORY)
02943 const char *version;
02944 #endif
02945 char filename[PATH_MAX];
02946 char *cut;
02947
02948 ast_copy_string(filename, module, sizeof(filename));
02949 if ((cut = strchr(filename, '.'))) {
02950 *cut = '\0';
02951 } else {
02952 cut = filename + strlen(filename);
02953 }
02954 snprintf(cut, (sizeof(filename) - strlen(filename)) - 1, ".so");
02955 ast_log(LOG_DEBUG, "**** ModuleCheck .so file %s\n", filename);
02956 res = ast_module_check(filename);
02957 if (!res) {
02958 astman_send_error(s, m, "Module not loaded");
02959 return 0;
02960 }
02961 snprintf(cut, (sizeof(filename) - strlen(filename)) - 1, ".c");
02962 ast_log(LOG_DEBUG, "**** ModuleCheck .c file %s\n", filename);
02963 #if !defined(LOW_MEMORY)
02964 version = ast_file_version_find(filename);
02965 #endif
02966
02967 if (!ast_strlen_zero(id))
02968 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
02969 else
02970 idText[0] = '\0';
02971 astman_append(s, "Response: Success\r\n%s", idText);
02972 #if !defined(LOW_MEMORY)
02973 astman_append(s, "Version: %s\r\n\r\n", version ? version : "");
02974 #endif
02975 return 0;
02976 }
02977
02978 static char mandescr_moduleload[] =
02979 "Description: Loads, unloads or reloads an Asterisk module in a running system.\n"
02980 "Variables: \n"
02981 " ActionID: <id> Action ID for this transaction. Will be returned.\n"
02982 " Module: <name> Asterisk module name (including .so extension)\n"
02983 " or subsystem identifier:\n"
02984 " cdr, enum, dnsmgr, extconfig, manager, rtp, http\n"
02985 " LoadType: load | unload | reload\n"
02986 " The operation to be done on module\n"
02987 " If no module is specified for a reload loadtype, all modules are reloaded";
02988
02989 static int manager_moduleload(struct mansession *s, const struct message *m)
02990 {
02991 int res;
02992 const char *module = astman_get_header(m, "Module");
02993 const char *loadtype = astman_get_header(m, "LoadType");
02994
02995 if (!loadtype || strlen(loadtype) == 0)
02996 astman_send_error(s, m, "Incomplete ModuleLoad action.");
02997 if ((!module || strlen(module) == 0) && strcasecmp(loadtype, "reload") != 0)
02998 astman_send_error(s, m, "Need module name");
02999
03000 if (!strcasecmp(loadtype, "load")) {
03001 res = ast_load_resource(module);
03002 if (res)
03003 astman_send_error(s, m, "Could not load module.");
03004 else
03005 astman_send_ack(s, m, "Module loaded.");
03006 } else if (!strcasecmp(loadtype, "unload")) {
03007 res = ast_unload_resource(module, AST_FORCE_SOFT);
03008 if (res)
03009 astman_send_error(s, m, "Could not unload module.");
03010 else
03011 astman_send_ack(s, m, "Module unloaded.");
03012 } else if (!strcasecmp(loadtype, "reload")) {
03013 if (module != NULL) {
03014 res = ast_module_reload(module);
03015 if (res == 0)
03016 astman_send_error(s, m, "No such module.");
03017 else if (res == 1)
03018 astman_send_error(s, m, "Module does not support reload action.");
03019 else
03020 astman_send_ack(s, m, "Module reloaded.");
03021 } else {
03022 ast_module_reload(NULL);
03023 astman_send_ack(s, m, "All modules reloaded");
03024 }
03025 } else
03026 astman_send_error(s, m, "Incomplete ModuleLoad action.");
03027 return 0;
03028 }
03029
03030
03031
03032
03033
03034
03035
03036
03037
03038
03039
03040
03041
03042
03043 static int process_message(struct mansession *s, const struct message *m)
03044 {
03045 char action[80] = "";
03046 int ret = 0;
03047 struct manager_action *tmp;
03048 const char *user = astman_get_header(m, "Username");
03049
03050 ast_copy_string(action, __astman_get_header(m, "Action", GET_HEADER_SKIP_EMPTY), sizeof(action));
03051 ast_debug(1, "Manager received command '%s'\n", action);
03052
03053 if (ast_strlen_zero(action)) {
03054 ast_mutex_lock(&s->session->__lock);
03055 astman_send_error(s, m, "Missing action in request");
03056 ast_mutex_unlock(&s->session->__lock);
03057 return 0;
03058 }
03059
03060 if (!s->session->authenticated && strcasecmp(action, "Login") && strcasecmp(action, "Logoff") && strcasecmp(action, "Challenge")) {
03061 ast_mutex_lock(&s->session->__lock);
03062 astman_send_error(s, m, "Permission denied");
03063 ast_mutex_unlock(&s->session->__lock);
03064 return 0;
03065 }
03066
03067 if (!allowmultiplelogin && !s->session->authenticated && user &&
03068 (!strcasecmp(action, "Login") || !strcasecmp(action, "Challenge"))) {
03069 if (check_manager_session_inuse(user)) {
03070 sleep(1);
03071 ast_mutex_lock(&s->session->__lock);
03072 astman_send_error(s, m, "Login Already In Use");
03073 ast_mutex_unlock(&s->session->__lock);
03074 return -1;
03075 }
03076 }
03077
03078 AST_RWLIST_RDLOCK(&actions);
03079 AST_RWLIST_TRAVERSE(&actions, tmp, list) {
03080 if (strcasecmp(action, tmp->action))
03081 continue;
03082 if (s->session->writeperm & tmp->authority || tmp->authority == 0)
03083 ret = tmp->func(s, m);
03084 else
03085 astman_send_error(s, m, "Permission denied");
03086 break;
03087 }
03088 AST_RWLIST_UNLOCK(&actions);
03089
03090 if (!tmp) {
03091 char buf[512];
03092 snprintf(buf, sizeof(buf), "Invalid/unknown command: %s. Use Action: ListCommands to show available commands.", action);
03093 ast_mutex_lock(&s->session->__lock);
03094 astman_send_error(s, m, buf);
03095 ast_mutex_unlock(&s->session->__lock);
03096 }
03097 if (ret)
03098 return ret;
03099
03100
03101
03102 if (ast_strlen_zero(astman_get_header(m, "SuppressEvents"))) {
03103 return process_events(s);
03104 } else {
03105 return ret;
03106 }
03107 }
03108
03109
03110
03111
03112
03113
03114
03115
03116
03117
03118 static int get_input(struct mansession *s, char *output)
03119 {
03120 int res, x;
03121 int maxlen = sizeof(s->session->inbuf) - 1;
03122 char *src = s->session->inbuf;
03123
03124
03125
03126
03127
03128 for (x = 0; x < s->session->inlen; x++) {
03129 int cr;
03130 if (src[x] == '\r' && x+1 < s->session->inlen && src[x+1] == '\n')
03131 cr = 2;
03132 else if (src[x] == '\n')
03133 cr = 1;
03134 else
03135 continue;
03136 memmove(output, src, x);
03137 output[x] = '\0';
03138 x += cr;
03139 s->session->inlen -= x;
03140 memmove(src, src + x, s->session->inlen);
03141 return 1;
03142 }
03143 if (s->session->inlen >= maxlen) {
03144
03145 ast_log(LOG_WARNING, "Dumping long line with no return from %s: %s\n", ast_inet_ntoa(s->session->sin.sin_addr), src);
03146 s->session->inlen = 0;
03147 }
03148 res = 0;
03149 while (res == 0) {
03150
03151 ast_mutex_lock(&s->session->__lock);
03152 if (s->session->pending_event) {
03153 s->session->pending_event = 0;
03154 ast_mutex_unlock(&s->session->__lock);
03155 return 0;
03156 }
03157 s->session->waiting_thread = pthread_self();
03158 ast_mutex_unlock(&s->session->__lock);
03159
03160 res = ast_wait_for_input(s->session->fd, -1);
03161
03162 ast_mutex_lock(&s->session->__lock);
03163 s->session->waiting_thread = AST_PTHREADT_NULL;
03164 ast_mutex_unlock(&s->session->__lock);
03165 }
03166 if (res < 0) {
03167
03168
03169
03170 if (errno == EINTR || errno == EAGAIN)
03171 return 0;
03172 ast_log(LOG_WARNING, "poll() returned error: %s\n", strerror(errno));
03173 return -1;
03174 }
03175 ast_mutex_lock(&s->session->__lock);
03176 res = fread(src + s->session->inlen, 1, maxlen - s->session->inlen, s->session->f);
03177 if (res < 1)
03178 res = -1;
03179 else {
03180 s->session->inlen += res;
03181 src[s->session->inlen] = '\0';
03182 res = 0;
03183 }
03184 ast_mutex_unlock(&s->session->__lock);
03185 return res;
03186 }
03187
03188 static int do_message(struct mansession *s)
03189 {
03190 struct message m = { 0 };
03191 char header_buf[sizeof(s->session->inbuf)] = { '\0' };
03192 int res;
03193
03194 for (;;) {
03195
03196 if (process_events(s))
03197 return -1;
03198 res = get_input(s, header_buf);
03199 if (res == 0) {
03200 continue;
03201 } else if (res > 0) {
03202 if (ast_strlen_zero(header_buf))
03203 return process_message(s, &m) ? -1 : 0;
03204 else if (m.hdrcount < (AST_MAX_MANHEADERS - 1))
03205 m.headers[m.hdrcount++] = ast_strdupa(header_buf);
03206 } else {
03207 return res;
03208 }
03209 }
03210 }
03211
03212
03213
03214
03215
03216
03217
03218
03219
03220 static void *session_do(void *data)
03221 {
03222 struct ast_tcptls_session_instance *ser = data;
03223 struct mansession_session *session = ast_calloc(1, sizeof(*session));
03224 struct mansession s = {.session = NULL, };
03225 int flags;
03226 int res;
03227 struct protoent *p;
03228
03229 if (session == NULL)
03230 goto done;
03231
03232
03233
03234
03235 p = getprotobyname("tcp");
03236 if (p) {
03237 int arg = 1;
03238 if( setsockopt(ser->fd, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
03239 ast_log(LOG_WARNING, "Failed to set manager tcp connection to TCP_NODELAY mode: %s\nSome manager actions may be slow to respond.\n", strerror(errno));
03240 }
03241 } else {
03242 ast_log(LOG_WARNING, "Failed to set manager tcp connection to TCP_NODELAY, getprotobyname(\"tcp\") failed\nSome manager actions may be slow to respond.\n");
03243 }
03244
03245 session->writetimeout = 100;
03246 session->waiting_thread = AST_PTHREADT_NULL;
03247
03248 flags = fcntl(ser->fd, F_GETFL);
03249 if (!block_sockets)
03250 flags |= O_NONBLOCK;
03251 else
03252 flags &= ~O_NONBLOCK;
03253 fcntl(ser->fd, F_SETFL, flags);
03254
03255 ast_mutex_init(&session->__lock);
03256 session->send_events = -1;
03257
03258 session->last_ev = grab_last();
03259
03260
03261 session->fd = ser->fd;
03262 session->f = ser->f;
03263 session->sin = ser->remote_address;
03264 s.session = session;
03265
03266 AST_LIST_HEAD_INIT_NOLOCK(&session->datastores);
03267
03268 AST_LIST_LOCK(&sessions);
03269 AST_LIST_INSERT_HEAD(&sessions, session, list);
03270 ast_atomic_fetchadd_int(&num_sessions, 1);
03271 AST_LIST_UNLOCK(&sessions);
03272
03273 astman_append(&s, "Asterisk Call Manager/%s\r\n", AMI_VERSION);
03274 for (;;) {
03275 if ((res = do_message(&s)) < 0)
03276 break;
03277 }
03278
03279 if (session->authenticated) {
03280 if (manager_displayconnects(session))
03281 ast_verb(2, "Manager '%s' logged off from %s\n", session->username, ast_inet_ntoa(session->sin.sin_addr));
03282 ast_log(LOG_EVENT, "Manager '%s' logged off from %s\n", session->username, ast_inet_ntoa(session->sin.sin_addr));
03283 } else {
03284 if (displayconnects)
03285 ast_verb(2, "Connect attempt from '%s' unable to authenticate\n", ast_inet_ntoa(session->sin.sin_addr));
03286 ast_log(LOG_EVENT, "Failed attempt from %s\n", ast_inet_ntoa(session->sin.sin_addr));
03287 }
03288
03289 destroy_session(session);
03290
03291 done:
03292 ao2_ref(ser, -1);
03293 ser = NULL;
03294 return NULL;
03295 }
03296
03297
03298 static void purge_sessions(int n_max)
03299 {
03300 struct mansession_session *session;
03301 time_t now = time(NULL);
03302
03303 AST_LIST_LOCK(&sessions);
03304 AST_LIST_TRAVERSE_SAFE_BEGIN(&sessions, session, list) {
03305 if (session->sessiontimeout && (now > session->sessiontimeout) && !session->inuse) {
03306 AST_LIST_REMOVE_CURRENT(list);
03307 ast_atomic_fetchadd_int(&num_sessions, -1);
03308 if (session->authenticated && (VERBOSITY_ATLEAST(2)) && manager_displayconnects(session)) {
03309 ast_verb(2, "HTTP Manager '%s' timed out from %s\n",
03310 session->username, ast_inet_ntoa(session->sin.sin_addr));
03311 }
03312 free_session(session);
03313 if (--n_max <= 0)
03314 break;
03315 }
03316 }
03317 AST_LIST_TRAVERSE_SAFE_END;
03318 AST_LIST_UNLOCK(&sessions);
03319 }
03320
03321
03322
03323
03324
03325 static int append_event(const char *str, int category)
03326 {
03327 struct eventqent *tmp = ast_malloc(sizeof(*tmp) + strlen(str));
03328 static int seq;
03329
03330 if (!tmp)
03331 return -1;
03332
03333
03334 tmp->usecount = 0;
03335 tmp->category = category;
03336 tmp->seq = ast_atomic_fetchadd_int(&seq, 1);
03337 tmp->tv = ast_tvnow();
03338 AST_RWLIST_NEXT(tmp, eq_next) = NULL;
03339 strcpy(tmp->eventdata, str);
03340
03341 AST_RWLIST_WRLOCK(&all_events);
03342 AST_RWLIST_INSERT_TAIL(&all_events, tmp, eq_next);
03343 AST_RWLIST_UNLOCK(&all_events);
03344
03345 return 0;
03346 }
03347
03348
03349 AST_THREADSTORAGE(manager_event_buf);
03350 #define MANAGER_EVENT_BUF_INITSIZE 256
03351
03352
03353 int __manager_event(int category, const char *event,
03354 const char *file, int line, const char *func, const char *fmt, ...)
03355 {
03356 struct mansession_session *session;
03357 struct manager_custom_hook *hook;
03358 struct ast_str *auth = ast_str_alloca(80);
03359 const char *cat_str;
03360 va_list ap;
03361 struct timeval now;
03362 struct ast_str *buf;
03363
03364
03365 if (!num_sessions && AST_RWLIST_EMPTY(&manager_hooks))
03366 return 0;
03367
03368 if (!(buf = ast_str_thread_get(&manager_event_buf, MANAGER_EVENT_BUF_INITSIZE)))
03369 return -1;
03370
03371 cat_str = authority_to_str(category, &auth);
03372 ast_str_set(&buf, 0,
03373 "Event: %s\r\nPrivilege: %s\r\n",
03374 event, cat_str);
03375
03376 if (timestampevents) {
03377 now = ast_tvnow();
03378 ast_str_append(&buf, 0,
03379 "Timestamp: %ld.%06lu\r\n",
03380 (long)now.tv_sec, (unsigned long) now.tv_usec);
03381 }
03382 if (manager_debug) {
03383 static int seq;
03384 ast_str_append(&buf, 0,
03385 "SequenceNumber: %d\r\n",
03386 ast_atomic_fetchadd_int(&seq, 1));
03387 ast_str_append(&buf, 0,
03388 "File: %s\r\nLine: %d\r\nFunc: %s\r\n", file, line, func);
03389 }
03390
03391 va_start(ap, fmt);
03392 ast_str_append_va(&buf, 0, fmt, ap);
03393 va_end(ap);
03394
03395 ast_str_append(&buf, 0, "\r\n");
03396
03397 append_event(ast_str_buffer(buf), category);
03398
03399 if (num_sessions) {
03400
03401 AST_LIST_LOCK(&sessions);
03402 AST_LIST_TRAVERSE(&sessions, session, list) {
03403 ast_mutex_lock(&session->__lock);
03404 if (session->waiting_thread != AST_PTHREADT_NULL)
03405 pthread_kill(session->waiting_thread, SIGURG);
03406 else
03407
03408
03409
03410
03411
03412 session->pending_event = 1;
03413 ast_mutex_unlock(&session->__lock);
03414 }
03415 AST_LIST_UNLOCK(&sessions);
03416 }
03417
03418 if (!AST_RWLIST_EMPTY(&manager_hooks)) {
03419 AST_RWLIST_RDLOCK(&manager_hooks);
03420 AST_RWLIST_TRAVERSE(&manager_hooks, hook, list) {
03421 hook->helper(category, event, ast_str_buffer(buf));
03422 }
03423 AST_RWLIST_UNLOCK(&manager_hooks);
03424 }
03425
03426 return 0;
03427 }
03428
03429
03430
03431
03432 int ast_manager_unregister(char *action)
03433 {
03434 struct manager_action *cur;
03435 struct timespec tv = { 5, };
03436
03437 if (AST_RWLIST_TIMEDWRLOCK(&actions, &tv)) {
03438 ast_log(LOG_ERROR, "Could not obtain lock on manager list\n");
03439 return -1;
03440 }
03441 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&actions, cur, list) {
03442 if (!strcasecmp(action, cur->action)) {
03443 AST_RWLIST_REMOVE_CURRENT(list);
03444 ast_free(cur);
03445 ast_verb(2, "Manager unregistered action %s\n", action);
03446 break;
03447 }
03448 }
03449 AST_RWLIST_TRAVERSE_SAFE_END;
03450 AST_RWLIST_UNLOCK(&actions);
03451
03452 return 0;
03453 }
03454
03455 static int manager_state_cb(char *context, char *exten, int state, void *data)
03456 {
03457
03458 char hint[512];
03459 ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten);
03460
03461 manager_event(EVENT_FLAG_CALL, "ExtensionStatus", "Exten: %s\r\nContext: %s\r\nHint: %s\r\nStatus: %d\r\n", exten, context, hint, state);
03462 return 0;
03463 }
03464
03465 static int ast_manager_register_struct(struct manager_action *act)
03466 {
03467 struct manager_action *cur, *prev = NULL;
03468 struct timespec tv = { 5, };
03469
03470 if (AST_RWLIST_TIMEDWRLOCK(&actions, &tv)) {
03471 ast_log(LOG_ERROR, "Could not obtain lock on manager list\n");
03472 return -1;
03473 }
03474 AST_RWLIST_TRAVERSE(&actions, cur, list) {
03475 int ret = strcasecmp(cur->action, act->action);
03476 if (ret == 0) {
03477 ast_log(LOG_WARNING, "Manager: Action '%s' already registered\n", act->action);
03478 AST_RWLIST_UNLOCK(&actions);
03479 return -1;
03480 }
03481 if (ret > 0) {
03482 prev = cur;
03483 break;
03484 }
03485 }
03486
03487 if (prev)
03488 AST_RWLIST_INSERT_AFTER(&actions, prev, act, list);
03489 else
03490 AST_RWLIST_INSERT_HEAD(&actions, act, list);
03491
03492 ast_verb(2, "Manager registered action %s\n", act->action);
03493
03494 AST_RWLIST_UNLOCK(&actions);
03495
03496 return 0;
03497 }
03498
03499
03500
03501 int ast_manager_register2(const char *action, int auth, int (*func)(struct mansession *s, const struct message *m), const char *synopsis, const char *description)
03502 {
03503 struct manager_action *cur = NULL;
03504
03505 if (!(cur = ast_calloc(1, sizeof(*cur))))
03506 return -1;
03507
03508 cur->action = action;
03509 cur->authority = auth;
03510 cur->func = func;
03511 cur->synopsis = synopsis;
03512 cur->description = description;
03513
03514 if (ast_manager_register_struct(cur)) {
03515 ast_free(cur);
03516 return -1;
03517 }
03518
03519 return 0;
03520 }
03521
03522
03523
03524
03525
03526
03527
03528
03529
03530
03531
03532
03533
03534
03535
03536 enum output_format {
03537 FORMAT_RAW,
03538 FORMAT_HTML,
03539 FORMAT_XML,
03540 };
03541
03542 static char *contenttype[] = {
03543 [FORMAT_RAW] = "plain",
03544 [FORMAT_HTML] = "html",
03545 [FORMAT_XML] = "xml",
03546 };
03547
03548
03549
03550
03551
03552
03553 static struct mansession_session *find_session(uint32_t ident, int incinuse)
03554 {
03555 struct mansession_session *session;
03556
03557 if (ident == 0)
03558 return NULL;
03559
03560 AST_LIST_LOCK(&sessions);
03561 AST_LIST_TRAVERSE(&sessions, session, list) {
03562 ast_mutex_lock(&session->__lock);
03563 if (session->managerid == ident && !session->needdestroy) {
03564 ast_atomic_fetchadd_int(&session->inuse, incinuse ? 1 : 0);
03565 break;
03566 }
03567 ast_mutex_unlock(&session->__lock);
03568 }
03569 AST_LIST_UNLOCK(&sessions);
03570
03571 return session;
03572 }
03573
03574 int astman_is_authed(uint32_t ident)
03575 {
03576 int authed;
03577 struct mansession_session *session;
03578
03579 if (!(session = find_session(ident, 0)))
03580 return 0;
03581
03582 authed = (session->authenticated != 0);
03583
03584 ast_mutex_unlock(&session->__lock);
03585
03586 return authed;
03587 }
03588
03589 int astman_verify_session_readpermissions(uint32_t ident, int perm)
03590 {
03591 int result = 0;
03592 struct mansession_session *session;
03593
03594 AST_LIST_LOCK(&sessions);
03595 AST_LIST_TRAVERSE(&sessions, session, list) {
03596 ast_mutex_lock(&session->__lock);
03597 if ((session->managerid == ident) && (session->readperm & perm)) {
03598 result = 1;
03599 ast_mutex_unlock(&session->__lock);
03600 break;
03601 }
03602 ast_mutex_unlock(&session->__lock);
03603 }
03604 AST_LIST_UNLOCK(&sessions);
03605 return result;
03606 }
03607
03608 int astman_verify_session_writepermissions(uint32_t ident, int perm)
03609 {
03610 int result = 0;
03611 struct mansession_session *session;
03612
03613 AST_LIST_LOCK(&sessions);
03614 AST_LIST_TRAVERSE(&sessions, session, list) {
03615 ast_mutex_lock(&session->__lock);
03616 if ((session->managerid == ident) && (session->writeperm & perm)) {
03617 result = 1;
03618 ast_mutex_unlock(&session->__lock);
03619 break;
03620 }
03621 ast_mutex_unlock(&session->__lock);
03622 }
03623 AST_LIST_UNLOCK(&sessions);
03624 return result;
03625 }
03626
03627
03628
03629
03630
03631
03632 static void xml_copy_escape(struct ast_str **out, const char *src, int mode)
03633 {
03634
03635 char buf[256];
03636 char *dst = buf;
03637 int space = sizeof(buf);
03638
03639 for ( ; *src || dst != buf ; src++) {
03640 if (*src == '\0' || space < 10) {
03641 *dst++ = '\0';
03642 ast_str_append(out, 0, "%s", buf);
03643 dst = buf;
03644 space = sizeof(buf);
03645 if (*src == '\0')
03646 break;
03647 }
03648
03649 if ( (mode & 2) && !isalnum(*src)) {
03650 *dst++ = '_';
03651 space--;
03652 continue;
03653 }
03654 switch (*src) {
03655 case '<':
03656 strcpy(dst, "<");
03657 dst += 4;
03658 space -= 4;
03659 break;
03660 case '>':
03661 strcpy(dst, ">");
03662 dst += 4;
03663 space -= 4;
03664 break;
03665 case '\"':
03666 strcpy(dst, """);
03667 dst += 6;
03668 space -= 6;
03669 break;
03670 case '\'':
03671 strcpy(dst, "'");
03672 dst += 6;
03673 space -= 6;
03674 break;
03675 case '&':
03676 strcpy(dst, "&");
03677 dst += 5;
03678 space -= 5;
03679 break;
03680
03681 default:
03682 *dst++ = mode ? tolower(*src) : *src;
03683 space--;
03684 }
03685 }
03686 }
03687
03688 struct variable_count {
03689 char *varname;
03690 int count;
03691 };
03692
03693 static int compress_char(char c)
03694 {
03695 c &= 0x7f;
03696 if (c < 32)
03697 return 0;
03698 else if (c >= 'a' && c <= 'z')
03699 return c - 64;
03700 else if (c > 'z')
03701 return '_';
03702 else
03703 return c - 32;
03704 }
03705
03706 static int variable_count_hash_fn(const void *vvc, const int flags)
03707 {
03708 const struct variable_count *vc = vvc;
03709 int res = 0, i;
03710 for (i = 0; i < 5; i++) {
03711 if (vc->varname[i] == '\0')
03712 break;
03713 res += compress_char(vc->varname[i]) << (i * 6);
03714 }
03715 return res;
03716 }
03717
03718 static int variable_count_cmp_fn(void *obj, void *vstr, int flags)
03719 {
03720
03721
03722
03723
03724 struct variable_count *vc = obj;
03725 char *str = vstr;
03726 return !strcmp(vc->varname, str) ? CMP_MATCH | CMP_STOP : 0;
03727 }
03728
03729
03730
03731
03732
03733
03734
03735
03736
03737
03738
03739
03740
03741
03742
03743
03744
03745
03746
03747
03748
03749
03750
03751
03752
03753
03754
03755
03756
03757 static void xml_translate(struct ast_str **out, char *in, struct ast_variable *vars, enum output_format format)
03758 {
03759 struct ast_variable *v;
03760 const char *dest = NULL;
03761 char *var, *val;
03762 const char *objtype = NULL;
03763 int in_data = 0;
03764 int inobj = 0;
03765 int xml = (format == FORMAT_XML);
03766 struct variable_count *vc = NULL;
03767 struct ao2_container *vco = NULL;
03768
03769 for (v = vars; v; v = v->next) {
03770 if (!dest && !strcasecmp(v->name, "ajaxdest"))
03771 dest = v->value;
03772 else if (!objtype && !strcasecmp(v->name, "ajaxobjtype"))
03773 objtype = v->value;
03774 }
03775 if (!dest)
03776 dest = "unknown";
03777 if (!objtype)
03778 objtype = "generic";
03779
03780
03781 while (in && *in) {
03782 val = strsep(&in, "\r\n");
03783 if (in && *in == '\n')
03784 in++;
03785 ast_trim_blanks(val);
03786 ast_debug(5, "inobj %d in_data %d line <%s>\n", inobj, in_data, val);
03787 if (ast_strlen_zero(val)) {
03788 if (in_data) {
03789 ast_str_append(out, 0, xml ? "'" : "</td></tr>\n");
03790 in_data = 0;
03791 }
03792 if (inobj) {
03793 ast_str_append(out, 0, xml ? " /></response>\n" :
03794 "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
03795 inobj = 0;
03796 ao2_ref(vco, -1);
03797 vco = NULL;
03798 }
03799 continue;
03800 }
03801
03802
03803 if (in_data) {
03804 var = NULL;
03805 } else {
03806 var = strsep(&val, ":");
03807 if (val) {
03808 val = ast_skip_blanks(val);
03809 ast_trim_blanks(var);
03810 } else {
03811 val = var;
03812 var = "Opaque-data";
03813 }
03814 }
03815
03816 if (!inobj) {
03817 if (xml)
03818 ast_str_append(out, 0, "<response type='object' id='%s'><%s", dest, objtype);
03819 else
03820 ast_str_append(out, 0, "<body>\n");
03821 vco = ao2_container_alloc(37, variable_count_hash_fn, variable_count_cmp_fn);
03822 inobj = 1;
03823 }
03824
03825 if (!in_data) {
03826 ast_str_append(out, 0, xml ? " " : "<tr><td>");
03827 if ((vc = ao2_find(vco, var, 0)))
03828 vc->count++;
03829 else {
03830
03831 vc = ao2_alloc(sizeof(*vc), NULL);
03832 vc->varname = var;
03833 vc->count = 1;
03834 ao2_link(vco, vc);
03835 }
03836 xml_copy_escape(out, var, xml ? 1 | 2 : 0);
03837 if (vc->count > 1)
03838 ast_str_append(out, 0, "-%d", vc->count);
03839 ao2_ref(vc, -1);
03840 ast_str_append(out, 0, xml ? "='" : "</td><td>");
03841 if (!strcmp(var, "Opaque-data"))
03842 in_data = 1;
03843 }
03844 xml_copy_escape(out, val, 0);
03845 if (!in_data)
03846 ast_str_append(out, 0, xml ? "'" : "</td></tr>\n");
03847 else
03848 ast_str_append(out, 0, xml ? "\n" : "<br>\n");
03849 }
03850 if (inobj) {
03851 ast_str_append(out, 0, xml ? " /></response>\n" :
03852 "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
03853 ao2_ref(vco, -1);
03854 }
03855 }
03856
03857 static struct ast_str *generic_http_callback(enum output_format format,
03858 struct sockaddr_in *remote_address, const char *uri, enum ast_http_method method,
03859 struct ast_variable *params, int *status,
03860 char **title, int *contentlength)
03861 {
03862 struct mansession s = {.session = NULL, };
03863 struct mansession_session *session = NULL;
03864 uint32_t ident = 0;
03865 int blastaway = 0;
03866 struct ast_variable *v;
03867 char template[] = "/tmp/ast-http-XXXXXX";
03868 struct ast_str *out = NULL;
03869 struct message m = { 0 };
03870 unsigned int x;
03871 size_t hdrlen;
03872
03873 for (v = params; v; v = v->next) {
03874 if (!strcasecmp(v->name, "mansession_id")) {
03875 sscanf(v->value, "%30x", &ident);
03876 break;
03877 }
03878 }
03879
03880 if (!(session = find_session(ident, 1))) {
03881
03882
03883
03884 if (!(session = ast_calloc(1, sizeof(*session)))) {
03885 *status = 500;
03886 goto generic_callback_out;
03887 }
03888 session->sin = *remote_address;
03889 session->fd = -1;
03890 session->waiting_thread = AST_PTHREADT_NULL;
03891 session->send_events = 0;
03892 ast_mutex_init(&session->__lock);
03893 ast_mutex_lock(&session->__lock);
03894 session->inuse = 1;
03895
03896
03897
03898
03899
03900 while ((session->managerid = ast_random() ^ (unsigned long) session) == 0);
03901 session->last_ev = grab_last();
03902 AST_LIST_HEAD_INIT_NOLOCK(&session->datastores);
03903 AST_LIST_LOCK(&sessions);
03904 AST_LIST_INSERT_HEAD(&sessions, session, list);
03905 ast_atomic_fetchadd_int(&num_sessions, 1);
03906 AST_LIST_UNLOCK(&sessions);
03907 }
03908
03909 s.session = session;
03910
03911 ast_mutex_unlock(&session->__lock);
03912
03913 if (!(out = ast_str_create(1024))) {
03914 *status = 500;
03915 goto generic_callback_out;
03916 }
03917
03918 s.fd = mkstemp(template);
03919 unlink(template);
03920 s.f = fdopen(s.fd, "w+");
03921
03922 for (x = 0, v = params; v && (x < AST_MAX_MANHEADERS); x++, v = v->next) {
03923 hdrlen = strlen(v->name) + strlen(v->value) + 3;
03924 m.headers[m.hdrcount] = alloca(hdrlen);
03925 snprintf((char *) m.headers[m.hdrcount], hdrlen, "%s: %s", v->name, v->value);
03926 ast_verb(4, "HTTP Manager add header %s\n", m.headers[m.hdrcount]);
03927 m.hdrcount = x + 1;
03928 }
03929
03930 if (process_message(&s, &m)) {
03931 if (session->authenticated) {
03932 if (manager_displayconnects(session)) {
03933 ast_verb(2, "HTTP Manager '%s' logged off from %s\n", session->username, ast_inet_ntoa(session->sin.sin_addr));
03934 }
03935 ast_log(LOG_EVENT, "HTTP Manager '%s' logged off from %s\n", session->username, ast_inet_ntoa(session->sin.sin_addr));
03936 } else {
03937 if (displayconnects) {
03938 ast_verb(2, "HTTP Connect attempt from '%s' unable to authenticate\n", ast_inet_ntoa(session->sin.sin_addr));
03939 }
03940 ast_log(LOG_EVENT, "HTTP Failed attempt from %s\n", ast_inet_ntoa(session->sin.sin_addr));
03941 }
03942 session->needdestroy = 1;
03943 }
03944
03945 ast_str_append(&out, 0,
03946 "Content-type: text/%s\r\n"
03947 "Cache-Control: no-cache;\r\n"
03948 "Set-Cookie: mansession_id=\"%08x\"; Version=1; Max-Age=%d\r\n"
03949 "Pragma: SuppressEvents\r\n"
03950 "\r\n",
03951 contenttype[format],
03952 session->managerid, httptimeout);
03953
03954 if (format == FORMAT_XML) {
03955 ast_str_append(&out, 0, "<ajax-response>\n");
03956 } else if (format == FORMAT_HTML) {
03957
03958
03959
03960
03961
03962
03963 #define ROW_FMT "<tr><td colspan=\"2\" bgcolor=\"#f1f1ff\">%s</td></tr>\r\n"
03964 #define TEST_STRING \
03965 "<form action=\"manager\">\n\
03966 Action: <select name=\"action\">\n\
03967 <option value=\"\">-----></option>\n\
03968 <option value=\"login\">login</option>\n\
03969 <option value=\"command\">Command</option>\n\
03970 <option value=\"waitevent\">waitevent</option>\n\
03971 <option value=\"listcommands\">listcommands</option>\n\
03972 </select>\n\
03973 or <input name=\"action\"><br/>\n\
03974 CLI Command <input name=\"command\"><br>\n\
03975 user <input name=\"username\"> pass <input type=\"password\" name=\"secret\"><br>\n\
03976 <input type=\"submit\">\n</form>\n"
03977
03978 ast_str_append(&out, 0, "<title>Asterisk™ Manager Interface</title>");
03979 ast_str_append(&out, 0, "<body bgcolor=\"#ffffff\"><table align=center bgcolor=\"#f1f1f1\" width=\"500\">\r\n");
03980 ast_str_append(&out, 0, ROW_FMT, "<h1>Manager Tester</h1>");
03981 ast_str_append(&out, 0, ROW_FMT, TEST_STRING);
03982 }
03983
03984 if (s.f != NULL) {
03985 char *buf;
03986 size_t l;
03987
03988 if ((l = ftell(s.f))) {
03989 if (MAP_FAILED == (buf = mmap(NULL, l + 1, PROT_READ | PROT_WRITE, MAP_PRIVATE, s.fd, 0))) {
03990 ast_log(LOG_WARNING, "mmap failed. Manager output was not processed\n");
03991 } else {
03992 buf[l] = '\0';
03993 if (format == FORMAT_XML || format == FORMAT_HTML) {
03994 xml_translate(&out, buf, params, format);
03995 } else {
03996 ast_str_append(&out, 0, "%s", buf);
03997 }
03998 munmap(buf, l + 1);
03999 }
04000 } else if (format == FORMAT_XML || format == FORMAT_HTML) {
04001 xml_translate(&out, "", params, format);
04002 }
04003 fclose(s.f);
04004 s.f = NULL;
04005 s.fd = -1;
04006 }
04007
04008 if (format == FORMAT_XML) {
04009 ast_str_append(&out, 0, "</ajax-response>\n");
04010 } else if (format == FORMAT_HTML)
04011 ast_str_append(&out, 0, "</table></body>\r\n");
04012
04013 ast_mutex_lock(&session->__lock);
04014
04015 session->sessiontimeout = time(NULL) + ((session->authenticated || httptimeout < 5) ? httptimeout : 5);
04016
04017 if (session->needdestroy) {
04018 if (session->inuse == 1) {
04019 ast_debug(1, "Need destroy, doing it now!\n");
04020 blastaway = 1;
04021 } else {
04022 ast_debug(1, "Need destroy, but can't do it yet!\n");
04023 if (session->waiting_thread != AST_PTHREADT_NULL)
04024 pthread_kill(session->waiting_thread, SIGURG);
04025 session->inuse--;
04026 }
04027 } else
04028 session->inuse--;
04029 ast_mutex_unlock(&session->__lock);
04030
04031 if (blastaway)
04032 destroy_session(session);
04033 generic_callback_out:
04034 if (*status != 200)
04035 return ast_http_error(500, "Server Error", NULL, "Internal Server Error (out of memory)\n");
04036 return out;
04037 }
04038
04039 static struct ast_str *manager_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *params, struct ast_variable *headers, int *status, char **title, int *contentlength)
04040 {
04041 return generic_http_callback(FORMAT_HTML, &ser->remote_address, uri, method, params, status, title, contentlength);
04042 }
04043
04044 static struct ast_str *mxml_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *params, struct ast_variable *headers, int *status, char **title, int *contentlength)
04045 {
04046 return generic_http_callback(FORMAT_XML, &ser->remote_address, uri, method, params, status, title, contentlength);
04047 }
04048
04049 static struct ast_str *rawman_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *params, struct ast_variable *headers, int *status, char **title, int *contentlength)
04050 {
04051 return generic_http_callback(FORMAT_RAW, &ser->remote_address, uri, method, params, status, title, contentlength);
04052 }
04053
04054 struct ast_http_uri rawmanuri = {
04055 .description = "Raw HTTP Manager Event Interface",
04056 .uri = "rawman",
04057 .callback = rawman_http_callback,
04058 .supports_get = 1,
04059 .data = NULL,
04060 .key = __FILE__,
04061 };
04062
04063 struct ast_http_uri manageruri = {
04064 .description = "HTML Manager Event Interface",
04065 .uri = "manager",
04066 .callback = manager_http_callback,
04067 .supports_get = 1,
04068 .data = NULL,
04069 .key = __FILE__,
04070 };
04071
04072 struct ast_http_uri managerxmluri = {
04073 .description = "XML Manager Event Interface",
04074 .uri = "mxml",
04075 .callback = mxml_http_callback,
04076 .supports_get = 1,
04077 .data = NULL,
04078 .key = __FILE__,
04079 };
04080
04081 static int registered = 0;
04082 static int webregged = 0;
04083
04084
04085
04086
04087 static void purge_old_stuff(void *data)
04088 {
04089 purge_sessions(1);
04090 purge_events();
04091 }
04092
04093 struct ast_tls_config ami_tls_cfg;
04094 static struct ast_tcptls_session_args ami_desc = {
04095 .accept_fd = -1,
04096 .master = AST_PTHREADT_NULL,
04097 .tls_cfg = NULL,
04098 .poll_timeout = 5000,
04099 .periodic_fn = purge_old_stuff,
04100 .name = "AMI server",
04101 .accept_fn = ast_tcptls_server_root,
04102 .worker_fn = session_do,
04103 };
04104
04105 static struct ast_tcptls_session_args amis_desc = {
04106 .accept_fd = -1,
04107 .master = AST_PTHREADT_NULL,
04108 .tls_cfg = &ami_tls_cfg,
04109 .poll_timeout = -1,
04110 .name = "AMI TLS server",
04111 .accept_fn = ast_tcptls_server_root,
04112 .worker_fn = session_do,
04113 };
04114
04115 static int __init_manager(int reload)
04116 {
04117 struct ast_config *ucfg = NULL, *cfg = NULL;
04118 const char *val;
04119 char *cat = NULL;
04120 int newhttptimeout = DEFAULT_HTTPTIMEOUT;
04121 int have_sslbindaddr = 0;
04122 struct hostent *hp;
04123 struct ast_hostent ahp;
04124 struct ast_manager_user *user = NULL;
04125 struct ast_variable *var;
04126 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
04127
04128 if (!registered) {
04129
04130 ast_manager_register2("Ping", 0, action_ping, "Keepalive command", mandescr_ping);
04131 ast_manager_register2("Events", 0, action_events, "Control Event Flow", mandescr_events);
04132 ast_manager_register2("Logoff", 0, action_logoff, "Logoff Manager", mandescr_logoff);
04133 ast_manager_register2("Login", 0, action_login, "Login Manager", NULL);
04134 ast_manager_register2("Challenge", 0, action_challenge, "Generate Challenge for MD5 Auth", NULL);
04135 ast_manager_register2("Hangup", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL, action_hangup, "Hangup Channel", mandescr_hangup);
04136 ast_manager_register2("Status", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_status, "Lists channel status", mandescr_status);
04137 ast_manager_register2("Setvar", EVENT_FLAG_CALL, action_setvar, "Set Channel Variable", mandescr_setvar);
04138 ast_manager_register2("Getvar", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_getvar, "Gets a Channel Variable", mandescr_getvar);
04139 ast_manager_register2("GetConfig", EVENT_FLAG_SYSTEM | EVENT_FLAG_CONFIG, action_getconfig, "Retrieve configuration", mandescr_getconfig);
04140 ast_manager_register2("GetConfigJSON", EVENT_FLAG_SYSTEM | EVENT_FLAG_CONFIG, action_getconfigjson, "Retrieve configuration (JSON format)", mandescr_getconfigjson);
04141 ast_manager_register2("UpdateConfig", EVENT_FLAG_CONFIG, action_updateconfig, "Update basic configuration", mandescr_updateconfig);
04142 ast_manager_register2("CreateConfig", EVENT_FLAG_CONFIG, action_createconfig, "Creates an empty file in the configuration directory", mandescr_createconfig);
04143 ast_manager_register2("ListCategories", EVENT_FLAG_CONFIG, action_listcategories, "List categories in configuration file", mandescr_listcategories);
04144 ast_manager_register2("Redirect", EVENT_FLAG_CALL, action_redirect, "Redirect (transfer) a call", mandescr_redirect );
04145 ast_manager_register2("Atxfer", EVENT_FLAG_CALL, action_atxfer, "Attended transfer", mandescr_atxfer);
04146 ast_manager_register2("Originate", EVENT_FLAG_ORIGINATE, action_originate, "Originate Call", mandescr_originate);
04147 ast_manager_register2("Command", EVENT_FLAG_COMMAND, action_command, "Execute Asterisk CLI Command", mandescr_command );
04148 ast_manager_register2("ExtensionState", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_extensionstate, "Check Extension Status", mandescr_extensionstate );
04149 ast_manager_register2("AbsoluteTimeout", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL, action_timeout, "Set Absolute Timeout", mandescr_timeout );
04150 ast_manager_register2("MailboxStatus", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_mailboxstatus, "Check Mailbox", mandescr_mailboxstatus );
04151 ast_manager_register2("MailboxCount", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_mailboxcount, "Check Mailbox Message Count", mandescr_mailboxcount );
04152 ast_manager_register2("ListCommands", 0, action_listcommands, "List available manager commands", mandescr_listcommands);
04153 ast_manager_register2("SendText", EVENT_FLAG_CALL, action_sendtext, "Send text message to channel", mandescr_sendtext);
04154 ast_manager_register2("UserEvent", EVENT_FLAG_USER, action_userevent, "Send an arbitrary event", mandescr_userevent);
04155 ast_manager_register2("WaitEvent", 0, action_waitevent, "Wait for an event to occur", mandescr_waitevent);
04156 ast_manager_register2("CoreSettings", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_coresettings, "Show PBX core settings (version etc)", mandescr_coresettings);
04157 ast_manager_register2("CoreStatus", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_corestatus, "Show PBX core status variables", mandescr_corestatus);
04158 ast_manager_register2("Reload", EVENT_FLAG_CONFIG | EVENT_FLAG_SYSTEM, action_reload, "Send a reload event", mandescr_reload);
04159 ast_manager_register2("CoreShowChannels", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_coreshowchannels, "List currently active channels", mandescr_coreshowchannels);
04160 ast_manager_register2("ModuleLoad", EVENT_FLAG_SYSTEM, manager_moduleload, "Module management", mandescr_moduleload);
04161 ast_manager_register2("ModuleCheck", EVENT_FLAG_SYSTEM, manager_modulecheck, "Check if module is loaded", mandescr_modulecheck);
04162
04163 ast_cli_register_multiple(cli_manager, ARRAY_LEN(cli_manager));
04164 ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
04165 registered = 1;
04166
04167 append_event("Event: Placeholder\r\n\r\n", 0);
04168 }
04169 if ((cfg = ast_config_load2("manager.conf", "manager", config_flags)) == CONFIG_STATUS_FILEUNCHANGED)
04170 return 0;
04171
04172 manager_enabled = DEFAULT_ENABLED;
04173 webmanager_enabled = DEFAULT_WEBENABLED;
04174 displayconnects = DEFAULT_DISPLAYCONNECTS;
04175 broken_events_action = DEFAULT_BROKENEVENTSACTION;
04176 block_sockets = DEFAULT_BLOCKSOCKETS;
04177 timestampevents = DEFAULT_TIMESTAMPEVENTS;
04178 httptimeout = DEFAULT_HTTPTIMEOUT;
04179
04180 if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
04181 ast_log(LOG_NOTICE, "Unable to open AMI configuration manager.conf, or configuration is invalid. Asterisk management interface (AMI) disabled.\n");
04182 return 0;
04183 }
04184
04185
04186 memset(&ami_desc.local_address, 0, sizeof(struct sockaddr_in));
04187 memset(&amis_desc.local_address, 0, sizeof(amis_desc.local_address));
04188 amis_desc.local_address.sin_port = htons(5039);
04189 ami_desc.local_address.sin_port = htons(DEFAULT_MANAGER_PORT);
04190
04191 ami_tls_cfg.enabled = 0;
04192 if (ami_tls_cfg.certfile)
04193 ast_free(ami_tls_cfg.certfile);
04194 ami_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
04195 if (ami_tls_cfg.cipher)
04196 ast_free(ami_tls_cfg.cipher);
04197 ami_tls_cfg.cipher = ast_strdup("");
04198
04199 for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
04200 val = var->value;
04201 if (!strcasecmp(var->name, "sslenable"))
04202 ami_tls_cfg.enabled = ast_true(val);
04203 else if (!strcasecmp(var->name, "sslbindport"))
04204 amis_desc.local_address.sin_port = htons(atoi(val));
04205 else if (!strcasecmp(var->name, "sslbindaddr")) {
04206 if ((hp = ast_gethostbyname(val, &ahp))) {
04207 memcpy(&amis_desc.local_address.sin_addr, hp->h_addr, sizeof(amis_desc.local_address.sin_addr));
04208 have_sslbindaddr = 1;
04209 } else {
04210 ast_log(LOG_WARNING, "Invalid bind address '%s'\n", val);
04211 }
04212 } else if (!strcasecmp(var->name, "sslcert")) {
04213 ast_free(ami_tls_cfg.certfile);
04214 ami_tls_cfg.certfile = ast_strdup(val);
04215 } else if (!strcasecmp(var->name, "sslcipher")) {
04216 ast_free(ami_tls_cfg.cipher);
04217 ami_tls_cfg.cipher = ast_strdup(val);
04218 } else if (!strcasecmp(var->name, "enabled")) {
04219 manager_enabled = ast_true(val);
04220 } else if (!strcasecmp(var->name, "block-sockets")) {
04221 block_sockets = ast_true(val);
04222 } else if (!strcasecmp(var->name, "webenabled")) {
04223 webmanager_enabled = ast_true(val);
04224 } else if (!strcasecmp(var->name, "port")) {
04225 ami_desc.local_address.sin_port = htons(atoi(val));
04226 } else if (!strcasecmp(var->name, "bindaddr")) {
04227 if (!inet_aton(val, &ami_desc.local_address.sin_addr)) {
04228 ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
04229 memset(&ami_desc.local_address.sin_addr, 0, sizeof(ami_desc.local_address.sin_addr));
04230 }
04231 } else if (!strcasecmp(var->name, "brokeneventsaction")) {
04232 broken_events_action = ast_true(val);
04233 } else if (!strcasecmp(var->name, "allowmultiplelogin")) {
04234 allowmultiplelogin = ast_true(val);
04235 } else if (!strcasecmp(var->name, "displayconnects")) {
04236 displayconnects = ast_true(val);
04237 } else if (!strcasecmp(var->name, "timestampevents")) {
04238 timestampevents = ast_true(val);
04239 } else if (!strcasecmp(var->name, "debug")) {
04240 manager_debug = ast_true(val);
04241 } else if (!strcasecmp(var->name, "httptimeout")) {
04242 newhttptimeout = atoi(val);
04243 } else {
04244 ast_log(LOG_NOTICE, "Invalid keyword <%s> = <%s> in manager.conf [general]\n",
04245 var->name, val);
04246 }
04247 }
04248
04249 if (manager_enabled)
04250 ami_desc.local_address.sin_family = AF_INET;
04251 if (!have_sslbindaddr)
04252 amis_desc.local_address.sin_addr = ami_desc.local_address.sin_addr;
04253 if (ami_tls_cfg.enabled)
04254 amis_desc.local_address.sin_family = AF_INET;
04255
04256
04257 AST_RWLIST_WRLOCK(&users);
04258
04259
04260 ucfg = ast_config_load2("users.conf", "manager", config_flags);
04261 if (ucfg && (ucfg != CONFIG_STATUS_FILEUNCHANGED) && ucfg != CONFIG_STATUS_FILEINVALID) {
04262 const char *hasmanager;
04263 int genhasmanager = ast_true(ast_variable_retrieve(ucfg, "general", "hasmanager"));
04264
04265 while ((cat = ast_category_browse(ucfg, cat))) {
04266 if (!strcasecmp(cat, "general"))
04267 continue;
04268
04269 hasmanager = ast_variable_retrieve(ucfg, cat, "hasmanager");
04270 if ((!hasmanager && genhasmanager) || ast_true(hasmanager)) {
04271 const char *user_secret = ast_variable_retrieve(ucfg, cat, "secret");
04272 const char *user_read = ast_variable_retrieve(ucfg, cat, "read");
04273 const char *user_write = ast_variable_retrieve(ucfg, cat, "write");
04274 const char *user_displayconnects = ast_variable_retrieve(ucfg, cat, "displayconnects");
04275 const char *user_writetimeout = ast_variable_retrieve(ucfg, cat, "writetimeout");
04276
04277
04278
04279
04280 if (!(user = get_manager_by_name_locked(cat))) {
04281 if (!(user = ast_calloc(1, sizeof(*user))))
04282 break;
04283
04284
04285 ast_copy_string(user->username, cat, sizeof(user->username));
04286
04287 AST_LIST_INSERT_TAIL(&users, user, list);
04288 user->ha = NULL;
04289 user->keep = 1;
04290 user->readperm = -1;
04291 user->writeperm = -1;
04292
04293 user->displayconnects = displayconnects;
04294 user->writetimeout = 100;
04295 }
04296
04297 if (!user_secret)
04298 user_secret = ast_variable_retrieve(ucfg, "general", "secret");
04299 if (!user_read)
04300 user_read = ast_variable_retrieve(ucfg, "general", "read");
04301 if (!user_write)
04302 user_write = ast_variable_retrieve(ucfg, "general", "write");
04303 if (!user_displayconnects)
04304 user_displayconnects = ast_variable_retrieve(ucfg, "general", "displayconnects");
04305 if (!user_writetimeout)
04306 user_writetimeout = ast_variable_retrieve(ucfg, "general", "writetimeout");
04307
04308 if (!ast_strlen_zero(user_secret)) {
04309 if (user->secret)
04310 ast_free(user->secret);
04311 user->secret = ast_strdup(user_secret);
04312 }
04313
04314 if (user_read)
04315 user->readperm = get_perm(user_read);
04316 if (user_write)
04317 user->writeperm = get_perm(user_write);
04318 if (user_displayconnects)
04319 user->displayconnects = ast_true(user_displayconnects);
04320
04321 if (user_writetimeout) {
04322 int value = atoi(user_writetimeout);
04323 if (value < 100)
04324 ast_log(LOG_WARNING, "Invalid writetimeout value '%s' at users.conf line %d\n", var->value, var->lineno);
04325 else
04326 user->writetimeout = value;
04327 }
04328 }
04329 }
04330 ast_config_destroy(ucfg);
04331 }
04332
04333
04334
04335 while ((cat = ast_category_browse(cfg, cat))) {
04336 struct ast_ha *oldha;
04337
04338 if (!strcasecmp(cat, "general"))
04339 continue;
04340
04341
04342 if (!(user = get_manager_by_name_locked(cat))) {
04343 if (!(user = ast_calloc(1, sizeof(*user))))
04344 break;
04345
04346 ast_copy_string(user->username, cat, sizeof(user->username));
04347
04348 user->ha = NULL;
04349 user->readperm = 0;
04350 user->writeperm = 0;
04351
04352 user->displayconnects = displayconnects;
04353 user->writetimeout = 100;
04354
04355
04356 AST_RWLIST_INSERT_TAIL(&users, user, list);
04357 }
04358
04359
04360 user->keep = 1;
04361 oldha = user->ha;
04362 user->ha = NULL;
04363
04364 var = ast_variable_browse(cfg, cat);
04365 for (; var; var = var->next) {
04366 if (!strcasecmp(var->name, "secret")) {
04367 if (user->secret)
04368 ast_free(user->secret);
04369 user->secret = ast_strdup(var->value);
04370 } else if (!strcasecmp(var->name, "deny") ||
04371 !strcasecmp(var->name, "permit")) {
04372 user->ha = ast_append_ha(var->name, var->value, user->ha, NULL);
04373 } else if (!strcasecmp(var->name, "read") ) {
04374 user->readperm = get_perm(var->value);
04375 } else if (!strcasecmp(var->name, "write") ) {
04376 user->writeperm = get_perm(var->value);
04377 } else if (!strcasecmp(var->name, "displayconnects") ) {
04378 user->displayconnects = ast_true(var->value);
04379 } else if (!strcasecmp(var->name, "writetimeout")) {
04380 int value = atoi(var->value);
04381 if (value < 100)
04382 ast_log(LOG_WARNING, "Invalid writetimeout value '%s' at line %d\n", var->value, var->lineno);
04383 else
04384 user->writetimeout = value;
04385 } else
04386 ast_debug(1, "%s is an unknown option.\n", var->name);
04387 }
04388 ast_free_ha(oldha);
04389 }
04390 ast_config_destroy(cfg);
04391
04392
04393 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&users, user, list) {
04394 if (user->keep) {
04395 user->keep = 0;
04396 continue;
04397 }
04398
04399 AST_RWLIST_REMOVE_CURRENT(list);
04400
04401 if (user->secret)
04402 ast_free(user->secret);
04403 ast_free_ha(user->ha);
04404 ast_free(user);
04405 }
04406 AST_RWLIST_TRAVERSE_SAFE_END;
04407
04408 AST_RWLIST_UNLOCK(&users);
04409
04410 if (webmanager_enabled && manager_enabled) {
04411 if (!webregged) {
04412 ast_http_uri_link(&rawmanuri);
04413 ast_http_uri_link(&manageruri);
04414 ast_http_uri_link(&managerxmluri);
04415 webregged = 1;
04416 }
04417 } else {
04418 if (webregged) {
04419 ast_http_uri_unlink(&rawmanuri);
04420 ast_http_uri_unlink(&manageruri);
04421 ast_http_uri_unlink(&managerxmluri);
04422 webregged = 0;
04423 }
04424 }
04425
04426 if (newhttptimeout > 0)
04427 httptimeout = newhttptimeout;
04428
04429 manager_event(EVENT_FLAG_SYSTEM, "Reload", "Module: Manager\r\nStatus: %s\r\nMessage: Manager reload Requested\r\n", manager_enabled ? "Enabled" : "Disabled");
04430
04431 ast_tcptls_server_start(&ami_desc);
04432 if (ast_ssl_setup(amis_desc.tls_cfg))
04433 ast_tcptls_server_start(&amis_desc);
04434 return 0;
04435 }
04436
04437 int init_manager(void)
04438 {
04439 return __init_manager(0);
04440 }
04441
04442 int reload_manager(void)
04443 {
04444 return __init_manager(1);
04445 }
04446
04447 int astman_datastore_add(struct mansession *s, struct ast_datastore *datastore)
04448 {
04449 AST_LIST_INSERT_HEAD(&s->session->datastores, datastore, entry);
04450
04451 return 0;
04452 }
04453
04454 int astman_datastore_remove(struct mansession *s, struct ast_datastore *datastore)
04455 {
04456 return AST_LIST_REMOVE(&s->session->datastores, datastore, entry) ? 0 : -1;
04457 }
04458
04459 struct ast_datastore *astman_datastore_find(struct mansession *s, const struct ast_datastore_info *info, const char *uid)
04460 {
04461 struct ast_datastore *datastore = NULL;
04462
04463 if (info == NULL)
04464 return NULL;
04465
04466 AST_LIST_TRAVERSE_SAFE_BEGIN(&s->session->datastores, datastore, entry) {
04467 if (datastore->info != info) {
04468 continue;
04469 }
04470
04471 if (uid == NULL) {
04472
04473 break;
04474 }
04475
04476 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
04477
04478 break;
04479 }
04480 }
04481 AST_LIST_TRAVERSE_SAFE_END;
04482
04483 return datastore;
04484 }