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