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

manager.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- A telephony toolkit for Linux.
00003  *
00004  * The Asterisk Management Interface - AMI
00005  *
00006  * Channel Management and more
00007  * 
00008  * Copyright (C) 1999-2004, Digium, Inc.
00009  *
00010  * Mark Spencer <markster@digium.com>
00011  *
00012  * This program is free software, distributed under the terms of
00013  * the GNU General Public License
00014  */
00015 
00016 #include <stdio.h>
00017 #include <stdlib.h>
00018 #include <string.h>
00019 #include <sys/time.h>
00020 #include <sys/types.h>
00021 #include <netdb.h>
00022 #include <sys/socket.h>
00023 #include <netinet/in.h>
00024 #include <netinet/tcp.h>
00025 #include <arpa/inet.h>
00026 #include <signal.h>
00027 #include <errno.h>
00028 #include <unistd.h>
00029 #include <sys/poll.h>
00030 #include <asterisk/channel.h>
00031 #include <asterisk/file.h>
00032 #include <asterisk/manager.h>
00033 #include <asterisk/config.h>
00034 #include <asterisk/lock.h>
00035 #include <asterisk/logger.h>
00036 #include <asterisk/options.h>
00037 #include <asterisk/cli.h>
00038 #include <asterisk/app.h>
00039 #include <asterisk/pbx.h>
00040 #include <asterisk/md5.h>
00041 #include <asterisk/acl.h>
00042 #include <asterisk/utils.h>
00043 
00044 struct fast_originate_helper
00045 {
00046    char tech[256];
00047    char data[256];
00048    int timeout;
00049    char app[256];
00050    char appdata[256];
00051    char callerid[256];
00052    char variable[256];
00053    char account[256];
00054    char context[256];
00055    char exten[256];
00056    char idtext[256];
00057    int priority;
00058 };
00059 
00060 static int enabled = 0;
00061 static int portno = DEFAULT_MANAGER_PORT;
00062 static int asock = -1;
00063 static pthread_t t;
00064 AST_MUTEX_DEFINE_STATIC(sessionlock);
00065 static int block_sockets = 0;
00066 
00067 static struct permalias {
00068    int num;
00069    char *label;
00070 } perms[] = {
00071    { EVENT_FLAG_SYSTEM, "system" },
00072    { EVENT_FLAG_CALL, "call" },
00073    { EVENT_FLAG_LOG, "log" },
00074    { EVENT_FLAG_VERBOSE, "verbose" },
00075    { EVENT_FLAG_COMMAND, "command" },
00076    { EVENT_FLAG_AGENT, "agent" },
00077    { EVENT_FLAG_USER, "user" },
00078    { -1, "all" },
00079 };
00080 
00081 static struct mansession *sessions = NULL;
00082 static struct manager_action *first_action = NULL;
00083 AST_MUTEX_DEFINE_STATIC(actionlock);
00084 
00085 int ast_carefulwrite(int fd, char *s, int len, int timeoutms) 
00086 {
00087    /* Try to write string, but wait no more than ms milliseconds
00088       before timing out */
00089    int res=0;
00090    struct pollfd fds[1];
00091    while(len) {
00092       res = write(fd, s, len);
00093       if ((res < 0) && (errno != EAGAIN)) {
00094          return -1;
00095       }
00096       if (res < 0) res = 0;
00097       len -= res;
00098       s += res;
00099       fds[0].fd = fd;
00100       fds[0].events = POLLOUT;
00101       /* Wait until writable again */
00102       res = poll(fds, 1, timeoutms);
00103       if (res < 1)
00104          return -1;
00105    }
00106    return res;
00107 }
00108 
00109 static char *authority_to_str(int authority, char *res, int reslen)
00110 {
00111    int running_total = 0, i;
00112    memset(res, 0, reslen);
00113    for (i=0; i<sizeof(perms) / sizeof(perms[0]) - 1; i++) {
00114       if (authority & perms[i].num) {
00115          if (*res) {
00116             strncat(res, ",", (reslen > running_total) ? reslen - running_total : 0);
00117             running_total++;
00118          }
00119          strncat(res, perms[i].label, (reslen > running_total) ? reslen - running_total : 0);
00120          running_total += strlen(perms[i].label);
00121       }
00122    }
00123    if (ast_strlen_zero(res)) {
00124       strncpy(res, "<none>", reslen);
00125    }
00126    return res;
00127 }
00128 
00129 static char *complete_show_mancmd(char *line, char *word, int pos, int state)
00130 {
00131    struct manager_action *cur = first_action;
00132    int which = 0;
00133 
00134    ast_mutex_lock(&actionlock);
00135    while (cur) { /* Walk the list of actions */
00136       if (!strncasecmp(word, cur->action, strlen(word))) {
00137          if (++which > state) {
00138             char *ret = strdup(cur->action);
00139             ast_mutex_unlock(&actionlock);
00140             return ret;
00141          }
00142       }
00143       cur = cur->next;
00144    }
00145    ast_mutex_unlock(&actionlock);
00146    return NULL;
00147 }
00148 
00149 static int handle_showmancmd(int fd, int argc, char *argv[])
00150 {
00151    struct manager_action *cur = first_action;
00152    char authority[80];
00153    int num;
00154 
00155    if (argc != 4)
00156       return RESULT_SHOWUSAGE;
00157    ast_mutex_lock(&actionlock);
00158    while (cur) { /* Walk the list of actions */
00159       for (num = 3; num < argc; num++) {
00160          if (!strcasecmp(cur->action, argv[num])) {
00161             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 : "");
00162          }
00163       }
00164       cur = cur->next;
00165    }
00166 
00167    ast_mutex_unlock(&actionlock);
00168    return RESULT_SUCCESS;
00169 }
00170 
00171 static int handle_showmancmds(int fd, int argc, char *argv[])
00172 {
00173    struct manager_action *cur = first_action;
00174    char authority[80];
00175    char *format = "  %-15.15s  %-10.10s  %-45.45s\n";
00176 
00177    ast_mutex_lock(&actionlock);
00178    ast_cli(fd, format, "Action", "Privilege", "Synopsis");
00179    while (cur) { /* Walk the list of actions */
00180       ast_cli(fd, format, cur->action, authority_to_str(cur->authority, authority, sizeof(authority) -1), cur->synopsis);
00181       cur = cur->next;
00182    }
00183 
00184    ast_mutex_unlock(&actionlock);
00185    return RESULT_SUCCESS;
00186 }
00187 
00188 static int handle_showmanconn(int fd, int argc, char *argv[])
00189 {
00190    struct mansession *s;
00191    char iabuf[INET_ADDRSTRLEN];
00192    char *format = "  %-15.15s  %-15.15s\n";
00193    ast_mutex_lock(&sessionlock);
00194    s = sessions;
00195    ast_cli(fd, format, "Username", "IP Address");
00196    while (s) {
00197       ast_cli(fd, format,s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
00198       s = s->next;
00199    }
00200 
00201    ast_mutex_unlock(&sessionlock);
00202    return RESULT_SUCCESS;
00203 }
00204 
00205 static char showmancmd_help[] = 
00206 "Usage: show manager command <actionname>\n"
00207 "  Shows the detailed description for a specific manager command.\n";
00208 
00209 static char showmancmds_help[] = 
00210 "Usage: show manager commands\n"
00211 "  Prints a listing of all the available manager commands.\n";
00212 
00213 static char showmanconn_help[] = 
00214 "Usage: show manager connected\n"
00215 "  Prints a listing of the users that are connected to the\n"
00216 "manager interface.\n";
00217 
00218 static struct ast_cli_entry show_mancmd_cli =
00219    { { "show", "manager", "command", NULL },
00220    handle_showmancmd, "Show manager command", showmancmd_help, complete_show_mancmd };
00221 
00222 static struct ast_cli_entry show_mancmds_cli =
00223    { { "show", "manager", "commands", NULL },
00224    handle_showmancmds, "Show manager commands", showmancmds_help };
00225 
00226 static struct ast_cli_entry show_manconn_cli =
00227    { { "show", "manager", "connected", NULL },
00228    handle_showmanconn, "Show connected manager users", showmanconn_help };
00229 
00230 static void destroy_session(struct mansession *s)
00231 {
00232    struct mansession *cur, *prev = NULL;
00233    ast_mutex_lock(&sessionlock);
00234    cur = sessions;
00235    while(cur) {
00236       if (cur == s)
00237          break;
00238       prev = cur;
00239       cur = cur->next;
00240    }
00241    if (cur) {
00242       if (prev)
00243          prev->next = cur->next;
00244       else
00245          sessions = cur->next;
00246       if (s->fd > -1)
00247          close(s->fd);
00248       ast_mutex_destroy(&s->lock);
00249       free(s);
00250    } else
00251       ast_log(LOG_WARNING, "Trying to delete nonexistent session %p?\n", s);
00252    ast_mutex_unlock(&sessionlock);
00253    
00254 }
00255 
00256 char *astman_get_header(struct message *m, char *var)
00257 {
00258    char cmp[80];
00259    int x;
00260    snprintf(cmp, sizeof(cmp), "%s: ", var);
00261    for (x=0;x<m->hdrcount;x++)
00262       if (!strncasecmp(cmp, m->headers[x], strlen(cmp)))
00263          return m->headers[x] + strlen(cmp);
00264    return "";
00265 }
00266 
00267 void astman_send_error(struct mansession *s, struct message *m, char *error)
00268 {
00269    char *id = astman_get_header(m,"ActionID");
00270    ast_mutex_lock(&s->lock);
00271    ast_cli(s->fd, "Response: Error\r\n");
00272    if (id && !ast_strlen_zero(id))
00273       ast_cli(s->fd, "ActionID: %s\r\n",id);
00274    ast_cli(s->fd, "Message: %s\r\n\r\n", error);
00275    ast_mutex_unlock(&s->lock);
00276 }
00277 
00278 void astman_send_response(struct mansession *s, struct message *m, char *resp, char *msg)
00279 {
00280    char *id = astman_get_header(m,"ActionID");
00281    ast_mutex_lock(&s->lock);
00282    ast_cli(s->fd, "Response: %s\r\n", resp);
00283    if (id && !ast_strlen_zero(id))
00284       ast_cli(s->fd, "ActionID: %s\r\n",id);
00285    if (msg)
00286       ast_cli(s->fd, "Message: %s\r\n\r\n", msg);
00287    else
00288       ast_cli(s->fd, "\r\n");
00289    ast_mutex_unlock(&s->lock);
00290 }
00291 
00292 void astman_send_ack(struct mansession *s, struct message *m, char *msg)
00293 {
00294    astman_send_response(s, m, "Success", msg);
00295 }
00296 
00297 /* Tells you if smallstr exists inside bigstr
00298    which is delim by delim and uses no buf or stringsep
00299    ast_instring("this|that|more","this",',') == 1;
00300 
00301    feel free to move this to app.c -anthm */
00302 static int ast_instring(char *bigstr, char *smallstr, char delim) 
00303 {
00304    char *val = bigstr, *next;
00305 
00306    do {
00307       if ((next = strchr(val, delim))) {
00308          if (!strncmp(val, smallstr, (next - val)))
00309             return 1;
00310          else
00311             continue;
00312       } else
00313          return !strcmp(smallstr, val);
00314 
00315    } while (*(val = (next + 1)));
00316 
00317    return 0;
00318 }
00319 
00320 static int get_perm(char *instr)
00321 {
00322    int x = 0, ret = 0;
00323 
00324    if (!instr)
00325       return 0;
00326 
00327    for (x=0; x<sizeof(perms) / sizeof(perms[0]); x++)
00328       if (ast_instring(instr, perms[x].label, ','))
00329          ret |= perms[x].num;
00330    
00331    return ret;
00332 }
00333 
00334 static int ast_is_number(char *string) 
00335 {
00336    int ret = 1, x = 0;
00337 
00338    if (!string)
00339       return 0;
00340 
00341    for (x=0; x < strlen(string); x++) {
00342       if (!(string[x] >= 48 && string[x] <= 57)) {
00343          ret = 0;
00344          break;
00345       }
00346    }
00347    
00348    return ret ? atoi(string) : 0;
00349 }
00350 
00351 static int ast_strings_to_mask(char *string) 
00352 {
00353    int x = 0, ret = -1;
00354    
00355    x = ast_is_number(string);
00356 
00357    if (x) 
00358       ret = x;
00359    else if (!string || ast_strlen_zero(string))
00360       ret = -1;
00361    else if (!strcasecmp(string, "off") || ast_false(string))
00362       ret = 0;
00363    else if (!strcasecmp(string, "on") || ast_true(string))
00364       ret = -1;
00365    else {
00366       ret = 0;
00367       for (x=0; x<sizeof(perms) / sizeof(perms[0]); x++) {
00368          if (ast_instring(string, perms[x].label, ',')) 
00369             ret |= perms[x].num;    
00370       }
00371    }
00372 
00373    return ret;
00374 }
00375 
00376 /* 
00377    Rather than braindead on,off this now can also accept a specific int mask value 
00378    or a ',' delim list of mask strings (the same as manager.conf) -anthm
00379 */
00380 
00381 static int set_eventmask(struct mansession *s, char *eventmask)
00382 {
00383    int maskint = ast_strings_to_mask(eventmask);
00384 
00385    ast_mutex_lock(&s->lock);
00386    s->send_events = maskint;
00387    ast_mutex_unlock(&s->lock);
00388    
00389    return s->send_events;
00390 }
00391 
00392 static int authenticate(struct mansession *s, struct message *m)
00393 {
00394    struct ast_config *cfg;
00395    char iabuf[INET_ADDRSTRLEN];
00396    char *cat;
00397    char *user = astman_get_header(m, "Username");
00398    char *pass = astman_get_header(m, "Secret");
00399    char *authtype = astman_get_header(m, "AuthType");
00400    char *key = astman_get_header(m, "Key");
00401    char *events = astman_get_header(m, "Events");
00402    
00403    cfg = ast_load("manager.conf");
00404    if (!cfg)
00405       return -1;
00406    cat = ast_category_browse(cfg, NULL);
00407    while(cat) {
00408       if (strcasecmp(cat, "general")) {
00409          /* This is a user */
00410          if (!strcasecmp(cat, user)) {
00411             struct ast_variable *v;
00412             struct ast_ha *ha = NULL;
00413             char *password = NULL;
00414             v = ast_variable_browse(cfg, cat);
00415             while (v) {
00416                if (!strcasecmp(v->name, "secret")) {
00417                   password = v->value;
00418                } else if (!strcasecmp(v->name, "permit") ||
00419                      !strcasecmp(v->name, "deny")) {
00420                      ha = ast_append_ha(v->name, v->value, ha);
00421                }                 
00422                v = v->next;
00423             }
00424             if (ha && !ast_apply_ha(ha, &(s->sin))) {
00425                ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr), user);
00426                ast_free_ha(ha);
00427                ast_destroy(cfg);
00428                return -1;
00429             } else if (ha)
00430                ast_free_ha(ha);
00431             if (!strcasecmp(authtype, "MD5")) {
00432                if (key && !ast_strlen_zero(key) && s->challenge) {
00433                   int x;
00434                   int len=0;
00435                   char md5key[256] = "";
00436                   struct MD5Context md5;
00437                   unsigned char digest[16];
00438                   MD5Init(&md5);
00439                   MD5Update(&md5, s->challenge, strlen(s->challenge));
00440                   MD5Update(&md5, password, strlen(password));
00441                   MD5Final(digest, &md5);
00442                   for (x=0;x<16;x++)
00443                      len += sprintf(md5key + len, "%2.2x", digest[x]);
00444                   if (!strcmp(md5key, key))
00445                      break;
00446                   else {
00447                      ast_destroy(cfg);
00448                      return -1;
00449                   }
00450                }
00451             } else if (password && !strcasecmp(password, pass)) {
00452                break;
00453             } else {
00454                ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr), user);
00455                ast_destroy(cfg);
00456                return -1;
00457             }  
00458          }
00459       }
00460       cat = ast_category_browse(cfg, cat);
00461    }
00462    if (cat) {
00463       strncpy(s->username, cat, sizeof(s->username) - 1);
00464       s->readperm = get_perm(ast_variable_retrieve(cfg, cat, "read"));
00465       s->writeperm = get_perm(ast_variable_retrieve(cfg, cat, "write"));
00466       ast_destroy(cfg);
00467       if (events)
00468          set_eventmask(s, events);
00469       return 0;
00470    }
00471    ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr), user);
00472    ast_destroy(cfg);
00473    return -1;
00474 }
00475 
00476 static char mandescr_ping[] = 
00477 "Description: A 'Ping' action will ellicit a 'Pong' response.  Used to keep the "
00478 "  manager connection open.\n"
00479 "Variables: NONE\n";
00480 
00481 static int action_ping(struct mansession *s, struct message *m)
00482 {
00483    astman_send_response(s, m, "Pong", NULL);
00484    return 0;
00485 }
00486 
00487 static char mandescr_listcommands[] = 
00488 "Description: Returns the action name and synopsis for every\n"
00489 "  action that is available to the user\n"
00490 "Variables: NONE\n";
00491 
00492 static int action_listcommands(struct mansession *s, struct message *m)
00493 {
00494    struct manager_action *cur = first_action;
00495    char idText[256] = "";
00496    char *id = astman_get_header(m,"ActionID");
00497 
00498    if (id && !ast_strlen_zero(id))
00499       snprintf(idText,256,"ActionID: %s\r\n",id);
00500    ast_cli(s->fd, "Response: Success\r\n%s", idText);
00501    ast_mutex_lock(&s->lock);
00502    ast_mutex_lock(&actionlock);
00503    while (cur) { /* Walk the list of actions */
00504       if ((s->writeperm & cur->authority) == cur->authority)
00505          ast_cli(s->fd, "%s: %s\r\n", cur->action, cur->synopsis);
00506       cur = cur->next;
00507    }
00508    ast_mutex_unlock(&actionlock);
00509    ast_cli(s->fd, "\r\n");
00510    ast_mutex_unlock(&s->lock);
00511 
00512    return 0;
00513 }
00514 
00515 static char mandescr_events[] = 
00516 "Description: Enable/Disable sending of events to this manager\n"
00517 "  client.\n"
00518 "Variables:\n"
00519 "  EventMask: 'on' if all events should be sent,\n"
00520 "     'off' if no events should be sent,\n"
00521 "     'system,call,log' to select which flags events should have to be sent.\n";
00522 
00523 static int action_events(struct mansession *s, struct message *m)
00524 {
00525    char *mask = astman_get_header(m, "EventMask");
00526    int res;
00527 
00528    res = set_eventmask(s, mask);
00529    if (res > 0)
00530       astman_send_response(s, m, "Events On", NULL);
00531    else if (res == 0)
00532       astman_send_response(s, m, "Events Off", NULL);
00533 
00534    return 0;
00535 }
00536 
00537 static char mandescr_logoff[] = 
00538 "Description: Logoff this manager session\n"
00539 "Variables: NONE\n";
00540 
00541 static int action_logoff(struct mansession *s, struct message *m)
00542 {
00543    astman_send_response(s, m, "Goodbye", "Thanks for all the fish.");
00544    return -1;
00545 }
00546 
00547 static char mandescr_hangup[] = 
00548 "Description: Hangup a channel\n"
00549 "Variables: \n"
00550 "  Channel: The channel name to be hungup\n";
00551 
00552 static int action_hangup(struct mansession *s, struct message *m)
00553 {
00554    struct ast_channel *c = NULL;
00555    char *name = astman_get_header(m, "Channel");
00556    if (ast_strlen_zero(name)) {
00557       astman_send_error(s, m, "No channel specified");
00558       return 0;
00559    }
00560    c = ast_channel_walk_locked(NULL);
00561    while(c) {
00562       if (!strcasecmp(c->name, name)) {
00563          break;
00564       }
00565       ast_mutex_unlock(&c->lock);
00566       c = ast_channel_walk_locked(c);
00567    }
00568    if (!c) {
00569       astman_send_error(s, m, "No such channel");
00570       return 0;
00571    }
00572    ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
00573    ast_mutex_unlock(&c->lock);
00574    astman_send_ack(s, m, "Channel Hungup");
00575    return 0;
00576 }
00577 
00578 static char mandescr_setvar[] = 
00579 "Description: Set a local channel variable.\n"
00580 "Variables: (Names marked with * are required)\n"
00581 "  *Channel: Channel to set variable for\n"
00582 "  *Variable: Variable name\n"
00583 "  *Value: Value\n";
00584 
00585 static int action_setvar(struct mansession *s, struct message *m)
00586 {
00587         struct ast_channel *c = NULL;
00588         char *name = astman_get_header(m, "Channel");
00589         char *varname = astman_get_header(m, "Variable");
00590         char *varval = astman_get_header(m, "Value");
00591    
00592    if (!strlen(name)) {
00593       astman_send_error(s, m, "No channel specified");
00594       return 0;
00595    }
00596    if (!strlen(varname)) {
00597       astman_send_error(s, m, "No variable specified");
00598       return 0;
00599    }
00600 
00601    c = ast_channel_walk_locked(NULL);
00602    while(c) {
00603       if (!strcasecmp(c->name, name)) {
00604          break;
00605       }
00606       ast_mutex_unlock(&c->lock);
00607       c = ast_channel_walk_locked(c);
00608    }
00609    if (!c) {
00610       astman_send_error(s, m, "No such channel");
00611       return 0;
00612    }
00613    
00614    pbx_builtin_setvar_helper(c,varname,varval);
00615      
00616    ast_mutex_unlock(&c->lock);
00617    astman_send_ack(s, m, "Variable Set");
00618    return 0;
00619 }
00620 
00621 static char mandescr_getvar[] = 
00622 "Description: Get the value of a local channel variable.\n"
00623 "Variables: (Names marked with * are required)\n"
00624 "  *Channel: Channel to read variable from\n"
00625 "  *Variable: Variable name\n"
00626 "  ActionID: Optional Action id for message matching.\n";
00627 
00628 static int action_getvar(struct mansession *s, struct message *m)
00629 {
00630         struct ast_channel *c = NULL;
00631         char *name = astman_get_header(m, "Channel");
00632         char *varname = astman_get_header(m, "Variable");
00633    char *id = astman_get_header(m,"ActionID");
00634    char *varval;
00635 
00636    if (!strlen(name)) {
00637       astman_send_error(s, m, "No channel specified");
00638       return 0;
00639    }
00640    if (!strlen(varname)) {
00641       astman_send_error(s, m, "No variable specified");
00642       return 0;
00643    }
00644 
00645    c = ast_channel_walk_locked(NULL);
00646    while(c) {
00647       if (!strcasecmp(c->name, name)) {
00648          break;
00649       }
00650       ast_mutex_unlock(&c->lock);
00651       c = ast_channel_walk_locked(c);
00652    }
00653    if (!c) {
00654       astman_send_error(s, m, "No such channel");
00655       return 0;
00656    }
00657    
00658    varval=pbx_builtin_getvar_helper(c,varname);
00659      
00660    ast_mutex_unlock(&c->lock);
00661    ast_mutex_lock(&s->lock);
00662    ast_cli(s->fd, "Response: Success\r\n"
00663       "%s: %s\r\n" ,varname,varval);
00664    if (id && !ast_strlen_zero(id))
00665       ast_cli(s->fd, "ActionID: %s\r\n",id);
00666    ast_cli(s->fd, "\r\n");
00667    ast_mutex_unlock(&s->lock);
00668 
00669    return 0;
00670 }
00671 
00672 
00673 static int action_status(struct mansession *s, struct message *m)
00674 {
00675    char *id = astman_get_header(m,"ActionID");
00676       char *name = astman_get_header(m,"Channel");
00677    char idText[256] = "";
00678    struct ast_channel *c;
00679    char bridge[256];
00680    struct timeval now;
00681    long elapsed_seconds=0;
00682 
00683    gettimeofday(&now, NULL);
00684    astman_send_ack(s, m, "Channel status will follow");
00685    c = ast_channel_walk_locked(NULL);
00686         if (id && !ast_strlen_zero(id))
00687                 snprintf(idText,256,"ActionID: %s\r\n",id);
00688    if (name && !ast_strlen_zero(name)) {
00689       while (c) {
00690          if (!strcasecmp(c->name, name)) {
00691             break;
00692          }
00693          ast_mutex_unlock(&c->lock);
00694          c = ast_channel_walk_locked(c);
00695       }
00696       if (!c) {
00697          astman_send_error(s, m, "No such channel");
00698          return 0;
00699       }
00700    }
00701    while(c) {
00702       if (c->bridge)
00703          snprintf(bridge, sizeof(bridge), "Link: %s\r\n", c->bridge->name);
00704       else
00705          bridge[0] = '\0';
00706       ast_mutex_lock(&s->lock);
00707       if (c->pbx) {
00708          if (c->cdr) {
00709             elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
00710          }
00711          ast_cli(s->fd,
00712          "Event: Status\r\n"
00713          "Channel: %s\r\n"
00714          "CallerID: %s\r\n"
00715          "Account: %s\r\n"
00716          "State: %s\r\n"
00717          "Context: %s\r\n"
00718          "Extension: %s\r\n"
00719          "Priority: %d\r\n"
00720          "Seconds: %ld\r\n"
00721          "%s"
00722          "Uniqueid: %s\r\n"
00723          "%s"
00724          "\r\n",
00725          c->name, c->callerid ? c->callerid : "<unknown>", 
00726          c->accountcode,
00727          ast_state2str(c->_state), c->context,
00728          c->exten, c->priority, (long)elapsed_seconds, bridge, c->uniqueid, idText);
00729       } else {
00730          ast_cli(s->fd,
00731          "Event: Status\r\n"
00732          "Channel: %s\r\n"
00733          "CallerID: %s\r\n"
00734          "Account: %s\r\n"
00735          "State: %s\r\n"
00736          "%s"
00737          "Uniqueid: %s\r\n"
00738          "%s"
00739          "\r\n",
00740          c->name, c->callerid ? c->callerid : "<unknown>", 
00741          c->accountcode,
00742          ast_state2str(c->_state), bridge, c->uniqueid, idText);
00743       }
00744       ast_mutex_unlock(&s->lock);
00745       ast_mutex_unlock(&c->lock);
00746       if (name && !ast_strlen_zero(name)) {
00747          break;
00748       }
00749       c = ast_channel_walk_locked(c);
00750    }
00751    ast_mutex_lock(&s->lock);
00752    ast_cli(s->fd,
00753    "Event: StatusComplete\r\n"
00754    "%s"
00755    "\r\n",idText);
00756    ast_mutex_unlock(&s->lock);
00757    return 0;
00758 }
00759 
00760 static int action_redirect(struct mansession *s, struct message *m)
00761 {
00762    char *name = astman_get_header(m, "Channel");
00763    char *name2 = astman_get_header(m, "ExtraChannel");
00764    char *exten = astman_get_header(m, "Exten");
00765    char *context = astman_get_header(m, "Context");
00766    char *priority = astman_get_header(m, "Priority");
00767    struct ast_channel *chan, *chan2 = NULL;
00768    int pi = 0;
00769    int res;
00770    if (!name || ast_strlen_zero(name)) {
00771       astman_send_error(s, m, "Channel not specified");
00772       return 0;
00773    }
00774    if (!ast_strlen_zero(priority) && (sscanf(priority, "%d", &pi) != 1)) {
00775       astman_send_error(s, m, "Invalid priority\n");
00776       return 0;
00777    }
00778    chan = ast_get_channel_by_name_locked(name);
00779    if (!chan) {
00780       astman_send_error(s, m, "Channel not existent");
00781       return 0;
00782    }
00783    if (!ast_strlen_zero(name2))
00784       chan2 = ast_get_channel_by_name_locked(name2);
00785    res = ast_async_goto(chan, context, exten, pi);
00786    if (!res) {
00787       if (!ast_strlen_zero(name2)) {
00788          if (chan2)
00789             res = ast_async_goto(chan2, context, exten, pi);
00790          else
00791             res = -1;
00792          if (!res)
00793             astman_send_ack(s, m, "Dual Redirect successful");
00794          else
00795             astman_send_error(s, m, "Secondary redirect failed");
00796       } else
00797          astman_send_ack(s, m, "Redirect successful");
00798    } else
00799       astman_send_error(s, m, "Redirect failed");
00800    if (chan)
00801       ast_mutex_unlock(&chan->lock);
00802    if (chan2)
00803       ast_mutex_unlock(&chan2->lock);
00804    return 0;
00805 }
00806 
00807 static char mandescr_command[] = 
00808 "Description: Run a CLI command.\n"
00809 "Variables: (Names marked with * are required)\n"
00810 "  *Command: Asterisk CLI command to run\n"
00811 "  ActionID: Optional Action id for message matching.\n";
00812 static int action_command(struct mansession *s, struct message *m)
00813 {
00814    char *cmd = astman_get_header(m, "Command");
00815    char *id = astman_get_header(m, "ActionID");
00816    ast_mutex_lock(&s->lock);
00817    s->blocking = 1;
00818    ast_mutex_unlock(&s->lock);
00819    ast_cli(s->fd, "Response: Follows\r\n");
00820    if (id && !ast_strlen_zero(id))
00821       ast_cli(s->fd, "ActionID: %s\r\n", id);
00822    /* FIXME: Wedge a ActionID response in here, waiting for later changes */
00823    ast_cli_command(s->fd, cmd);
00824    ast_cli(s->fd, "--END COMMAND--\r\n\r\n");
00825    ast_mutex_lock(&s->lock);
00826    s->blocking = 0;
00827    ast_mutex_unlock(&s->lock);
00828    return 0;
00829 }
00830 
00831 static void *fast_originate(void *data)
00832 {
00833    struct fast_originate_helper *in = data;
00834    int res;
00835    int reason = 0;
00836    if (!ast_strlen_zero(in->app)) {
00837       res = ast_pbx_outgoing_app(in->tech, AST_FORMAT_SLINEAR, in->data, in->timeout, in->app, in->appdata, &reason, 1, !ast_strlen_zero(in->callerid) ? in->callerid : NULL, in->variable, in->account);
00838    } else {
00839       res = ast_pbx_outgoing_exten(in->tech, AST_FORMAT_SLINEAR, in->data, in->timeout, in->context, in->exten, in->priority, &reason, 1, !ast_strlen_zero(in->callerid) ? in->callerid : NULL, in->variable, in->account);
00840    }   
00841    if (!res)
00842       manager_event(EVENT_FLAG_CALL,
00843          "OriginateSuccess",
00844          "%s"
00845          "Channel: %s/%s\r\n"
00846          "Context: %s\r\n"
00847          "Exten: %s\r\n",
00848          in->idtext, in->tech, in->data, in->context, in->exten);
00849    else
00850       manager_event(EVENT_FLAG_CALL,
00851          "OriginateFailure",
00852          "%s"
00853          "Channel: %s/%s\r\n"
00854          "Context: %s\r\n"
00855          "Exten: %s\r\n",
00856          in->idtext, in->tech, in->data, in->context, in->exten);
00857 
00858    free(in);
00859    return NULL;
00860 }
00861 
00862 static char mandescr_originate[] = 
00863 "Description: Generates an outgoing call to a Extension/Context/Priority or\n"
00864 "  Application/Data\n"
00865 "Variables: (Names marked with * are required)\n"
00866 "  *Channel: Channel name to call\n"
00867 "  Exten: Extension to use (requires 'Context' and 'Priority')\n"
00868 "  Context: Context to use (requires 'Exten' and 'Priority')\n"
00869 "  Priority: Priority to use (requires 'Exten' and 'Context')\n"
00870 "  Application: Application to use\n"
00871 "  Data: Data to use (requires 'Application')\n"
00872 "  Timeout: How long to wait for call to be answered (in ms)\n"
00873 "  CallerID: Caller ID to be set on the outgoing channel\n"
00874 "  Variable: Channel variable to set (VAR1=value1|VAR2=value2)\n"
00875 "  Account: Account code\n"
00876 "  Async: Set to 'true' for fast origination\n";
00877 
00878 static int action_originate(struct mansession *s, struct message *m)
00879 {
00880    char *name = astman_get_header(m, "Channel");
00881    char *exten = astman_get_header(m, "Exten");
00882    char *context = astman_get_header(m, "Context");
00883    char *priority = astman_get_header(m, "Priority");
00884    char *timeout = astman_get_header(m, "Timeout");
00885    char *callerid = astman_get_header(m, "CallerID");
00886       char *variable = astman_get_header(m, "Variable");
00887       char *account = astman_get_header(m, "Account");
00888    char *app = astman_get_header(m, "Application");
00889    char *appdata = astman_get_header(m, "Data");
00890    char *async = astman_get_header(m, "Async");
00891    char *id = astman_get_header(m, "ActionID");
00892    char *tech, *data;
00893    int pi = 0;
00894    int res;
00895    int to = 30000;
00896    int reason = 0;
00897    char tmp[256];
00898    pthread_t th;
00899    pthread_attr_t attr;
00900    if (!name) {
00901       astman_send_error(s, m, "Channel not specified");
00902       return 0;
00903    }
00904    if (!ast_strlen_zero(priority) && (sscanf(priority, "%d", &pi) != 1)) {
00905       astman_send_error(s, m, "Invalid priority\n");
00906       return 0;
00907    }
00908    if (!ast_strlen_zero(timeout) && (sscanf(timeout, "%d", &to) != 1)) {
00909       astman_send_error(s, m, "Invalid timeout\n");
00910       return 0;
00911    }
00912    strncpy(tmp, name, sizeof(tmp) - 1);
00913    tech = tmp;
00914    data = strchr(tmp, '/');
00915    if (!data) {
00916       astman_send_error(s, m, "Invalid channel\n");
00917       return 0;
00918    }
00919    *data = '\0';
00920    data++;
00921    if (ast_true(async)) {
00922       struct fast_originate_helper *fast = malloc(sizeof(struct fast_originate_helper));
00923       if (!fast) {
00924          res = -1;
00925       } else {
00926          memset(fast, 0, sizeof(struct fast_originate_helper));
00927          if (id && !ast_strlen_zero(id))
00928             snprintf(fast->idtext, sizeof(fast->idtext), "ActionID: %s\r\n", id);
00929          strncpy(fast->tech, tech, sizeof(fast->tech) - 1);
00930             strncpy(fast->data, data, sizeof(fast->data) - 1);
00931          strncpy(fast->app, app, sizeof(fast->app) - 1);
00932          strncpy(fast->appdata, appdata, sizeof(fast->appdata) - 1);
00933          strncpy(fast->callerid, callerid, sizeof(fast->callerid) - 1);
00934          strncpy(fast->variable, variable, sizeof(fast->variable) - 1);
00935          strncpy(fast->account, account, sizeof(fast->account) - 1);
00936          strncpy(fast->context, context, sizeof(fast->context) - 1);
00937          strncpy(fast->exten, exten, sizeof(fast->exten) - 1);
00938          fast->timeout = to;
00939          fast->priority = pi;
00940          pthread_attr_init(&attr);
00941          pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
00942          if (ast_pthread_create(&th, &attr, fast_originate, fast)) {
00943             res = -1;
00944          } else {
00945             res = 0;
00946          }
00947       }
00948    } else if (!ast_strlen_zero(app)) {
00949          res = ast_pbx_outgoing_app(tech, AST_FORMAT_SLINEAR, data, to, app, appdata, &reason, 1, !ast_strlen_zero(callerid) ? callerid : NULL, variable, account);
00950       } else {
00951       if (exten && context && pi)
00952             res = ast_pbx_outgoing_exten(tech, AST_FORMAT_SLINEAR, data, to, context, exten, pi, &reason, 1, !ast_strlen_zero(callerid) ? callerid : NULL, variable, account);
00953       else {
00954          astman_send_error(s, m, "Originate with 'Exten' requires 'Context' and 'Priority'");
00955          return 0;
00956       }
00957    }   
00958    if (!res)
00959       astman_send_ack(s, m, "Originate successfully queued");
00960    else
00961       astman_send_error(s, m, "Originate failed");
00962    return 0;
00963 }
00964 
00965 static char mandescr_mailboxstatus[] = 
00966 "Description: Checks a voicemail account for status.\n"
00967 "Variables: (Names marked with * are required)\n"
00968 "  *Mailbox: Full mailbox ID <mailbox>@<vm-context>\n"
00969 "  ActionID: Optional ActionID for message matching.\n"
00970 "Returns number of messages.\n"
00971 "  Message: Mailbox Status\n"
00972 "  Mailbox: <mailboxid>\n"
00973 "  Waiting: <count>\n"
00974 "\n";
00975 static int action_mailboxstatus(struct mansession *s, struct message *m)
00976 {
00977    char *mailbox = astman_get_header(m, "Mailbox");
00978    char *id = astman_get_header(m,"ActionID");
00979    char idText[256] = "";
00980    int ret;
00981    if (!mailbox || ast_strlen_zero(mailbox)) {
00982       astman_send_error(s, m, "Mailbox not specified");
00983       return 0;
00984    }
00985         if (id && !ast_strlen_zero(id))
00986                 snprintf(idText,256,"ActionID: %s\r\n",id);
00987    ret = ast_app_has_voicemail(mailbox);
00988    ast_mutex_lock(&s->lock);
00989    ast_cli(s->fd, "Response: Success\r\n"
00990                "%s"
00991                "Message: Mailbox Status\r\n"
00992                "Mailbox: %s\r\n"
00993                "Waiting: %d\r\n\r\n", idText, mailbox, ret);
00994    ast_mutex_unlock(&s->lock);
00995    return 0;
00996 }
00997 
00998 static char mandescr_mailboxcount[] = 
00999 "Description: Checks a voicemail account for new messages.\n"
01000 "Variables: (Names marked with * are required)\n"
01001 "  *Mailbox: Full mailbox ID <mailbox>@<vm-context>\n"
01002 "  ActionID: Optional ActionID for message matching.\n"
01003 "Returns number of new and old messages.\n"
01004 "  Message: Mailbox Message Count\n"
01005 "  Mailbox: <mailboxid>\n"
01006 "  NewMessages: <count>\n"
01007 "  OldMessages: <count>\n"
01008 "\n";
01009 static int action_mailboxcount(struct mansession *s, struct message *m)
01010 {
01011    char *mailbox = astman_get_header(m, "Mailbox");
01012    char *id = astman_get_header(m,"ActionID");
01013    char idText[256] = "";
01014    int newmsgs = 0, oldmsgs = 0;
01015    if (!mailbox || ast_strlen_zero(mailbox)) {
01016       astman_send_error(s, m, "Mailbox not specified");
01017       return 0;
01018    }
01019    ast_app_messagecount(mailbox, &newmsgs, &oldmsgs);
01020         if (id && !ast_strlen_zero(id)) {
01021                 snprintf(idText,256,"ActionID: %s\r\n",id);
01022         }
01023    ast_mutex_lock(&s->lock);
01024    ast_cli(s->fd, "Response: Success\r\n"
01025                "%s"
01026                "Message: Mailbox Message Count\r\n"
01027                "Mailbox: %s\r\n"
01028                "NewMessages: %d\r\n"
01029                "OldMessages: %d\r\n" 
01030                "\r\n",
01031                 idText,mailbox, newmsgs, oldmsgs);
01032    ast_mutex_unlock(&s->lock);
01033    return 0;
01034 }
01035 
01036 static char mandescr_extensionstate[] = 
01037 "Description: Report the extension state for given extension.\n"
01038 "  If the extension has a hint, will use devicestate to check\n"
01039 "  the status of the device connected to the extension.\n"
01040 "Variables: (Names marked with * are required)\n"
01041 "  *Exten: Extension to check state on\n"
01042 "  *Context: Context for extension\n"
01043 "  ActionId: Optional ID for this transaction\n"
01044 "Will return an \"Extension Status\" message.\n"
01045 "The response will include the hint for the extension and the status.\n";
01046 
01047 static int action_extensionstate(struct mansession *s, struct message *m)
01048 {
01049    char *exten = astman_get_header(m, "Exten");
01050    char *context = astman_get_header(m, "Context");
01051    char *id = astman_get_header(m,"ActionID");
01052    char idText[256] = "";
01053    char hint[256] = "";
01054    int status;
01055    if (!exten || ast_strlen_zero(exten)) {
01056       astman_send_error(s, m, "Extension not specified");
01057       return 0;
01058    }
01059    if (!context || ast_strlen_zero(context))
01060       context = "default";
01061    status = ast_extension_state(NULL, context, exten);
01062    ast_get_hint(hint, sizeof(hint) - 1, NULL, context, exten);
01063         if (id && !ast_strlen_zero(id)) {
01064                 snprintf(idText,256,"ActionID: %s\r\n",id);
01065         }
01066    ast_mutex_lock(&s->lock);
01067    ast_cli(s->fd, "Response: Success\r\n"
01068                     "%s"
01069                "Message: Extension Status\r\n"
01070                "Exten: %s\r\n"
01071                "Context: %s\r\n"
01072                "Hint: %s\r\n"
01073                "Status: %d\r\n\r\n",
01074                idText,exten, context, hint, status);
01075    ast_mutex_unlock(&s->lock);
01076    return 0;
01077 }
01078 
01079 static char mandescr_timeout[] = 
01080 "Description: Hangup a channel after a certain time.\n"
01081 "Variables: (Names marked with * are required)\n"
01082 "  *Channel: Channel name to hangup\n"
01083 "  *Timeout: Maximum duration of the call (sec)\n"
01084 "Acknowledges set time with 'Timeout Set' message\n";
01085 
01086 static int action_timeout(struct mansession *s, struct message *m)
01087 {
01088    struct ast_channel *c = NULL;
01089    char *name = astman_get_header(m, "Channel");
01090    int timeout = atoi(astman_get_header(m, "Timeout"));
01091    if (ast_strlen_zero(name)) {
01092       astman_send_error(s, m, "No channel specified");
01093       return 0;
01094    }
01095    if (!timeout) {
01096       astman_send_error(s, m, "No timeout specified");
01097       return 0;
01098    }
01099    c = ast_channel_walk_locked(NULL);
01100    while(c) {
01101       if (!strcasecmp(c->name, name)) {
01102          break;
01103       }
01104       ast_mutex_unlock(&c->lock);
01105       c = ast_channel_walk_locked(c);
01106    }
01107    if (!c) {
01108       astman_send_error(s, m, "No such channel");
01109       return 0;
01110    }
01111    ast_channel_setwhentohangup(c, timeout);
01112    ast_mutex_unlock(&c->lock);
01113    astman_send_ack(s, m, "Timeout Set");
01114    return 0;
01115 }
01116 
01117 static int process_message(struct mansession *s, struct message *m)
01118 {
01119    char action[80] = "";
01120    struct manager_action *tmp = first_action;
01121    char *id = astman_get_header(m,"ActionID");
01122    char idText[256] = "";
01123    char iabuf[INET_ADDRSTRLEN];
01124 
01125    strncpy(action, astman_get_header(m, "Action"), sizeof(action) - 1);
01126    ast_log( LOG_DEBUG, "Manager received command '%s'\n", action );
01127 
01128    if (ast_strlen_zero(action)) {
01129       astman_send_error(s, m, "Missing action in request");
01130       return 0;
01131    }
01132         if (id && !ast_strlen_zero(id)) {
01133                 snprintf(idText,256,"ActionID: %s\r\n",id);
01134         }
01135    if (!s->authenticated) {
01136       if (!strcasecmp(action, "Challenge")) {
01137          char *authtype;
01138          authtype = astman_get_header(m, "AuthType");
01139          if (!strcasecmp(authtype, "MD5")) {
01140             if (!s->challenge || ast_strlen_zero(s->challenge)) {
01141                ast_mutex_lock(&s->lock);
01142                snprintf(s->challenge, sizeof(s->challenge), "%d", rand());
01143                ast_mutex_unlock(&s->lock);
01144             }
01145             ast_mutex_lock(&s->lock);
01146             ast_cli(s->fd, "Response: Success\r\n"
01147                   "%s"
01148                   "Challenge: %s\r\n\r\n",
01149                   idText,s->challenge);
01150             ast_mutex_unlock(&s->lock);
01151             return 0;
01152          } else {
01153             astman_send_error(s, m, "Must specify AuthType");
01154             return 0;
01155          }
01156       } else if (!strcasecmp(action, "Login")) {
01157          if (authenticate(s, m)) {
01158             sleep(1);
01159             astman_send_error(s, m, "Authentication failed");
01160             return -1;
01161          } else {
01162             s->authenticated = 1;
01163             if (option_verbose > 1) 
01164                ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged on from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
01165             ast_log(LOG_EVENT, "Manager '%s' logged on from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
01166             astman_send_ack(s, m, "Authentication accepted");
01167          }
01168       } else if (!strcasecmp(action, "Logoff")) {
01169          astman_send_ack(s, m, "See ya");
01170          return -1;
01171       } else
01172          astman_send_error(s, m, "Authentication Required");
01173    } else {
01174       while( tmp ) {       
01175          if (!strcasecmp(action, tmp->action)) {
01176             if ((s->writeperm & tmp->authority) == tmp->authority) {
01177                if (tmp->func(s, m))
01178                   return -1;
01179             } else {
01180                astman_send_error(s, m, "Permission denied");
01181             }
01182             return 0;
01183          }
01184          tmp = tmp->next;
01185       }
01186       astman_send_error(s, m, "Invalid/unknown command");
01187    }
01188    return 0;
01189 }
01190 
01191 static int get_input(struct mansession *s, char *output)
01192 {
01193    /* output must have at least sizeof(s->inbuf) space */
01194    int res;
01195    int x;
01196    struct pollfd fds[1];
01197    char iabuf[INET_ADDRSTRLEN];
01198    for (x=1;x<s->inlen;x++) {
01199       if ((s->inbuf[x] == '\n') && (s->inbuf[x-1] == '\r')) {
01200          /* Copy output data up to and including \r\n */
01201          memcpy(output, s->inbuf, x + 1);
01202          /* Add trailing \0 */
01203          output[x+1] = '\0';
01204          /* Move remaining data back to the front */
01205          memmove(s->inbuf, s->inbuf + x + 1, s->inlen - x);
01206          s->inlen -= (x + 1);
01207          return 1;
01208       }
01209    } 
01210    if (s->inlen >= sizeof(s->inbuf) - 1) {
01211       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);
01212       s->inlen = 0;
01213    }
01214    fds[0].fd = s->fd;
01215    fds[0].events = POLLIN;
01216    res = poll(fds, 1, -1);
01217    if (res < 0) {
01218       ast_log(LOG_WARNING, "Select returned error: %s\n", strerror(errno));
01219    } else if (res > 0) {
01220       ast_mutex_lock(&s->lock);
01221       res = read(s->fd, s->inbuf + s->inlen, sizeof(s->inbuf) - 1 - s->inlen);
01222       ast_mutex_unlock(&s->lock);
01223       if (res < 1)
01224          return -1;
01225    }
01226    s->inlen += res;
01227    s->inbuf[s->inlen] = '\0';
01228    return 0;
01229 }
01230 
01231 static void *session_do(void *data)
01232 {
01233    struct mansession *s = data;
01234    struct message m;
01235    char iabuf[INET_ADDRSTRLEN];
01236    int res;
01237    
01238    ast_mutex_lock(&s->lock);
01239    ast_cli(s->fd, "Asterisk Call Manager/1.0\r\n");
01240    ast_mutex_unlock(&s->lock);
01241    memset(&m, 0, sizeof(&m));
01242    for (;;) {
01243       res = get_input(s, m.headers[m.hdrcount]);
01244       if (res > 0) {
01245          /* Strip trailing \r\n */
01246          if (strlen(m.headers[m.hdrcount]) < 2)
01247             continue;
01248          m.headers[m.hdrcount][strlen(m.headers[m.hdrcount]) - 2] = '\0';
01249          if (ast_strlen_zero(m.headers[m.hdrcount])) {
01250             if (process_message(s, &m))
01251                break;
01252             memset(&m, 0, sizeof(&m));
01253          } else if (m.hdrcount < MAX_HEADERS - 1)
01254             m.hdrcount++;
01255       } else if (res < 0)
01256          break;
01257    }
01258    if (s->authenticated) {
01259       if (option_verbose > 1) 
01260          ast_verbose(VERBOSE_PREFIX_2 "Manager '%s' logged off from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
01261       ast_log(LOG_EVENT, "Manager '%s' logged off from %s\n", s->username, ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
01262    } else {
01263       if (option_verbose > 1)
01264          ast_verbose(VERBOSE_PREFIX_2 "Connect attempt from '%s' unable to authenticate\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
01265       ast_log(LOG_EVENT, "Failed attempt from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), s->sin.sin_addr));
01266    }
01267    destroy_session(s);
01268    return NULL;
01269 }
01270 
01271 static void *accept_thread(void *ignore)
01272 {
01273    int as;
01274    struct sockaddr_in sin;
01275    int sinlen;
01276    struct mansession *s;
01277    struct protoent *p;
01278    int arg = 1;
01279    int flags;
01280    pthread_attr_t attr;
01281 
01282    pthread_attr_init(&attr);
01283    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
01284 
01285    for (;;) {
01286       sinlen = sizeof(sin);
01287       as = accept(asock, (struct sockaddr *)&sin, &sinlen);
01288       if (as < 0) {
01289          ast_log(LOG_NOTICE, "Accept returned -1: %s\n", strerror(errno));
01290          continue;
01291       }
01292       p = getprotobyname("tcp");
01293       if( p ) {
01294          if( setsockopt(as, p->p_proto, TCP_NODELAY, (char *)&arg, sizeof(arg) ) < 0 ) {
01295             ast_log(LOG_WARNING, "Failed to set manager tcp connection to TCP_NODELAY mode: %s\n", strerror(errno));
01296          }
01297       }
01298       s = malloc(sizeof(struct mansession));
01299       if (!s) {
01300          ast_log(LOG_WARNING, "Failed to allocate management session: %s\n", strerror(errno));
01301          continue;
01302       } 
01303       memset(s, 0, sizeof(struct mansession));
01304       memcpy(&s->sin, &sin, sizeof(sin));
01305 
01306       if(! block_sockets) {
01307          /* For safety, make sure socket is non-blocking */
01308          flags = fcntl(as, F_GETFL);
01309          fcntl(as, F_SETFL, flags | O_NONBLOCK);
01310       }
01311       ast_mutex_init(&s->lock);
01312       s->fd = as;
01313       s->send_events = -1;
01314       ast_mutex_lock(&sessionlock);
01315       s->next = sessions;
01316       sessions = s;
01317       ast_mutex_unlock(&sessionlock);
01318       if (ast_pthread_create(&t, &attr, session_do, s))
01319          destroy_session(s);
01320    }
01321    pthread_attr_destroy(&attr);
01322    return NULL;
01323 }
01324 
01325 int manager_event(int category, char *event, char *fmt, ...)
01326 {
01327    struct mansession *s;
01328    char tmp[4096];
01329    va_list ap;
01330 
01331    ast_mutex_lock(&sessionlock);
01332    s = sessions;
01333    while(s) {
01334       if (((s->readperm & category) == category) && ((s->send_events & category) == category) ) {
01335          ast_mutex_lock(&s->lock);
01336          if (!s->blocking) {
01337             ast_cli(s->fd, "Event: %s\r\n", event);
01338             va_start(ap, fmt);
01339             vsnprintf(tmp, sizeof(tmp), fmt, ap);
01340             va_end(ap);
01341             ast_carefulwrite(s->fd,tmp,strlen(tmp),100);
01342             ast_cli(s->fd, "\r\n");
01343          }
01344          ast_mutex_unlock(&s->lock);
01345       }
01346       s = s->next;
01347    }
01348    ast_mutex_unlock(&sessionlock);
01349    return 0;
01350 }
01351 
01352 int ast_manager_unregister( char *action ) {
01353    struct manager_action *cur = first_action, *prev = first_action;
01354 
01355    ast_mutex_lock(&actionlock);
01356    while( cur ) {       
01357       if (!strcasecmp(action, cur->action)) {
01358          prev->next = cur->next;
01359          free(cur);
01360          if (option_verbose > 1) 
01361             ast_verbose(VERBOSE_PREFIX_2 "Manager unregistered action %s\n", action);
01362          ast_mutex_unlock(&actionlock);
01363          return 0;
01364       }
01365       prev = cur;
01366       cur = cur->next;
01367    }
01368    ast_mutex_unlock(&actionlock);
01369    return 0;
01370 }
01371 
01372 static int manager_state_cb(char *context, char *exten, int state, void *data)
01373 {
01374    /* Notify managers of change */
01375    manager_event(EVENT_FLAG_CALL, "ExtensionStatus", "Exten: %s\r\nContext: %s\r\nStatus: %d\r\n", exten, context, state);
01376    return 0;
01377 }
01378 
01379 static int ast_manager_register_struct(struct manager_action *act)
01380 {
01381    struct manager_action *cur = first_action, *prev = NULL;
01382    int ret;
01383 
01384    ast_mutex_lock(&actionlock);
01385    while(cur) { /* Walk the list of actions */
01386       ret = strcasecmp(cur->action, act->action);
01387       if (ret == 0) {
01388          ast_log(LOG_WARNING, "Manager: Action '%s' already registered\n", act->action);
01389          ast_mutex_unlock(&actionlock);
01390          return -1;
01391       } else if (ret > 0) {
01392          /* Insert these alphabetically */
01393          if (prev) {
01394             act->next = prev->next;
01395             prev->next = act;
01396          } else {
01397             act->next = first_action;
01398             first_action = act;
01399          }
01400          break;
01401       }
01402       prev = cur; 
01403       cur = cur->next;
01404    }
01405    
01406    if (!cur) {
01407       if (prev)
01408          prev->next = act;
01409       else
01410          first_action = act;
01411       act->next = NULL;
01412    }
01413 
01414    if (option_verbose > 1) 
01415       ast_verbose(VERBOSE_PREFIX_2 "Manager registered action %s\n", act->action);
01416    ast_mutex_unlock(&actionlock);
01417    return 0;
01418 }
01419 
01420 int ast_manager_register2(char *action, int auth, int (*func)(struct mansession *s, struct message *m), char *synopsis, char *description)
01421 {
01422    struct manager_action *cur;
01423 
01424    cur = malloc(sizeof(struct manager_action));
01425    if (!cur) {
01426       ast_log(LOG_WARNING, "Manager: out of memory trying to register action\n");
01427       ast_mutex_unlock(&actionlock);
01428       return -1;
01429    }
01430    cur->action = action;
01431    cur->authority = auth;
01432    cur->func = func;
01433    cur->synopsis = synopsis;
01434    cur->description = description;
01435    cur->next = NULL;
01436 
01437    ast_manager_register_struct(cur);
01438 
01439    return 0;
01440 }
01441 
01442 static int registered = 0;
01443 
01444 int init_manager(void)
01445 {
01446    struct ast_config *cfg;
01447    char *val;
01448    int oldportno = portno;
01449    static struct sockaddr_in ba;
01450    int x = 1;
01451    if (!registered) {
01452       /* Register default actions */
01453       ast_manager_register2("Ping", 0, action_ping, "Ping", mandescr_ping);
01454       ast_manager_register2("Events", 0, action_events, "Contol Event Flow", mandescr_events);
01455       ast_manager_register2("Logoff", 0, action_logoff, "Logoff Manager", mandescr_logoff);
01456       ast_manager_register2("Hangup", EVENT_FLAG_CALL, action_hangup, "Hangup Channel", mandescr_hangup);
01457       ast_manager_register( "Status", EVENT_FLAG_CALL, action_status, "Status" );
01458       ast_manager_register2( "Setvar", EVENT_FLAG_CALL, action_setvar, "Set Channel Variable", mandescr_setvar );
01459       ast_manager_register2( "Getvar", EVENT_FLAG_CALL, action_getvar, "Gets a Channel Variable", mandescr_getvar );
01460       ast_manager_register( "Redirect", EVENT_FLAG_CALL, action_redirect, "Redirect" );
01461       ast_manager_register2("Originate", EVENT_FLAG_CALL, action_originate, "Originate Call", mandescr_originate);
01462       ast_manager_register2( "Command", EVENT_FLAG_COMMAND, action_command, "Execute Command", mandescr_command );
01463       ast_manager_register2( "ExtensionState", EVENT_FLAG_CALL, action_extensionstate, "Check Extension Status", mandescr_extensionstate );
01464       ast_manager_register2( "AbsoluteTimeout", EVENT_FLAG_CALL, action_timeout, "Set Absolute Timeout", mandescr_timeout );
01465       ast_manager_register2( "MailboxStatus", EVENT_FLAG_CALL, action_mailboxstatus, "Check Mailbox", mandescr_mailboxstatus );
01466       ast_manager_register2( "MailboxCount", EVENT_FLAG_CALL, action_mailboxcount, "Check Mailbox Message Count", mandescr_mailboxcount );
01467       ast_manager_register2("ListCommands", 0, action_listcommands, "List available manager commands", mandescr_listcommands);
01468 
01469       ast_cli_register(&show_mancmd_cli);
01470       ast_cli_register(&show_mancmds_cli);
01471       ast_cli_register(&show_manconn_cli);
01472       ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
01473       registered = 1;
01474    }
01475    portno = DEFAULT_MANAGER_PORT;
01476    cfg = ast_load("manager.conf");
01477    if (!cfg) {
01478       ast_log(LOG_NOTICE, "Unable to open management configuration manager.conf.  Call management disabled.\n");
01479       return 0;
01480    }
01481    memset(&ba, 0, sizeof(ba));
01482    val = ast_variable_retrieve(cfg, "general", "enabled");
01483    if (val)
01484       enabled = ast_true(val);
01485 
01486    val = ast_variable_retrieve(cfg, "general", "block-sockets");
01487    if(val)
01488       block_sockets = ast_true(val);
01489 
01490    if ((val = ast_variable_retrieve(cfg, "general", "port"))) {
01491       if (sscanf(val, "%d", &portno) != 1) {
01492          ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
01493          portno = DEFAULT_MANAGER_PORT;
01494       }
01495    } else if ((val = ast_variable_retrieve(cfg, "general", "portno"))) {
01496       if (sscanf(val, "%d", &portno) != 1) {
01497          ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
01498          portno = DEFAULT_MANAGER_PORT;
01499       }
01500       ast_log(LOG_NOTICE, "Use of portno in manager.conf deprecated.  Please use 'port=%s' instead.\n", val);
01501    }
01502    
01503    ba.sin_family = AF_INET;
01504    ba.sin_port = htons(portno);
01505    memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
01506    
01507    if ((val = ast_variable_retrieve(cfg, "general", "bindaddr"))) {
01508       if (!inet_aton(val, &ba.sin_addr)) { 
01509          ast_log(LOG_WARNING, "Invalid address '%s' specified, using 0.0.0.0\n", val);
01510          memset(&ba.sin_addr, 0, sizeof(ba.sin_addr));
01511       }
01512    }
01513    
01514    if ((asock > -1) && ((portno != oldportno) || !enabled)) {
01515 #if 0
01516       /* Can't be done yet */
01517       close(asock);
01518       asock = -1;
01519 #else
01520       ast_log(LOG_WARNING, "Unable to change management port / enabled\n");
01521 #endif
01522    }
01523    ast_destroy(cfg);
01524    
01525    /* If not enabled, do nothing */
01526    if (!enabled) {
01527       return 0;
01528    }
01529    if (asock < 0) {
01530       asock = socket(AF_INET, SOCK_STREAM, 0);
01531       if (asock < 0) {
01532          ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
01533          return -1;
01534       }
01535       setsockopt(asock, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(x));
01536       if (bind(asock, (struct sockaddr *)&ba, sizeof(ba))) {
01537          ast_log(LOG_WARNING, "Unable to bind socket: %s\n", strerror(errno));
01538          close(asock);
01539          asock = -1;
01540          return -1;
01541       }
01542       if (listen(asock, 2)) {
01543          ast_log(LOG_WARNING, "Unable to listen on socket: %s\n", strerror(errno));
01544          close(asock);
01545          asock = -1;
01546          return -1;
01547       }
01548       if (option_verbose)
01549          ast_verbose("Asterisk Management interface listening on port %d\n", portno);
01550       ast_pthread_create(&t, NULL, accept_thread, NULL);
01551    }
01552    return 0;
01553 }
01554 
01555 int reload_manager(void)
01556 {
01557    manager_event(EVENT_FLAG_SYSTEM, "Reload", "Message: Reload Requested\r\n");
01558    return init_manager();
01559 }

Generated on Wed Aug 10 11:36:32 2005 for Asterisk by  doxygen 1.4.4