Main Page | Alphabetical List | Data Structures | File List | Data Fields | Globals

manager.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- A telephony toolkit for Linux.
00003  *
00004  * Channel Management and more
00005  * 
00006  * Copyright (C) 1999, Mark Spencer
00007  *
00008  * Mark Spencer <markster@linux-support.net>
00009  *
00010  * This program is free software, distributed under the terms of
00011  * the GNU General Public License
00012  */
00013 
00014 #include <stdio.h>
00015 #include <stdlib.h>
00016 #include <pthread.h>
00017 #include <string.h>
00018 #include <sys/time.h>
00019 #include <sys/types.h>
00020 #include <netdb.h>
00021 #include <sys/socket.h>
00022 #include <netinet/in.h>
00023 #include <netinet/tcp.h>
00024 #include <arpa/inet.h>
00025 #include <signal.h>
00026 #include <errno.h>
00027 #include <unistd.h>
00028 #include <asterisk/channel.h>
00029 #include <asterisk/file.h>
00030 #include <asterisk/manager.h>
00031 #include <asterisk/config.h>
00032 #include <asterisk/lock.h>
00033 #include <asterisk/logger.h>
00034 #include <asterisk/options.h>
00035 #include <asterisk/cli.h>
00036 #include <asterisk/app.h>
00037 #include <asterisk/pbx.h>
00038 #include <asterisk/md5.h>
00039 #include <asterisk/acl.h>
00040 
00041 static int enabled = 0;
00042 static int portno = DEFAULT_MANAGER_PORT;
00043 static int asock = -1;
00044 static pthread_t t;
00045 static ast_mutex_t sessionlock = AST_MUTEX_INITIALIZER;
00046 static int block_sockets = 0;
00047 
00048 static struct permalias {
00049    int num;
00050    char *label;
00051 } perms[] = {
00052    { EVENT_FLAG_SYSTEM, "system" },
00053    { EVENT_FLAG_CALL, "call" },
00054    { EVENT_FLAG_LOG, "log" },
00055    { EVENT_FLAG_VERBOSE, "verbose" },
00056    { EVENT_FLAG_COMMAND, "command" },
00057    { EVENT_FLAG_AGENT, "agent" },
00058    { EVENT_FLAG_USER, "user" },
00059    { -1, "all" },
00060 };
00061 
00062 static struct mansession *sessions = NULL;
00063 static struct manager_action *first_action = NULL;
00064 static ast_mutex_t actionlock = AST_MUTEX_INITIALIZER;
00065 
00066 int ast_carefulwrite(int fd, char *s, int len, int timeoutms) 
00067 {
00068    /* Try to write string, but wait no more than ms milliseconds
00069       before timing out */
00070    int res=0;
00071    struct timeval tv;
00072    fd_set fds;
00073    while(len) {
00074       res = write(fd, s, len);
00075       if ((res < 0) && (errno != EAGAIN)) {
00076          return -1;
00077       }
00078       if (res < 0) res = 0;
00079       len -= res;
00080       s += res;
00081       tv.tv_sec = timeoutms / 1000;
00082       tv.tv_usec = timeoutms % 1000;
00083       FD_ZERO(&fds);
00084       FD_SET(fd, &fds);
00085       /* Wait until writable again */
00086       res = select(fd + 1, NULL, &fds, NULL, &tv);
00087       if (res < 1)
00088          return -1;
00089    }
00090    return res;
00091 }
00092 
00093 static int handle_showmancmds(int fd, int argc, char *argv[])
00094 {
00095    struct manager_action *cur = first_action;
00096    char *format = "  %-15.15s  %-45.45s\n";
00097 
00098    ast_mutex_lock(&actionlock);
00099    ast_cli(fd, format, "Action", "Synopsis");
00100    while(cur) { /* Walk the list of actions */
00101       ast_cli(fd, format, cur->action, cur->synopsis);
00102       cur = cur->next;
00103    }
00104 
00105    ast_mutex_unlock(&actionlock);
00106    return RESULT_SUCCESS;
00107 }
00108 
00109 static int handle_showmanconn(int fd, int argc, char *argv[])
00110 {
00111    struct mansession *s;
00112    char *format = "  %-15.15s  %-15.15s\n";
00113    ast_mutex_lock(&sessionlock);
00114    s = sessions;
00115    ast_cli(fd, format, "Username", "IP Address");
00116    while(s) {
00117       ast_cli(fd, format,s->username, inet_ntoa(s->sin.sin_addr));
00118       s = s->next;
00119    }
00120 
00121    ast_mutex_unlock(&sessionlock);
00122    return RESULT_SUCCESS;
00123 }
00124 
00125 static char showmancmds_help[] = 
00126 "Usage: show manager commands\n"
00127 "  Prints a listing of all the available manager commands.\n";
00128 
00129 static char showmanconn_help[] = 
00130 "Usage: show manager connected\n"
00131 "  Prints a listing of the users that are connected to the\n"
00132 "manager interface.\n";
00133 
00134 static struct ast_cli_entry show_mancmds_cli =
00135    { { "show", "manager", "commands", NULL },
00136    handle_showmancmds, "Show manager commands", showmancmds_help };
00137 
00138 static struct ast_cli_entry show_manconn_cli =
00139    { { "show", "manager", "connected", NULL },
00140    handle_showmanconn, "Show connected manager users", showmanconn_help };
00141 
00142 static void destroy_session(struct mansession *s)
00143 {
00144    struct mansession *cur, *prev = NULL;
00145    ast_mutex_lock(&sessionlock);
00146    cur = sessions;
00147    while(cur) {
00148       if (cur == s)
00149          break;
00150       prev = cur;
00151       cur = cur->next;
00152    }
00153    if (cur) {
00154       if (prev)
00155          prev->next = cur->next;
00156       else
00157          sessions = cur->next;
00158       if (s->fd > -1)
00159          close(s->fd);
00160       free(s);
00161    } else
00162       ast_log(LOG_WARNING, "Trying to delete non-existant session %p?\n", s);
00163    ast_mutex_unlock(&sessionlock);
00164    
00165 }
00166 
00167 char *astman_get_header(struct message *m, char *var)
00168 {
00169    char cmp[80];
00170    int x;
00171    snprintf(cmp, sizeof(cmp), "%s: ", var);
00172    for (x=0;x<m->hdrcount;x++)
00173       if (!strncasecmp(cmp, m->headers[x], strlen(cmp)))
00174          return m->headers[x] + strlen(cmp);
00175    return "";
00176 }
00177 
00178 void astman_send_error(struct mansession *s, struct message *m, char *error)
00179 {
00180    char *id = astman_get_header(m,"ActionID");
00181    ast_mutex_lock(&s->lock);
00182    ast_cli(s->fd, "Response: Error\r\n");
00183    if (id && strlen(id))
00184       ast_cli(s->fd, "ActionID: %s\r\n",id);
00185    ast_cli(s->fd, "Message: %s\r\n\r\n", error);
00186    ast_mutex_unlock(&s->lock);
00187 }
00188 
00189 void astman_send_response(struct mansession *s, struct message *m, char *resp, char *msg)
00190 {
00191    char *id = astman_get_header(m,"ActionID");
00192    ast_mutex_lock(&s->lock);
00193    ast_cli(s->fd, "Response: %s\r\n", resp);
00194    if (id && strlen(id))
00195       ast_cli(s->fd, "ActionID: %s\r\n",id);
00196    if (msg)
00197       ast_cli(s->fd, "Message: %s\r\n\r\n", msg);
00198    else
00199       ast_cli(s->fd, "\r\n");
00200    ast_mutex_unlock(&s->lock);
00201 }
00202 
00203 void astman_send_ack(struct mansession *s, struct message *m, char *msg)
00204 {
00205    astman_send_response(s, m, "Success", msg);
00206 }
00207 
00208 static int get_perm(char *instr)
00209 {
00210    char tmp[256];
00211    char *c;
00212    int x;
00213    int ret = 0;
00214    char *stringp=NULL;
00215    if (!instr)
00216       return 0;
00217    strncpy(tmp, instr, sizeof(tmp) - 1);
00218    stringp=tmp;
00219    c = strsep(&stringp, ",");
00220    while(c) {
00221       for (x=0;x<sizeof(perms) / sizeof(perms[0]);x++) {
00222          if (!strcasecmp(perms[x].label, c)) 
00223             ret |= perms[x].num;
00224       }
00225       c = strsep(&stringp, ",");
00226    }
00227    return ret;
00228 }
00229 
00230 static int set_eventmask(struct mansession *s, char *eventmask)
00231 {
00232    if (!eventmask)
00233       return -1;
00234    if (!strcasecmp(eventmask, "on") || ast_true(eventmask)) {
00235       ast_mutex_lock(&s->lock);
00236       s->send_events = 1;
00237       ast_mutex_unlock(&s->lock);
00238       return 1;
00239    } else if (!strcasecmp(eventmask, "off") || ast_false(eventmask)) {
00240       ast_mutex_lock(&s->lock);
00241       s->send_events = 0;
00242       ast_mutex_unlock(&s->lock);
00243       return 0;
00244    }
00245    return -1;
00246 }
00247 
00248 static int authenticate(struct mansession *s, struct message *m)
00249 {
00250    struct ast_config *cfg;
00251    char *cat;
00252    char *user = astman_get_header(m, "Username");
00253    char *pass = astman_get_header(m, "Secret");
00254    char *authtype = astman_get_header(m, "AuthType");
00255    char *key = astman_get_header(m, "Key");
00256    char *events = astman_get_header(m, "Events");
00257    
00258    cfg = ast_load("manager.conf");
00259    if (!cfg)
00260       return -1;
00261    cat = ast_category_browse(cfg, NULL);
00262    while(cat) {
00263       if (strcasecmp(cat, "general")) {
00264          /* This is a user */
00265          if (!strcasecmp(cat, user)) {
00266             struct ast_variable *v;
00267             struct ast_ha *ha = NULL;
00268             char *password = NULL;
00269             v = ast_variable_browse(cfg, cat);
00270             while (v) {
00271                if (!strcasecmp(v->name, "secret")) {
00272                   password = v->value;
00273                } else if (!strcasecmp(v->name, "permit") ||
00274                      !strcasecmp(v->name, "deny")) {
00275                      ha = ast_append_ha(v->name, v->value, ha);
00276                }                 
00277                v = v->next;
00278             }
00279             if (ha && !ast_apply_ha(ha, &(s->sin))) {
00280                ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", inet_ntoa(s->sin.sin_addr), user);
00281                ast_free_ha(ha);
00282                ast_destroy(cfg);
00283                return -1;
00284             } else if (ha)
00285                ast_free_ha(ha);
00286             if (!strcasecmp(authtype, "MD5")) {
00287                if (key && strlen(key) && s->challenge) {
00288                   int x;
00289                   int len=0;
00290                   char md5key[256] = "";
00291                   struct MD5Context md5;
00292                   unsigned char digest[16];
00293                   MD5Init(&md5);
00294                   MD5Update(&md5, s->challenge, strlen(s->challenge));
00295                   MD5Update(&md5, password, strlen(password));
00296                   MD5Final(digest, &md5);
00297                   for (x=0;x<16;x++)
00298                      len += sprintf(md5key + len, "%2.2x", digest[x]);
00299                   if (!strcmp(md5key, key))
00300                      break;
00301                   else {
00302                      ast_destroy(cfg);
00303                      return -1;
00304                   }
00305                }
00306             } else if (password && !strcasecmp(password, pass)) {
00307                break;
00308             } else {
00309                ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", inet_ntoa(s->sin.sin_addr), user);
00310                ast_destroy(cfg);
00311                return -1;
00312             }  
00313          }
00314       }
00315       cat = ast_category_browse(cfg, cat);
00316    }
00317    if (cat) {
00318       strncpy(s->username, cat, sizeof(s->username) - 1);
00319       s->readperm = get_perm(ast_variable_retrieve(cfg, cat, "read"));
00320       s->writeperm = get_perm(ast_variable_retrieve(cfg, cat, "write"));
00321       ast_destroy(cfg);
00322       if (events)
00323          set_eventmask(s, events);
00324       return 0;
00325    }
00326    ast_log(LOG_NOTICE, "%s tried to authenticate with non-existant user '%s'\n", inet_ntoa(s->sin.sin_addr), user);
00327    ast_destroy(cfg);
00328    return -1;
00329 }
00330 
00331 static int action_ping(struct mansession *s, struct message *m)
00332 {
00333    astman_send_response(s, m, "Pong", NULL);
00334    return 0;
00335 }
00336 
00337 static int action_events(struct mansession *s, struct message *m)
00338 {
00339    char *mask = astman_get_header(m, "EventMask");
00340    int res;
00341 
00342    res = set_eventmask(s, mask);
00343    if (res > 0)
00344       astman_send_response(s, m, "Events On", NULL);
00345    else if (res == 0)
00346       astman_send_response(s, m, "Events Off", NULL);
00347    else
00348       astman_send_response(s, m, "EventMask parse error", NULL);
00349    return 0;
00350 }
00351 
00352 static int action_logoff(struct mansession *s, struct message *m)
00353 {
00354    astman_send_response(s, m, "Goodbye", "Thanks for all the fish.");
00355    return -1;
00356 }
00357 
00358 static int action_hangup(struct mansession *s, struct message *m)
00359 {
00360    struct ast_channel *c = NULL;
00361    char *name = astman_get_header(m, "Channel");
00362    if (!strlen(name)) {
00363       astman_send_error(s, m, "No channel specified");
00364       return 0;
00365    }
00366    c = ast_channel_walk(NULL);
00367    while(c) {
00368       if (!strcasecmp(c->name, name)) {
00369          break;
00370       }
00371       c = ast_channel_walk(c);
00372    }
00373    if (!c) {
00374       astman_send_error(s, m, "No such channel");
00375       return 0;
00376    }
00377    ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
00378    astman_send_ack(s, m, "Channel Hungup");
00379    return 0;
00380 }
00381 
00382 static int action_status(struct mansession *s, struct message *m)
00383 {
00384    char *id = astman_get_header(m,"ActionID");
00385    char idText[256] = "";
00386    struct ast_channel *c;
00387    char bridge[256];
00388    astman_send_ack(s, m, "Channel status will follow");
00389    c = ast_channel_walk(NULL);
00390         if (id && strlen(id))
00391                 snprintf(idText,256,"ActionID: %s\r\n",id);
00392    while(c) {
00393       if (c->bridge)
00394          snprintf(bridge, sizeof(bridge), "Link: %s\r\n", c->bridge->name);
00395       else
00396          strcpy(bridge, "");
00397       if (c->pbx) {
00398          ast_cli(s->fd,
00399          "Event: Status\r\n"
00400          "Channel: %s\r\n"
00401          "CallerID: %s\r\n"
00402          "State: %s\r\n"
00403          "Context: %s\r\n"
00404          "Extension: %s\r\n"
00405          "Priority: %d\r\n"
00406          "%s"
00407          "Uniqueid: %s\r\n"
00408          "%s"
00409          "\r\n",
00410          c->name, c->callerid ? c->callerid : "<unknown>", 
00411          ast_state2str(c->_state), c->context,
00412          c->exten, c->priority, bridge, c->uniqueid, idText);
00413       } else {
00414          ast_cli(s->fd,
00415          "Event: Status\r\n"
00416          "Channel: %s\r\n"
00417          "CallerID: %s\r\n"
00418          "State: %s\r\n"
00419          "%s"
00420          "Uniqueid: %s\r\n"
00421          "%s"
00422          "\r\n",
00423          c->name, c->callerid ? c->callerid : "<unknown>", 
00424          ast_state2str(c->_state), bridge, c->uniqueid, idText);
00425       }
00426       c = ast_channel_walk(c);
00427    }
00428    ast_cli(s->fd,
00429    "Event: StatusComplete\r\n"
00430    "%s"
00431    "\r\n",idText);
00432    return 0;
00433 }
00434 
00435 static int action_redirect(struct mansession *s, struct message *m)
00436 {
00437    char *name = astman_get_header(m, "Channel");
00438    char *name2 = astman_get_header(m, "ExtraChannel");
00439    char *exten = astman_get_header(m, "Exten");
00440    char *context = astman_get_header(m, "Context");
00441    char *priority = astman_get_header(m, "Priority");
00442    int pi = 0;
00443    int res;
00444    if (!name || !strlen(name)) {
00445       astman_send_error(s, m, "Channel not specified");
00446       return 0;
00447    }
00448    if (strlen(priority) && (sscanf(priority, "%d", &pi) != 1)) {
00449       astman_send_error(s, m, "Invalid priority\n");
00450       return 0;
00451    }
00452    res = ast_async_goto_by_name(name, context, exten, pi);
00453    if (!res) {
00454       if (strlen(name2)) {
00455          res = ast_async_goto_by_name(name2, context, exten, pi);
00456          if (!res)
00457             astman_send_ack(s, m, "Dual Redirect successful");
00458          else
00459             astman_send_error(s, m, "Secondary redirect failed");
00460       } else
00461          astman_send_ack(s, m, "Redirect successful");
00462    } else
00463       astman_send_error(s, m, "Redirect failed");
00464    return 0;
00465 }
00466 
00467 static int action_command(struct mansession *s, struct message *m)
00468 {
00469    char *cmd = astman_get_header(m, "Command");
00470    ast_mutex_lock(&s->lock);
00471    s->blocking = 1;
00472    ast_mutex_unlock(&s->lock);
00473    ast_cli(s->fd, "Response: Follows\r\n");
00474    /* FIXME: Wedge a ActionID response in here, waiting for later changes */
00475    ast_cli_command(s->fd, cmd);
00476    ast_cli(s->fd, "--END COMMAND--\r\n\r\n");
00477    ast_mutex_lock(&s->lock);
00478    s->blocking = 0;
00479    ast_mutex_unlock(&s->lock);
00480    return 0;
00481 }
00482 
00483 static int action_originate(struct mansession *s, struct message *m)
00484 {
00485    char *name = astman_get_header(m, "Channel");
00486    char *exten = astman_get_header(m, "Exten");
00487    char *context = astman_get_header(m, "Context");
00488    char *priority = astman_get_header(m, "Priority");
00489    char *timeout = astman_get_header(m, "Timeout");
00490    char *callerid = astman_get_header(m, "CallerID");
00491       char *variable = astman_get_header(m, "Variable");
00492       char *account = astman_get_header(m, "Account");
00493    char *app = astman_get_header(m, "Application");
00494    char *appdata = astman_get_header(m, "Data");
00495    char *tech, *data;
00496    int pi = 0;
00497    int res;
00498    int to = 30000;
00499    int reason = 0;
00500    char tmp[256];
00501    if (!name) {
00502       astman_send_error(s, m, "Channel not specified");
00503       return 0;
00504    }
00505    if (strlen(priority) && (sscanf(priority, "%d", &pi) != 1)) {
00506       astman_send_error(s, m, "Invalid priority\n");
00507       return 0;
00508    }
00509    if (strlen(timeout) && (sscanf(timeout, "%d", &to) != 1)) {
00510       astman_send_error(s, m, "Invalid timeout\n");
00511       return 0;
00512    }
00513    strncpy(tmp, name, sizeof(tmp) - 1);
00514    tech = tmp;
00515    data = strchr(tmp, '/');
00516    if (!data) {
00517       astman_send_error(s, m, "Invalid channel\n");
00518       return 0;
00519    }
00520    *data = '\0';
00521    data++;
00522    if (strlen(app)) {
00523          res = ast_pbx_outgoing_app(tech, AST_FORMAT_SLINEAR, data, to, app, appdata, &reason, 0, strlen(callerid) ? callerid : NULL, variable, account);
00524       } else {
00525       if (exten && context && pi)
00526             res = ast_pbx_outgoing_exten(tech, AST_FORMAT_SLINEAR, data, to, context, exten, pi, &reason, 0, strlen(callerid) ? callerid : NULL, variable, account);
00527       else {
00528          astman_send_error(s, m, "Originate with 'Exten' requires 'Context' and 'Priority'");
00529          return 0;
00530       }
00531    }   
00532    if (!res)
00533       astman_send_ack(s, m, "Originate successfully queued");
00534    else
00535       astman_send_error(s, m, "Originate failed");
00536    return 0;
00537 }
00538 
00539 static int action_mailboxstatus(struct mansession *s, struct message *m)
00540 {
00541    char *mailbox = astman_get_header(m, "Mailbox");
00542    char *id = astman_get_header(m,"ActionID");
00543    char idText[256] = "";
00544    if (!mailbox || !strlen(mailbox)) {
00545       astman_send_error(s, m, "Mailbox not specified");
00546       return 0;
00547    }
00548         if (id && strlen(id))
00549                 snprintf(idText,256,"ActionID: %s\r\n",id);
00550    ast_cli(s->fd, "Response: Success\r\n"
00551                "%s"
00552                "Message: Mailbox Status\r\n"
00553                "Mailbox: %s\r\n"
00554                "Waiting: %d\r\n\r\n", idText, mailbox, ast_app_has_voicemail(mailbox));
00555    return 0;
00556 }
00557 
00558 static int action_mailboxcount(struct mansession *s, struct message *m)
00559 {
00560    char *mailbox = astman_get_header(m, "Mailbox");
00561    char *id = astman_get_header(m,"ActionID");
00562    char idText[256] = "";
00563    int newmsgs = 0, oldmsgs = 0;
00564    if (!mailbox || !strlen(mailbox)) {
00565       astman_send_error(s, m, "Mailbox not specified");
00566       return 0;
00567    }
00568    ast_app_messagecount(mailbox, &newmsgs, &oldmsgs);
00569         if (id && strlen(id)) {
00570                 snprintf(idText,256,"ActionID: %s\r\n",id);
00571         }
00572    ast_cli(s->fd, "Response: Success\r\n"
00573                "%s"
00574                "Message: Mailbox Message Count\r\n"
00575                "Mailbox: %s\r\n"
00576                "NewMessages: %d\r\n"
00577                "OldMessages: %d\r\n" 
00578                "\r\n",
00579                 idText,mailbox, newmsgs, oldmsgs);
00580    return 0;
00581 }
00582 
00583 static int action_extensionstate(struct mansession *s, struct message *m)
00584 {
00585    char *exten = astman_get_header(m, "Exten");
00586    char *context = astman_get_header(m, "Context");
00587    char *id = astman_get_header(m,"ActionID");
00588    char idText[256] = "";
00589    char hint[256] = "";
00590    int status;
00591    if (!exten || !strlen(exten)) {
00592       astman_send_error(s, m, "Extension not specified");
00593       return 0;
00594    }
00595    if (!context || !strlen(context))
00596       context = "default";
00597    status = ast_extension_state(NULL, context, exten);
00598    ast_get_hint(hint, sizeof(hint) - 1, NULL, context, exten);
00599         if (id && strlen(id)) {
00600                 snprintf(idText,256,"ActionID: %s\r\n",id);
00601         }
00602    ast_cli(s->fd, "Response: Success\r\n"
00603                     "%s"
00604                "Message: Extension Status\r\n"
00605                "Exten: %s\r\n"
00606                "Context: %s\r\n"
00607                "Hint: %s\r\n"
00608                "Status: %d\r\n\r\n",
00609                idText,exten, context, hint, status);
00610    return 0;
00611 }
00612 
00613 static int action_timeout(struct mansession *s, struct message *m)
00614 {
00615    struct ast_channel *c = NULL;
00616    char *name = astman_get_header(m, "Channel");
00617    int timeout = atoi(astman_get_header(m, "Timeout"));
00618    if (!strlen(name)) {
00619       astman_send_error(s, m, "No channel specified");
00620       return 0;
00621    }
00622    if (!timeout) {
00623       astman_send_error(s, m, "No timeout specified");
00624       return 0;
00625    }
00626    c = ast_channel_walk(NULL);
00627    while(c) {
00628       if (!strcasecmp(c->name, name)) {
00629          break;
00630       }
00631       c = ast_channel_walk(c);
00632    }
00633    if (!c) {
00634       astman_send_error(s, m, "No such channel");
00635       return 0;
00636    }
00637    ast_channel_setwhentohangup(c, timeout);
00638    astman_send_ack(s, m, "Timeout Set");
00639    return 0;
00640 }
00641 
00642 static int process_message(struct mansession *s, struct message *m)
00643 {
00644    char action[80];
00645    struct manager_action *tmp = first_action;
00646    char *id = astman_get_header(m,"ActionID");
00647    char idText[256] = "";
00648 
00649    strncpy(action, astman_get_header(m, "Action"), sizeof(action));
00650    ast_log( LOG_DEBUG, "Manager received command '%s'\n", action );
00651 
00652    if (!strlen(action)) {
00653       astman_send_error(s, m, "Missing action in request");
00654       return 0;
00655    }
00656         if (id && strlen(id)) {
00657                 snprintf(idText,256,"ActionID: %s\r\n",id);
00658         }
00659    if (!s->authenticated) {
00660       if (!strcasecmp(action, "Challenge")) {
00661          char *authtype;
00662          authtype = astman_get_header(m, "AuthType");
00663          if (!strcasecmp(authtype, "MD5")) {
00664             if (!s->challenge || !strlen(s->challenge)) {
00665                ast_mutex_lock(&s->lock);
00666                snprintf(s->challenge, sizeof(s->challenge), "%d", rand());
00667                ast_mutex_unlock(&s->lock);
00668             }
00669             ast_cli(s->fd, "Response: Success\r\n"
00670                   "%s"
00671                   "Challenge: %s\r\n\r\n",
00672                   idText,s->challenge);
00673             return 0;
00674          } else {
00675             astman_send_error(s, m, "Must specify AuthType");
00676             return 0;
00677          }
00678       } else if (!strcasecmp(action, "Login")) {
00679          if (authenticate(s, m)) {
00680             sleep(1);
00681             astman_send_error(s, m, "Authentication failed");
00682             return -1;
00683          } else {
00684             s->authenticated = 1;
00685             if (option_verbose > 1) 
00686                ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged on from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
00687             ast_log(LOG_EVENT, "Manager '%s' logged on from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
00688             astman_send_ack(s, m, "Authentication accepted");
00689          }
00690       } else if (!strcasecmp(action, "Logoff")) {
00691          astman_send_ack(s, m, "See ya");
00692          return -1;
00693       } else
00694          astman_send_error(s, m, "Authentication Required");
00695    } else {
00696       while( tmp ) {       
00697          if (!strcasecmp(action, tmp->action)) {
00698             if ((s->writeperm & tmp->authority) == tmp->authority) {
00699                if (tmp->func(s, m))
00700                   return -1;
00701             } else {
00702                astman_send_error(s, m, "Permission denied");
00703             }
00704             return 0;
00705          }
00706          tmp = tmp->next;
00707       }
00708       astman_send_error(s, m, "Invalid/unknown command");
00709    }
00710    return 0;
00711 }
00712 
00713 static int get_input(struct mansession *s, char *output)
00714 {
00715    /* output must have at least sizeof(s->inbuf) space */
00716    int res;
00717    int x;
00718    fd_set fds;
00719    for (x=1;x<s->inlen;x++) {
00720       if ((s->inbuf[x] == '\n') && (s->inbuf[x-1] == '\r')) {
00721          /* Copy output data up to and including \r\n */
00722          memcpy(output, s->inbuf, x + 1);
00723          /* Add trailing \0 */
00724          output[x+1] = '\0';
00725          /* Move remaining data back to the front */
00726          memmove(s->inbuf, s->inbuf + x + 1, s->inlen - x);
00727          s->inlen -= (x + 1);
00728          return 1;
00729       }
00730    } 
00731    if (s->inlen >= sizeof(s->inbuf) - 1) {
00732       ast_log(LOG_WARNING, "Dumping long line with no return from %s: %s\n", inet_ntoa(s->sin.sin_addr), s->inbuf);
00733       s->inlen = 0;
00734    }
00735    FD_ZERO(&fds);
00736    FD_SET(s->fd, &fds);
00737    res = ast_select(s->fd + 1, &fds, NULL, NULL, NULL);
00738    if (res < 0) {
00739       ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
00740    } else if (res > 0) {
00741       ast_mutex_lock(&s->lock);
00742       res = read(s->fd, s->inbuf + s->inlen, sizeof(s->inbuf) - 1 - s->inlen);
00743       ast_mutex_unlock(&s->lock);
00744       if (res < 1)
00745          return -1;
00746    }
00747    s->inlen += res;
00748    s->inbuf[s->inlen] = '\0';
00749    return 0;
00750 }
00751 
00752 static void *session_do(void *data)
00753 {
00754    struct mansession *s = data;
00755    struct message m;
00756    int res;
00757    
00758    ast_mutex_lock(&s->lock);
00759    ast_cli(s->fd, "Asterisk Call Manager/1.0\r\n");
00760    ast_mutex_unlock(&s->lock);
00761    memset(&m, 0, sizeof(&m));
00762    for (;;) {
00763       res = get_input(s, m.headers[m.hdrcount]);
00764       if (res > 0) {
00765          /* Strip trailing \r\n */
00766          if (strlen(m.headers[m.hdrcount]) < 2)
00767             continue;
00768          m.headers[m.hdrcount][strlen(m.headers[m.hdrcount]) - 2] = '\0';
00769          if (!strlen(m.headers[m.hdrcount])) {
00770             if (process_message(s, &m))
00771                break;
00772             memset(&m, 0, sizeof(&m));
00773          } else if (m.hdrcount < MAX_HEADERS - 1)
00774             m.hdrcount++;
00775       } else if (res < 0)
00776          break;
00777    }
00778    if (s->authenticated) {
00779       if (option_verbose > 1) 
00780          ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged off from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
00781       ast_log(LOG_EVENT, "Manager '%s' logged off from %s\n", s->username, inet_ntoa(s->sin.sin_addr));
00782    } else {
00783       if (option_verbose > 1)
00784          ast_verbose(VERBOSE_PREFIX_2 "Connect attempt from '%s' unable to authenticate\n", inet_ntoa(s->sin.sin_addr));
00785       ast_log(LOG_EVENT, "Failed attempt from %s\n", inet_ntoa(s->sin.sin_addr));
00786    }
00787    destroy_session(s);
00788    return NULL;
00789 }
00790 
00791 static void *accept_thread(void *ignore)
00792 {
00793    int as;
00794    struct sockaddr_in sin;
00795    int sinlen;
00796    struct mansession *s;
00797    struct protoent *p;
00798    int arg = 1;
00799    int flags;
00800    pthread_attr_t attr;
00801 
00802    pthread_attr_init(&attr);
00803    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
00804 
00805    for (;;) {
00806       sinlen = sizeof(sin);
00807       as = accept(asock, (struct sockaddr *)&sin, &sinlen);
00808       if (as < 0) {
00809          ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
00810          continue;
00811       }
00812       p = getprotobyname("tcp");
00813       if( p ) {
00814          if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
00815             ast_log(LOG_WARNING, "Failed to set manager tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
00816          }
00817       }
00818       s = malloc(sizeof(struct mansession));
00819       if (!s) {
00820          ast_log(LOG_WARNING, "Failed to allocate management session: %s\n", strerror(errno));
00821          continue;
00822       } 
00823       memset(s, 0, sizeof(struct mansession));
00824       memcpy(&s->sin, &sin, sizeof(sin));
00825 
00826       if(! block_sockets) {
00827          /* For safety, make sure socket is non-blocking */
00828          flags = fcntl(as, F_GETFL);
00829          fcntl(as, F_SETFL, flags | O_NONBLOCK);
00830       }
00831       ast_mutex_init(&s->lock);
00832       s->fd = as;
00833       s->send_events = 1;
00834       ast_mutex_lock(&sessionlock);
00835       s->next = sessions;
00836       sessions = s;
00837       ast_mutex_unlock(&sessionlock);
00838       if (pthread_create(&t, &attr, session_do, s))
00839          destroy_session(s);
00840    }
00841    pthread_attr_destroy(&attr);
00842    return NULL;
00843 }
00844 
00845 int manager_event(int category, char *event, char *fmt, ...)
00846 {
00847    struct mansession *s;
00848    char tmp[4096];
00849    va_list ap;
00850 
00851    ast_mutex_lock(&sessionlock);
00852    s = sessions;
00853    while(s) {
00854       if (((s->readperm & category) == category) && s->send_events) {
00855          ast_mutex_lock(&s->lock);
00856          if (!s->blocking) {
00857             ast_cli(s->fd, "Event: %s\r\n", event);
00858             va_start(ap, fmt);
00859             vsnprintf(tmp, sizeof(tmp), fmt, ap);
00860             va_end(ap);
00861             ast_carefulwrite(s->fd,tmp,strlen(tmp),100);
00862             ast_cli(s->fd, "\r\n");
00863          }
00864          ast_mutex_unlock(&s->lock);
00865       }
00866       s = s->next;
00867    }
00868    ast_mutex_unlock(&sessionlock);
00869    return 0;
00870 }
00871 
00872 int ast_manager_unregister( char *action ) {
00873    struct manager_action *cur = first_action, *prev = first_action;
00874 
00875    ast_mutex_lock(&actionlock);
00876    while( cur ) {       
00877       if (!strcasecmp(action, cur->action)) {
00878          prev->next = cur->next;
00879          free(cur);
00880          if (option_verbose > 1) 
00881             ast_verbose(VERBOSE_PREFIX_2 "Manager unregistered action %s\n", action);
00882          ast_mutex_unlock(&actionlock);
00883          return 0;
00884       }
00885       prev = cur;
00886       cur = cur->next;
00887    }
00888    ast_mutex_unlock(&actionlock);
00889    return 0;
00890 }
00891 
00892 static int manager_state_cb(char *context, char *exten, int state, void *data)
00893 {
00894    /* Notify managers of change */
00895    manager_event(EVENT_FLAG_CALL, "ExtensionStatus", "Exten: %s\r\nContext: %s\r\nStatus: %d\r\n", exten, context, state);
00896    return 0;
00897 }
00898 
00899 int ast_manager_register( char *action, int auth, 
00900    int (*func)(struct mansession *s, struct message *m), char *synopsis)
00901 {
00902    struct manager_action *cur = first_action, *prev = NULL;
00903 
00904    ast_mutex_lock(&actionlock);
00905    while(cur) { /* Walk the list of actions */
00906       if (!strcasecmp(cur->action, action)) {
00907          ast_log(LOG_WARNING, "Manager: Action '%s' already registered\n", action);
00908          ast_mutex_unlock(&actionlock);
00909          return -1;
00910       }
00911       prev = cur; 
00912       cur = cur->next;
00913    }
00914    cur = malloc( sizeof(struct manager_action) );
00915    if( !cur ) {
00916       ast_log(LOG_WARNING, "Manager: out of memory trying to register action\n");
00917       ast_mutex_unlock(&actionlock);
00918       return -1;
00919    }
00920    strncpy( cur->action, action, 255 );
00921    cur->authority = auth;
00922    cur->func = func;
00923    cur->synopsis = synopsis;
00924    cur->next = NULL;
00925 
00926    if( prev ) prev->next = cur;
00927    else first_action = cur;
00928 
00929    if (option_verbose > 1) 
00930       ast_verbose(VERBOSE_PREFIX_2 "Manager registered action %s\n", action);
00931    ast_mutex_unlock(&actionlock);
00932    return 0;
00933 }
00934 
00935 static int registered = 0;
00936 
00937 int init_manager(void)
00938 {
00939    struct ast_config *cfg;
00940    char *val;
00941    int oldportno = portno;
00942    static struct sockaddr_in ba;
00943    int x = 1;
00944    if (!registered) {
00945       /* Register default actions */
00946       ast_manager_register( "Ping", 0, action_ping, "Ping" );
00947       ast_manager_register( "Events", 0, action_events, "Contol Event Flow" );
00948       ast_manager_register( "Logoff", 0, action_logoff, "Logoff Manager" );
00949       ast_manager_register( "Hangup", EVENT_FLAG_CALL, action_hangup, "Hangup Channel" );
00950       ast_manager_register( "Status", EVENT_FLAG_CALL, action_status, "Status" );
00951       ast_manager_register( "Redirect", EVENT_FLAG_CALL, action_redirect, "Redirect" );
00952       ast_manager_register( "Originate", EVENT_FLAG_CALL, action_originate, "Originate Call" );
00953       ast_manager_register( "MailboxStatus", EVENT_FLAG_CALL, action_mailboxstatus, "Check Mailbox" );
00954       ast_manager_register( "Command", EVENT_FLAG_COMMAND, action_command, "Execute Command" );
00955       ast_manager_register( "ExtensionState", EVENT_FLAG_CALL, action_extensionstate, "Check Extension Status" );
00956       ast_manager_register( "AbsoluteTimeout", EVENT_FLAG_CALL, action_timeout, "Set Absolute Timeout" );
00957       ast_manager_register( "MailboxCount", EVENT_FLAG_CALL, action_mailboxcount, "Check Mailbox Message Count" );
00958 
00959       ast_cli_register(&show_mancmds_cli);
00960       ast_cli_register(&show_manconn_cli);
00961       ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
00962       registered = 1;
00963    }
00964    portno = DEFAULT_MANAGER_PORT;
00965    cfg = ast_load("manager.conf");
00966    if (!cfg) {
00967       ast_log(LOG_NOTICE, "Unable to open management configuration manager.conf.  Call management disabled.\n");
00968       return 0;
00969    }
00970    memset(&ba, 0, sizeof(ba));
00971    val = ast_variable_retrieve(cfg, "general", "enabled");
00972    if (val)
00973       enabled = ast_true(val);
00974 
00975    val = ast_variable_retrieve(cfg, "general", "block-sockets");
00976    if(val)
00977       block_sockets = ast_true(val);
00978 
00979    if ((val = ast_variable_retrieve(cfg, "general", "port"))) {
00980       if (sscanf(val, "%d", &portno) != 1) {
00981          ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
00982          portno = DEFAULT_MANAGER_PORT;
00983       }
00984    } else if ((val = ast_variable_retrieve(cfg, "general", "portno"))) {
00985       if (sscanf(val, "%d", &portno) != 1) {
00986          ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
00987          portno = DEFAULT_MANAGER_PORT;
00988       }
00989       ast_log(LOG_NOTICE, "Use of portno in manager.conf deprecated.  Please use 'port=%s' instead.\n", val);
00990    }
00991    
00992    ba.sin_family = AF_INET;
00993    ba.sin_port = htons(portno);
00994    memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
00995    
00996    if ((val = ast_variable_retrieve(cfg, "general", "bindaddr"))) {
00997       if (!inet_aton(val, &ba.sin_addr)) { 
00998          ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
00999          memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
01000       }
01001    }
01002    
01003    if ((asock > -1) && ((portno != oldportno) || !enabled)) {
01004 #if 0
01005       /* Can't be done yet */
01006       close(asock);
01007       asock = -1;
01008 #else
01009       ast_log(LOG_WARNING, "Unable to change management port / enabled\n");
01010 #endif
01011    }
01012    ast_destroy(cfg);
01013    
01014    /* If not enabled, do nothing */
01015    if (!enabled) {
01016       return 0;
01017    }
01018    if (asock < 0) {
01019       asock = socket(AF_INET, SOCK_STREAM, 0);
01020       if (asock < 0) {
01021          ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
01022          return -1;
01023       }
01024       setsockopt(asock, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
01025       if (bind(asock, (struct sockaddr *)&ba, sizeof(ba))) {
01026          ast_log(LOG_WARNING, "Unable to bind socket: %s\n", strerror(errno));
01027          close(asock);
01028          asock = -1;
01029          return -1;
01030       }
01031       if (listen(asock, 2)) {
01032          ast_log(LOG_WARNING, "Unable to listen on socket: %s\n", strerror(errno));
01033          close(asock);
01034          asock = -1;
01035          return -1;
01036       }
01037       if (option_verbose)
01038          ast_verbose("Asterisk Management interface listening on port %d\n", portno);
01039       pthread_create(&t, NULL, accept_thread, NULL);
01040    }
01041    return 0;
01042 }
01043 
01044 int reload_manager(void)
01045 {
01046    manager_event(EVENT_FLAG_SYSTEM, "Reload", "Message: Reload Requested\r\n");
01047    return init_manager();
01048 }

Generated on Sun Apr 18 23:33:52 2004 for Asterisk by doxygen 1.3.6-20040222