2 * Asterisk -- A telephony toolkit for Linux.
4 * Channel Management and more
6 * Copyright (C) 1999, Mark Spencer
8 * Mark Spencer <markster@linux-support.net>
10 * This program is free software, distributed under the terms of
11 * the GNU General Public License
19 #include <sys/types.h>
21 #include <sys/socket.h>
22 #include <netinet/in.h>
23 #include <netinet/tcp.h>
24 #include <arpa/inet.h>
28 #include <asterisk/channel.h>
29 #include <asterisk/file.h>
30 #include <asterisk/manager.h>
31 #include <asterisk/config.h>
32 #include <asterisk/lock.h>
33 #include <asterisk/logger.h>
34 #include <asterisk/options.h>
35 #include <asterisk/cli.h>
36 #include <asterisk/app.h>
37 #include <asterisk/pbx.h>
38 #include <asterisk/md5.h>
39 #include <asterisk/acl.h>
41 static int enabled = 0;
42 static int portno = DEFAULT_MANAGER_PORT;
43 static int asock = -1;
45 static pthread_mutex_t sessionlock = AST_MUTEX_INITIALIZER;
47 static struct permalias {
51 { EVENT_FLAG_SYSTEM, "system" },
52 { EVENT_FLAG_CALL, "call" },
53 { EVENT_FLAG_LOG, "log" },
54 { EVENT_FLAG_VERBOSE, "verbose" },
55 { EVENT_FLAG_COMMAND, "command" },
56 { EVENT_FLAG_AGENT, "agent" },
57 { EVENT_FLAG_USER, "user" },
61 static struct mansession *sessions = NULL;
62 static struct manager_action *first_action = NULL;
63 static pthread_mutex_t actionlock = AST_MUTEX_INITIALIZER;
65 static int handle_showmancmds(int fd, int argc, char *argv[])
67 struct manager_action *cur = first_action;
69 ast_pthread_mutex_lock(&actionlock);
70 while(cur) { /* Walk the list of actions */
71 ast_cli(fd, "\t%s %s\r\n",cur->action, cur->synopsis);
75 ast_pthread_mutex_unlock(&actionlock);
76 return RESULT_SUCCESS;
79 static int handle_showmanconn(int fd, int argc, char *argv[])
83 ast_pthread_mutex_lock(&sessionlock);
85 ast_cli(fd, " Username\tIP Address\n");
87 ast_cli(fd, " %s\t\t%s\r\n",s->username, inet_ntoa(s->sin.sin_addr));
91 ast_pthread_mutex_unlock(&sessionlock);
92 return RESULT_SUCCESS;
95 static char showmancmds_help[] =
96 "Usage: show manager commands\n"
97 " Prints a listing of all the available manager commands.\n";
99 static char showmanconn_help[] =
100 "Usage: show manager connected\n"
101 " Prints a listing of the users that are connected to the\n"
102 "manager interface.\n";
104 static struct ast_cli_entry show_mancmds_cli =
105 { { "show", "manager", "commands", NULL },
106 handle_showmancmds, "Show manager commands", showmancmds_help };
108 static struct ast_cli_entry show_manconn_cli =
109 { { "show", "manager", "connected", NULL },
110 handle_showmanconn, "Show connected manager users", showmanconn_help };
112 static void destroy_session(struct mansession *s)
114 struct mansession *cur, *prev = NULL;
115 ast_pthread_mutex_lock(&sessionlock);
125 prev->next = cur->next;
127 sessions = cur->next;
132 ast_log(LOG_WARNING, "Trying to delete non-existant session %p?\n", s);
133 ast_pthread_mutex_unlock(&sessionlock);
137 char *astman_get_header(struct message *m, char *var)
141 snprintf(cmp, sizeof(cmp), "%s: ", var);
142 for (x=0;x<m->hdrcount;x++)
143 if (!strncasecmp(cmp, m->headers[x], strlen(cmp)))
144 return m->headers[x] + strlen(cmp);
148 void astman_send_error(struct mansession *s, char *error)
150 ast_pthread_mutex_lock(&s->lock);
151 ast_cli(s->fd, "Response: Error\r\n");
152 ast_cli(s->fd, "Message: %s\r\n\r\n", error);
153 ast_pthread_mutex_unlock(&s->lock);
156 void astman_send_response(struct mansession *s, char *resp, char *msg)
158 ast_pthread_mutex_lock(&s->lock);
159 ast_cli(s->fd, "Response: %s\r\n", resp);
161 ast_cli(s->fd, "Message: %s\r\n\r\n", msg);
163 ast_cli(s->fd, "\r\n");
164 ast_pthread_mutex_unlock(&s->lock);
167 void astman_send_ack(struct mansession *s, char *msg)
169 astman_send_response(s, "Success", msg);
172 static int get_perm(char *instr)
181 strncpy(tmp, instr, sizeof(tmp) - 1);
183 c = strsep(&stringp, ",");
185 for (x=0;x<sizeof(perms) / sizeof(perms[0]);x++) {
186 if (!strcasecmp(perms[x].label, c))
189 c = strsep(&stringp, ",");
194 static int authenticate(struct mansession *s, struct message *m)
196 struct ast_config *cfg;
198 char *user = astman_get_header(m, "Username");
199 char *pass = astman_get_header(m, "Secret");
200 char *authtype = astman_get_header(m, "AuthType");
201 char *key = astman_get_header(m, "Key");
203 cfg = ast_load("manager.conf");
206 cat = ast_category_browse(cfg, NULL);
208 if (strcasecmp(cat, "general")) {
210 if (!strcasecmp(cat, user)) {
211 struct ast_variable *v;
212 struct ast_ha *ha = NULL;
213 char *password = NULL;
214 v = ast_variable_browse(cfg, cat);
216 if (!strcasecmp(v->name, "secret")) {
218 } else if (!strcasecmp(v->name, "permit") ||
219 !strcasecmp(v->name, "deny")) {
220 ha = ast_append_ha(v->name, v->value, ha);
224 if (ha && !ast_apply_ha(ha, &(s->sin))) {
225 ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", inet_ntoa(s->sin.sin_addr), user);
231 if (!strcasecmp(authtype, "MD5")) {
232 if (key && strlen(key) && s->challenge) {
235 char md5key[256] = "";
236 struct MD5Context md5;
237 unsigned char digest[16];
239 MD5Update(&md5, s->challenge, strlen(s->challenge));
240 MD5Update(&md5, password, strlen(password));
241 MD5Final(digest, &md5);
243 len += sprintf(md5key + len, "%2.2x", digest[x]);
244 if (!strcmp(md5key, key))
251 } else if (password && !strcasecmp(password, pass)) {
254 ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", inet_ntoa(s->sin.sin_addr), user);
260 cat = ast_category_browse(cfg, cat);
263 strncpy(s->username, cat, sizeof(s->username) - 1);
264 s->readperm = get_perm(ast_variable_retrieve(cfg, cat, "read"));
265 s->writeperm = get_perm(ast_variable_retrieve(cfg, cat, "write"));
269 ast_log(LOG_NOTICE, "%s tried to authenticate with non-existant user '%s'\n", inet_ntoa(s->sin.sin_addr), user);
274 static int action_ping(struct mansession *s, struct message *m)
276 astman_send_response(s, "Pong", NULL);
280 static int action_logoff(struct mansession *s, struct message *m)
282 astman_send_response(s, "Goodbye", "Thanks for all the fish.");
286 static int action_hangup(struct mansession *s, struct message *m)
288 struct ast_channel *c = NULL;
289 char *name = astman_get_header(m, "Channel");
291 astman_send_error(s, "No channel specified");
294 c = ast_channel_walk(NULL);
296 if (!strcasecmp(c->name, name)) {
299 c = ast_channel_walk(c);
302 astman_send_error(s, "No such channel");
305 ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
306 astman_send_ack(s, "Channel Hungup");
310 static int action_status(struct mansession *s, struct message *m)
312 struct ast_channel *c;
314 astman_send_ack(s, "Channel status will follow");
315 c = ast_channel_walk(NULL);
318 snprintf(bridge, sizeof(bridge), "Link: %s\r\n", c->bridge->name);
333 c->name, c->callerid ? c->callerid : "<unknown>",
334 ast_state2str(c->_state), c->context,
335 c->exten, c->priority, bridge, c->uniqueid);
345 c->name, c->callerid ? c->callerid : "<unknown>",
346 ast_state2str(c->_state), bridge, c->uniqueid);
348 c = ast_channel_walk(c);
353 static int action_redirect(struct mansession *s, struct message *m)
355 char *name = astman_get_header(m, "Channel");
356 char *name2 = astman_get_header(m, "ExtraChannel");
357 char *exten = astman_get_header(m, "Exten");
358 char *context = astman_get_header(m, "Context");
359 char *priority = astman_get_header(m, "Priority");
362 if (!name || !strlen(name)) {
363 astman_send_error(s, "Channel not specified");
366 if (strlen(priority) && (sscanf(priority, "%d", &pi) != 1)) {
367 astman_send_error(s, "Invalid priority\n");
370 res = ast_async_goto_by_name(name, context, exten, pi);
373 res = ast_async_goto_by_name(name2, context, exten, pi);
375 astman_send_ack(s, "Dual Redirect successful");
377 astman_send_error(s, "Secondary redirect failed");
379 astman_send_ack(s, "Redirect successful");
381 astman_send_error(s, "Redirect failed");
385 static int action_command(struct mansession *s, struct message *m)
387 char *cmd = astman_get_header(m, "Command");
388 ast_pthread_mutex_lock(&s->lock);
390 ast_pthread_mutex_unlock(&s->lock);
391 ast_cli(s->fd, "Response: Follows\r\n");
392 ast_cli_command(s->fd, cmd);
393 ast_cli(s->fd, "--END COMMAND--\r\n\r\n");
394 ast_pthread_mutex_lock(&s->lock);
396 ast_pthread_mutex_unlock(&s->lock);
400 static int action_originate(struct mansession *s, struct message *m)
402 char *name = astman_get_header(m, "Channel");
403 char *exten = astman_get_header(m, "Exten");
404 char *context = astman_get_header(m, "Context");
405 char *priority = astman_get_header(m, "Priority");
406 char *timeout = astman_get_header(m, "Timeout");
407 char *callerid = astman_get_header(m, "CallerID");
415 astman_send_error(s, "Channel not specified");
418 if (strlen(priority) && (sscanf(priority, "%d", &pi) != 1)) {
419 astman_send_error(s, "Invalid priority\n");
422 if (strlen(timeout) && (sscanf(timeout, "%d", &to) != 1)) {
423 astman_send_error(s, "Invalid timeout\n");
426 strncpy(tmp, name, sizeof(tmp) - 1);
428 data = strchr(tmp, '/');
430 astman_send_error(s, "Invalid channel\n");
435 res = ast_pbx_outgoing_exten(tech, AST_FORMAT_SLINEAR, data, to, context, exten, pi, &reason, 0, strlen(callerid) ? callerid : NULL, NULL );
437 astman_send_ack(s, "Originate successfully queued");
439 astman_send_error(s, "Originate failed");
443 static int action_mailboxstatus(struct mansession *s, struct message *m)
445 char *mailbox = astman_get_header(m, "Mailbox");
446 if (!mailbox || !strlen(mailbox)) {
447 astman_send_error(s, "Mailbox not specified");
450 ast_cli(s->fd, "Response: Success\r\n"
451 "Message: Mailbox Status\r\n"
453 "Waiting: %d\r\n\r\n", mailbox, ast_app_has_voicemail(mailbox));
457 static int action_extensionstate(struct mansession *s, struct message *m)
459 char *exten = astman_get_header(m, "Exten");
460 char *context = astman_get_header(m, "Context");
463 if (!exten || !strlen(exten)) {
464 astman_send_error(s, "Extension not specified");
467 if (!context || !strlen(context))
469 status = ast_extension_state(NULL, context, exten);
470 ast_get_hint(hint, sizeof(hint) - 1, NULL, context, exten);
471 ast_cli(s->fd, "Response: Success\r\n"
472 "Message: Extension Status\r\n"
476 "Status: %d\r\n\r\n", exten, context, hint, status);
480 static int action_timeout(struct mansession *s, struct message *m)
482 struct ast_channel *c = NULL;
483 char *name = astman_get_header(m, "Channel");
484 int timeout = atoi(astman_get_header(m, "Timeout"));
486 astman_send_error(s, "No channel specified");
490 astman_send_error(s, "No timeout specified");
493 c = ast_channel_walk(NULL);
495 if (!strcasecmp(c->name, name)) {
498 c = ast_channel_walk(c);
501 astman_send_error(s, "No such channel");
504 ast_channel_setwhentohangup(c, timeout);
505 astman_send_ack(s, "Timeout Set");
509 static int process_message(struct mansession *s, struct message *m)
512 struct manager_action *tmp = first_action;
514 strncpy(action, astman_get_header(m, "Action"), sizeof(action));
515 ast_log( LOG_DEBUG, "Manager received command '%s'\n", action );
517 if (!strlen(action)) {
518 astman_send_error(s, "Missing action in request");
521 if (!s->authenticated) {
522 if (!strcasecmp(action, "Challenge")) {
524 authtype = astman_get_header(m, "AuthType");
525 if (!strcasecmp(authtype, "MD5")) {
526 if (!s->challenge || !strlen(s->challenge)) {
527 ast_pthread_mutex_lock(&s->lock);
528 snprintf(s->challenge, sizeof(s->challenge), "%d", rand());
529 ast_pthread_mutex_unlock(&s->lock);
531 ast_cli(s->fd, "Response: Success\r\nChallenge: %s\r\n\r\n", s->challenge);
534 astman_send_error(s, "Must specify AuthType");
537 } else if (!strcasecmp(action, "Login")) {
538 if (authenticate(s, m)) {
540 astman_send_error(s, "Authentication failed");
543 s->authenticated = 1;
544 if (option_verbose > 1)
545 ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged on from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
546 ast_log(LOG_EVENT, "Manager '%s' logged on from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
547 astman_send_ack(s, "Authentication accepted");
550 astman_send_error(s, "Authentication Required");
553 if (!strcasecmp(action, tmp->action)) {
554 if ((s->writeperm & tmp->authority) == tmp->authority) {
558 astman_send_error(s, "Permission denied");
564 astman_send_error(s, "Invalid/unknown command");
569 static int get_input(struct mansession *s, char *output)
571 /* output must have at least sizeof(s->inbuf) space */
575 for (x=1;x<s->inlen;x++) {
576 if ((s->inbuf[x] == '\n') && (s->inbuf[x-1] == '\r')) {
577 /* Copy output data up to and including \r\n */
578 memcpy(output, s->inbuf, x + 1);
579 /* Add trailing \0 */
581 /* Move remaining data back to the front */
582 memmove(s->inbuf, s->inbuf + x + 1, s->inlen - x);
587 if (s->inlen >= sizeof(s->inbuf) - 1) {
588 ast_log(LOG_WARNING, "Dumping long line with no return from %s: %s\n", inet_ntoa(s->sin.sin_addr), s->inbuf);
593 res = ast_select(s->fd + 1, &fds, NULL, NULL, NULL);
595 ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
596 } else if (res > 0) {
597 ast_pthread_mutex_lock(&s->lock);
598 res = read(s->fd, s->inbuf + s->inlen, sizeof(s->inbuf) - 1 - s->inlen);
599 ast_pthread_mutex_unlock(&s->lock);
604 s->inbuf[s->inlen] = '\0';
608 static void *session_do(void *data)
610 struct mansession *s = data;
614 ast_pthread_mutex_lock(&s->lock);
615 ast_cli(s->fd, "Asterisk Call Manager/1.0\r\n");
616 ast_pthread_mutex_unlock(&s->lock);
617 memset(&m, 0, sizeof(&m));
619 res = get_input(s, m.headers[m.hdrcount]);
621 /* Strip trailing \r\n */
622 if (strlen(m.headers[m.hdrcount]) < 2)
624 m.headers[m.hdrcount][strlen(m.headers[m.hdrcount]) - 2] = '\0';
625 if (!strlen(m.headers[m.hdrcount])) {
626 if (process_message(s, &m))
628 memset(&m, 0, sizeof(&m));
629 } else if (m.hdrcount < MAX_HEADERS - 1)
634 if (s->authenticated) {
635 if (option_verbose > 1)
636 ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged off from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
637 ast_log(LOG_EVENT, "Manager '%s' logged off from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
639 if (option_verbose > 1)
640 ast_verbose(VERBOSE_PREFIX_2 "Connect attempt from '%s' unable to authenticate\n", inet_ntoa(s->sin.sin_addr));
641 ast_log(LOG_EVENT, "Failed attempt from %s\n", inet_ntoa(s->sin.sin_addr));
647 static void *accept_thread(void *ignore)
650 struct sockaddr_in sin;
652 struct mansession *s;
657 pthread_attr_init(&attr);
658 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
661 sinlen = sizeof(sin);
662 as = accept(asock, &sin, &sinlen);
664 ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
667 p = getprotobyname("tcp");
669 if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
670 ast_log(LOG_WARNING, "Failed to set manager tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
673 s = malloc(sizeof(struct mansession));
675 ast_log(LOG_WARNING, "Failed to allocate management session: %s\n", strerror(errno));
678 memset(s, 0, sizeof(struct mansession));
679 memcpy(&s->sin, &sin, sizeof(sin));
680 ast_pthread_mutex_init(&s->lock);
682 ast_pthread_mutex_lock(&sessionlock);
685 ast_pthread_mutex_unlock(&sessionlock);
686 if (pthread_create(&t, &attr, session_do, s))
689 pthread_attr_destroy(&attr);
693 int manager_event(int category, char *event, char *fmt, ...)
695 struct mansession *s;
699 ast_pthread_mutex_lock(&sessionlock);
702 if ((s->readperm & category) == category) {
703 ast_pthread_mutex_lock(&s->lock);
705 ast_cli(s->fd, "Event: %s\r\n", event);
707 vsnprintf(tmp, sizeof(tmp), fmt, ap);
709 write(s->fd, tmp, strlen(tmp));
710 ast_cli(s->fd, "\r\n");
712 ast_pthread_mutex_unlock(&s->lock);
716 ast_pthread_mutex_unlock(&sessionlock);
720 int ast_manager_unregister( char *action ) {
721 struct manager_action *cur = first_action, *prev = first_action;
723 ast_pthread_mutex_lock(&actionlock);
725 if (!strcasecmp(action, cur->action)) {
726 prev->next = cur->next;
728 if (option_verbose > 1)
729 ast_verbose(VERBOSE_PREFIX_2 "Manager unregistered action %s\n", action);
730 ast_pthread_mutex_unlock(&actionlock);
736 ast_pthread_mutex_unlock(&actionlock);
740 static int manager_state_cb(char *context, char *exten, int state, void *data)
742 /* Notify managers of change */
743 manager_event(EVENT_FLAG_CALL, "ExtensionStatus", "Exten: %s\r\nContext: %s\r\nStatus: %d\r\n", exten, context, state);
747 int ast_manager_register( char *action, int auth,
748 int (*func)(struct mansession *s, struct message *m), char *synopsis)
750 struct manager_action *cur = first_action, *prev = NULL;
752 ast_pthread_mutex_lock(&actionlock);
753 while(cur) { /* Walk the list of actions */
757 cur = malloc( sizeof(struct manager_action) );
759 ast_log(LOG_WARNING, "Manager: out of memory trying to register action\n");
760 ast_pthread_mutex_unlock(&actionlock);
763 strncpy( cur->action, action, 255 );
764 cur->authority = auth;
766 cur->synopsis = synopsis;
769 if( prev ) prev->next = cur;
770 else first_action = cur;
772 if (option_verbose > 1)
773 ast_verbose(VERBOSE_PREFIX_2 "Manager registered action %s\n", action);
774 ast_pthread_mutex_unlock(&actionlock);
778 static int registered = 0;
780 int init_manager(void)
782 struct ast_config *cfg;
784 int oldportno = portno;
785 static struct sockaddr_in ba;
788 /* Register default actions */
789 ast_manager_register( "Ping", 0, action_ping, "Ping" );
790 ast_manager_register( "Logoff", 0, action_logoff, "Logoff Manager" );
791 ast_manager_register( "Hangup", EVENT_FLAG_CALL, action_hangup, "Hangup Channel" );
792 ast_manager_register( "Status", EVENT_FLAG_CALL, action_status, "Status" );
793 ast_manager_register( "Redirect", EVENT_FLAG_CALL, action_redirect, "Redirect" );
794 ast_manager_register( "Originate", EVENT_FLAG_CALL, action_originate, "Originate Call" );
795 ast_manager_register( "MailboxStatus", EVENT_FLAG_CALL, action_mailboxstatus, "Check Mailbox" );
796 ast_manager_register( "Command", EVENT_FLAG_COMMAND, action_command, "Execute Command" );
797 ast_manager_register( "ExtensionState", EVENT_FLAG_CALL, action_extensionstate, "Check Extension Status" );
798 ast_manager_register( "AbsoluteTimeout", EVENT_FLAG_CALL, action_timeout, "Set Absolute Timeout" );
800 ast_cli_register(&show_mancmds_cli);
801 ast_cli_register(&show_manconn_cli);
802 ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
805 portno = DEFAULT_MANAGER_PORT;
806 cfg = ast_load("manager.conf");
808 ast_log(LOG_NOTICE, "Unable to open management configuration manager.conf. Call management disabled.\n");
811 memset(&ba, 0, sizeof(ba));
812 val = ast_variable_retrieve(cfg, "general", "enabled");
814 enabled = ast_true(val);
816 if ((val = ast_variable_retrieve(cfg, "general", "portno"))) {
817 if (sscanf(val, "%d", &portno) != 1) {
818 ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
819 portno = DEFAULT_MANAGER_PORT;
823 ba.sin_family = AF_INET;
824 ba.sin_port = htons(portno);
825 memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
827 if ((val = ast_variable_retrieve(cfg, "general", "bindaddr"))) {
828 if (!inet_aton(val, &ba.sin_addr)) {
829 ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
830 memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
834 if ((asock > -1) && ((portno != oldportno) || !enabled)) {
836 /* Can't be done yet */
840 ast_log(LOG_WARNING, "Unable to change management port / enabled\n");
843 /* If not enabled, do nothing */
847 asock = socket(AF_INET, SOCK_STREAM, 0);
849 ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
852 setsockopt(asock, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
853 if (bind(asock, &ba, sizeof(ba))) {
854 ast_log(LOG_WARNING, "Unable to bind socket: %s\n", strerror(errno));
859 if (listen(asock, 2)) {
860 ast_log(LOG_WARNING, "Unable to listen on socket: %s\n", strerror(errno));
866 ast_verbose("Asterisk Management interface listening on port %d\n", portno);
867 pthread_create(&t, NULL, accept_thread, NULL);
873 int reload_manager(void)
875 manager_event(EVENT_FLAG_SYSTEM, "Reload", "Message: Reload Requested\r\n");
876 return init_manager();