2 * Asterisk -- A telephony toolkit for Linux.
4 * The Asterisk Management Interface - AMI
6 * Channel Management and more
8 * Copyright (C) 1999 - 2005, Digium, Inc.
10 * Mark Spencer <markster@digium.com>
12 * This program is free software, distributed under the terms of
13 * the GNU General Public License
20 #include <sys/types.h>
22 #include <sys/socket.h>
23 #include <netinet/in.h>
24 #include <netinet/tcp.h>
25 #include <arpa/inet.h>
29 #include <asterisk/channel.h>
30 #include <asterisk/file.h>
31 #include <asterisk/manager.h>
32 #include <asterisk/config.h>
33 #include <asterisk/callerid.h>
34 #include <asterisk/lock.h>
35 #include <asterisk/logger.h>
36 #include <asterisk/options.h>
37 #include <asterisk/cli.h>
38 #include <asterisk/app.h>
39 #include <asterisk/pbx.h>
40 #include <asterisk/md5.h>
41 #include <asterisk/acl.h>
42 #include <asterisk/utils.h>
44 struct fast_originate_helper
61 static int enabled = 0;
62 static int portno = DEFAULT_MANAGER_PORT;
63 static int asock = -1;
64 static int displayconnects = 1;
67 AST_MUTEX_DEFINE_STATIC(sessionlock);
68 static int block_sockets = 0;
70 static struct permalias {
74 { EVENT_FLAG_SYSTEM, "system" },
75 { EVENT_FLAG_CALL, "call" },
76 { EVENT_FLAG_LOG, "log" },
77 { EVENT_FLAG_VERBOSE, "verbose" },
78 { EVENT_FLAG_COMMAND, "command" },
79 { EVENT_FLAG_AGENT, "agent" },
80 { EVENT_FLAG_USER, "user" },
85 static struct mansession *sessions = NULL;
86 static struct manager_action *first_action = NULL;
87 AST_MUTEX_DEFINE_STATIC(actionlock);
89 int ast_carefulwrite(int fd, char *s, int len, int timeoutms)
91 /* Try to write string, but wait no more than ms milliseconds
96 res = write(fd, s, len);
97 if ((res < 0) && (errno != EAGAIN)) {
100 if (res < 0) res = 0;
104 fds[0].events = POLLOUT;
105 /* Wait until writable again */
106 res = poll(fds, 1, timeoutms);
113 /*--- authority_to_str: Convert authority code to string with serveral options */
114 static char *authority_to_str(int authority, char *res, int reslen)
116 int running_total = 0, i;
117 memset(res, 0, reslen);
118 for (i=0; i<sizeof(perms) / sizeof(perms[0]) - 1; i++) {
119 if (authority & perms[i].num) {
121 strncat(res, ",", (reslen > running_total) ? reslen - running_total : 0);
124 strncat(res, perms[i].label, (reslen > running_total) ? reslen - running_total : 0);
125 running_total += strlen(perms[i].label);
128 if (ast_strlen_zero(res)) {
129 strncpy(res, "<none>", reslen);
134 static char *complete_show_mancmd(char *line, char *word, int pos, int state)
136 struct manager_action *cur = first_action;
139 ast_mutex_lock(&actionlock);
140 while (cur) { /* Walk the list of actions */
141 if (!strncasecmp(word, cur->action, strlen(word))) {
142 if (++which > state) {
143 char *ret = strdup(cur->action);
144 ast_mutex_unlock(&actionlock);
150 ast_mutex_unlock(&actionlock);
154 static int handle_showmancmd(int fd, int argc, char *argv[])
156 struct manager_action *cur = first_action;
161 return RESULT_SHOWUSAGE;
162 ast_mutex_lock(&actionlock);
163 while (cur) { /* Walk the list of actions */
164 for (num = 3; num < argc; num++) {
165 if (!strcasecmp(cur->action, argv[num])) {
166 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 : "");
172 ast_mutex_unlock(&actionlock);
173 return RESULT_SUCCESS;
176 /*--- handle_showmancmds: CLI command */
177 /* Should change to "manager show commands" */
178 static int handle_showmancmds(int fd, int argc, char *argv[])
180 struct manager_action *cur = first_action;
182 char *format = " %-15.15s %-15.15s %-55.55s\n";
184 ast_mutex_lock(&actionlock);
185 ast_cli(fd, format, "Action", "Privilege", "Synopsis");
186 ast_cli(fd, format, "------", "---------", "--------");
187 while (cur) { /* Walk the list of actions */
188 ast_cli(fd, format, cur->action, authority_to_str(cur->authority, authority, sizeof(authority) -1), cur->synopsis);
192 ast_mutex_unlock(&actionlock);
193 return RESULT_SUCCESS;
196 /*--- handle_showmanconn: CLI command show manager connected */
197 /* Should change to "manager show connected" */
198 static int handle_showmanconn(int fd, int argc, char *argv[])
200 struct mansession *s;
201 char iabuf[INET_ADDRSTRLEN];
202 char *format = " %-15.15s %-15.15s\n";
203 ast_mutex_lock(&sessionlock);
205 ast_cli(fd, format, "Username", "IP Address");
207 ast_cli(fd, format,s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
211 ast_mutex_unlock(&sessionlock);
212 return RESULT_SUCCESS;
215 static char showmancmd_help[] =
216 "Usage: show manager command <actionname>\n"
217 " Shows the detailed description for a specific Asterisk manager interface command.\n";
219 static char showmancmds_help[] =
220 "Usage: show manager commands\n"
221 " Prints a listing of all the available Asterisk manager interface commands.\n";
223 static char showmanconn_help[] =
224 "Usage: show manager connected\n"
225 " Prints a listing of the users that are currently connected to the\n"
226 "Asterisk manager interface.\n";
228 static struct ast_cli_entry show_mancmd_cli =
229 { { "show", "manager", "command", NULL },
230 handle_showmancmd, "Show a manager interface command", showmancmd_help, complete_show_mancmd };
232 static struct ast_cli_entry show_mancmds_cli =
233 { { "show", "manager", "commands", NULL },
234 handle_showmancmds, "List manager interface commands", showmancmds_help };
236 static struct ast_cli_entry show_manconn_cli =
237 { { "show", "manager", "connected", NULL },
238 handle_showmanconn, "Show connected manager interface users", showmanconn_help };
240 static void destroy_session(struct mansession *s)
242 struct mansession *cur, *prev = NULL;
243 ast_mutex_lock(&sessionlock);
253 prev->next = cur->next;
255 sessions = cur->next;
258 ast_mutex_destroy(&s->lock);
261 ast_log(LOG_WARNING, "Trying to delete non-existant session %p?\n", s);
262 ast_mutex_unlock(&sessionlock);
266 char *astman_get_header(struct message *m, char *var)
270 snprintf(cmp, sizeof(cmp), "%s: ", var);
271 for (x=0;x<m->hdrcount;x++)
272 if (!strncasecmp(cmp, m->headers[x], strlen(cmp)))
273 return m->headers[x] + strlen(cmp);
277 void astman_send_error(struct mansession *s, struct message *m, char *error)
279 char *id = astman_get_header(m,"ActionID");
280 ast_mutex_lock(&s->lock);
281 ast_cli(s->fd, "Response: Error\r\n");
282 if (id && !ast_strlen_zero(id))
283 ast_cli(s->fd, "ActionID: %s\r\n",id);
284 ast_cli(s->fd, "Message: %s\r\n\r\n", error);
285 ast_mutex_unlock(&s->lock);
288 void astman_send_response(struct mansession *s, struct message *m, char *resp, char *msg)
290 char *id = astman_get_header(m,"ActionID");
291 ast_mutex_lock(&s->lock);
292 ast_cli(s->fd, "Response: %s\r\n", resp);
293 if (id && !ast_strlen_zero(id))
294 ast_cli(s->fd, "ActionID: %s\r\n",id);
296 ast_cli(s->fd, "Message: %s\r\n\r\n", msg);
298 ast_cli(s->fd, "\r\n");
299 ast_mutex_unlock(&s->lock);
302 void astman_send_ack(struct mansession *s, struct message *m, char *msg)
304 astman_send_response(s, m, "Success", msg);
307 /* Tells you if smallstr exists inside bigstr
308 which is delim by delim and uses no buf or stringsep
309 ast_instring("this|that|more","this",',') == 1;
311 feel free to move this to app.c -anthm */
312 static int ast_instring(char *bigstr, char *smallstr, char delim)
314 char *val = bigstr, *next;
317 if ((next = strchr(val, delim))) {
318 if (!strncmp(val, smallstr, (next - val)))
323 return !strcmp(smallstr, val);
325 } while (*(val = (next + 1)));
330 static int get_perm(char *instr)
337 for (x=0; x<sizeof(perms) / sizeof(perms[0]); x++)
338 if (ast_instring(instr, perms[x].label, ','))
344 static int ast_is_number(char *string)
351 for (x=0; x < strlen(string); x++) {
352 if (!(string[x] >= 48 && string[x] <= 57)) {
358 return ret ? atoi(string) : 0;
361 static int ast_strings_to_mask(char *string)
365 x = ast_is_number(string);
369 else if (!string || ast_strlen_zero(string))
371 else if (!strcasecmp(string, "off") || ast_false(string))
373 else if (!strcasecmp(string, "on") || ast_true(string))
377 for (x=0; x<sizeof(perms) / sizeof(perms[0]); x++) {
378 if (ast_instring(string, perms[x].label, ','))
387 Rather than braindead on,off this now can also accept a specific int mask value
388 or a ',' delim list of mask strings (the same as manager.conf) -anthm
391 static int set_eventmask(struct mansession *s, char *eventmask)
393 int maskint = ast_strings_to_mask(eventmask);
395 ast_mutex_lock(&s->lock);
396 s->send_events = maskint;
397 ast_mutex_unlock(&s->lock);
399 return s->send_events;
402 static int authenticate(struct mansession *s, struct message *m)
404 struct ast_config *cfg;
405 char iabuf[INET_ADDRSTRLEN];
407 char *user = astman_get_header(m, "Username");
408 char *pass = astman_get_header(m, "Secret");
409 char *authtype = astman_get_header(m, "AuthType");
410 char *key = astman_get_header(m, "Key");
411 char *events = astman_get_header(m, "Events");
413 cfg = ast_config_load("manager.conf");
416 cat = ast_category_browse(cfg, NULL);
418 if (strcasecmp(cat, "general")) {
420 if (!strcasecmp(cat, user)) {
421 struct ast_variable *v;
422 struct ast_ha *ha = NULL;
423 char *password = NULL;
424 v = ast_variable_browse(cfg, cat);
426 if (!strcasecmp(v->name, "secret")) {
428 } else if (!strcasecmp(v->name, "permit") ||
429 !strcasecmp(v->name, "deny")) {
430 ha = ast_append_ha(v->name, v->value, ha);
435 if (ha && !ast_apply_ha(ha, &(s->sin))) {
436 ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr), user);
438 ast_config_destroy(cfg);
442 if (!strcasecmp(authtype, "MD5")) {
443 if (key && !ast_strlen_zero(key) && s->challenge) {
446 char md5key[256] = "";
447 struct MD5Context md5;
448 unsigned char digest[16];
450 MD5Update(&md5, s->challenge, strlen(s->challenge));
451 MD5Update(&md5, password, strlen(password));
452 MD5Final(digest, &md5);
454 len += sprintf(md5key + len, "%2.2x", digest[x]);
455 if (!strcmp(md5key, key))
458 ast_config_destroy(cfg);
462 } else if (password && !strcasecmp(password, pass)) {
465 ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr), user);
466 ast_config_destroy(cfg);
471 cat = ast_category_browse(cfg, cat);
474 strncpy(s->username, cat, sizeof(s->username) - 1);
475 s->readperm = get_perm(ast_variable_retrieve(cfg, cat, "read"));
476 s->writeperm = get_perm(ast_variable_retrieve(cfg, cat, "write"));
477 ast_config_destroy(cfg);
479 set_eventmask(s, events);
482 ast_log(LOG_NOTICE, "%s tried to authenticate with non-existant user '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr), user);
483 ast_config_destroy(cfg);
487 static char mandescr_ping[] =
488 "Description: A 'Ping' action will ellicit a 'Pong' response. Used to keep the "
489 " manager connection open.\n"
492 static int action_ping(struct mansession *s, struct message *m)
494 astman_send_response(s, m, "Pong", NULL);
498 static char mandescr_listcommands[] =
499 "Description: Returns the action name and synopsis for every\n"
500 " action that is available to the user\n"
503 static int action_listcommands(struct mansession *s, struct message *m)
505 struct manager_action *cur = first_action;
506 char idText[256] = "";
508 char *id = astman_get_header(m,"ActionID");
510 if (id && !ast_strlen_zero(id))
511 snprintf(idText,256,"ActionID: %s\r\n",id);
512 ast_cli(s->fd, "Response: Success\r\n%s", idText);
513 ast_mutex_lock(&s->lock);
514 ast_mutex_lock(&actionlock);
515 while (cur) { /* Walk the list of actions */
516 if ((s->writeperm & cur->authority) == cur->authority)
517 ast_cli(s->fd, "%s: %s (Priv: %s)\r\n", cur->action, cur->synopsis, authority_to_str(cur->authority, temp, sizeof(temp)) );
520 ast_mutex_unlock(&actionlock);
521 ast_cli(s->fd, "\r\n");
522 ast_mutex_unlock(&s->lock);
527 static char mandescr_events[] =
528 "Description: Enable/Disable sending of events to this manager\n"
531 " EventMask: 'on' if all events should be sent,\n"
532 " 'off' if no events should be sent,\n"
533 " 'system,call,log' to select which flags events should have to be sent.\n";
535 static int action_events(struct mansession *s, struct message *m)
537 char *mask = astman_get_header(m, "EventMask");
540 res = set_eventmask(s, mask);
542 astman_send_response(s, m, "Events On", NULL);
544 astman_send_response(s, m, "Events Off", NULL);
549 static char mandescr_logoff[] =
550 "Description: Logoff this manager session\n"
553 static int action_logoff(struct mansession *s, struct message *m)
555 astman_send_response(s, m, "Goodbye", "Thanks for all the fish.");
559 static char mandescr_hangup[] =
560 "Description: Hangup a channel\n"
562 " Channel: The channel name to be hungup\n";
564 static int action_hangup(struct mansession *s, struct message *m)
566 struct ast_channel *c = NULL;
567 char *name = astman_get_header(m, "Channel");
568 if (ast_strlen_zero(name)) {
569 astman_send_error(s, m, "No channel specified");
572 c = ast_channel_walk_locked(NULL);
574 if (!strcasecmp(c->name, name)) {
577 ast_mutex_unlock(&c->lock);
578 c = ast_channel_walk_locked(c);
581 astman_send_error(s, m, "No such channel");
584 ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
585 ast_mutex_unlock(&c->lock);
586 astman_send_ack(s, m, "Channel Hungup");
590 static char mandescr_setvar[] =
591 "Description: Set a local channel variable.\n"
592 "Variables: (Names marked with * are required)\n"
593 " *Channel: Channel to set variable for\n"
594 " *Variable: Variable name\n"
597 static int action_setvar(struct mansession *s, struct message *m)
599 struct ast_channel *c = NULL;
600 char *name = astman_get_header(m, "Channel");
601 char *varname = astman_get_header(m, "Variable");
602 char *varval = astman_get_header(m, "Value");
605 astman_send_error(s, m, "No channel specified");
608 if (!strlen(varname)) {
609 astman_send_error(s, m, "No variable specified");
613 c = ast_channel_walk_locked(NULL);
615 if (!strcasecmp(c->name, name)) {
618 ast_mutex_unlock(&c->lock);
619 c = ast_channel_walk_locked(c);
622 astman_send_error(s, m, "No such channel");
626 pbx_builtin_setvar_helper(c,varname,varval);
628 ast_mutex_unlock(&c->lock);
629 astman_send_ack(s, m, "Variable Set");
633 static char mandescr_getvar[] =
634 "Description: Get the value of a local channel variable.\n"
635 "Variables: (Names marked with * are required)\n"
636 " *Channel: Channel to read variable from\n"
637 " *Variable: Variable name\n"
638 " ActionID: Optional Action id for message matching.\n";
640 static int action_getvar(struct mansession *s, struct message *m)
642 struct ast_channel *c = NULL;
643 char *name = astman_get_header(m, "Channel");
644 char *varname = astman_get_header(m, "Variable");
645 char *id = astman_get_header(m,"ActionID");
650 astman_send_error(s, m, "No channel specified");
653 if (!strlen(varname)) {
654 astman_send_error(s, m, "No variable specified");
658 c = ast_channel_walk_locked(NULL);
660 if (!strcasecmp(c->name, name)) {
663 ast_mutex_unlock(&c->lock);
664 c = ast_channel_walk_locked(c);
667 astman_send_error(s, m, "No such channel");
671 varval=pbx_builtin_getvar_helper(c,varname);
673 varval2 = ast_strdupa(varval);
676 ast_mutex_unlock(&c->lock);
677 ast_mutex_lock(&s->lock);
678 ast_cli(s->fd, "Response: Success\r\n"
679 "%s: %s\r\n" ,varname,varval2);
680 if (id && !ast_strlen_zero(id))
681 ast_cli(s->fd, "ActionID: %s\r\n",id);
682 ast_cli(s->fd, "\r\n");
683 ast_mutex_unlock(&s->lock);
689 static int action_status(struct mansession *s, struct message *m)
691 char *id = astman_get_header(m,"ActionID");
692 char *name = astman_get_header(m,"Channel");
693 char idText[256] = "";
694 struct ast_channel *c;
697 long elapsed_seconds=0;
699 gettimeofday(&now, NULL);
700 astman_send_ack(s, m, "Channel status will follow");
701 c = ast_channel_walk_locked(NULL);
702 if (id && !ast_strlen_zero(id))
703 snprintf(idText,256,"ActionID: %s\r\n",id);
704 if (name && !ast_strlen_zero(name)) {
706 if (!strcasecmp(c->name, name)) {
709 ast_mutex_unlock(&c->lock);
710 c = ast_channel_walk_locked(c);
713 astman_send_error(s, m, "No such channel");
719 snprintf(bridge, sizeof(bridge), "Link: %s\r\n", c->_bridge->name);
722 ast_mutex_lock(&s->lock);
725 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
729 "Privilege: Call\r\n"
732 "CallerIDName: %s\r\n"
744 c->cid.cid_num ? c->cid.cid_num : "<unknown>",
745 c->cid.cid_name ? c->cid.cid_name : "<unknown>",
747 ast_state2str(c->_state), c->context,
748 c->exten, c->priority, (long)elapsed_seconds, bridge, c->uniqueid, idText);
752 "Privilege: Call\r\n"
755 "CallerIDName: %s\r\n"
763 c->cid.cid_num ? c->cid.cid_num : "<unknown>",
764 c->cid.cid_name ? c->cid.cid_name : "<unknown>",
766 ast_state2str(c->_state), bridge, c->uniqueid, idText);
768 ast_mutex_unlock(&s->lock);
769 ast_mutex_unlock(&c->lock);
770 if (name && !ast_strlen_zero(name)) {
773 c = ast_channel_walk_locked(c);
775 ast_mutex_lock(&s->lock);
777 "Event: StatusComplete\r\n"
780 ast_mutex_unlock(&s->lock);
784 static int action_redirect(struct mansession *s, struct message *m)
786 char *name = astman_get_header(m, "Channel");
787 char *name2 = astman_get_header(m, "ExtraChannel");
788 char *exten = astman_get_header(m, "Exten");
789 char *context = astman_get_header(m, "Context");
790 char *priority = astman_get_header(m, "Priority");
791 struct ast_channel *chan, *chan2 = NULL;
794 if (!name || ast_strlen_zero(name)) {
795 astman_send_error(s, m, "Channel not specified");
798 if (!ast_strlen_zero(priority) && (sscanf(priority, "%d", &pi) != 1)) {
799 astman_send_error(s, m, "Invalid priority\n");
802 chan = ast_get_channel_by_name_locked(name);
804 astman_send_error(s, m, "Channel not existant");
807 if (!ast_strlen_zero(name2))
808 chan2 = ast_get_channel_by_name_locked(name2);
809 res = ast_async_goto(chan, context, exten, pi);
811 if (!ast_strlen_zero(name2)) {
813 res = ast_async_goto(chan2, context, exten, pi);
817 astman_send_ack(s, m, "Dual Redirect successful");
819 astman_send_error(s, m, "Secondary redirect failed");
821 astman_send_ack(s, m, "Redirect successful");
823 astman_send_error(s, m, "Redirect failed");
825 ast_mutex_unlock(&chan->lock);
827 ast_mutex_unlock(&chan2->lock);
831 static char mandescr_command[] =
832 "Description: Run a CLI command.\n"
833 "Variables: (Names marked with * are required)\n"
834 " *Command: Asterisk CLI command to run\n"
835 " ActionID: Optional Action id for message matching.\n";
836 static int action_command(struct mansession *s, struct message *m)
838 char *cmd = astman_get_header(m, "Command");
839 char *id = astman_get_header(m, "ActionID");
840 ast_mutex_lock(&s->lock);
842 ast_mutex_unlock(&s->lock);
843 ast_cli(s->fd, "Response: Follows\r\nPrivilege: Command\r\n");
844 if (id && !ast_strlen_zero(id))
845 ast_cli(s->fd, "ActionID: %s\r\n", id);
846 /* FIXME: Wedge a ActionID response in here, waiting for later changes */
847 ast_cli_command(s->fd, cmd);
848 ast_cli(s->fd, "--END COMMAND--\r\n\r\n");
849 ast_mutex_lock(&s->lock);
851 ast_mutex_unlock(&s->lock);
855 static void *fast_originate(void *data)
857 struct fast_originate_helper *in = data;
860 struct ast_channel *chan = NULL;
862 if (!ast_strlen_zero(in->app)) {
863 res = ast_pbx_outgoing_app(in->tech, AST_FORMAT_SLINEAR, in->data, in->timeout, in->app, in->appdata, &reason, 1,
864 !ast_strlen_zero(in->cid_num) ? in->cid_num : NULL,
865 !ast_strlen_zero(in->cid_name) ? in->cid_name : NULL,
866 in->variable, in->account, &chan);
868 res = ast_pbx_outgoing_exten(in->tech, AST_FORMAT_SLINEAR, in->data, in->timeout, in->context, in->exten, in->priority, &reason, 1,
869 !ast_strlen_zero(in->cid_num) ? in->cid_num : NULL,
870 !ast_strlen_zero(in->cid_name) ? in->cid_name : NULL,
871 in->variable, in->account, &chan);
874 manager_event(EVENT_FLAG_CALL,
882 in->idtext, in->tech, in->data, in->context, in->exten, reason, chan ? chan->uniqueid : "<null>");
884 manager_event(EVENT_FLAG_CALL,
892 in->idtext, in->tech, in->data, in->context, in->exten, reason, chan ? chan->uniqueid : "<null>");
894 /* Locked by ast_pbx_outgoing_exten or ast_pbx_outgoing_app */
896 ast_mutex_unlock(&chan->lock);
901 static char mandescr_originate[] =
902 "Description: Generates an outgoing call to a Extension/Context/Priority or\n"
903 " Application/Data\n"
904 "Variables: (Names marked with * are required)\n"
905 " *Channel: Channel name to call\n"
906 " Exten: Extension to use (requires 'Context' and 'Priority')\n"
907 " Context: Context to use (requires 'Exten' and 'Priority')\n"
908 " Priority: Priority to use (requires 'Exten' and 'Context')\n"
909 " Application: Application to use\n"
910 " Data: Data to use (requires 'Application')\n"
911 " Timeout: How long to wait for call to be answered (in ms)\n"
912 " CallerID: Caller ID to be set on the outgoing channel\n"
913 " Variable: Channel variable to set (VAR1=value1|VAR2=value2)\n"
914 " Account: Account code\n"
915 " Async: Set to 'true' for fast origination\n";
917 static int action_originate(struct mansession *s, struct message *m)
919 char *name = astman_get_header(m, "Channel");
920 char *exten = astman_get_header(m, "Exten");
921 char *context = astman_get_header(m, "Context");
922 char *priority = astman_get_header(m, "Priority");
923 char *timeout = astman_get_header(m, "Timeout");
924 char *callerid = astman_get_header(m, "CallerID");
925 char *variable = astman_get_header(m, "Variable");
926 char *account = astman_get_header(m, "Account");
927 char *app = astman_get_header(m, "Application");
928 char *appdata = astman_get_header(m, "Data");
929 char *async = astman_get_header(m, "Async");
930 char *id = astman_get_header(m, "ActionID");
932 char *l=NULL, *n=NULL;
943 astman_send_error(s, m, "Channel not specified");
946 if (!ast_strlen_zero(priority) && (sscanf(priority, "%d", &pi) != 1)) {
947 astman_send_error(s, m, "Invalid priority\n");
950 if (!ast_strlen_zero(timeout) && (sscanf(timeout, "%d", &to) != 1)) {
951 astman_send_error(s, m, "Invalid timeout\n");
954 strncpy(tmp, name, sizeof(tmp) - 1);
956 data = strchr(tmp, '/');
958 astman_send_error(s, m, "Invalid channel\n");
963 strncpy(tmp2, callerid, sizeof(tmp2) - 1);
964 ast_callerid_parse(tmp2, &n, &l);
966 if (ast_strlen_zero(n))
970 ast_shrink_phone_number(l);
971 if (ast_strlen_zero(l))
974 if (ast_true(async)) {
975 struct fast_originate_helper *fast = malloc(sizeof(struct fast_originate_helper));
979 memset(fast, 0, sizeof(struct fast_originate_helper));
980 if (id && !ast_strlen_zero(id))
981 snprintf(fast->idtext, sizeof(fast->idtext), "ActionID: %s\r\n", id);
982 strncpy(fast->tech, tech, sizeof(fast->tech) - 1);
983 strncpy(fast->data, data, sizeof(fast->data) - 1);
984 strncpy(fast->app, app, sizeof(fast->app) - 1);
985 strncpy(fast->appdata, appdata, sizeof(fast->appdata) - 1);
987 strncpy(fast->cid_num, l, sizeof(fast->cid_num) - 1);
989 strncpy(fast->cid_name, n, sizeof(fast->cid_name) - 1);
990 strncpy(fast->variable, variable, sizeof(fast->variable) - 1);
991 strncpy(fast->account, account, sizeof(fast->account) - 1);
992 strncpy(fast->context, context, sizeof(fast->context) - 1);
993 strncpy(fast->exten, exten, sizeof(fast->exten) - 1);
996 pthread_attr_init(&attr);
997 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
998 if (ast_pthread_create(&th, &attr, fast_originate, fast)) {
1004 } else if (!ast_strlen_zero(app)) {
1005 res = ast_pbx_outgoing_app(tech, AST_FORMAT_SLINEAR, data, to, app, appdata, &reason, 1, l, n, variable, account, NULL);
1007 if (exten && context && pi)
1008 res = ast_pbx_outgoing_exten(tech, AST_FORMAT_SLINEAR, data, to, context, exten, pi, &reason, 1, l, n, variable, account, NULL);
1010 astman_send_error(s, m, "Originate with 'Exten' requires 'Context' and 'Priority'");
1015 astman_send_ack(s, m, "Originate successfully queued");
1017 astman_send_error(s, m, "Originate failed");
1021 static char mandescr_mailboxstatus[] =
1022 "Description: Checks a voicemail account for status.\n"
1023 "Variables: (Names marked with * are required)\n"
1024 " *Mailbox: Full mailbox ID <mailbox>@<vm-context>\n"
1025 " ActionID: Optional ActionID for message matching.\n"
1026 "Returns number of messages.\n"
1027 " Message: Mailbox Status\n"
1028 " Mailbox: <mailboxid>\n"
1029 " Waiting: <count>\n"
1031 static int action_mailboxstatus(struct mansession *s, struct message *m)
1033 char *mailbox = astman_get_header(m, "Mailbox");
1034 char *id = astman_get_header(m,"ActionID");
1035 char idText[256] = "";
1037 if (!mailbox || ast_strlen_zero(mailbox)) {
1038 astman_send_error(s, m, "Mailbox not specified");
1041 if (id && !ast_strlen_zero(id))
1042 snprintf(idText,256,"ActionID: %s\r\n",id);
1043 ret = ast_app_has_voicemail(mailbox, NULL);
1044 ast_mutex_lock(&s->lock);
1045 ast_cli(s->fd, "Response: Success\r\n"
1047 "Message: Mailbox Status\r\n"
1049 "Waiting: %d\r\n\r\n", idText, mailbox, ret);
1050 ast_mutex_unlock(&s->lock);
1054 static char mandescr_mailboxcount[] =
1055 "Description: Checks a voicemail account for new messages.\n"
1056 "Variables: (Names marked with * are required)\n"
1057 " *Mailbox: Full mailbox ID <mailbox>@<vm-context>\n"
1058 " ActionID: Optional ActionID for message matching.\n"
1059 "Returns number of new and old messages.\n"
1060 " Message: Mailbox Message Count\n"
1061 " Mailbox: <mailboxid>\n"
1062 " NewMessages: <count>\n"
1063 " OldMessages: <count>\n"
1065 static int action_mailboxcount(struct mansession *s, struct message *m)
1067 char *mailbox = astman_get_header(m, "Mailbox");
1068 char *id = astman_get_header(m,"ActionID");
1069 char idText[256] = "";
1070 int newmsgs = 0, oldmsgs = 0;
1071 if (!mailbox || ast_strlen_zero(mailbox)) {
1072 astman_send_error(s, m, "Mailbox not specified");
1075 ast_app_messagecount(mailbox, &newmsgs, &oldmsgs);
1076 if (id && !ast_strlen_zero(id)) {
1077 snprintf(idText,256,"ActionID: %s\r\n",id);
1079 ast_mutex_lock(&s->lock);
1080 ast_cli(s->fd, "Response: Success\r\n"
1082 "Message: Mailbox Message Count\r\n"
1084 "NewMessages: %d\r\n"
1085 "OldMessages: %d\r\n"
1087 idText,mailbox, newmsgs, oldmsgs);
1088 ast_mutex_unlock(&s->lock);
1092 static char mandescr_extensionstate[] =
1093 "Description: Report the extension state for given extension.\n"
1094 " If the extension has a hint, will use devicestate to check\n"
1095 " the status of the device connected to the extension.\n"
1096 "Variables: (Names marked with * are required)\n"
1097 " *Exten: Extension to check state on\n"
1098 " *Context: Context for extension\n"
1099 " ActionId: Optional ID for this transaction\n"
1100 "Will return an \"Extension Status\" message.\n"
1101 "The response will include the hint for the extension and the status.\n";
1103 static int action_extensionstate(struct mansession *s, struct message *m)
1105 char *exten = astman_get_header(m, "Exten");
1106 char *context = astman_get_header(m, "Context");
1107 char *id = astman_get_header(m,"ActionID");
1108 char idText[256] = "";
1109 char hint[256] = "";
1111 if (!exten || ast_strlen_zero(exten)) {
1112 astman_send_error(s, m, "Extension not specified");
1115 if (!context || ast_strlen_zero(context))
1116 context = "default";
1117 status = ast_extension_state(NULL, context, exten);
1118 ast_get_hint(hint, sizeof(hint) - 1, NULL, 0, NULL, context, exten);
1119 if (id && !ast_strlen_zero(id)) {
1120 snprintf(idText,256,"ActionID: %s\r\n",id);
1122 ast_mutex_lock(&s->lock);
1123 ast_cli(s->fd, "Response: Success\r\n"
1125 "Message: Extension Status\r\n"
1129 "Status: %d\r\n\r\n",
1130 idText,exten, context, hint, status);
1131 ast_mutex_unlock(&s->lock);
1135 static char mandescr_timeout[] =
1136 "Description: Hangup a channel after a certain time.\n"
1137 "Variables: (Names marked with * are required)\n"
1138 " *Channel: Channel name to hangup\n"
1139 " *Timeout: Maximum duration of the call (sec)\n"
1140 "Acknowledges set time with 'Timeout Set' message\n";
1142 static int action_timeout(struct mansession *s, struct message *m)
1144 struct ast_channel *c = NULL;
1145 char *name = astman_get_header(m, "Channel");
1146 int timeout = atoi(astman_get_header(m, "Timeout"));
1147 if (ast_strlen_zero(name)) {
1148 astman_send_error(s, m, "No channel specified");
1152 astman_send_error(s, m, "No timeout specified");
1155 c = ast_channel_walk_locked(NULL);
1157 if (!strcasecmp(c->name, name)) {
1160 ast_mutex_unlock(&c->lock);
1161 c = ast_channel_walk_locked(c);
1164 astman_send_error(s, m, "No such channel");
1167 ast_channel_setwhentohangup(c, timeout);
1168 ast_mutex_unlock(&c->lock);
1169 astman_send_ack(s, m, "Timeout Set");
1173 static int process_message(struct mansession *s, struct message *m)
1175 char action[80] = "";
1176 struct manager_action *tmp = first_action;
1177 char *id = astman_get_header(m,"ActionID");
1178 char idText[256] = "";
1179 char iabuf[INET_ADDRSTRLEN];
1181 strncpy(action, astman_get_header(m, "Action"), sizeof(action) - 1);
1182 ast_log( LOG_DEBUG, "Manager received command '%s'\n", action );
1184 if (ast_strlen_zero(action)) {
1185 astman_send_error(s, m, "Missing action in request");
1188 if (id && !ast_strlen_zero(id)) {
1189 snprintf(idText,256,"ActionID: %s\r\n",id);
1191 if (!s->authenticated) {
1192 if (!strcasecmp(action, "Challenge")) {
1194 authtype = astman_get_header(m, "AuthType");
1195 if (!strcasecmp(authtype, "MD5")) {
1196 if (!s->challenge || ast_strlen_zero(s->challenge)) {
1197 ast_mutex_lock(&s->lock);
1198 snprintf(s->challenge, sizeof(s->challenge), "%d", rand());
1199 ast_mutex_unlock(&s->lock);
1201 ast_mutex_lock(&s->lock);
1202 ast_cli(s->fd, "Response: Success\r\n"
1204 "Challenge: %s\r\n\r\n",
1205 idText,s->challenge);
1206 ast_mutex_unlock(&s->lock);
1209 astman_send_error(s, m, "Must specify AuthType");
1212 } else if (!strcasecmp(action, "Login")) {
1213 if (authenticate(s, m)) {
1215 astman_send_error(s, m, "Authentication failed");
1218 s->authenticated = 1;
1219 if (option_verbose > 1) {
1220 if ( displayconnects ) {
1221 ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged on from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1224 ast_log(LOG_EVENT, "Manager '%s' logged on from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1225 astman_send_ack(s, m, "Authentication accepted");
1227 } else if (!strcasecmp(action, "Logoff")) {
1228 astman_send_ack(s, m, "See ya");
1231 astman_send_error(s, m, "Authentication Required");
1234 if (!strcasecmp(action, tmp->action)) {
1235 if ((s->writeperm & tmp->authority) == tmp->authority) {
1236 if (tmp->func(s, m))
1239 astman_send_error(s, m, "Permission denied");
1245 astman_send_error(s, m, "Invalid/unknown command");
1250 static int get_input(struct mansession *s, char *output)
1252 /* output must have at least sizeof(s->inbuf) space */
1255 struct pollfd fds[1];
1256 char iabuf[INET_ADDRSTRLEN];
1257 for (x=1;x<s->inlen;x++) {
1258 if ((s->inbuf[x] == '\n') && (s->inbuf[x-1] == '\r')) {
1259 /* Copy output data up to and including \r\n */
1260 memcpy(output, s->inbuf, x + 1);
1261 /* Add trailing \0 */
1263 /* Move remaining data back to the front */
1264 memmove(s->inbuf, s->inbuf + x + 1, s->inlen - x);
1265 s->inlen -= (x + 1);
1269 if (s->inlen >= sizeof(s->inbuf) - 1) {
1270 ast_log(LOG_WARNING, "Dumping long line with no return from %s: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr), s->inbuf);
1274 fds[0].events = POLLIN;
1275 res = poll(fds, 1, -1);
1277 ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
1278 } else if (res > 0) {
1279 ast_mutex_lock(&s->lock);
1280 res = read(s->fd, s->inbuf + s->inlen, sizeof(s->inbuf) - 1 - s->inlen);
1281 ast_mutex_unlock(&s->lock);
1286 s->inbuf[s->inlen] = '\0';
1290 static void *session_do(void *data)
1292 struct mansession *s = data;
1294 char iabuf[INET_ADDRSTRLEN];
1297 ast_mutex_lock(&s->lock);
1298 ast_cli(s->fd, "Asterisk Call Manager/1.0\r\n");
1299 ast_mutex_unlock(&s->lock);
1300 memset(&m, 0, sizeof(&m));
1302 res = get_input(s, m.headers[m.hdrcount]);
1304 /* Strip trailing \r\n */
1305 if (strlen(m.headers[m.hdrcount]) < 2)
1307 m.headers[m.hdrcount][strlen(m.headers[m.hdrcount]) - 2] = '\0';
1308 if (ast_strlen_zero(m.headers[m.hdrcount])) {
1309 if (process_message(s, &m))
1311 memset(&m, 0, sizeof(&m));
1312 } else if (m.hdrcount < MAX_HEADERS - 1)
1317 if (s->authenticated) {
1318 if (option_verbose > 1) {
1319 if (displayconnects)
1320 ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged off from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1322 ast_log(LOG_EVENT, "Manager '%s' logged off from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1324 if (option_verbose > 1) {
1325 if ( displayconnects )
1326 ast_verbose(VERBOSE_PREFIX_2 "Connect attempt from '%s' unable to authenticate\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1328 ast_log(LOG_EVENT, "Failed attempt from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
1334 static void *accept_thread(void *ignore)
1337 struct sockaddr_in sin;
1339 struct mansession *s;
1343 pthread_attr_t attr;
1345 pthread_attr_init(&attr);
1346 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1349 sinlen = sizeof(sin);
1350 as = accept(asock, (struct sockaddr *)&sin, &sinlen);
1352 ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
1355 p = getprotobyname("tcp");
1357 if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
1358 ast_log(LOG_WARNING, "Failed to set manager tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
1361 s = malloc(sizeof(struct mansession));
1363 ast_log(LOG_WARNING, "Failed to allocate management session: %s\n", strerror(errno));
1366 memset(s, 0, sizeof(struct mansession));
1367 memcpy(&s->sin, &sin, sizeof(sin));
1369 if(! block_sockets) {
1370 /* For safety, make sure socket is non-blocking */
1371 flags = fcntl(as, F_GETFL);
1372 fcntl(as, F_SETFL, flags | O_NONBLOCK);
1374 ast_mutex_init(&s->lock);
1376 s->send_events = -1;
1377 ast_mutex_lock(&sessionlock);
1380 ast_mutex_unlock(&sessionlock);
1381 if (ast_pthread_create(&t, &attr, session_do, s))
1384 pthread_attr_destroy(&attr);
1388 /*--- manager_event: Send AMI event to client */
1389 int manager_event(int category, char *event, char *fmt, ...)
1391 struct mansession *s;
1395 ast_mutex_lock(&sessionlock);
1398 if (((s->readperm & category) == category) && ((s->send_events & category) == category) ) {
1399 ast_mutex_lock(&s->lock);
1401 ast_cli(s->fd, "Event: %s\r\n", event);
1402 ast_cli(s->fd, "Privilege: %s\r\n", authority_to_str(category, tmp, sizeof(tmp)));
1404 vsnprintf(tmp, sizeof(tmp), fmt, ap);
1406 ast_carefulwrite(s->fd,tmp,strlen(tmp),100);
1407 ast_cli(s->fd, "\r\n");
1409 ast_mutex_unlock(&s->lock);
1413 ast_mutex_unlock(&sessionlock);
1417 int ast_manager_unregister( char *action ) {
1418 struct manager_action *cur = first_action, *prev = first_action;
1420 ast_mutex_lock(&actionlock);
1422 if (!strcasecmp(action, cur->action)) {
1423 prev->next = cur->next;
1425 if (option_verbose > 1)
1426 ast_verbose(VERBOSE_PREFIX_2 "Manager unregistered action %s\n", action);
1427 ast_mutex_unlock(&actionlock);
1433 ast_mutex_unlock(&actionlock);
1437 static int manager_state_cb(char *context, char *exten, int state, void *data)
1439 /* Notify managers of change */
1440 manager_event(EVENT_FLAG_CALL, "ExtensionStatus", "Exten: %s\r\nContext: %s\r\nStatus: %d\r\n", exten, context, state);
1444 static int ast_manager_register_struct(struct manager_action *act)
1446 struct manager_action *cur = first_action, *prev = NULL;
1449 ast_mutex_lock(&actionlock);
1450 while(cur) { /* Walk the list of actions */
1451 ret = strcasecmp(cur->action, act->action);
1453 ast_log(LOG_WARNING, "Manager: Action '%s' already registered\n", act->action);
1454 ast_mutex_unlock(&actionlock);
1456 } else if (ret > 0) {
1457 /* Insert these alphabetically */
1459 act->next = prev->next;
1462 act->next = first_action;
1479 if (option_verbose > 1)
1480 ast_verbose(VERBOSE_PREFIX_2 "Manager registered action %s\n", act->action);
1481 ast_mutex_unlock(&actionlock);
1485 int ast_manager_register2(const char *action, int auth, int (*func)(struct mansession *s, struct message *m), const char *synopsis, const char *description)
1487 struct manager_action *cur;
1489 cur = malloc(sizeof(struct manager_action));
1491 ast_log(LOG_WARNING, "Manager: out of memory trying to register action\n");
1492 ast_mutex_unlock(&actionlock);
1495 cur->action = action;
1496 cur->authority = auth;
1498 cur->synopsis = synopsis;
1499 cur->description = description;
1502 ast_manager_register_struct(cur);
1507 static int registered = 0;
1509 int init_manager(void)
1511 struct ast_config *cfg;
1513 int oldportno = portno;
1514 static struct sockaddr_in ba;
1517 /* Register default actions */
1518 ast_manager_register2("Ping", 0, action_ping, "Keepalive command", mandescr_ping);
1519 ast_manager_register2("Events", 0, action_events, "Control Event Flow", mandescr_events);
1520 ast_manager_register2("Logoff", 0, action_logoff, "Logoff Manager", mandescr_logoff);
1521 ast_manager_register2("Hangup", EVENT_FLAG_CALL, action_hangup, "Hangup Channel", mandescr_hangup);
1522 ast_manager_register( "Status", EVENT_FLAG_CALL, action_status, "Lists channel status" );
1523 ast_manager_register2( "Setvar", EVENT_FLAG_CALL, action_setvar, "Set Channel Variable", mandescr_setvar );
1524 ast_manager_register2( "Getvar", EVENT_FLAG_CALL, action_getvar, "Gets a Channel Variable", mandescr_getvar );
1525 ast_manager_register( "Redirect", EVENT_FLAG_CALL, action_redirect, "Redirect (transfer) a call" );
1526 ast_manager_register2("Originate", EVENT_FLAG_CALL, action_originate, "Originate Call", mandescr_originate);
1527 ast_manager_register2( "Command", EVENT_FLAG_COMMAND, action_command, "Execute Asterisk CLI Command", mandescr_command );
1528 ast_manager_register2( "ExtensionState", EVENT_FLAG_CALL, action_extensionstate, "Check Extension Status", mandescr_extensionstate );
1529 ast_manager_register2( "AbsoluteTimeout", EVENT_FLAG_CALL, action_timeout, "Set Absolute Timeout", mandescr_timeout );
1530 ast_manager_register2( "MailboxStatus", EVENT_FLAG_CALL, action_mailboxstatus, "Check Mailbox", mandescr_mailboxstatus );
1531 ast_manager_register2( "MailboxCount", EVENT_FLAG_CALL, action_mailboxcount, "Check Mailbox Message Count", mandescr_mailboxcount );
1532 ast_manager_register2("ListCommands", 0, action_listcommands, "List available manager commands", mandescr_listcommands);
1534 ast_cli_register(&show_mancmd_cli);
1535 ast_cli_register(&show_mancmds_cli);
1536 ast_cli_register(&show_manconn_cli);
1537 ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
1540 portno = DEFAULT_MANAGER_PORT;
1541 displayconnects = 1;
1542 cfg = ast_config_load("manager.conf");
1544 ast_log(LOG_NOTICE, "Unable to open management configuration manager.conf. Call management disabled.\n");
1547 memset(&ba, 0, sizeof(ba));
1548 val = ast_variable_retrieve(cfg, "general", "enabled");
1550 enabled = ast_true(val);
1552 val = ast_variable_retrieve(cfg, "general", "block-sockets");
1554 block_sockets = ast_true(val);
1556 if ((val = ast_variable_retrieve(cfg, "general", "port"))) {
1557 if (sscanf(val, "%d", &portno) != 1) {
1558 ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
1559 portno = DEFAULT_MANAGER_PORT;
1561 } else if ((val = ast_variable_retrieve(cfg, "general", "portno"))) {
1562 if (sscanf(val, "%d", &portno) != 1) {
1563 ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
1564 portno = DEFAULT_MANAGER_PORT;
1566 ast_log(LOG_NOTICE, "Use of portno in manager.conf deprecated. Please use 'port=%s' instead.\n", val);
1568 /* Parsing the displayconnects */
1569 if ((val = ast_variable_retrieve(cfg, "general", "displayconnects"))) {
1570 displayconnects = ast_true(val);;
1574 ba.sin_family = AF_INET;
1575 ba.sin_port = htons(portno);
1576 memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
1578 if ((val = ast_variable_retrieve(cfg, "general", "bindaddr"))) {
1579 if (!inet_aton(val, &ba.sin_addr)) {
1580 ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
1581 memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
1585 if ((asock > -1) && ((portno != oldportno) || !enabled)) {
1587 /* Can't be done yet */
1591 ast_log(LOG_WARNING, "Unable to change management port / enabled\n");
1594 ast_config_destroy(cfg);
1596 /* If not enabled, do nothing */
1601 asock = socket(AF_INET, SOCK_STREAM, 0);
1603 ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
1606 setsockopt(asock, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
1607 if (bind(asock, (struct sockaddr *)&ba, sizeof(ba))) {
1608 ast_log(LOG_WARNING, "Unable to bind socket: %s\n", strerror(errno));
1613 if (listen(asock, 2)) {
1614 ast_log(LOG_WARNING, "Unable to listen on socket: %s\n", strerror(errno));
1620 ast_verbose("Asterisk Management interface listening on port %d\n", portno);
1621 ast_pthread_create(&t, NULL, accept_thread, NULL);
1626 int reload_manager(void)
1628 manager_event(EVENT_FLAG_SYSTEM, "Reload", "Message: Reload Requested\r\n");
1629 return init_manager();