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 #include "asterisk.h"
00036
00037 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
00038
00039 #include <stdio.h>
00040 #include <stdlib.h>
00041 #include <string.h>
00042 #include <ctype.h>
00043 #include <sys/time.h>
00044 #include <sys/types.h>
00045 #include <netdb.h>
00046 #include <sys/socket.h>
00047 #include <netinet/in.h>
00048 #include <netinet/tcp.h>
00049 #include <arpa/inet.h>
00050 #include <signal.h>
00051 #include <errno.h>
00052 #include <unistd.h>
00053
00054 #include "asterisk/channel.h"
00055 #include "asterisk/file.h"
00056 #include "asterisk/manager.h"
00057 #include "asterisk/config.h"
00058 #include "asterisk/callerid.h"
00059 #include "asterisk/lock.h"
00060 #include "asterisk/logger.h"
00061 #include "asterisk/options.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/http.h"
00069 #include "asterisk/threadstorage.h"
00070 #include "asterisk/linkedlists.h"
00071 #include "asterisk/term.h"
00072 #include "asterisk/astobj2.h"
00073
00074 struct fast_originate_helper {
00075 char tech[AST_MAX_EXTENSION];
00076
00077 char data[512];
00078 int timeout;
00079 int format;
00080 char app[AST_MAX_APP];
00081 char appdata[AST_MAX_EXTENSION];
00082 char cid_name[AST_MAX_EXTENSION];
00083 char cid_num[AST_MAX_EXTENSION];
00084 char context[AST_MAX_CONTEXT];
00085 char exten[AST_MAX_EXTENSION];
00086 char idtext[AST_MAX_EXTENSION];
00087 char account[AST_MAX_ACCOUNT_CODE];
00088 int priority;
00089 struct ast_variable *vars;
00090 };
00091
00092 struct eventqent {
00093 int usecount;
00094 int category;
00095 struct eventqent *next;
00096 char eventdata[1];
00097 };
00098
00099 static int enabled;
00100 static int portno = DEFAULT_MANAGER_PORT;
00101 static int asock = -1;
00102 static int displayconnects = 1;
00103 static int timestampevents;
00104 static int httptimeout = 60;
00105
00106 static pthread_t t;
00107 static int block_sockets;
00108 static int num_sessions;
00109
00110
00111 struct eventqent *master_eventq = NULL;
00112
00113 AST_THREADSTORAGE(manager_event_buf, manager_event_buf_init);
00114 #define MANAGER_EVENT_BUF_INITSIZE 256
00115
00116 AST_THREADSTORAGE(astman_append_buf, astman_append_buf_init);
00117 #define ASTMAN_APPEND_BUF_INITSIZE 256
00118
00119 static struct permalias {
00120 int num;
00121 char *label;
00122 } perms[] = {
00123 { EVENT_FLAG_SYSTEM, "system" },
00124 { EVENT_FLAG_CALL, "call" },
00125 { EVENT_FLAG_LOG, "log" },
00126 { EVENT_FLAG_VERBOSE, "verbose" },
00127 { EVENT_FLAG_COMMAND, "command" },
00128 { EVENT_FLAG_AGENT, "agent" },
00129 { EVENT_FLAG_USER, "user" },
00130 { EVENT_FLAG_CONFIG, "config" },
00131 { -1, "all" },
00132 { 0, "none" },
00133 };
00134
00135 #define MAX_BLACKLIST_CMD_LEN 2
00136 static struct {
00137 char *words[AST_MAX_CMD_LEN];
00138 } command_blacklist[] = {
00139 {{ "module", "load", NULL }},
00140 {{ "module", "unload", NULL }},
00141 {{ "restart", "gracefully", NULL }},
00142 };
00143
00144 struct mansession {
00145
00146 pthread_t t;
00147
00148 ast_mutex_t __lock;
00149
00150 struct sockaddr_in sin;
00151
00152 int fd;
00153
00154 int inuse;
00155
00156 int needdestroy;
00157
00158 pthread_t waiting_thread;
00159
00160 uint32_t managerid;
00161
00162 time_t sessiontimeout;
00163
00164 struct ast_dynamic_str *outputstr;
00165
00166 char username[80];
00167
00168 char challenge[10];
00169
00170 int authenticated;
00171
00172 int readperm;
00173
00174 int writeperm;
00175
00176 char inbuf[1024];
00177 int inlen;
00178 int send_events;
00179 int displaysystemname;
00180
00181 struct eventqent *eventq;
00182
00183 int writetimeout;
00184 int pending_event;
00185 AST_LIST_ENTRY(mansession) list;
00186 };
00187
00188 static AST_LIST_HEAD_STATIC(sessions, mansession);
00189
00190 struct ast_manager_user {
00191 char username[80];
00192 char *secret;
00193 char *deny;
00194 char *permit;
00195 char *read;
00196 char *write;
00197 unsigned int displayconnects:1;
00198 int keep;
00199 AST_LIST_ENTRY(ast_manager_user) list;
00200 };
00201
00202 static AST_LIST_HEAD_STATIC(users, ast_manager_user);
00203
00204 static struct manager_action *first_action;
00205 AST_RWLOCK_DEFINE_STATIC(actionlock);
00206
00207
00208 static char *authority_to_str(int authority, char *res, int reslen)
00209 {
00210 int running_total = 0, i;
00211
00212 memset(res, 0, reslen);
00213 for (i = 0; i < (sizeof(perms) / sizeof(perms[0])) - 1; i++) {
00214 if (authority & perms[i].num) {
00215 if (*res) {
00216 strncat(res, ",", (reslen > running_total) ? reslen - running_total - 1 : 0);
00217 running_total++;
00218 }
00219 strncat(res, perms[i].label, (reslen > running_total) ? reslen - running_total - 1 : 0);
00220 running_total += strlen(perms[i].label);
00221 }
00222 }
00223
00224 if (ast_strlen_zero(res))
00225 ast_copy_string(res, "<none>", reslen);
00226
00227 return res;
00228 }
00229
00230 static char *complete_show_mancmd(const char *line, const char *word, int pos, int state)
00231 {
00232 struct manager_action *cur;
00233 int which = 0;
00234 char *ret = NULL;
00235
00236 ast_rwlock_rdlock(&actionlock);
00237 for (cur = first_action; cur; cur = cur->next) {
00238 if (!strncasecmp(word, cur->action, strlen(word)) && ++which > state) {
00239 ret = ast_strdup(cur->action);
00240 break;
00241 }
00242 }
00243 ast_rwlock_unlock(&actionlock);
00244
00245 return ret;
00246 }
00247
00248 static void xml_copy_escape(char **dst, size_t *maxlen, const char *src, int lower)
00249 {
00250 while (*src && (*maxlen > 6)) {
00251 switch (*src) {
00252 case '<':
00253 strcpy(*dst, "<");
00254 (*dst) += 4;
00255 *maxlen -= 4;
00256 break;
00257 case '>':
00258 strcpy(*dst, ">");
00259 (*dst) += 4;
00260 *maxlen -= 4;
00261 break;
00262 case '\"':
00263 strcpy(*dst, """);
00264 (*dst) += 6;
00265 *maxlen -= 6;
00266 break;
00267 case '\'':
00268 strcpy(*dst, "'");
00269 (*dst) += 6;
00270 *maxlen -= 6;
00271 break;
00272 case '&':
00273 strcpy(*dst, "&");
00274 (*dst) += 5;
00275 *maxlen -= 5;
00276 break;
00277 default:
00278 *(*dst)++ = lower ? tolower(*src) : *src;
00279 (*maxlen)--;
00280 }
00281 src++;
00282 }
00283 }
00284
00285 struct variable_count {
00286 char *varname;
00287 int count;
00288 };
00289
00290 static int compress_char(char c)
00291 {
00292 c &= 0x7f;
00293 if (c < 32)
00294 return 0;
00295 else if (c >= 'a' && c <= 'z')
00296 return c - 64;
00297 else if (c > 'z')
00298 return '_';
00299 else
00300 return c - 32;
00301 }
00302
00303 static int variable_count_hash_fn(const void *vvc, const int flags)
00304 {
00305 const struct variable_count *vc = vvc;
00306 int res = 0, i;
00307 for (i = 0; i < 5; i++) {
00308 if (vc->varname[i] == '\0')
00309 break;
00310 res += compress_char(vc->varname[i]) << (i * 6);
00311 }
00312 return res;
00313 }
00314
00315 static int variable_count_cmp_fn(void *obj, void *vstr, int flags)
00316 {
00317
00318
00319
00320
00321 struct variable_count *vc = obj;
00322 char *str = vstr;
00323 return !strcmp(vc->varname, str) ? CMP_MATCH | CMP_STOP : 0;
00324 }
00325
00326 static char *xml_translate(char *in, struct ast_variable *vars)
00327 {
00328 struct ast_variable *v;
00329 char *dest = NULL;
00330 char *out, *tmp, *var, *val;
00331 char *objtype = NULL;
00332 int colons = 0;
00333 int breaks = 0;
00334 size_t len;
00335 int count = 1;
00336 int escaped = 0;
00337 int inobj = 0;
00338 int x;
00339 struct variable_count *vc = NULL;
00340 struct ao2_container *vco = NULL;
00341
00342 for (v = vars; v; v = v->next) {
00343 if (!dest && !strcasecmp(v->name, "ajaxdest"))
00344 dest = v->value;
00345 else if (!objtype && !strcasecmp(v->name, "ajaxobjtype"))
00346 objtype = v->value;
00347 }
00348 if (!dest)
00349 dest = "unknown";
00350 if (!objtype)
00351 objtype = "generic";
00352 for (x = 0; in[x]; x++) {
00353 if (in[x] == ':')
00354 colons++;
00355 else if (in[x] == '\n')
00356 breaks++;
00357 else if (strchr("&\"<>\'", in[x]))
00358 escaped++;
00359 }
00360 len = (size_t) (strlen(in) + colons * 5 + breaks * (40 + strlen(dest) + strlen(objtype)) + escaped * 10);
00361 out = ast_malloc(len);
00362 if (!out)
00363 return 0;
00364 tmp = out;
00365 while (*in) {
00366 var = in;
00367 while (*in && (*in >= 32))
00368 in++;
00369 if (*in) {
00370 if ((count > 3) && inobj) {
00371 ast_build_string(&tmp, &len, " /></response>\n");
00372 inobj = 0;
00373
00374
00375 ao2_ref(vco, -1);
00376 vco = NULL;
00377 }
00378 count = 0;
00379 while (*in && (*in < 32)) {
00380 *in = '\0';
00381 in++;
00382 count++;
00383 }
00384 val = strchr(var, ':');
00385 if (val) {
00386 *val = '\0';
00387 val++;
00388 if (*val == ' ')
00389 val++;
00390 if (!inobj) {
00391 vco = ao2_container_alloc(37, variable_count_hash_fn, variable_count_cmp_fn);
00392 ast_build_string(&tmp, &len, "<response type='object' id='%s'><%s", dest, objtype);
00393 inobj = 1;
00394 }
00395
00396
00397 if ((vc = ao2_find(vco, var, 0)))
00398 vc->count++;
00399 else {
00400
00401 vc = ao2_alloc(sizeof(*vc), NULL);
00402 vc->varname = var;
00403 vc->count = 1;
00404 ao2_link(vco, vc);
00405 }
00406
00407 ast_build_string(&tmp, &len, " ");
00408 xml_copy_escape(&tmp, &len, var, 1);
00409 if (vc->count > 1)
00410 ast_build_string(&tmp, &len, "-%d", vc->count);
00411 ast_build_string(&tmp, &len, "='");
00412 xml_copy_escape(&tmp, &len, val, 0);
00413 ast_build_string(&tmp, &len, "'");
00414 ao2_ref(vc, -1);
00415 }
00416 }
00417 }
00418 if (inobj)
00419 ast_build_string(&tmp, &len, " /></response>\n");
00420 if (vco)
00421 ao2_ref(vco, -1);
00422 return out;
00423 }
00424
00425 static char *html_translate(char *in)
00426 {
00427 int x;
00428 int colons = 0;
00429 int breaks = 0;
00430 size_t len;
00431 int count = 1;
00432 char *tmp, *var, *val, *out;
00433
00434 for (x=0; in[x]; x++) {
00435 if (in[x] == ':')
00436 colons++;
00437 if (in[x] == '\n')
00438 breaks++;
00439 }
00440 len = strlen(in) + colons * 40 + breaks * 40;
00441 out = ast_malloc(len);
00442 if (!out)
00443 return 0;
00444 tmp = out;
00445 while (*in) {
00446 var = in;
00447 while (*in && (*in >= 32))
00448 in++;
00449 if (*in) {
00450 if ((count % 4) == 0){
00451 ast_build_string(&tmp, &len, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
00452 }
00453 count = 0;
00454 while (*in && (*in < 32)) {
00455 *in = '\0';
00456 in++;
00457 count++;
00458 }
00459 val = strchr(var, ':');
00460 if (val) {
00461 *val = '\0';
00462 val++;
00463 if (*val == ' ')
00464 val++;
00465 ast_build_string(&tmp, &len, "<tr><td>%s</td><td>%s</td></tr>\r\n", var, val);
00466 }
00467 }
00468 }
00469 return out;
00470 }
00471
00472
00473
00474 static struct ast_manager_user *ast_get_manager_by_name_locked(const char *name)
00475 {
00476 struct ast_manager_user *user = NULL;
00477
00478 AST_LIST_TRAVERSE(&users, user, list)
00479 if (!strcasecmp(user->username, name))
00480 break;
00481 return user;
00482 }
00483
00484 void astman_append(struct mansession *s, const char *fmt, ...)
00485 {
00486 va_list ap;
00487 struct ast_dynamic_str *buf;
00488
00489 ast_mutex_lock(&s->__lock);
00490
00491 if (!(buf = ast_dynamic_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
00492 ast_mutex_unlock(&s->__lock);
00493 return;
00494 }
00495
00496 va_start(ap, fmt);
00497 ast_dynamic_str_thread_set_va(&buf, 0, &astman_append_buf, fmt, ap);
00498 va_end(ap);
00499
00500 if (s->fd > -1)
00501 ast_carefulwrite(s->fd, buf->str, strlen(buf->str), s->writetimeout);
00502 else {
00503 if (!s->outputstr && !(s->outputstr = ast_calloc(1, sizeof(*s->outputstr)))) {
00504 ast_mutex_unlock(&s->__lock);
00505 return;
00506 }
00507
00508 ast_dynamic_str_append(&s->outputstr, 0, "%s", buf->str);
00509 }
00510
00511 ast_mutex_unlock(&s->__lock);
00512 }
00513
00514 static int handle_showmancmd(int fd, int argc, char *argv[])
00515 {
00516 struct manager_action *cur;
00517 char authority[80];
00518 int num;
00519
00520 if (argc != 4)
00521 return RESULT_SHOWUSAGE;
00522
00523 ast_rwlock_rdlock(&actionlock);
00524 for (cur = first_action; cur; cur = cur->next) {
00525 for (num = 3; num < argc; num++) {
00526 if (!strcasecmp(cur->action, argv[num])) {
00527 ast_cli(fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n", cur->action, cur->synopsis, authority_to_str(cur->authority, authority, sizeof(authority) -1), cur->description ? cur->description : "");
00528 }
00529 }
00530 }
00531 ast_rwlock_unlock(&actionlock);
00532
00533 return RESULT_SUCCESS;
00534 }
00535
00536 static int handle_showmanager(int fd, int argc, char *argv[])
00537 {
00538 struct ast_manager_user *user = NULL;
00539
00540 if (argc != 4)
00541 return RESULT_SHOWUSAGE;
00542
00543 AST_LIST_LOCK(&users);
00544
00545 if (!(user = ast_get_manager_by_name_locked(argv[3]))) {
00546 ast_cli(fd, "There is no manager called %s\n", argv[3]);
00547 AST_LIST_UNLOCK(&users);
00548 return -1;
00549 }
00550
00551 ast_cli(fd,"\n");
00552 ast_cli(fd,
00553 " username: %s\n"
00554 " secret: %s\n"
00555 " deny: %s\n"
00556 " permit: %s\n"
00557 " read: %s\n"
00558 " write: %s\n"
00559 "displayconnects: %s\n",
00560 (user->username ? user->username : "(N/A)"),
00561 (user->secret ? "<Set>" : "(N/A)"),
00562 (user->deny ? user->deny : "(N/A)"),
00563 (user->permit ? user->permit : "(N/A)"),
00564 (user->read ? user->read : "(N/A)"),
00565 (user->write ? user->write : "(N/A)"),
00566 (user->displayconnects ? "yes" : "no"));
00567
00568 AST_LIST_UNLOCK(&users);
00569
00570 return RESULT_SUCCESS;
00571 }
00572
00573
00574 static int handle_showmanagers(int fd, int argc, char *argv[])
00575 {
00576 struct ast_manager_user *user = NULL;
00577 int count_amu = 0;
00578
00579 if (argc != 3)
00580 return RESULT_SHOWUSAGE;
00581
00582 AST_LIST_LOCK(&users);
00583
00584
00585 if (AST_LIST_EMPTY(&users)) {
00586 ast_cli(fd, "There are no manager users.\n");
00587 AST_LIST_UNLOCK(&users);
00588 return RESULT_SUCCESS;
00589 }
00590
00591 ast_cli(fd, "\nusername\n--------\n");
00592
00593 AST_LIST_TRAVERSE(&users, user, list) {
00594 ast_cli(fd, "%s\n", user->username);
00595 count_amu++;
00596 }
00597
00598 AST_LIST_UNLOCK(&users);
00599
00600 ast_cli(fd,"-------------------\n");
00601 ast_cli(fd,"%d manager users configured.\n", count_amu);
00602
00603 return RESULT_SUCCESS;
00604 }
00605
00606
00607
00608
00609 static int handle_showmancmds(int fd, int argc, char *argv[])
00610 {
00611 struct manager_action *cur;
00612 char authority[80];
00613 char *format = " %-15.15s %-15.15s %-55.55s\n";
00614
00615 ast_cli(fd, format, "Action", "Privilege", "Synopsis");
00616 ast_cli(fd, format, "------", "---------", "--------");
00617
00618 ast_rwlock_rdlock(&actionlock);
00619 for (cur = first_action; cur; cur = cur->next)
00620 ast_cli(fd, format, cur->action, authority_to_str(cur->authority, authority, sizeof(authority) -1), cur->synopsis);
00621 ast_rwlock_unlock(&actionlock);
00622
00623 return RESULT_SUCCESS;
00624 }
00625
00626
00627
00628 static int handle_showmanconn(int fd, int argc, char *argv[])
00629 {
00630 struct mansession *s;
00631 char *format = " %-15.15s %-15.15s\n";
00632
00633 ast_cli(fd, format, "Username", "IP Address");
00634
00635 AST_LIST_LOCK(&sessions);
00636 AST_LIST_TRAVERSE(&sessions, s, list)
00637 ast_cli(fd, format,s->username, ast_inet_ntoa(s->sin.sin_addr));
00638 AST_LIST_UNLOCK(&sessions);
00639
00640 return RESULT_SUCCESS;
00641 }
00642
00643
00644
00645 static int handle_showmaneventq(int fd, int argc, char *argv[])
00646 {
00647 struct eventqent *s;
00648
00649 AST_LIST_LOCK(&sessions);
00650 for (s = master_eventq; s; s = s->next) {
00651 ast_cli(fd, "Usecount: %d\n",s->usecount);
00652 ast_cli(fd, "Category: %d\n", s->category);
00653 ast_cli(fd, "Event:\n%s", s->eventdata);
00654 }
00655 AST_LIST_UNLOCK(&sessions);
00656
00657 return RESULT_SUCCESS;
00658 }
00659
00660 static char showmancmd_help[] =
00661 "Usage: manager show command <actionname>\n"
00662 " Shows the detailed description for a specific Asterisk manager interface command.\n";
00663
00664 static char showmancmds_help[] =
00665 "Usage: manager show commands\n"
00666 " Prints a listing of all the available Asterisk manager interface commands.\n";
00667
00668 static char showmanconn_help[] =
00669 "Usage: manager show connected\n"
00670 " Prints a listing of the users that are currently connected to the\n"
00671 "Asterisk manager interface.\n";
00672
00673 static char showmaneventq_help[] =
00674 "Usage: manager show eventq\n"
00675 " Prints a listing of all events pending in the Asterisk manger\n"
00676 "event queue.\n";
00677
00678 static char showmanagers_help[] =
00679 "Usage: manager show users\n"
00680 " Prints a listing of all managers that are currently configured on that\n"
00681 " system.\n";
00682
00683 static char showmanager_help[] =
00684 " Usage: manager show user <user>\n"
00685 " Display all information related to the manager user specified.\n";
00686
00687 static struct ast_cli_entry cli_show_manager_command_deprecated = {
00688 { "show", "manager", "command", NULL },
00689 handle_showmancmd, NULL,
00690 NULL, complete_show_mancmd };
00691
00692 static struct ast_cli_entry cli_show_manager_commands_deprecated = {
00693 { "show", "manager", "commands", NULL },
00694 handle_showmancmds, NULL,
00695 NULL };
00696
00697 static struct ast_cli_entry cli_show_manager_connected_deprecated = {
00698 { "show", "manager", "connected", NULL },
00699 handle_showmanconn, NULL,
00700 NULL };
00701
00702 static struct ast_cli_entry cli_show_manager_eventq_deprecated = {
00703 { "show", "manager", "eventq", NULL },
00704 handle_showmaneventq, NULL,
00705 NULL };
00706
00707 static struct ast_cli_entry cli_manager[] = {
00708 { { "manager", "show", "command", NULL },
00709 handle_showmancmd, "Show a manager interface command",
00710 showmancmd_help, complete_show_mancmd, &cli_show_manager_command_deprecated },
00711
00712 { { "manager", "show", "commands", NULL },
00713 handle_showmancmds, "List manager interface commands",
00714 showmancmds_help, NULL, &cli_show_manager_commands_deprecated },
00715
00716 { { "manager", "show", "connected", NULL },
00717 handle_showmanconn, "List connected manager interface users",
00718 showmanconn_help, NULL, &cli_show_manager_connected_deprecated },
00719
00720 { { "manager", "show", "eventq", NULL },
00721 handle_showmaneventq, "List manager interface queued events",
00722 showmaneventq_help, NULL, &cli_show_manager_eventq_deprecated },
00723
00724 { { "manager", "show", "users", NULL },
00725 handle_showmanagers, "List configured manager users",
00726 showmanagers_help, NULL, NULL },
00727
00728 { { "manager", "show", "user", NULL },
00729 handle_showmanager, "Display information on a specific manager user",
00730 showmanager_help, NULL, NULL },
00731 };
00732
00733 static void unuse_eventqent(struct eventqent *e)
00734 {
00735 if (ast_atomic_dec_and_test(&e->usecount) && e->next)
00736 pthread_kill(t, SIGURG);
00737 }
00738
00739 static void free_session(struct mansession *s)
00740 {
00741 struct eventqent *eqe;
00742 if (s->fd > -1)
00743 close(s->fd);
00744 if (s->outputstr)
00745 free(s->outputstr);
00746 ast_mutex_destroy(&s->__lock);
00747 while (s->eventq) {
00748 eqe = s->eventq;
00749 s->eventq = s->eventq->next;
00750 unuse_eventqent(eqe);
00751 }
00752 free(s);
00753 }
00754
00755 static void destroy_session(struct mansession *s)
00756 {
00757 AST_LIST_LOCK(&sessions);
00758 AST_LIST_REMOVE(&sessions, s, list);
00759 num_sessions--;
00760 free_session(s);
00761 AST_LIST_UNLOCK(&sessions);
00762 }
00763
00764 const char *astman_get_header(const struct message *m, char *var)
00765 {
00766 char cmp[80];
00767 int x;
00768
00769 snprintf(cmp, sizeof(cmp), "%s: ", var);
00770
00771 for (x = 0; x < m->hdrcount; x++) {
00772 if (!strncasecmp(cmp, m->headers[x], strlen(cmp)))
00773 return m->headers[x] + strlen(cmp);
00774 }
00775
00776 return "";
00777 }
00778
00779 struct ast_variable *astman_get_variables(const struct message *m)
00780 {
00781 int varlen, x, y;
00782 struct ast_variable *head = NULL, *cur;
00783 char *var, *val;
00784
00785 char *parse;
00786 AST_DECLARE_APP_ARGS(args,
00787 AST_APP_ARG(vars)[32];
00788 );
00789
00790 varlen = strlen("Variable: ");
00791
00792 for (x = 0; x < m->hdrcount; x++) {
00793 if (strncasecmp("Variable: ", m->headers[x], varlen))
00794 continue;
00795
00796 parse = ast_strdupa(m->headers[x] + varlen);
00797
00798 AST_STANDARD_APP_ARGS(args, parse);
00799 if (args.argc) {
00800 for (y = 0; y < args.argc; y++) {
00801 if (!args.vars[y])
00802 continue;
00803 var = val = ast_strdupa(args.vars[y]);
00804 strsep(&val, "=");
00805 if (!val || ast_strlen_zero(var))
00806 continue;
00807 cur = ast_variable_new(var, val);
00808 if (head) {
00809 cur->next = head;
00810 head = cur;
00811 } else
00812 head = cur;
00813 }
00814 }
00815 }
00816
00817 return head;
00818 }
00819
00820
00821
00822
00823
00824
00825
00826
00827
00828 void astman_send_error(struct mansession *s, const struct message *m, char *error)
00829 {
00830 const char *id = astman_get_header(m,"ActionID");
00831
00832 astman_append(s, "Response: Error\r\n");
00833 if (!ast_strlen_zero(id))
00834 astman_append(s, "ActionID: %s\r\n", id);
00835 astman_append(s, "Message: %s\r\n\r\n", error);
00836 }
00837
00838 void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
00839 {
00840 const char *id = astman_get_header(m,"ActionID");
00841
00842 astman_append(s, "Response: %s\r\n", resp);
00843 if (!ast_strlen_zero(id))
00844 astman_append(s, "ActionID: %s\r\n", id);
00845 if (msg)
00846 astman_append(s, "Message: %s\r\n\r\n", msg);
00847 else
00848 astman_append(s, "\r\n");
00849 }
00850
00851 void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
00852 {
00853 astman_send_response(s, m, "Success", msg);
00854 }
00855
00856
00857
00858
00859
00860
00861 static int ast_instring(const char *bigstr, const char *smallstr, char delim)
00862 {
00863 const char *val = bigstr, *next;
00864
00865 do {
00866 if ((next = strchr(val, delim))) {
00867 if (!strncmp(val, smallstr, (next - val)))
00868 return 1;
00869 else
00870 continue;
00871 } else
00872 return !strcmp(smallstr, val);
00873
00874 } while (*(val = (next + 1)));
00875
00876 return 0;
00877 }
00878
00879 static int get_perm(const char *instr)
00880 {
00881 int x = 0, ret = 0;
00882
00883 if (!instr)
00884 return 0;
00885
00886 for (x = 0; x < (sizeof(perms) / sizeof(perms[0])); x++) {
00887 if (ast_instring(instr, perms[x].label, ','))
00888 ret |= perms[x].num;
00889 }
00890
00891 return ret;
00892 }
00893
00894 static int ast_is_number(const char *string)
00895 {
00896 int ret = 1, x = 0;
00897
00898 if (!string)
00899 return 0;
00900
00901 for (x = 0; x < strlen(string); x++) {
00902 if (!(string[x] >= 48 && string[x] <= 57)) {
00903 ret = 0;
00904 break;
00905 }
00906 }
00907
00908 return ret ? atoi(string) : 0;
00909 }
00910
00911 static int strings_to_mask(const char *string)
00912 {
00913 int x, ret = -1;
00914
00915 x = ast_is_number(string);
00916
00917 if (x)
00918 ret = x;
00919 else if (ast_strlen_zero(string))
00920 ret = -1;
00921 else if (ast_false(string))
00922 ret = 0;
00923 else if (ast_true(string)) {
00924 ret = 0;
00925 for (x=0; x<sizeof(perms) / sizeof(perms[0]); x++)
00926 ret |= perms[x].num;
00927 } else {
00928 ret = 0;
00929 for (x=0; x<sizeof(perms) / sizeof(perms[0]); x++) {
00930 if (ast_instring(string, perms[x].label, ','))
00931 ret |= perms[x].num;
00932 }
00933 }
00934
00935 return ret;
00936 }
00937
00938
00939
00940
00941
00942 static int set_eventmask(struct mansession *s, const char *eventmask)
00943 {
00944 int maskint = strings_to_mask(eventmask);
00945
00946 ast_mutex_lock(&s->__lock);
00947 if (maskint >= 0)
00948 s->send_events = maskint;
00949 ast_mutex_unlock(&s->__lock);
00950
00951 return maskint;
00952 }
00953
00954 static int authenticate(struct mansession *s, const struct message *m)
00955 {
00956 struct ast_config *cfg;
00957 char *cat;
00958 const char *user = astman_get_header(m, "Username");
00959 const char *pass = astman_get_header(m, "Secret");
00960 const char *authtype = astman_get_header(m, "AuthType");
00961 const char *key = astman_get_header(m, "Key");
00962 const char *events = astman_get_header(m, "Events");
00963
00964 cfg = ast_config_load("manager.conf");
00965 if (!cfg)
00966 return -1;
00967 cat = ast_category_browse(cfg, NULL);
00968 while (cat) {
00969 if (strcasecmp(cat, "general")) {
00970
00971 if (!strcasecmp(cat, user)) {
00972 struct ast_variable *v;
00973 struct ast_ha *ha = NULL;
00974 char *password = NULL;
00975
00976 for (v = ast_variable_browse(cfg, cat); v; v = v->next) {
00977 if (!strcasecmp(v->name, "secret")) {
00978 password = v->value;
00979 } else if (!strcasecmp(v->name, "displaysystemname")) {
00980 if (ast_true(v->value)) {
00981 if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
00982 s->displaysystemname = 1;
00983 } else {
00984 ast_log(LOG_ERROR, "Can't enable displaysystemname in manager.conf - no system name configured in asterisk.conf\n");
00985 }
00986 }
00987 } else if (!strcasecmp(v->name, "permit") ||
00988 !strcasecmp(v->name, "deny")) {
00989 ha = ast_append_ha(v->name, v->value, ha);
00990 } else if (!strcasecmp(v->name, "writetimeout")) {
00991 int val = atoi(v->value);
00992
00993 if (val < 100)
00994 ast_log(LOG_WARNING, "Invalid writetimeout value '%s' at line %d\n", v->value, v->lineno);
00995 else
00996 s->writetimeout = val;
00997 }
00998
00999 }
01000 if (ha && !ast_apply_ha(ha, &(s->sin))) {
01001 ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_inet_ntoa(s->sin.sin_addr), user);
01002 ast_free_ha(ha);
01003 ast_config_destroy(cfg);
01004 return -1;
01005 } else if (ha)
01006 ast_free_ha(ha);
01007 if (!strcasecmp(authtype, "MD5")) {
01008 if (!ast_strlen_zero(key) &&
01009 !ast_strlen_zero(s->challenge) && !ast_strlen_zero(password)) {
01010 int x;
01011 int len = 0;
01012 char md5key[256] = "";
01013 struct MD5Context md5;
01014 unsigned char digest[16];
01015 MD5Init(&md5);
01016 MD5Update(&md5, (unsigned char *) s->challenge, strlen(s->challenge));
01017 MD5Update(&md5, (unsigned char *) password, strlen(password));
01018 MD5Final(digest, &md5);
01019 for (x=0; x<16; x++)
01020 len += sprintf(md5key + len, "%2.2x", digest[x]);
01021 if (!strcmp(md5key, key))
01022 break;
01023 else {
01024 ast_config_destroy(cfg);
01025 return -1;
01026 }
01027 } else {
01028 ast_log(LOG_DEBUG, "MD5 authentication is not possible. challenge: '%s'\n",
01029 S_OR(s->challenge, ""));
01030 ast_config_destroy(cfg);
01031 return -1;
01032 }
01033 } else if (password && !strcmp(password, pass)) {
01034 break;
01035 } else {
01036 ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_inet_ntoa(s->sin.sin_addr), user);
01037 ast_config_destroy(cfg);
01038 return -1;
01039 }
01040 }
01041 }
01042 cat = ast_category_browse(cfg, cat);
01043 }
01044 if (cat) {
01045 ast_copy_string(s->username, cat, sizeof(s->username));
01046 s->readperm = get_perm(ast_variable_retrieve(cfg, cat, "read"));
01047 s->writeperm = get_perm(ast_variable_retrieve(cfg, cat, "write"));
01048 ast_config_destroy(cfg);
01049 if (events)
01050 set_eventmask(s, events);
01051 return 0;
01052 }
01053 ast_config_destroy(cfg);
01054 cfg = ast_config_load("users.conf");
01055 if (!cfg)
01056 return -1;
01057 cat = ast_category_browse(cfg, NULL);
01058 while (cat) {
01059 struct ast_variable *v;
01060 const char *password = NULL;
01061 int hasmanager = 0;
01062 const char *readperms = NULL;
01063 const char *writeperms = NULL;
01064
01065 if (strcasecmp(cat, user) || !strcasecmp(cat, "general")) {
01066 cat = ast_category_browse(cfg, cat);
01067 continue;
01068 }
01069 for (v = ast_variable_browse(cfg, cat); v; v = v->next) {
01070 if (!strcasecmp(v->name, "secret"))
01071 password = v->value;
01072 else if (!strcasecmp(v->name, "hasmanager"))
01073 hasmanager = ast_true(v->value);
01074 else if (!strcasecmp(v->name, "managerread"))
01075 readperms = v->value;
01076 else if (!strcasecmp(v->name, "managerwrite"))
01077 writeperms = v->value;
01078 }
01079 if (!hasmanager)
01080 break;
01081 if (!password || strcmp(password, pass)) {
01082 ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_inet_ntoa(s->sin.sin_addr), user);
01083 ast_config_destroy(cfg);
01084 return -1;
01085 }
01086 ast_copy_string(s->username, cat, sizeof(s->username));
01087 s->readperm = readperms ? get_perm(readperms) : -1;
01088 s->writeperm = writeperms ? get_perm(writeperms) : -1;
01089 ast_config_destroy(cfg);
01090 if (events)
01091 set_eventmask(s, events);
01092 return 0;
01093 }
01094 ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_inet_ntoa(s->sin.sin_addr), user);
01095 ast_config_destroy(cfg);
01096 return -1;
01097 }
01098
01099
01100 static char mandescr_ping[] =
01101 "Description: A 'Ping' action will ellicit a 'Pong' response. Used to keep the\n"
01102 " manager connection open.\n"
01103 "Variables: NONE\n";
01104
01105 static int action_ping(struct mansession *s, const struct message *m)
01106 {
01107 astman_send_response(s, m, "Pong", NULL);
01108 return 0;
01109 }
01110
01111 static char mandescr_getconfig[] =
01112 "Description: A 'GetConfig' action will dump the contents of a configuration\n"
01113 "file by category and contents.\n"
01114 "Variables:\n"
01115 " Filename: Configuration filename (e.g. foo.conf)\n";
01116
01117 static int action_getconfig(struct mansession *s, const struct message *m)
01118 {
01119 struct ast_config *cfg;
01120 const char *fn = astman_get_header(m, "Filename");
01121 int catcount = 0;
01122 int lineno = 0;
01123 char *category=NULL;
01124 struct ast_variable *v;
01125 char idText[256] = "";
01126 const char *id = astman_get_header(m, "ActionID");
01127
01128 if (!ast_strlen_zero(id))
01129 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
01130
01131 if (ast_strlen_zero(fn)) {
01132 astman_send_error(s, m, "Filename not specified");
01133 return 0;
01134 }
01135 if (!(cfg = ast_config_load_with_comments(fn))) {
01136 astman_send_error(s, m, "Config file not found");
01137 return 0;
01138 }
01139 astman_append(s, "Response: Success\r\n%s", idText);
01140 while ((category = ast_category_browse(cfg, category))) {
01141 lineno = 0;
01142 astman_append(s, "Category-%06d: %s\r\n", catcount, category);
01143 for (v = ast_variable_browse(cfg, category); v; v = v->next)
01144 astman_append(s, "Line-%06d-%06d: %s=%s\r\n", catcount, lineno++, v->name, v->value);
01145 catcount++;
01146 }
01147 ast_config_destroy(cfg);
01148 astman_append(s, "\r\n");
01149
01150 return 0;
01151 }
01152
01153
01154 static void handle_updates(struct mansession *s, const struct message *m, struct ast_config *cfg)
01155 {
01156 int x;
01157 char hdr[40];
01158 const char *action, *cat, *var, *value, *match;
01159 struct ast_category *category;
01160 struct ast_variable *v;
01161
01162 for (x=0;x<100000;x++) {
01163 unsigned int object = 0;
01164
01165 snprintf(hdr, sizeof(hdr), "Action-%06d", x);
01166 action = astman_get_header(m, hdr);
01167 if (ast_strlen_zero(action))
01168 break;
01169 snprintf(hdr, sizeof(hdr), "Cat-%06d", x);
01170 cat = astman_get_header(m, hdr);
01171 snprintf(hdr, sizeof(hdr), "Var-%06d", x);
01172 var = astman_get_header(m, hdr);
01173 snprintf(hdr, sizeof(hdr), "Value-%06d", x);
01174 value = astman_get_header(m, hdr);
01175 if (!ast_strlen_zero(value) && *value == '>') {
01176 object = 1;
01177 value++;
01178 }
01179 snprintf(hdr, sizeof(hdr), "Match-%06d", x);
01180 match = astman_get_header(m, hdr);
01181 if (!strcasecmp(action, "newcat")) {
01182 if (!ast_strlen_zero(cat)) {
01183 category = ast_category_new(cat);
01184 if (category) {
01185 ast_category_append(cfg, category);
01186 }
01187 }
01188 } else if (!strcasecmp(action, "renamecat")) {
01189 if (!ast_strlen_zero(cat) && !ast_strlen_zero(value)) {
01190 category = ast_category_get(cfg, cat);
01191 if (category)
01192 ast_category_rename(category, value);
01193 }
01194 } else if (!strcasecmp(action, "delcat")) {
01195 if (!ast_strlen_zero(cat))
01196 ast_category_delete(cfg, (char *) cat);
01197 } else if (!strcasecmp(action, "update")) {
01198 if (!ast_strlen_zero(cat) && !ast_strlen_zero(var) && (category = ast_category_get(cfg, cat)))
01199 ast_variable_update(category, var, value, match, object);
01200 } else if (!strcasecmp(action, "delete")) {
01201 if (!ast_strlen_zero(cat) && !ast_strlen_zero(var) && (category = ast_category_get(cfg, cat)))
01202 ast_variable_delete(category, (char *) var, (char *) match);
01203 } else if (!strcasecmp(action, "append")) {
01204 if (!ast_strlen_zero(cat) && !ast_strlen_zero(var) &&
01205 (category = ast_category_get(cfg, cat)) &&
01206 (v = ast_variable_new(var, value))){
01207 if (object || (match && !strcasecmp(match, "object")))
01208 v->object = 1;
01209 ast_variable_append(category, v);
01210 }
01211 }
01212 }
01213 }
01214
01215 static char mandescr_updateconfig[] =
01216 "Description: A 'UpdateConfig' action will modify, create, or delete\n"
01217 "configuration elements in Asterisk configuration files.\n"
01218 "Variables (X's represent 6 digit number beginning with 000000):\n"
01219 " SrcFilename: Configuration filename to read(e.g. foo.conf)\n"
01220 " DstFilename: Configuration filename to write(e.g. foo.conf)\n"
01221 " Reload: Whether or not a reload should take place (or name of specific module)\n"
01222 " Action-XXXXXX: Action to Take (NewCat,RenameCat,DelCat,Update,Delete,Append)\n"
01223 " Cat-XXXXXX: Category to operate on\n"
01224 " Var-XXXXXX: Variable to work on\n"
01225 " Value-XXXXXX: Value to work on\n"
01226 " Match-XXXXXX: Extra match required to match line\n";
01227
01228 static int action_updateconfig(struct mansession *s, const struct message *m)
01229 {
01230 struct ast_config *cfg;
01231 const char *sfn = astman_get_header(m, "SrcFilename");
01232 const char *dfn = astman_get_header(m, "DstFilename");
01233 int res;
01234 char idText[256] = "";
01235 const char *id = astman_get_header(m, "ActionID");
01236 const char *rld = astman_get_header(m, "Reload");
01237
01238 if (!ast_strlen_zero(id))
01239 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
01240
01241 if (ast_strlen_zero(sfn) || ast_strlen_zero(dfn)) {
01242 astman_send_error(s, m, "Filename not specified");
01243 return 0;
01244 }
01245 if (!(cfg = ast_config_load_with_comments(sfn))) {
01246 astman_send_error(s, m, "Config file not found");
01247 return 0;
01248 }
01249 handle_updates(s, m, cfg);
01250 res = config_text_file_save(dfn, cfg, "Manager");
01251 ast_config_destroy(cfg);
01252 if (res) {
01253 astman_send_error(s, m, "Save of config failed");
01254 return 0;
01255 }
01256 astman_append(s, "Response: Success\r\n%s\r\n", idText);
01257 if (!ast_strlen_zero(rld)) {
01258 if (ast_true(rld))
01259 rld = NULL;
01260 ast_module_reload(rld);
01261 }
01262 return 0;
01263 }
01264
01265
01266 static char mandescr_waitevent[] =
01267 "Description: A 'WaitEvent' action will ellicit a 'Success' response. Whenever\n"
01268 "a manager event is queued. Once WaitEvent has been called on an HTTP manager\n"
01269 "session, events will be generated and queued.\n"
01270 "Variables: \n"
01271 " Timeout: Maximum time to wait for events\n";
01272
01273 static int action_waitevent(struct mansession *s, const struct message *m)
01274 {
01275 const char *timeouts = astman_get_header(m, "Timeout");
01276 int timeout = -1, max;
01277 int x;
01278 int needexit = 0;
01279 time_t now;
01280 struct eventqent *eqe;
01281 const char *id = astman_get_header(m,"ActionID");
01282 char idText[256] = "";
01283
01284 if (!ast_strlen_zero(id))
01285 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
01286
01287 if (!ast_strlen_zero(timeouts)) {
01288 sscanf(timeouts, "%i", &timeout);
01289 }
01290
01291 ast_mutex_lock(&s->__lock);
01292 if (s->waiting_thread != AST_PTHREADT_NULL) {
01293 pthread_kill(s->waiting_thread, SIGURG);
01294 }
01295 if (s->sessiontimeout) {
01296 time(&now);
01297 max = s->sessiontimeout - now - 10;
01298 if (max < 0)
01299 max = 0;
01300 if ((timeout < 0) || (timeout > max))
01301 timeout = max;
01302 if (!s->send_events)
01303 s->send_events = -1;
01304
01305 }
01306 ast_mutex_unlock(&s->__lock);
01307 s->waiting_thread = pthread_self();
01308 if (option_debug)
01309 ast_log(LOG_DEBUG, "Starting waiting for an event!\n");
01310 for (x=0; ((x < timeout) || (timeout < 0)); x++) {
01311 ast_mutex_lock(&s->__lock);
01312 if (s->eventq && s->eventq->next)
01313 needexit = 1;
01314 if (s->waiting_thread != pthread_self())
01315 needexit = 1;
01316 if (s->needdestroy)
01317 needexit = 1;
01318 ast_mutex_unlock(&s->__lock);
01319 if (needexit)
01320 break;
01321 if (s->fd > 0) {
01322 if (ast_wait_for_input(s->fd, 1000))
01323 break;
01324 } else {
01325 sleep(1);
01326 }
01327 }
01328 if (option_debug)
01329 ast_log(LOG_DEBUG, "Finished waiting for an event!\n");
01330 ast_mutex_lock(&s->__lock);
01331 if (s->waiting_thread == pthread_self()) {
01332 astman_send_response(s, m, "Success", "Waiting for Event...");
01333
01334 while(s->eventq->next) {
01335 eqe = s->eventq->next;
01336 if (((s->readperm & eqe->category) == eqe->category) &&
01337 ((s->send_events & eqe->category) == eqe->category)) {
01338 astman_append(s, "%s", eqe->eventdata);
01339 }
01340 unuse_eventqent(s->eventq);
01341 s->eventq = eqe;
01342 }
01343 astman_append(s,
01344 "Event: WaitEventComplete\r\n"
01345 "%s"
01346 "\r\n", idText);
01347 s->waiting_thread = AST_PTHREADT_NULL;
01348 } else {
01349 ast_log(LOG_DEBUG, "Abandoning event request!\n");
01350 }
01351 ast_mutex_unlock(&s->__lock);
01352 return 0;
01353 }
01354
01355 static char mandescr_listcommands[] =
01356 "Description: Returns the action name and synopsis for every\n"
01357 " action that is available to the user\n"
01358 "Variables: NONE\n";
01359
01360
01361 static int action_listcommands(struct mansession *s, const struct message *m)
01362 {
01363 struct manager_action *cur;
01364 char idText[256] = "";
01365 char temp[BUFSIZ];
01366 const char *id = astman_get_header(m,"ActionID");
01367
01368 if (!ast_strlen_zero(id))
01369 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
01370 astman_append(s, "Response: Success\r\n%s", idText);
01371 for (cur = first_action; cur; cur = cur->next) {
01372 if ((s->writeperm & cur->authority) == cur->authority)
01373 astman_append(s, "%s: %s (Priv: %s)\r\n", cur->action, cur->synopsis, authority_to_str(cur->authority, temp, sizeof(temp)));
01374 }
01375 astman_append(s, "\r\n");
01376
01377 return 0;
01378 }
01379
01380 static char mandescr_events[] =
01381 "Description: Enable/Disable sending of events to this manager\n"
01382 " client.\n"
01383 "Variables:\n"
01384 " EventMask: 'on' if all events should be sent,\n"
01385 " 'off' if no events should be sent,\n"
01386 " 'system,call,log' to select which flags events should have to be sent.\n";
01387
01388 static int action_events(struct mansession *s, const struct message *m)
01389 {
01390 const char *mask = astman_get_header(m, "EventMask");
01391 int res;
01392
01393 res = set_eventmask(s, mask);
01394 if (res > 0)
01395 astman_send_response(s, m, "Events On", NULL);
01396 else if (res == 0)
01397 astman_send_response(s, m, "Events Off", NULL);
01398
01399 return 0;
01400 }
01401
01402 static char mandescr_logoff[] =
01403 "Description: Logoff this manager session\n"
01404 "Variables: NONE\n";
01405
01406 static int action_logoff(struct mansession *s, const struct message *m)
01407 {
01408 astman_send_response(s, m, "Goodbye", "Thanks for all the fish.");
01409 return -1;
01410 }
01411
01412 static char mandescr_hangup[] =
01413 "Description: Hangup a channel\n"
01414 "Variables: \n"
01415 " Channel: The channel name to be hungup\n";
01416
01417 static int action_hangup(struct mansession *s, const struct message *m)
01418 {
01419 struct ast_channel *c = NULL;
01420 const char *name = astman_get_header(m, "Channel");
01421 if (ast_strlen_zero(name)) {
01422 astman_send_error(s, m, "No channel specified");
01423 return 0;
01424 }
01425 c = ast_get_channel_by_name_locked(name);
01426 if (!c) {
01427 astman_send_error(s, m, "No such channel");
01428 return 0;
01429 }
01430 ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
01431 ast_channel_unlock(c);
01432 astman_send_ack(s, m, "Channel Hungup");
01433 return 0;
01434 }
01435
01436 static char mandescr_setvar[] =
01437 "Description: Set a global or local channel variable.\n"
01438 "Variables: (Names marked with * are required)\n"
01439 " Channel: Channel to set variable for\n"
01440 " *Variable: Variable name\n"
01441 " *Value: Value\n";
01442
01443 static int action_setvar(struct mansession *s, const struct message *m)
01444 {
01445 struct ast_channel *c = NULL;
01446 const char *name = astman_get_header(m, "Channel");
01447 const char *varname = astman_get_header(m, "Variable");
01448 const char *varval = astman_get_header(m, "Value");
01449
01450 if (ast_strlen_zero(varname)) {
01451 astman_send_error(s, m, "No variable specified");
01452 return 0;
01453 }
01454
01455 if (!ast_strlen_zero(name)) {
01456 c = ast_get_channel_by_name_locked(name);
01457 if (!c) {
01458 astman_send_error(s, m, "No such channel");
01459 return 0;
01460 }
01461 }
01462
01463 pbx_builtin_setvar_helper(c, varname, S_OR(varval, ""));
01464
01465 if (c)
01466 ast_channel_unlock(c);
01467
01468 astman_send_ack(s, m, "Variable Set");
01469
01470 return 0;
01471 }
01472
01473 static char mandescr_getvar[] =
01474 "Description: Get the value of a global or local channel variable.\n"
01475 "Variables: (Names marked with * are required)\n"
01476 " Channel: Channel to read variable from\n"
01477 " *Variable: Variable name\n"
01478 " ActionID: Optional Action id for message matching.\n";
01479
01480 static int action_getvar(struct mansession *s, const struct message *m)
01481 {
01482 struct ast_channel *c = NULL;
01483 const char *name = astman_get_header(m, "Channel");
01484 const char *varname = astman_get_header(m, "Variable");
01485 const char *id = astman_get_header(m,"ActionID");
01486 char *varval;
01487 char workspace[1024] = "";
01488
01489 if (ast_strlen_zero(varname)) {
01490 astman_send_error(s, m, "No variable specified");
01491 return 0;
01492 }
01493
01494 if (!ast_strlen_zero(name)) {
01495 c = ast_get_channel_by_name_locked(name);
01496 if (!c) {
01497 astman_send_error(s, m, "No such channel");
01498 return 0;
01499 }
01500 }
01501
01502 if (varname[strlen(varname) - 1] == ')') {
01503 char *copy = ast_strdupa(varname);
01504 if (!c) {
01505 c = ast_channel_alloc(0, 0, "", "", "", "", "", 0, "Bogus/manager");
01506 if (c) {
01507 ast_func_read(c, copy, workspace, sizeof(workspace));
01508 ast_channel_free(c);
01509 } else
01510 ast_log(LOG_ERROR, "Unable to allocate bogus channel for variable substitution. Function results may be blank.\n");
01511 } else
01512 ast_func_read(c, copy, workspace, sizeof(workspace));
01513 varval = workspace;
01514 } else {
01515 pbx_retrieve_variable(c, varname, &varval, workspace, sizeof(workspace), NULL);
01516 }
01517
01518 if (c)
01519 ast_channel_unlock(c);
01520 astman_append(s, "Response: Success\r\n"
01521 "Variable: %s\r\nValue: %s\r\n", varname, varval);
01522 if (!ast_strlen_zero(id))
01523 astman_append(s, "ActionID: %s\r\n",id);
01524 astman_append(s, "\r\n");
01525
01526 return 0;
01527 }
01528
01529
01530
01531
01532 static int action_status(struct mansession *s, const struct message *m)
01533 {
01534 const char *id = astman_get_header(m,"ActionID");
01535 const char *name = astman_get_header(m,"Channel");
01536 char idText[256] = "";
01537 struct ast_channel *c;
01538 char bridge[256];
01539 struct timeval now = ast_tvnow();
01540 long elapsed_seconds = 0;
01541 int all = ast_strlen_zero(name);
01542
01543 if (!ast_strlen_zero(id))
01544 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
01545 if (all)
01546 c = ast_channel_walk_locked(NULL);
01547 else {
01548 c = ast_get_channel_by_name_locked(name);
01549 if (!c) {
01550 astman_send_error(s, m, "No such channel");
01551 return 0;
01552 }
01553 }
01554 astman_send_ack(s, m, "Channel status will follow");
01555
01556 while (c) {
01557 if (c->_bridge)
01558 snprintf(bridge, sizeof(bridge), "Link: %s\r\n", c->_bridge->name);
01559 else
01560 bridge[0] = '\0';
01561 if (c->pbx) {
01562 if (c->cdr) {
01563 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
01564 }
01565 astman_append(s,
01566 "Event: Status\r\n"
01567 "Privilege: Call\r\n"
01568 "Channel: %s\r\n"
01569 "CallerID: %s\r\n"
01570 "CallerIDNum: %s\r\n"
01571 "CallerIDName: %s\r\n"
01572 "Account: %s\r\n"
01573 "State: %s\r\n"
01574 "Context: %s\r\n"
01575 "Extension: %s\r\n"
01576 "Priority: %d\r\n"
01577 "Seconds: %ld\r\n"
01578 "%s"
01579 "Uniqueid: %s\r\n"
01580 "%s"
01581 "\r\n",
01582 c->name,
01583 S_OR(c->cid.cid_num, "<unknown>"),
01584 S_OR(c->cid.cid_num, "<unknown>"),
01585 S_OR(c->cid.cid_name, "<unknown>"),
01586 c->accountcode,
01587 ast_state2str(c->_state), c->context,
01588 c->exten, c->priority, (long)elapsed_seconds, bridge, c->uniqueid, idText);
01589 } else {
01590 astman_append(s,
01591 "Event: Status\r\n"
01592 "Privilege: Call\r\n"
01593 "Channel: %s\r\n"
01594 "CallerID: %s\r\n"
01595 "CallerIDNum: %s\r\n"
01596 "CallerIDName: %s\r\n"
01597 "Account: %s\r\n"
01598 "State: %s\r\n"
01599 "%s"
01600 "Uniqueid: %s\r\n"
01601 "%s"
01602 "\r\n",
01603 c->name,
01604 S_OR(c->cid.cid_num, "<unknown>"),
01605 S_OR(c->cid.cid_num, "<unknown>"),
01606 S_OR(c->cid.cid_name, "<unknown>"),
01607 c->accountcode,
01608 ast_state2str(c->_state), bridge, c->uniqueid, idText);
01609 }
01610 ast_channel_unlock(c);
01611 if (!all)
01612 break;
01613 c = ast_channel_walk_locked(c);
01614 }
01615 astman_append(s,
01616 "Event: StatusComplete\r\n"
01617 "%s"
01618 "\r\n",idText);
01619 return 0;
01620 }
01621
01622 static char mandescr_redirect[] =
01623 "Description: Redirect (transfer) a call.\n"
01624 "Variables: (Names marked with * are required)\n"
01625 " *Channel: Channel to redirect\n"
01626 " ExtraChannel: Second call leg to transfer (optional)\n"
01627 " *Exten: Extension to transfer to\n"
01628 " *Context: Context to transfer to\n"
01629 " *Priority: Priority to transfer to\n"
01630 " ActionID: Optional Action id for message matching.\n";
01631
01632
01633 static int action_redirect(struct mansession *s, const struct message *m)
01634 {
01635 const char *name = astman_get_header(m, "Channel");
01636 const char *name2 = astman_get_header(m, "ExtraChannel");
01637 const char *exten = astman_get_header(m, "Exten");
01638 const char *context = astman_get_header(m, "Context");
01639 const char *priority = astman_get_header(m, "Priority");
01640 struct ast_channel *chan, *chan2 = NULL;
01641 int pi = 0;
01642 int res;
01643
01644 if (ast_strlen_zero(name)) {
01645 astman_send_error(s, m, "Channel not specified");
01646 return 0;
01647 }
01648 if (!ast_strlen_zero(priority) && (sscanf(priority, "%d", &pi) != 1)) {
01649 if ((pi = ast_findlabel_extension(NULL, context, exten, priority, NULL)) < 1) {
01650 astman_send_error(s, m, "Invalid priority");
01651 return 0;
01652 }
01653 }
01654
01655 chan = ast_get_channel_by_name_locked(name);
01656 if (!chan) {
01657 char buf[BUFSIZ];
01658 snprintf(buf, sizeof(buf), "Channel does not exist: %s", name);
01659 astman_send_error(s, m, buf);
01660 return 0;
01661 }
01662 if (ast_check_hangup(chan)) {
01663 astman_send_error(s, m, "Redirect failed, channel not up.");
01664 ast_channel_unlock(chan);
01665 return 0;
01666 }
01667 if (!ast_strlen_zero(name2))
01668 chan2 = ast_get_channel_by_name_locked(name2);
01669 if (chan2 && ast_check_hangup(chan2)) {
01670 astman_send_error(s, m, "Redirect failed, extra channel not up.");
01671 ast_channel_unlock(chan);
01672 ast_channel_unlock(chan2);
01673 return 0;
01674 }
01675 res = ast_async_goto(chan, context, exten, pi);
01676 if (!res) {
01677 if (!ast_strlen_zero(name2)) {
01678 if (chan2)
01679 res = ast_async_goto(chan2, context, exten, pi);
01680 else
01681 res = -1;
01682 if (!res)
01683 astman_send_ack(s, m, "Dual Redirect successful");
01684 else
01685 astman_send_error(s, m, "Secondary redirect failed");
01686 } else
01687 astman_send_ack(s, m, "Redirect successful");
01688 } else
01689 astman_send_error(s, m, "Redirect failed");
01690 if (chan)
01691 ast_channel_unlock(chan);
01692 if (chan2)
01693 ast_channel_unlock(chan2);
01694 return 0;
01695 }
01696
01697 static int check_blacklist(const char *cmd)
01698 {
01699 char *cmd_copy, *cur_cmd;
01700 char *cmd_words[MAX_BLACKLIST_CMD_LEN] = { NULL, };
01701 int i;
01702
01703 cmd_copy = ast_strdupa(cmd);
01704 for (i = 0; i < MAX_BLACKLIST_CMD_LEN && (cur_cmd = strsep(&cmd_copy, " ")); i++) {
01705 cur_cmd = ast_strip(cur_cmd);
01706 if (ast_strlen_zero(cur_cmd)) {
01707 i--;
01708 continue;
01709 }
01710
01711 cmd_words[i] = cur_cmd;
01712 }
01713
01714 for (i = 0; i < ARRAY_LEN(command_blacklist); i++) {
01715 int j, match = 1;
01716
01717 for (j = 0; command_blacklist[i].words[j]; j++) {
01718 if (ast_strlen_zero(cmd_words[j]) || strcasecmp(cmd_words[j], command_blacklist[i].words[j])) {
01719 match = 0;
01720 break;
01721 }
01722 }
01723
01724 if (match) {
01725 return 1;
01726 }
01727 }
01728
01729 return 0;
01730 }
01731
01732 static char mandescr_command[] =
01733 "Description: Run a CLI command.\n"
01734 "Variables: (Names marked with * are required)\n"
01735 " *Command: Asterisk CLI command to run\n"
01736 " ActionID: Optional Action id for message matching.\n";
01737
01738
01739 static int action_command(struct mansession *s, const struct message *m)
01740 {
01741 const char *cmd = astman_get_header(m, "Command");
01742 const char *id = astman_get_header(m, "ActionID");
01743 char *buf, *final_buf;
01744 char template[] = "/tmp/ast-ami-XXXXXX";
01745 int fd = mkstemp(template);
01746 off_t l;
01747
01748 if (ast_strlen_zero(cmd)) {
01749 astman_send_error(s, m, "No command provided");
01750 return 0;
01751 }
01752
01753 if (check_blacklist(cmd)) {
01754 astman_send_error(s, m, "Command blacklisted");
01755 return 0;
01756 }
01757
01758 astman_append(s, "Response: Follows\r\nPrivilege: Command\r\n");
01759 if (!ast_strlen_zero(id))
01760 astman_append(s, "ActionID: %s\r\n", id);
01761
01762 ast_cli_command(fd, cmd);
01763 l = lseek(fd, 0, SEEK_END);
01764
01765
01766 buf = ast_calloc(1, l + 1);
01767 final_buf = ast_calloc(1, l + 1);
01768 if (buf) {
01769 lseek(fd, 0, SEEK_SET);
01770 if (read(fd, buf, l) < 0) {
01771 ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
01772 }
01773 buf[l] = '\0';
01774 if (final_buf) {
01775 term_strip(final_buf, buf, l);
01776 final_buf[l] = '\0';
01777 }
01778 astman_append(s, "%s", S_OR(final_buf, buf));
01779 ast_free(buf);
01780 }
01781 close(fd);
01782 unlink(template);
01783 astman_append(s, "--END COMMAND--\r\n\r\n");
01784 if (final_buf)
01785 ast_free(final_buf);
01786 return 0;
01787 }
01788
01789 static void *fast_originate(void *data)
01790 {
01791 struct fast_originate_helper *in = data;
01792 int res;
01793 int reason = 0;
01794 struct ast_channel *chan = NULL;
01795 char requested_channel[AST_CHANNEL_NAME];
01796
01797 if (!ast_strlen_zero(in->app)) {
01798 res = ast_pbx_outgoing_app(in->tech, in->format, in->data, in->timeout, in->app, in->appdata, &reason, 1,
01799 S_OR(in->cid_num, NULL),
01800 S_OR(in->cid_name, NULL),
01801 in->vars, in->account, &chan);
01802 } else {
01803 res = ast_pbx_outgoing_exten(in->tech, in->format, in->data, in->timeout, in->context, in->exten, in->priority, &reason, 1,
01804 S_OR(in->cid_num, NULL),
01805 S_OR(in->cid_name, NULL),
01806 in->vars, in->account, &chan);
01807 }
01808
01809 if (!chan)
01810 snprintf(requested_channel, AST_CHANNEL_NAME, "%s/%s", in->tech, in->data);
01811
01812 manager_event(EVENT_FLAG_CALL, "OriginateResponse",
01813 "%s"
01814 "Response: %s\r\n"
01815 "Channel: %s\r\n"
01816 "Context: %s\r\n"
01817 "Exten: %s\r\n"
01818 "Reason: %d\r\n"
01819 "Uniqueid: %s\r\n"
01820 "CallerID: %s\r\n"
01821 "CallerIDNum: %s\r\n"
01822 "CallerIDName: %s\r\n",
01823 in->idtext, res ? "Failure" : "Success", chan ? chan->name : requested_channel, in->context, in->exten, reason,
01824 chan ? chan->uniqueid : "<null>",
01825 S_OR(in->cid_num, "<unknown>"),
01826 S_OR(in->cid_num, "<unknown>"),
01827 S_OR(in->cid_name, "<unknown>")
01828 );
01829
01830
01831 if (chan)
01832 ast_channel_unlock(chan);
01833 free(in);
01834 return NULL;
01835 }
01836
01837 static char mandescr_originate[] =
01838 "Description: Generates an outgoing call to a Extension/Context/Priority or\n"
01839 " Application/Data\n"
01840 "Variables: (Names marked with * are required)\n"
01841 " *Channel: Channel name to call\n"
01842 " Exten: Extension to use (requires 'Context' and 'Priority')\n"
01843 " Context: Context to use (requires 'Exten' and 'Priority')\n"
01844 " Priority: Priority to use (requires 'Exten' and 'Context')\n"
01845 " Application: Application to use\n"
01846 " Data: Data to use (requires 'Application')\n"
01847 " Timeout: How long to wait for call to be answered (in ms)\n"
01848 " CallerID: Caller ID to be set on the outgoing channel\n"
01849 " Variable: Channel variable to set, multiple Variable: headers are allowed\n"
01850 " Account: Account code\n"
01851 " Async: Set to 'true' for fast origination\n";
01852
01853 static int action_originate(struct mansession *s, const struct message *m)
01854 {
01855 const char *name = astman_get_header(m, "Channel");
01856 const char *exten = astman_get_header(m, "Exten");
01857 const char *context = astman_get_header(m, "Context");
01858 const char *priority = astman_get_header(m, "Priority");
01859 const char *timeout = astman_get_header(m, "Timeout");
01860 const char *callerid = astman_get_header(m, "CallerID");
01861 const char *account = astman_get_header(m, "Account");
01862 const char *app = astman_get_header(m, "Application");
01863 const char *appdata = astman_get_header(m, "Data");
01864 const char *async = astman_get_header(m, "Async");
01865 const char *id = astman_get_header(m, "ActionID");
01866 const char *codecs = astman_get_header(m, "Codecs");
01867 struct ast_variable *vars = astman_get_variables(m);
01868 char *tech, *data;
01869 char *l = NULL, *n = NULL;
01870 int pi = 0;
01871 int res;
01872 int to = 30000;
01873 int reason = 0;
01874 char tmp[256];
01875 char tmp2[256];
01876 int format = AST_FORMAT_SLINEAR;
01877
01878 pthread_t th;
01879 pthread_attr_t attr;
01880 if (ast_strlen_zero(name)) {
01881 astman_send_error(s, m, "Channel not specified");
01882 return 0;
01883 }
01884 if (!ast_strlen_zero(priority) && (sscanf(priority, "%d", &pi) != 1)) {
01885 if ((pi = ast_findlabel_extension(NULL, context, exten, priority, NULL)) < 1) {
01886 astman_send_error(s, m, "Invalid priority");
01887 return 0;
01888 }
01889 }
01890 if (!ast_strlen_zero(timeout) && (sscanf(timeout, "%d", &to) != 1)) {
01891 astman_send_error(s, m, "Invalid timeout");
01892 return 0;
01893 }
01894 ast_copy_string(tmp, name, sizeof(tmp));
01895 tech = tmp;
01896 data = strchr(tmp, '/');
01897 if (!data) {
01898 astman_send_error(s, m, "Invalid channel");
01899 return 0;
01900 }
01901 *data++ = '\0';
01902 ast_copy_string(tmp2, callerid, sizeof(tmp2));
01903 ast_callerid_parse(tmp2, &n, &l);
01904 if (n) {
01905 if (ast_strlen_zero(n))
01906 n = NULL;
01907 }
01908 if (l) {
01909 ast_shrink_phone_number(l);
01910 if (ast_strlen_zero(l))
01911 l = NULL;
01912 }
01913 if (!ast_strlen_zero(codecs)) {
01914 format = 0;
01915 ast_parse_allow_disallow(NULL, &format, codecs, 1);
01916 }
01917 if (ast_true(async)) {
01918 struct fast_originate_helper *fast = ast_calloc(1, sizeof(*fast));
01919 if (!fast) {
01920 res = -1;
01921 } else {
01922 if (!ast_strlen_zero(id))
01923 snprintf(fast->idtext, sizeof(fast->idtext), "ActionID: %s\r\n", id);
01924 ast_copy_string(fast->tech, tech, sizeof(fast->tech));
01925 ast_copy_string(fast->data, data, sizeof(fast->data));
01926 ast_copy_string(fast->app, app, sizeof(fast->app));
01927 ast_copy_string(fast->appdata, appdata, sizeof(fast->appdata));
01928 if (l)
01929 ast_copy_string(fast->cid_num, l, sizeof(fast->cid_num));
01930 if (n)
01931 ast_copy_string(fast->cid_name, n, sizeof(fast->cid_name));
01932 fast->vars = vars;
01933 ast_copy_string(fast->context, context, sizeof(fast->context));
01934 ast_copy_string(fast->exten, exten, sizeof(fast->exten));
01935 ast_copy_string(fast->account, account, sizeof(fast->account));
01936 fast->format = format;
01937 fast->timeout = to;
01938 fast->priority = pi;
01939 pthread_attr_init(&attr);
01940 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
01941 if (ast_pthread_create(&th, &attr, fast_originate, fast)) {
01942 ast_free(fast);
01943 res = -1;
01944 } else {
01945 res = 0;
01946 }
01947 pthread_attr_destroy(&attr);
01948 }
01949 } else if (!ast_strlen_zero(app)) {
01950 res = ast_pbx_outgoing_app(tech, format, data, to, app, appdata, &reason, 1, l, n, vars, account, NULL);
01951 } else {
01952 if (exten && context && pi)
01953 res = ast_pbx_outgoing_exten(tech, format, data, to, context, exten, pi, &reason, 1, l, n, vars, account, NULL);
01954 else {
01955 astman_send_error(s, m, "Originate with 'Exten' requires 'Context' and 'Priority'");
01956 return 0;
01957 }
01958 }
01959 if (!res)
01960 astman_send_ack(s, m, "Originate successfully queued");
01961 else
01962 astman_send_error(s, m, "Originate failed");
01963 return 0;
01964 }
01965
01966
01967
01968 static char mandescr_mailboxstatus[] =
01969 "Description: Checks a voicemail account for status.\n"
01970 "Variables: (Names marked with * are required)\n"
01971 " *Mailbox: Full mailbox ID <mailbox>@<vm-context>\n"
01972 " ActionID: Optional ActionID for message matching.\n"
01973 "Returns number of messages.\n"
01974 " Message: Mailbox Status\n"
01975 " Mailbox: <mailboxid>\n"
01976 " Waiting: <count>\n"
01977 "\n";
01978
01979 static int action_mailboxstatus(struct mansession *s, const struct message *m)
01980 {
01981 const char *mailbox = astman_get_header(m, "Mailbox");
01982 const char *id = astman_get_header(m,"ActionID");
01983 char idText[256] = "";
01984 int ret;
01985 if (ast_strlen_zero(mailbox)) {
01986 astman_send_error(s, m, "Mailbox not specified");
01987 return 0;
01988 }
01989 if (!ast_strlen_zero(id))
01990 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
01991 ret = ast_app_has_voicemail(mailbox, NULL);
01992 astman_append(s, "Response: Success\r\n"
01993 "%s"
01994 "Message: Mailbox Status\r\n"
01995 "Mailbox: %s\r\n"
01996 "Waiting: %d\r\n\r\n", idText, mailbox, ret);
01997 return 0;
01998 }
01999
02000 static char mandescr_mailboxcount[] =
02001 "Description: Checks a voicemail account for new messages.\n"
02002 "Variables: (Names marked with * are required)\n"
02003 " *Mailbox: Full mailbox ID <mailbox>@<vm-context>\n"
02004 " ActionID: Optional ActionID for message matching.\n"
02005 "Returns number of new and old messages.\n"
02006 " Message: Mailbox Message Count\n"
02007 " Mailbox: <mailboxid>\n"
02008 " NewMessages: <count>\n"
02009 " OldMessages: <count>\n"
02010 "\n";
02011 static int action_mailboxcount(struct mansession *s, const struct message *m)
02012 {
02013 const char *mailbox = astman_get_header(m, "Mailbox");
02014 const char *id = astman_get_header(m,"ActionID");
02015 char idText[256] = "";
02016 int newmsgs = 0, oldmsgs = 0;
02017 if (ast_strlen_zero(mailbox)) {
02018 astman_send_error(s, m, "Mailbox not specified");
02019 return 0;
02020 }
02021 ast_app_inboxcount(mailbox, &newmsgs, &oldmsgs);
02022 if (!ast_strlen_zero(id)) {
02023 snprintf(idText, sizeof(idText), "ActionID: %s\r\n",id);
02024 }
02025 astman_append(s, "Response: Success\r\n"
02026 "%s"
02027 "Message: Mailbox Message Count\r\n"
02028 "Mailbox: %s\r\n"
02029 "NewMessages: %d\r\n"
02030 "OldMessages: %d\r\n"
02031 "\r\n",
02032 idText,mailbox, newmsgs, oldmsgs);
02033 return 0;
02034 }
02035
02036 static char mandescr_extensionstate[] =
02037 "Description: Report the extension state for given extension.\n"
02038 " If the extension has a hint, will use devicestate to check\n"
02039 " the status of the device connected to the extension.\n"
02040 "Variables: (Names marked with * are required)\n"
02041 " *Exten: Extension to check state on\n"
02042 " *Context: Context for extension\n"
02043 " ActionId: Optional ID for this transaction\n"
02044 "Will return an \"Extension Status\" message.\n"
02045 "The response will include the hint for the extension and the status.\n";
02046
02047 static int action_extensionstate(struct mansession *s, const struct message *m)
02048 {
02049 const char *exten = astman_get_header(m, "Exten");
02050 const char *context = astman_get_header(m, "Context");
02051 const char *id = astman_get_header(m,"ActionID");
02052 char idText[256] = "";
02053 char hint[256] = "";
02054 int status;
02055 if (ast_strlen_zero(exten)) {
02056 astman_send_error(s, m, "Extension not specified");
02057 return 0;
02058 }
02059 if (ast_strlen_zero(context))
02060 context = "default";
02061 status = ast_extension_state(NULL, context, exten);
02062 ast_get_hint(hint, sizeof(hint) - 1, NULL, 0, NULL, context, exten);
02063 if (!ast_strlen_zero(id)) {
02064 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
02065 }
02066 astman_append(s, "Response: Success\r\n"
02067 "%s"
02068 "Message: Extension Status\r\n"
02069 "Exten: %s\r\n"
02070 "Context: %s\r\n"
02071 "Hint: %s\r\n"
02072 "Status: %d\r\n\r\n",
02073 idText,exten, context, hint, status);
02074 return 0;
02075 }
02076
02077 static char mandescr_timeout[] =
02078 "Description: Hangup a channel after a certain time.\n"
02079 "Variables: (Names marked with * are required)\n"
02080 " *Channel: Channel name to hangup\n"
02081 " *Timeout: Maximum duration of the call (sec)\n"
02082 "Acknowledges set time with 'Timeout Set' message\n";
02083
02084 static int action_timeout(struct mansession *s, const struct message *m)
02085 {
02086 struct ast_channel *c = NULL;
02087 const char *name = astman_get_header(m, "Channel");
02088 int timeout = atoi(astman_get_header(m, "Timeout"));
02089 if (ast_strlen_zero(name)) {
02090 astman_send_error(s, m, "No channel specified");
02091 return 0;
02092 }
02093 if (!timeout) {
02094 astman_send_error(s, m, "No timeout specified");
02095 return 0;
02096 }
02097 c = ast_get_channel_by_name_locked(name);
02098 if (!c) {
02099 astman_send_error(s, m, "No such channel");
02100 return 0;
02101 }
02102 ast_channel_setwhentohangup(c, timeout);
02103 ast_channel_unlock(c);
02104 astman_send_ack(s, m, "Timeout Set");
02105 return 0;
02106 }
02107
02108 static int process_events(struct mansession *s)
02109 {
02110 struct eventqent *eqe;
02111 int ret = 0;
02112 ast_mutex_lock(&s->__lock);
02113 if (!s->eventq)
02114 s->eventq = master_eventq;
02115 while(s->eventq->next) {
02116 eqe = s->eventq->next;
02117 if ((s->authenticated && (s->readperm & eqe->category) == eqe->category) &&
02118 ((s->send_events & eqe->category) == eqe->category)) {
02119 if (s->fd > -1) {
02120 if (!ret && ast_carefulwrite(s->fd, eqe->eventdata, strlen(eqe->eventdata), s->writetimeout) < 0)
02121 ret = -1;
02122 } else if (!s->outputstr && !(s->outputstr = ast_calloc(1, sizeof(*s->outputstr))))
02123 ret = -1;
02124 else
02125 ast_dynamic_str_append(&s->outputstr, 0, "%s", eqe->eventdata);
02126 }
02127 unuse_eventqent(s->eventq);
02128 s->eventq = eqe;
02129 }
02130 ast_mutex_unlock(&s->__lock);
02131 return ret;
02132 }
02133
02134 static char mandescr_userevent[] =
02135 "Description: Send an event to manager sessions.\n"
02136 "Variables: (Names marked with * are required)\n"
02137 " *UserEvent: EventStringToSend\n"
02138 " Header1: Content1\n"
02139 " HeaderN: ContentN\n";
02140
02141 static int action_userevent(struct mansession *s, const struct message *m)
02142 {
02143 const char *event = astman_get_header(m, "UserEvent");
02144 char body[2048] = "";
02145 int x, bodylen = 0;
02146 for (x = 0; x < m->hdrcount; x++) {
02147 if (strncasecmp("UserEvent:", m->headers[x], strlen("UserEvent:"))) {
02148 ast_copy_string(body + bodylen, m->headers[x], sizeof(body) - bodylen - 3);
02149 bodylen += strlen(m->headers[x]);
02150 ast_copy_string(body + bodylen, "\r\n", 3);
02151 bodylen += 2;
02152 }
02153 }
02154
02155 manager_event(EVENT_FLAG_USER, "UserEvent", "UserEvent: %s\r\n%s", event, body);
02156 return 0;
02157 }
02158
02159 static int process_message(struct mansession *s, const struct message *m)
02160 {
02161 char action[80] = "";
02162 struct manager_action *tmp;
02163 const char *id = astman_get_header(m,"ActionID");
02164 char idText[256] = "";
02165 int ret = 0;
02166
02167 ast_copy_string(action, astman_get_header(m, "Action"), sizeof(action));
02168 if (option_debug)
02169 ast_log( LOG_DEBUG, "Manager received command '%s'\n", action );
02170
02171 if (ast_strlen_zero(action)) {
02172 astman_send_error(s, m, "Missing action in request");
02173 return 0;
02174 }
02175 if (!ast_strlen_zero(id)) {
02176 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
02177 }
02178 if (!s->authenticated) {
02179 if (!strcasecmp(action, "Challenge")) {
02180 const char *authtype = astman_get_header(m, "AuthType");
02181
02182 if (!strcasecmp(authtype, "MD5")) {
02183 if (ast_strlen_zero(s->challenge))
02184 snprintf(s->challenge, sizeof(s->challenge), "%ld", ast_random());
02185 astman_append(s, "Response: Success\r\n"
02186 "%s"
02187 "Challenge: %s\r\n\r\n",
02188 idText, s->challenge);
02189 return 0;
02190 } else {
02191 astman_send_error(s, m, "Must specify AuthType");
02192 return 0;
02193 }
02194 } else if (!strcasecmp(action, "Login")) {
02195 if (authenticate(s, m)) {
02196 sleep(1);
02197 astman_send_error(s, m, "Authentication failed");
02198 return -1;
02199 } else {
02200 s->authenticated = 1;
02201 if (option_verbose > 1) {
02202 if (displayconnects) {
02203 ast_verbose(VERBOSE_PREFIX_2 "%sManager '%s' logged on from %s\n",
02204 (s->sessiontimeout ? "HTTP " : ""), s->username, ast_inet_ntoa(s->sin.sin_addr));
02205 }
02206 }
02207 ast_log(LOG_EVENT, "%sManager '%s' logged on from %s\n",
02208 (s->sessiontimeout ? "HTTP " : ""), s->username, ast_inet_ntoa(s->sin.sin_addr));
02209 astman_send_ack(s, m, "Authentication accepted");
02210 }
02211 } else if (!strcasecmp(action, "Logoff")) {
02212 astman_send_ack(s, m, "See ya");
02213 return -1;
02214 } else
02215 astman_send_error(s, m, "Authentication Required");
02216 } else {
02217 if (!strcasecmp(action, "Login"))
02218 astman_send_ack(s, m, "Already logged in");
02219 else {
02220 ast_rwlock_rdlock(&actionlock);
02221 for (tmp = first_action; tmp; tmp = tmp->next) {
02222 if (strcasecmp(action, tmp->action))
02223 continue;
02224 if ((s->writeperm & tmp->authority) == tmp->authority) {
02225 if (tmp->func(s, m))
02226 ret = -1;
02227 } else
02228 astman_send_error(s, m, "Permission denied");
02229 break;
02230 }
02231 ast_rwlock_unlock(&actionlock);
02232 if (!tmp)
02233 astman_send_error(s, m, "Invalid/unknown command");
02234 }
02235 }
02236 if (ret)
02237 return ret;
02238 return process_events(s);
02239 }
02240
02241 static int get_input(struct mansession *s, char *output)
02242 {
02243
02244 int res;
02245 int x;
02246 struct pollfd fds[1];
02247 for (x = 1; x < s->inlen; x++) {
02248 if ((s->inbuf[x] == '\n') && (s->inbuf[x-1] == '\r')) {
02249
02250 memcpy(output, s->inbuf, x + 1);
02251
02252 output[x+1] = '\0';
02253
02254 memmove(s->inbuf, s->inbuf + x + 1, s->inlen - x);
02255 s->inlen -= (x + 1);
02256 return 1;
02257 }
02258 }
02259 if (s->inlen >= sizeof(s->inbuf) - 1) {
02260 ast_log(LOG_WARNING, "Dumping long line with no return from %s: %s\n", ast_inet_ntoa(s->sin.sin_addr), s->inbuf);
02261 s->inlen = 0;
02262 }
02263 fds[0].fd = s->fd;
02264 fds[0].events = POLLIN;
02265 do {
02266 ast_mutex_lock(&s->__lock);
02267 if (s->pending_event) {
02268 s->pending_event = 0;
02269 ast_mutex_unlock(&s->__lock);
02270 return 0;
02271 }
02272 s->waiting_thread = pthread_self();
02273 ast_mutex_unlock(&s->__lock);
02274
02275 res = poll(fds, 1, -1);
02276
02277 ast_mutex_lock(&s->__lock);
02278 s->waiting_thread = AST_PTHREADT_NULL;
02279 ast_mutex_unlock(&s->__lock);
02280 if (res < 0) {
02281 if (errno == EINTR || errno == EAGAIN) {
02282 return 0;
02283 }
02284 ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
02285 return -1;
02286 } else if (res > 0) {
02287 ast_mutex_lock(&s->__lock);
02288 res = read(s->fd, s->inbuf + s->inlen, sizeof(s->inbuf) - 1 - s->inlen);
02289 ast_mutex_unlock(&s->__lock);
02290 if (res < 1)
02291 return -1;
02292 break;
02293 }
02294 } while(1);
02295 s->inlen += res;
02296 s->inbuf[s->inlen] = '\0';
02297 return 0;
02298 }
02299
02300 static int do_message(struct mansession *s)
02301 {
02302 struct message m = { 0 };
02303 char header_buf[sizeof(s->inbuf)] = { '\0' };
02304 int res;
02305
02306 for (;;) {
02307
02308 if (s->eventq->next) {
02309 if (process_events(s))
02310 return -1;
02311 }
02312 res = get_input(s, header_buf);
02313 if (res == 0) {
02314 continue;
02315 } else if (res > 0) {
02316
02317 if (strlen(header_buf) < 2)
02318 continue;
02319 header_buf[strlen(header_buf) - 2] = '\0';
02320 if (ast_strlen_zero(header_buf))
02321 return process_message(s, &m) ? -1 : 0;
02322 else if (m.hdrcount < (AST_MAX_MANHEADERS - 1))
02323 m.headers[m.hdrcount++] = ast_strdupa(header_buf);
02324 } else {
02325 return res;
02326 }
02327 }
02328 }
02329
02330 static void *session_do(void *data)
02331 {
02332 struct mansession *s = data;
02333 int res;
02334
02335 astman_append(s, "Asterisk Call Manager/1.0\r\n");
02336 for (;;) {
02337 if ((res = do_message(s)) < 0)
02338 break;
02339 }
02340 if (s->authenticated) {
02341 if (option_verbose > 1) {
02342 if (displayconnects)
02343 ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged off from %s\n", s->username, ast_inet_ntoa(s->sin.sin_addr));
02344 }
02345 ast_log(LOG_EVENT, "Manager '%s' logged off from %s\n", s->username, ast_inet_ntoa(s->sin.sin_addr));
02346 } else {
02347 if (option_verbose > 1) {
02348 if (displayconnects)
02349 ast_verbose(VERBOSE_PREFIX_2 "Connect attempt from '%s' unable to authenticate\n", ast_inet_ntoa(s->sin.sin_addr));
02350 }
02351 ast_log(LOG_EVENT, "Failed attempt from %s\n", ast_inet_ntoa(s->sin.sin_addr));
02352 }
02353
02354
02355
02356
02357
02358
02359
02360
02361
02362
02363
02364
02365 usleep(1);
02366
02367 destroy_session(s);
02368 return NULL;
02369 }
02370
02371 static void *accept_thread(void *ignore)
02372 {
02373 int as;
02374 struct sockaddr_in sin;
02375 socklen_t sinlen;
02376 struct eventqent *eqe;
02377 struct mansession *s;
02378 struct protoent *p;
02379 int arg = 1;
02380 int flags;
02381 pthread_attr_t attr;
02382 time_t now;
02383 struct pollfd pfds[1];
02384
02385 pthread_attr_init(&attr);
02386 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
02387
02388 for (;;) {
02389 time(&now);
02390 AST_LIST_LOCK(&sessions);
02391 AST_LIST_TRAVERSE_SAFE_BEGIN(&sessions, s, list) {
02392 if (s->sessiontimeout && (now > s->sessiontimeout) && !s->inuse) {
02393 AST_LIST_REMOVE_CURRENT(&sessions, list);
02394 num_sessions--;
02395 if (s->authenticated && (option_verbose > 1) && displayconnects) {
02396 ast_verbose(VERBOSE_PREFIX_2 "HTTP Manager '%s' timed out from %s\n",
02397 s->username, ast_inet_ntoa(s->sin.sin_addr));
02398 }
02399 free_session(s);
02400 break;
02401 }
02402 }
02403 AST_LIST_TRAVERSE_SAFE_END
02404
02405
02406 eqe = master_eventq;
02407 while (master_eventq->next && !master_eventq->usecount) {
02408 eqe = master_eventq;
02409 master_eventq = master_eventq->next;
02410 free(eqe);
02411 }
02412 AST_LIST_UNLOCK(&sessions);
02413
02414 sinlen = sizeof(sin);
02415 pfds[0].fd = asock;
02416 pfds[0].events = POLLIN;
02417
02418
02419 if (poll(pfds, 1, 5000) < 1)
02420 continue;
02421 as = accept(asock, (struct sockaddr *)&sin, &sinlen);
02422 if (as < 0) {
02423 ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
02424 continue;
02425 }
02426 p = getprotobyname("tcp");
02427 if (p) {
02428 if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
02429 ast_log(LOG_WARNING, "Failed to set manager tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
02430 }
02431 }
02432 if (!(s = ast_calloc(1, sizeof(*s))))
02433 continue;
02434
02435 memcpy(&s->sin, &sin, sizeof(sin));
02436 s->writetimeout = 100;
02437 s->waiting_thread = AST_PTHREADT_NULL;
02438
02439 if (!block_sockets) {
02440
02441 flags = fcntl(as, F_GETFL);
02442 fcntl(as, F_SETFL, flags | O_NONBLOCK);
02443 } else {
02444 flags = fcntl(as, F_GETFL);
02445 fcntl(as, F_SETFL, flags & ~O_NONBLOCK);
02446 }
02447 ast_mutex_init(&s->__lock);
02448 s->fd = as;
02449 s->send_events = -1;
02450 AST_LIST_LOCK(&sessions);
02451 AST_LIST_INSERT_HEAD(&sessions, s, list);
02452 num_sessions++;
02453
02454
02455 s->eventq = master_eventq;
02456 while(s->eventq->next)
02457 s->eventq = s->eventq->next;
02458 ast_atomic_fetchadd_int(&s->eventq->usecount, 1);
02459 AST_LIST_UNLOCK(&sessions);
02460 if (ast_pthread_create_background(&s->t, &attr, session_do, s))
02461 destroy_session(s);
02462 }
02463 pthread_attr_destroy(&attr);
02464 return NULL;
02465 }
02466
02467 static int append_event(const char *str, int category)
02468 {
02469 struct eventqent *tmp, *prev = NULL;
02470 tmp = ast_malloc(sizeof(*tmp) + strlen(str));
02471
02472 if (!tmp)
02473 return -1;
02474
02475 tmp->next = NULL;
02476 tmp->category = category;
02477 strcpy(tmp->eventdata, str);
02478
02479 if (master_eventq) {
02480 prev = master_eventq;
02481 while (prev->next)
02482 prev = prev->next;
02483 prev->next = tmp;
02484 } else {
02485 master_eventq = tmp;
02486 }
02487
02488 tmp->usecount = num_sessions;
02489
02490 return 0;
02491 }
02492
02493
02494 int manager_event(int category, const char *event, const char *fmt, ...)
02495 {
02496 struct mansession *s;
02497 char auth[80];
02498 va_list ap;
02499 struct timeval now;
02500 struct ast_dynamic_str *buf;
02501
02502
02503 if (!num_sessions)
02504 return 0;
02505
02506 if (!(buf = ast_dynamic_str_thread_get(&manager_event_buf, MANAGER_EVENT_BUF_INITSIZE)))
02507 return -1;
02508
02509 ast_dynamic_str_thread_set(&buf, 0, &manager_event_buf,
02510 "Event: %s\r\nPrivilege: %s\r\n",
02511 event, authority_to_str(category, auth, sizeof(auth)));
02512
02513 if (timestampevents) {
02514 now = ast_tvnow();
02515 ast_dynamic_str_thread_append(&buf, 0, &manager_event_buf,
02516 "Timestamp: %ld.%06lu\r\n",
02517 now.tv_sec, (unsigned long) now.tv_usec);
02518 }
02519
02520 va_start(ap, fmt);
02521 ast_dynamic_str_thread_append_va(&buf, 0, &manager_event_buf, fmt, ap);
02522 va_end(ap);
02523
02524 ast_dynamic_str_thread_append(&buf, 0, &manager_event_buf, "\r\n");
02525
02526
02527 AST_LIST_LOCK(&sessions);
02528 append_event(buf->str, category);
02529 AST_LIST_TRAVERSE(&sessions, s, list) {
02530 ast_mutex_lock(&s->__lock);
02531 if (s->waiting_thread != AST_PTHREADT_NULL)
02532 pthread_kill(s->waiting_thread, SIGURG);
02533 else
02534
02535
02536
02537
02538
02539 s->pending_event = 1;
02540 ast_mutex_unlock(&s->__lock);
02541 }
02542 AST_LIST_UNLOCK(&sessions);
02543
02544 return 0;
02545 }
02546
02547 int ast_manager_unregister(char *action)
02548 {
02549 struct manager_action *cur, *prev;
02550
02551 ast_rwlock_wrlock(&actionlock);
02552 cur = prev = first_action;
02553 while (cur) {
02554 if (!strcasecmp(action, cur->action)) {
02555 prev->next = cur->next;
02556 free(cur);
02557 if (option_verbose > 1)
02558 ast_verbose(VERBOSE_PREFIX_2 "Manager unregistered action %s\n", action);
02559 ast_rwlock_unlock(&actionlock);
02560 return 0;
02561 }
02562 prev = cur;
02563 cur = cur->next;
02564 }
02565 ast_rwlock_unlock(&actionlock);
02566 return 0;
02567 }
02568
02569 static int manager_state_cb(char *context, char *exten, int state, void *data)
02570 {
02571
02572 manager_event(EVENT_FLAG_CALL, "ExtensionStatus", "Exten: %s\r\nContext: %s\r\nStatus: %d\r\n", exten, context, state);
02573 return 0;
02574 }
02575
02576 static int ast_manager_register_struct(struct manager_action *act)
02577 {
02578 struct manager_action *cur, *prev = NULL;
02579 int ret;
02580
02581 ast_rwlock_wrlock(&actionlock);
02582 cur = first_action;
02583 while (cur) {
02584 ret = strcasecmp(cur->action, act->action);
02585 if (ret == 0) {
02586 ast_log(LOG_WARNING, "Manager: Action '%s' already registered\n", act->action);
02587 ast_rwlock_unlock(&actionlock);
02588 return -1;
02589 } else if (ret > 0) {
02590
02591 if (prev) {
02592 act->next = prev->next;
02593 prev->next = act;
02594 } else {
02595 act->next = first_action;
02596 first_action = act;
02597 }
02598 break;
02599 }
02600 prev = cur;
02601 cur = cur->next;
02602 }
02603
02604 if (!cur) {
02605 if (prev)
02606 prev->next = act;
02607 else
02608 first_action = act;
02609 act->next = NULL;
02610 }
02611
02612 if (option_verbose > 1)
02613 ast_verbose(VERBOSE_PREFIX_2 "Manager registered action %s\n", act->action);
02614 ast_rwlock_unlock(&actionlock);
02615 return 0;
02616 }
02617
02618
02619
02620 int ast_manager_register2(const char *action, int auth, int (*func)(struct mansession *s, const struct message *m), const char *synopsis, const char *description)
02621 {
02622 struct manager_action *cur;
02623
02624 cur = ast_malloc(sizeof(*cur));
02625 if (!cur)
02626 return -1;
02627
02628 cur->action = action;
02629 cur->authority = auth;
02630 cur->func = func;
02631 cur->synopsis = synopsis;
02632 cur->description = description;
02633 cur->next = NULL;
02634
02635 ast_manager_register_struct(cur);
02636
02637 return 0;
02638 }
02639
02640
02641
02642 static struct mansession *find_session(uint32_t ident)
02643 {
02644 struct mansession *s;
02645
02646 AST_LIST_LOCK(&sessions);
02647 AST_LIST_TRAVERSE(&sessions, s, list) {
02648 ast_mutex_lock(&s->__lock);
02649 if (s->sessiontimeout && (s->managerid == ident) && !s->needdestroy) {
02650 s->inuse++;
02651 break;
02652 }
02653 ast_mutex_unlock(&s->__lock);
02654 }
02655 AST_LIST_UNLOCK(&sessions);
02656
02657 return s;
02658 }
02659
02660 int astman_verify_session_readpermissions(uint32_t ident, int perm)
02661 {
02662 int result = 0;
02663 struct mansession *s;
02664
02665 AST_LIST_LOCK(&sessions);
02666 AST_LIST_TRAVERSE(&sessions, s, list) {
02667 ast_mutex_lock(&s->__lock);
02668 if ((s->managerid == ident) && (s->readperm & perm)) {
02669 result = 1;
02670 ast_mutex_unlock(&s->__lock);
02671 break;
02672 }
02673 ast_mutex_unlock(&s->__lock);
02674 }
02675 AST_LIST_UNLOCK(&sessions);
02676 return result;
02677 }
02678
02679 int astman_verify_session_writepermissions(uint32_t ident, int perm)
02680 {
02681 int result = 0;
02682 struct mansession *s;
02683
02684 AST_LIST_LOCK(&sessions);
02685 AST_LIST_TRAVERSE(&sessions, s, list) {
02686 ast_mutex_lock(&s->__lock);
02687 if ((s->managerid == ident) && (s->writeperm & perm)) {
02688 result = 1;
02689 ast_mutex_unlock(&s->__lock);
02690 break;
02691 }
02692 ast_mutex_unlock(&s->__lock);
02693 }
02694 AST_LIST_UNLOCK(&sessions);
02695 return result;
02696 }
02697
02698 enum {
02699 FORMAT_RAW,
02700 FORMAT_HTML,
02701 FORMAT_XML,
02702 };
02703 static char *contenttype[] = { "plain", "html", "xml" };
02704
02705 static char *generic_http_callback(int format, struct sockaddr_in *requestor, const char *uri, struct ast_variable *params, int *status, char **title, int *contentlength)
02706 {
02707 struct mansession *s = NULL;
02708 uint32_t ident = 0;
02709 char workspace[512];
02710 char cookie[128];
02711 size_t len = sizeof(workspace);
02712 int blastaway = 0;
02713 char *c = workspace;
02714 char *retval = NULL;
02715 struct ast_variable *v;
02716
02717 for (v = params; v; v = v->next) {
02718 if (!strcasecmp(v->name, "mansession_id")) {
02719 sscanf(v->value, "%x", &ident);
02720 break;
02721 }
02722 }
02723
02724 if (!(s = find_session(ident))) {
02725
02726 if (!(s = ast_calloc(1, sizeof(*s)))) {
02727 *status = 500;
02728 goto generic_callback_out;
02729 }
02730 memcpy(&s->sin, requestor, sizeof(s->sin));
02731 s->fd = -1;
02732 s->waiting_thread = AST_PTHREADT_NULL;
02733 s->send_events = 0;
02734 ast_mutex_init(&s->__lock);
02735 ast_mutex_lock(&s->__lock);
02736 s->inuse = 1;
02737
02738
02739
02740
02741
02742 while ((s->managerid = rand() ^ (unsigned long) s) == 0);
02743 AST_LIST_LOCK(&sessions);
02744 AST_LIST_INSERT_HEAD(&sessions, s, list);
02745
02746 s->eventq = master_eventq;
02747 while (s->eventq->next)
02748 s->eventq = s->eventq->next;
02749 ast_atomic_fetchadd_int(&s->eventq->usecount, 1);
02750 ast_atomic_fetchadd_int(&num_sessions, 1);
02751 AST_LIST_UNLOCK(&sessions);
02752 }
02753
02754
02755 time(&s->sessiontimeout);
02756 if (!s->authenticated && (httptimeout > 5))
02757 s->sessiontimeout += 5;
02758 else
02759 s->sessiontimeout += httptimeout;
02760 ast_mutex_unlock(&s->__lock);
02761
02762 if (s) {
02763 struct message m = { 0 };
02764 char tmp[80];
02765 unsigned int x;
02766 size_t hdrlen;
02767
02768 for (x = 0, v = params; v && (x < AST_MAX_MANHEADERS); x++, v = v->next) {
02769 hdrlen = strlen(v->name) + strlen(v->value) + 3;
02770 m.headers[m.hdrcount] = alloca(hdrlen);
02771 snprintf((char *) m.headers[m.hdrcount], hdrlen, "%s: %s", v->name, v->value);
02772 m.hdrcount = x + 1;
02773 }
02774
02775 if (process_message(s, &m)) {
02776 if (s->authenticated) {
02777 if (option_verbose > 1) {
02778 if (displayconnects)
02779 ast_verbose(VERBOSE_PREFIX_2 "HTTP Manager '%s' logged off from %s\n", s->username, ast_inet_ntoa(s->sin.sin_addr));
02780 }
02781 ast_log(LOG_EVENT, "HTTP Manager '%s' logged off from %s\n", s->username, ast_inet_ntoa(s->sin.sin_addr));
02782 } else {
02783 if (option_verbose > 1) {
02784 if (displayconnects)
02785 ast_verbose(VERBOSE_PREFIX_2 "HTTP Connect attempt from '%s' unable to authenticate\n", ast_inet_ntoa(s->sin.sin_addr));
02786 }
02787 ast_log(LOG_EVENT, "HTTP Failed attempt from %s\n", ast_inet_ntoa(s->sin.sin_addr));
02788 }
02789 s->needdestroy = 1;
02790 }
02791 ast_build_string(&c, &len, "Content-type: text/%s\r\n", contenttype[format]);
02792 sprintf(tmp, "%08x", s->managerid);
02793 ast_build_string(&c, &len, "%s\r\n", ast_http_setcookie("mansession_id", tmp, httptimeout, cookie, sizeof(cookie)));
02794 if (format == FORMAT_HTML)
02795 ast_build_string(&c, &len, "<title>Asterisk™ Manager Interface</title>");
02796 if (format == FORMAT_XML) {
02797 ast_build_string(&c, &len, "<ajax-response>\n");
02798 } else if (format == FORMAT_HTML) {
02799 ast_build_string(&c, &len, "<body bgcolor=\"#ffffff\"><table align=center bgcolor=\"#f1f1f1\" width=\"500\">\r\n");
02800 ast_build_string(&c, &len, "<tr><td colspan=\"2\" bgcolor=\"#f1f1ff\"><h1> Manager Tester</h1></td></tr>\r\n");
02801 }
02802 ast_mutex_lock(&s->__lock);
02803 if (s->outputstr) {
02804 char *tmp;
02805 if (format == FORMAT_XML)
02806 tmp = xml_translate(s->outputstr->str, params);
02807 else if (format == FORMAT_HTML)
02808 tmp = html_translate(s->outputstr->str);
02809 else
02810 tmp = s->outputstr->str;
02811 if (tmp) {
02812 retval = malloc(strlen(workspace) + strlen(tmp) + 128);
02813 if (retval) {
02814 strcpy(retval, workspace);
02815 strcpy(retval + strlen(retval), tmp);
02816 c = retval + strlen(retval);
02817 len = 120;
02818 }
02819 }
02820 if (tmp != s->outputstr->str)
02821 free(tmp);
02822 free(s->outputstr);
02823 s->outputstr = NULL;
02824 }
02825 ast_mutex_unlock(&s->__lock);
02826
02827
02828 if (format == FORMAT_XML) {
02829 ast_build_string(&c, &len, "</ajax-response>\n");
02830 } else if (format == FORMAT_HTML)
02831 ast_build_string(&c, &len, "</table></body>\r\n");
02832 } else {
02833 *status = 500;
02834 *title = strdup("Server Error");
02835 }
02836 ast_mutex_lock(&s->__lock);
02837 if (s->needdestroy) {
02838 if (s->inuse == 1) {
02839 ast_log(LOG_DEBUG, "Need destroy, doing it now!\n");
02840 blastaway = 1;
02841 } else {
02842 ast_log(LOG_DEBUG, "Need destroy, but can't do it yet!\n");
02843 if (s->waiting_thread != AST_PTHREADT_NULL)
02844 pthread_kill(s->waiting_thread, SIGURG);
02845 s->inuse--;
02846 }
02847 } else
02848 s->inuse--;
02849 ast_mutex_unlock(&s->__lock);
02850
02851 if (blastaway)
02852 destroy_session(s);
02853 generic_callback_out:
02854 if (*status != 200)
02855 return ast_http_error(500, "Server Error", NULL, "Internal Server Error (out of memory)\n");
02856 return retval;
02857 }
02858
02859 static char *manager_http_callback(struct sockaddr_in *requestor, const char *uri, struct ast_variable *params, int *status, char **title, int *contentlength)
02860 {
02861 return generic_http_callback(FORMAT_HTML, requestor, uri, params, status, title, contentlength);
02862 }
02863
02864 static char *mxml_http_callback(struct sockaddr_in *requestor, const char *uri, struct ast_variable *params, int *status, char **title, int *contentlength)
02865 {
02866 return generic_http_callback(FORMAT_XML, requestor, uri, params, status, title, contentlength);
02867 }
02868
02869 static char *rawman_http_callback(struct sockaddr_in *requestor, const char *uri, struct ast_variable *params, int *status, char **title, int *contentlength)
02870 {
02871 return generic_http_callback(FORMAT_RAW, requestor, uri, params, status, title, contentlength);
02872 }
02873
02874 struct ast_http_uri rawmanuri = {
02875 .description = "Raw HTTP Manager Event Interface",
02876 .uri = "rawman",
02877 .has_subtree = 0,
02878 .callback = rawman_http_callback,
02879 };
02880
02881 struct ast_http_uri manageruri = {
02882 .description = "HTML Manager Event Interface",
02883 .uri = "manager",
02884 .has_subtree = 0,
02885 .callback = manager_http_callback,
02886 };
02887
02888 struct ast_http_uri managerxmluri = {
02889 .description = "XML Manager Event Interface",
02890 .uri = "mxml",
02891 .has_subtree = 0,
02892 .callback = mxml_http_callback,
02893 };
02894
02895 static int registered = 0;
02896 static int webregged = 0;
02897
02898 int init_manager(void)
02899 {
02900 struct ast_config *cfg = NULL, *ucfg = NULL;
02901 const char *val;
02902 char *cat = NULL;
02903 int oldportno = portno;
02904 static struct sockaddr_in ba;
02905 int x = 1;
02906 int flags;
02907 int webenabled = 0;
02908 int newhttptimeout = 60;
02909 struct ast_manager_user *user = NULL;
02910
02911 if (!registered) {
02912
02913 ast_manager_register2("Ping", 0, action_ping, "Keepalive command", mandescr_ping);
02914 ast_manager_register2("Events", 0, action_events, "Control Event Flow", mandescr_events);
02915 ast_manager_register2("Logoff", 0, action_logoff, "Logoff Manager", mandescr_logoff);
02916 ast_manager_register2("Hangup", EVENT_FLAG_CALL, action_hangup, "Hangup Channel", mandescr_hangup);
02917 ast_manager_register("Status", EVENT_FLAG_CALL, action_status, "Lists channel status" );
02918 ast_manager_register2("Setvar", EVENT_FLAG_CALL, action_setvar, "Set Channel Variable", mandescr_setvar );
02919 ast_manager_register2("Getvar", EVENT_FLAG_CALL, action_getvar, "Gets a Channel Variable", mandescr_getvar );
02920 ast_manager_register2("GetConfig", EVENT_FLAG_CONFIG, action_getconfig, "Retrieve configuration", mandescr_getconfig);
02921 ast_manager_register2("UpdateConfig", EVENT_FLAG_CONFIG, action_updateconfig, "Update basic configuration", mandescr_updateconfig);
02922 ast_manager_register2("Redirect", EVENT_FLAG_CALL, action_redirect, "Redirect (transfer) a call", mandescr_redirect );
02923 ast_manager_register2("Originate", EVENT_FLAG_CALL, action_originate, "Originate Call", mandescr_originate);
02924 ast_manager_register2("Command", EVENT_FLAG_COMMAND, action_command, "Execute Asterisk CLI Command", mandescr_command );
02925 ast_manager_register2("ExtensionState", EVENT_FLAG_CALL, action_extensionstate, "Check Extension Status", mandescr_extensionstate );
02926 ast_manager_register2("AbsoluteTimeout", EVENT_FLAG_CALL, action_timeout, "Set Absolute Timeout", mandescr_timeout );
02927 ast_manager_register2("MailboxStatus", EVENT_FLAG_CALL, action_mailboxstatus, "Check Mailbox", mandescr_mailboxstatus );
02928 ast_manager_register2("MailboxCount", EVENT_FLAG_CALL, action_mailboxcount, "Check Mailbox Message Count", mandescr_mailboxcount );
02929 ast_manager_register2("ListCommands", 0, action_listcommands, "List available manager commands", mandescr_listcommands);
02930 ast_manager_register2("UserEvent", EVENT_FLAG_USER, action_userevent, "Send an arbitrary event", mandescr_userevent);
02931 ast_manager_register2("WaitEvent", 0, action_waitevent, "Wait for an event to occur", mandescr_waitevent);
02932
02933 ast_cli_register_multiple(cli_manager, sizeof(cli_manager) / sizeof(struct ast_cli_entry));
02934 ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
02935 registered = 1;
02936
02937 append_event("Event: Placeholder\r\n\r\n", 0);
02938 }
02939 portno = DEFAULT_MANAGER_PORT;
02940 displayconnects = 1;
02941 cfg = ast_config_load("manager.conf");
02942 if (!cfg) {
02943 ast_log(LOG_NOTICE, "Unable to open management configuration manager.conf. Call management disabled.\n");
02944 return 0;
02945 }
02946 val = ast_variable_retrieve(cfg, "general", "enabled");
02947 if (val)
02948 enabled = ast_true(val);
02949
02950 val = ast_variable_retrieve(cfg, "general", "block-sockets");
02951 if (val)
02952 block_sockets = ast_true(val);
02953
02954 val = ast_variable_retrieve(cfg, "general", "webenabled");
02955 if (val)
02956 webenabled = ast_true(val);
02957
02958 if ((val = ast_variable_retrieve(cfg, "general", "port"))) {
02959 if (sscanf(val, "%d", &portno) != 1) {
02960 ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
02961 portno = DEFAULT_MANAGER_PORT;
02962 }
02963 }
02964
02965 if ((val = ast_variable_retrieve(cfg, "general", "displayconnects")))
02966 displayconnects = ast_true(val);
02967
02968 if ((val = ast_variable_retrieve(cfg, "general", "timestampevents")))
02969 timestampevents = ast_true(val);
02970
02971 if ((val = ast_variable_retrieve(cfg, "general", "httptimeout")))
02972 newhttptimeout = atoi(val);
02973
02974 memset(&ba, 0, sizeof(ba));
02975 ba.sin_family = AF_INET;
02976 ba.sin_port = htons(portno);
02977
02978 if ((val = ast_variable_retrieve(cfg, "general", "bindaddr"))) {
02979 if (!inet_aton(val, &ba.sin_addr)) {
02980 ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
02981 memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
02982 }
02983 }
02984
02985
02986 if ((asock > -1) && ((portno != oldportno) || !enabled)) {
02987 #if 0
02988
02989 close(asock);
02990 asock = -1;
02991 #else
02992 ast_log(LOG_WARNING, "Unable to change management port / enabled\n");
02993 #endif
02994 }
02995
02996 AST_LIST_LOCK(&users);
02997
02998 if ((ucfg = ast_config_load("users.conf"))) {
02999 while ((cat = ast_category_browse(ucfg, cat))) {
03000 int hasmanager = 0;
03001 struct ast_variable *var = NULL;
03002
03003 if (!strcasecmp(cat, "general")) {
03004 continue;
03005 }
03006
03007 if (!(hasmanager = ast_true(ast_variable_retrieve(ucfg, cat, "hasmanager")))) {
03008 continue;
03009 }
03010
03011
03012 if (!(user = ast_get_manager_by_name_locked(cat))) {
03013 if (!(user = ast_calloc(1, sizeof(*user)))) {
03014 break;
03015 }
03016
03017 ast_copy_string(user->username, cat, sizeof(user->username));
03018
03019 AST_LIST_INSERT_TAIL(&users, user, list);
03020 }
03021
03022
03023 user->keep = 1;
03024
03025 for (var = ast_variable_browse(ucfg, cat); var; var = var->next) {
03026 if (!strcasecmp(var->name, "secret")) {
03027 if (user->secret) {
03028 free(user->secret);
03029 }
03030 user->secret = ast_strdup(var->value);
03031 } else if (!strcasecmp(var->name, "deny") ) {
03032 if (user->deny) {
03033 free(user->deny);
03034 }
03035 user->deny = ast_strdup(var->value);
03036 } else if (!strcasecmp(var->name, "permit") ) {
03037 if (user->permit) {
03038 free(user->permit);
03039 }
03040 user->permit = ast_strdup(var->value);
03041 } else if (!strcasecmp(var->name, "read") ) {
03042 if (user->read) {
03043 free(user->read);
03044 }
03045 user->read = ast_strdup(var->value);
03046 } else if (!strcasecmp(var->name, "write") ) {
03047 if (user->write) {
03048 free(user->write);
03049 }
03050 user->write = ast_strdup(var->value);
03051 } else if (!strcasecmp(var->name, "displayconnects") ) {
03052 user->displayconnects = ast_true(var->value);
03053 } else if (!strcasecmp(var->name, "hasmanager")) {
03054
03055 } else {
03056 ast_log(LOG_DEBUG, "%s is an unknown option (to the manager module).\n", var->name);
03057 }
03058 }
03059 }
03060 ast_config_destroy(ucfg);
03061 }
03062
03063 while ((cat = ast_category_browse(cfg, cat))) {
03064 struct ast_variable *var = NULL;
03065
03066 if (!strcasecmp(cat, "general"))
03067 continue;
03068
03069
03070 if (!(user = ast_get_manager_by_name_locked(cat))) {
03071 if (!(user = ast_calloc(1, sizeof(*user))))
03072 break;
03073
03074 ast_copy_string(user->username, cat, sizeof(user->username));
03075
03076 AST_LIST_INSERT_TAIL(&users, user, list);
03077 }
03078
03079
03080 user->keep = 1;
03081
03082 var = ast_variable_browse(cfg, cat);
03083 while (var) {
03084 if (!strcasecmp(var->name, "secret")) {
03085 if (user->secret)
03086 free(user->secret);
03087 user->secret = ast_strdup(var->value);
03088 } else if (!strcasecmp(var->name, "deny") ) {
03089 if (user->deny)
03090 free(user->deny);
03091 user->deny = ast_strdup(var->value);
03092 } else if (!strcasecmp(var->name, "permit") ) {
03093 if (user->permit)
03094 free(user->permit);
03095 user->permit = ast_strdup(var->value);
03096 } else if (!strcasecmp(var->name, "read") ) {
03097 if (user->read)
03098 free(user->read);
03099 user->read = ast_strdup(var->value);
03100 } else if (!strcasecmp(var->name, "write") ) {
03101 if (user->write)
03102 free(user->write);
03103 user->write = ast_strdup(var->value);
03104 } else if (!strcasecmp(var->name, "displayconnects") )
03105 user->displayconnects = ast_true(var->value);
03106 else
03107 ast_log(LOG_DEBUG, "%s is an unknown option.\n", var->name);
03108 var = var->next;
03109 }
03110 }
03111
03112
03113 AST_LIST_TRAVERSE_SAFE_BEGIN(&users, user, list) {
03114 if (user->keep) {
03115 user->keep = 0;
03116 continue;
03117 }
03118
03119 AST_LIST_REMOVE_CURRENT(&users, list);
03120
03121 if (user->secret)
03122 free(user->secret);
03123 if (user->deny)
03124 free(user->deny);
03125 if (user->permit)
03126 free(user->permit);
03127 if (user->read)
03128 free(user->read);
03129 if (user->write)
03130 free(user->write);
03131 free(user);
03132 }
03133 AST_LIST_TRAVERSE_SAFE_END
03134
03135 AST_LIST_UNLOCK(&users);
03136
03137 ast_config_destroy(cfg);
03138
03139 if (webenabled && enabled) {
03140 if (!webregged) {
03141 ast_http_uri_link(&rawmanuri);
03142 ast_http_uri_link(&manageruri);
03143 ast_http_uri_link(&managerxmluri);
03144 webregged = 1;
03145 }
03146 } else {
03147 if (webregged) {
03148 ast_http_uri_unlink(&rawmanuri);
03149 ast_http_uri_unlink(&manageruri);
03150 ast_http_uri_unlink(&managerxmluri);
03151 webregged = 0;
03152 }
03153 }
03154
03155 if (newhttptimeout > 0)
03156 httptimeout = newhttptimeout;
03157
03158
03159 if (!enabled)
03160 return 0;
03161
03162 if (asock < 0) {
03163 asock = socket(AF_INET, SOCK_STREAM, 0);
03164 if (asock < 0) {
03165 ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
03166 return -1;
03167 }
03168 setsockopt(asock, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
03169 if (bind(asock, (struct sockaddr *)&ba, sizeof(ba))) {
03170 ast_log(LOG_WARNING, "Unable to bind socket: %s\n", strerror(errno));
03171 close(asock);
03172 asock = -1;
03173 return -1;
03174 }
03175 if (listen(asock, 2)) {
03176 ast_log(LOG_WARNING, "Unable to listen on socket: %s\n", strerror(errno));
03177 close(asock);
03178 asock = -1;
03179 return -1;
03180 }
03181 flags = fcntl(asock, F_GETFL);
03182 fcntl(asock, F_SETFL, flags | O_NONBLOCK);
03183 if (option_verbose)
03184 ast_verbose("Asterisk Management interface listening on port %d\n", portno);
03185 ast_pthread_create_background(&t, NULL, accept_thread, NULL);
03186 }
03187 return 0;
03188 }
03189
03190 int reload_manager(void)
03191 {
03192 manager_event(EVENT_FLAG_SYSTEM, "Reload", "Message: Reload Requested\r\n");
03193 return init_manager();
03194 }