chan_mgcp.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2006, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! \file
00020  *
00021  * \brief Implementation of Media Gateway Control Protocol
00022  *
00023  * \author Mark Spencer <markster@digium.com>
00024  *
00025  * \ingroup channel_drivers
00026  */
00027 
00028 /*! \li \ref chan_mgcp.c uses the configuration file \ref mgcp.conf
00029  * \addtogroup configuration_file
00030  */
00031 
00032 /*! \page mgcp.conf mgcp.conf
00033  * \verbinclude mgcp.conf.sample
00034  */
00035 
00036 /*** MODULEINFO
00037         <use type="module">res_pktccops</use>
00038    <support_level>extended</support_level>
00039  ***/
00040 
00041 #include "asterisk.h"
00042 
00043 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 428688 $")
00044 
00045 #include <sys/socket.h>
00046 #include <sys/ioctl.h>
00047 #include <net/if.h>
00048 #include <fcntl.h>
00049 #include <netdb.h>
00050 #include <sys/signal.h>
00051 #include <signal.h>
00052 #include <netinet/in.h>
00053 #include <netinet/in_systm.h>
00054 #include <netinet/ip.h>
00055 #include <arpa/inet.h>
00056 #include <ctype.h>
00057 
00058 #include "asterisk/lock.h"
00059 #include "asterisk/channel.h"
00060 #include "asterisk/config.h"
00061 #include "asterisk/module.h"
00062 #include "asterisk/pickup.h"
00063 #include "asterisk/pbx.h"
00064 #include "asterisk/sched.h"
00065 #include "asterisk/io.h"
00066 #include "asterisk/rtp_engine.h"
00067 #include "asterisk/acl.h"
00068 #include "asterisk/callerid.h"
00069 #include "asterisk/cli.h"
00070 #include "asterisk/say.h"
00071 #include "asterisk/astdb.h"
00072 #include "asterisk/features.h"
00073 #include "asterisk/app.h"
00074 #include "asterisk/musiconhold.h"
00075 #include "asterisk/utils.h"
00076 #include "asterisk/netsock2.h"
00077 #include "asterisk/causes.h"
00078 #include "asterisk/dsp.h"
00079 #include "asterisk/devicestate.h"
00080 #include "asterisk/stringfields.h"
00081 #include "asterisk/abstract_jb.h"
00082 #include "asterisk/chanvars.h"
00083 #include "asterisk/pktccops.h"
00084 #include "asterisk/stasis.h"
00085 #include "asterisk/bridge.h"
00086 #include "asterisk/features_config.h"
00087 #include "asterisk/parking.h"
00088 #include "asterisk/stasis_channels.h"
00089 #include "asterisk/format_cache.h"
00090 
00091 /*
00092  * Define to work around buggy dlink MGCP phone firmware which
00093  * appears not to know that "rt" is part of the "G" package.
00094  */
00095 /* #define DLINK_BUGGY_FIRMWARE  */
00096 
00097 #define MGCPDUMPER
00098 #define DEFAULT_EXPIRY  120
00099 #define MAX_EXPIRY   3600
00100 #define DIRECTMEDIA  1
00101 
00102 #ifndef INADDR_NONE
00103 #define INADDR_NONE (in_addr_t)(-1)
00104 #endif
00105 
00106 /*! Global jitterbuffer configuration - by default, jb is disabled
00107  *  \note Values shown here match the defaults shown in mgcp.conf.sample */
00108 static struct ast_jb_conf default_jbconf =
00109 {
00110    .flags = 0,
00111    .max_size = 200,
00112    .resync_threshold = 1000,
00113    .impl = "fixed",
00114    .target_extra = 40,
00115 };
00116 static struct ast_jb_conf global_jbconf;
00117 
00118 static const char tdesc[] = "Media Gateway Control Protocol (MGCP)";
00119 static const char config[] = "mgcp.conf";
00120 
00121 #define MGCP_DTMF_RFC2833  (1 << 0)
00122 #define MGCP_DTMF_INBAND   (1 << 1)
00123 #define MGCP_DTMF_HYBRID   (1 << 2)
00124 
00125 #define DEFAULT_MGCP_GW_PORT  2427 /*!< From RFC 2705 */
00126 #define DEFAULT_MGCP_CA_PORT  2727 /*!< From RFC 2705 */
00127 #define MGCP_MAX_PACKET    1500 /*!< Also from RFC 2543, should sub headers tho */
00128 #define DEFAULT_RETRANS    1000 /*!< How frequently to retransmit */
00129 #define MAX_RETRANS     5    /*!< Try only 5 times for retransmissions */
00130 
00131 /*! MGCP rtp stream modes { */
00132 #define MGCP_CX_SENDONLY   0
00133 #define MGCP_CX_RECVONLY   1
00134 #define MGCP_CX_SENDRECV   2
00135 #define MGCP_CX_CONF    3
00136 #define MGCP_CX_CONFERENCE 3
00137 #define MGCP_CX_MUTE    4
00138 #define MGCP_CX_INACTIVE   4
00139 /*! } */
00140 
00141 static const char * const mgcp_cxmodes[] = {
00142    "sendonly",
00143    "recvonly",
00144    "sendrecv",
00145    "confrnce",
00146    "inactive"
00147 };
00148 
00149 enum {
00150    MGCP_CMD_EPCF,
00151    MGCP_CMD_CRCX,
00152    MGCP_CMD_MDCX,
00153    MGCP_CMD_DLCX,
00154    MGCP_CMD_RQNT,
00155    MGCP_CMD_NTFY,
00156    MGCP_CMD_AUEP,
00157    MGCP_CMD_AUCX,
00158    MGCP_CMD_RSIP
00159 };
00160 
00161 static char context[AST_MAX_EXTENSION] = "default";
00162 
00163 static char language[MAX_LANGUAGE] = "";
00164 static char musicclass[MAX_MUSICCLASS] = "";
00165 static char parkinglot[AST_MAX_CONTEXT];
00166 static char cid_num[AST_MAX_EXTENSION] = "";
00167 static char cid_name[AST_MAX_EXTENSION] = "";
00168 
00169 static int dtmfmode = 0;
00170 static int nat = 0;
00171 static int ncs = 0;
00172 static int pktcgatealloc = 0;
00173 static int hangupongateremove = 0;
00174 
00175 static ast_group_t cur_callergroup = 0;
00176 static ast_group_t cur_pickupgroup = 0;
00177 
00178 static struct {
00179    unsigned int tos;
00180    unsigned int tos_audio;
00181    unsigned int cos;
00182    unsigned int cos_audio;
00183 } qos = { 0, 0, 0, 0 };
00184 
00185 static int immediate = 0;
00186 
00187 static int callwaiting = 0;
00188 
00189 static int callreturn = 0;
00190 
00191 static int slowsequence = 0;
00192 
00193 static int threewaycalling = 0;
00194 
00195 /*! This is for flashhook transfers */
00196 static int transfer = 0;
00197 
00198 static int cancallforward = 0;
00199 
00200 static int singlepath = 0;
00201 
00202 static int directmedia = DIRECTMEDIA;
00203 
00204 static char accountcode[AST_MAX_ACCOUNT_CODE] = "";
00205 
00206 static char mailbox[AST_MAX_MAILBOX_UNIQUEID];
00207 
00208 static int amaflags = 0;
00209 
00210 static int adsi = 0;
00211 
00212 static unsigned int oseq_global = 0;
00213 AST_MUTEX_DEFINE_STATIC(oseq_lock);
00214 
00215 /*! Wait up to 16 seconds for first digit (FXO logic) */
00216 static int firstdigittimeout = 16000;
00217 
00218 /*! How long to wait for following digits (FXO logic) */
00219 static int gendigittimeout = 8000;
00220 
00221 /*! How long to wait for an extra digit, if there is an ambiguous match */
00222 static int matchdigittimeout = 3000;
00223 
00224 /*! Protect the monitoring thread, so only one process can kill or start it, and not
00225     when it's doing something critical. */
00226 AST_MUTEX_DEFINE_STATIC(netlock);
00227 
00228 AST_MUTEX_DEFINE_STATIC(monlock);
00229 
00230 /*! This is the thread for the monitor which checks for input on the channels
00231  *  which are not currently in use.
00232  */
00233 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00234 
00235 static int restart_monitor(void);
00236 
00237 static struct ast_format_cap *global_capability;
00238 static int nonCodecCapability = AST_RTP_DTMF;
00239 
00240 static char ourhost[MAXHOSTNAMELEN];
00241 static struct in_addr __ourip;
00242 static int ourport;
00243 
00244 static int mgcpdebug = 0;
00245 
00246 static struct ast_sched_context *sched;
00247 static struct io_context *io;
00248 /*! The private structures of the mgcp channels are linked for
00249  * selecting outgoing channels
00250  */
00251 
00252 #define MGCP_MAX_HEADERS   64
00253 #define MGCP_MAX_LINES     64
00254 
00255 struct mgcp_request {
00256    int len;
00257    char *verb;
00258    char *identifier;
00259    char *endpoint;
00260    char *version;
00261    int headers;         /*!< MGCP Headers */
00262    char *header[MGCP_MAX_HEADERS];
00263    int lines;        /*!< SDP Content */
00264    char *line[MGCP_MAX_LINES];
00265    char data[MGCP_MAX_PACKET];
00266    int cmd;                        /*!< int version of verb = command */
00267    unsigned int trid;              /*!< int version of identifier = transaction id */
00268    struct mgcp_request *next;      /*!< next in the queue */
00269 };
00270 
00271 /*! \brief mgcp_message: MGCP message for queuing up */
00272 struct mgcp_message {
00273    struct mgcp_endpoint *owner_ep;
00274    struct mgcp_subchannel *owner_sub;
00275    int retrans;
00276    unsigned long expire;
00277    unsigned int seqno;
00278    int len;
00279    struct mgcp_message *next;
00280    char buf[0];
00281 };
00282 
00283 #define RESPONSE_TIMEOUT 30   /*!< in seconds */
00284 
00285 struct mgcp_response {
00286    time_t whensent;
00287    int len;
00288    int seqno;
00289    struct mgcp_response *next;
00290    char buf[0];
00291 };
00292 
00293 #define MAX_SUBS 2
00294 
00295 #define SUB_REAL 0
00296 #define SUB_ALT  1
00297 
00298 struct mgcp_subchannel {
00299    /*! subchannel magic string.
00300       Needed to prove that any subchannel pointer passed by asterisk
00301       really points to a valid subchannel memory area.
00302       Ugly.. But serves the purpose for the time being.
00303     */
00304 #define MGCP_SUBCHANNEL_MAGIC "!978!"
00305    char magic[6];
00306    ast_mutex_t lock;
00307    int id;
00308    struct ast_channel *owner;
00309    struct mgcp_endpoint *parent;
00310    struct ast_rtp_instance *rtp;
00311    struct sockaddr_in tmpdest;
00312    char txident[80]; /*! \todo FIXME txident is replaced by rqnt_ident in endpoint.
00313          This should be obsoleted */
00314    char cxident[80];
00315    char callid[80];
00316    int cxmode;
00317    struct mgcp_request *cx_queue; /*!< pending CX commands */
00318    ast_mutex_t cx_queue_lock;     /*!< CX queue lock */
00319    int nat;
00320    int iseq;                      /*!< Not used? RTP? */
00321    int outgoing;
00322    int alreadygone;
00323    int sdpsent;
00324    struct cops_gate *gate;
00325    struct mgcp_subchannel *next;  /*!< for out circular linked list */
00326 };
00327 
00328 #define MGCP_ONHOOK  1
00329 #define MGCP_OFFHOOK 2
00330 
00331 #define TYPE_TRUNK 1
00332 #define TYPE_LINE  2
00333 
00334 struct mgcp_endpoint {
00335    ast_mutex_t lock;
00336    char name[80];
00337    struct mgcp_subchannel *sub;     /*!< Pointer to our current connection, channel and stuff */
00338    char accountcode[AST_MAX_ACCOUNT_CODE];
00339    char exten[AST_MAX_EXTENSION];      /*!< Extention where to start */
00340    char context[AST_MAX_EXTENSION];
00341    char language[MAX_LANGUAGE];
00342    char cid_num[AST_MAX_EXTENSION]; /*!< Caller*ID number */
00343    char cid_name[AST_MAX_EXTENSION];   /*!< Caller*ID name */
00344    char lastcallerid[AST_MAX_EXTENSION];  /*!< Last Caller*ID */
00345    char dtmf_buf[AST_MAX_EXTENSION];   /*!< place to collect digits be */
00346    char call_forward[AST_MAX_EXTENSION];  /*!< Last Caller*ID */
00347    char musicclass[MAX_MUSICCLASS];
00348    char curtone[80];       /*!< Current tone */
00349    char mailbox[AST_MAX_EXTENSION];
00350    char parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
00351    struct stasis_subscription *mwi_event_sub;
00352    ast_group_t callgroup;
00353    ast_group_t pickupgroup;
00354    int callwaiting;
00355    int hascallwaiting;
00356    int transfer;
00357    int threewaycalling;
00358    int singlepath;
00359    int cancallforward;
00360    int directmedia;
00361    int callreturn;
00362    int dnd; /* How does this affect callwait? Do we just deny a mgcp_request if we're dnd? */
00363    int hascallerid;
00364    int hidecallerid;
00365    int dtmfmode;
00366    int amaflags;
00367    int ncs;
00368    int pktcgatealloc;
00369    int hangupongateremove;
00370    int type;
00371    int slowsequence;       /*!< MS: Sequence the endpoint as a whole */
00372    int group;
00373    int iseq; /*!< Not used? */
00374    int lastout; /*!< tracking this on the subchannels.  Is it needed here? */
00375    int needdestroy; /*!< Not used? */
00376    struct ast_format_cap *cap;
00377    int nonCodecCapability;
00378    int onhooktime;
00379    int msgstate; /*!< voicemail message state */
00380    int immediate;
00381    int hookstate;
00382    int adsi;
00383    char rqnt_ident[80];             /*!< request identifier */
00384    struct mgcp_request *rqnt_queue; /*!< pending RQNT commands */
00385    ast_mutex_t rqnt_queue_lock;
00386    struct mgcp_request *cmd_queue;  /*!< pending commands other than RQNT */
00387    ast_mutex_t cmd_queue_lock;
00388    int delme;                       /*!< needed for reload */
00389    int needaudit;                   /*!< needed for reload */
00390    struct ast_dsp *dsp; /*!< XXX Should there be a dsp/subchannel? XXX */
00391    /* owner is tracked on the subchannels, and the *sub indicates whos in charge */
00392    /* struct ast_channel *owner; */
00393    /* struct ast_rtp *rtp; */
00394    /* struct sockaddr_in tmpdest; */
00395    /* message go the the endpoint and not the channel so they stay here */
00396    struct ast_variable *chanvars;      /*!< Variables to set for channel created by user */
00397    struct mgcp_endpoint *next;
00398    struct mgcp_gateway *parent;
00399 };
00400 
00401 static struct mgcp_gateway {
00402    /* A gateway containing one or more endpoints */
00403    char name[80];
00404    int isnamedottedip; /*!< is the name FQDN or dotted ip */
00405    struct sockaddr_in addr;
00406    struct sockaddr_in defaddr;
00407    struct in_addr ourip;
00408    int dynamic;
00409    int expire;    /*!< XXX Should we ever expire dynamic registrations? XXX */
00410    struct mgcp_endpoint *endpoints;
00411    struct ast_ha *ha;
00412 /* obsolete
00413    time_t lastouttime;
00414    int lastout;
00415    int messagepending;
00416 */
00417 /* Wildcard endpoint name */
00418    char wcardep[30];
00419    struct mgcp_message *msgs; /*!< gw msg queue */
00420    ast_mutex_t msgs_lock;     /*!< queue lock */
00421    int retransid;             /*!< retrans timer id */
00422    int delme;                 /*!< needed for reload */
00423    int realtime;
00424    struct mgcp_response *responses;
00425    struct mgcp_gateway *next;
00426 } *gateways = NULL;
00427 
00428 AST_MUTEX_DEFINE_STATIC(mgcp_reload_lock);
00429 static int mgcp_reloading = 0;
00430 
00431 /*! \brief gatelock: mutex for gateway/endpoint lists */
00432 AST_MUTEX_DEFINE_STATIC(gatelock);
00433 
00434 static int mgcpsock  = -1;
00435 
00436 static struct sockaddr_in bindaddr;
00437 
00438 static void mgcp_set_owner(struct mgcp_subchannel *sub, struct ast_channel *chan);
00439 static struct ast_frame  *mgcp_read(struct ast_channel *ast);
00440 static int transmit_response(struct mgcp_subchannel *sub, char *msg, struct mgcp_request *req, char *msgrest);
00441 static int transmit_notify_request(struct mgcp_subchannel *sub, char *tone);
00442 static int transmit_modify_request(struct mgcp_subchannel *sub);
00443 static int transmit_connect(struct mgcp_subchannel *sub);
00444 static int transmit_notify_request_with_callerid(struct mgcp_subchannel *sub, char *tone, char *callernum, char *callername);
00445 static int transmit_modify_with_sdp(struct mgcp_subchannel *sub, struct ast_rtp_instance *rtp, const struct ast_format_cap *codecs);
00446 static int transmit_connection_del(struct mgcp_subchannel *sub);
00447 static int transmit_audit_endpoint(struct mgcp_endpoint *p);
00448 static void start_rtp(struct mgcp_subchannel *sub);
00449 static void handle_response(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,
00450                             int result, unsigned int ident, struct mgcp_request *resp);
00451 static void dump_cmd_queues(struct mgcp_endpoint *p, struct mgcp_subchannel *sub);
00452 static char *mgcp_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
00453 static int reload_config(int reload);
00454 
00455 static struct ast_channel *mgcp_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *dest, int *cause);
00456 static int mgcp_call(struct ast_channel *ast, const char *dest, int timeout);
00457 static int mgcp_hangup(struct ast_channel *ast);
00458 static int mgcp_answer(struct ast_channel *ast);
00459 static struct ast_frame *mgcp_read(struct ast_channel *ast);
00460 static int mgcp_write(struct ast_channel *ast, struct ast_frame *frame);
00461 static int mgcp_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen);
00462 static int mgcp_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
00463 static int mgcp_senddigit_begin(struct ast_channel *ast, char digit);
00464 static int mgcp_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
00465 static int mgcp_devicestate(const char *data);
00466 static void add_header_offhook(struct mgcp_subchannel *sub, struct mgcp_request *resp, char *tone);
00467 static int transmit_connect_with_sdp(struct mgcp_subchannel *sub, struct ast_rtp_instance *rtp);
00468 static struct mgcp_gateway *build_gateway(char *cat, struct ast_variable *v);
00469 static int mgcp_alloc_pktcgate(struct mgcp_subchannel *sub);
00470 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
00471 static struct ast_variable *add_var(const char *buf, struct ast_variable *list);
00472 static struct ast_variable *copy_vars(struct ast_variable *src);
00473 
00474 static struct ast_channel_tech mgcp_tech = {
00475    .type = "MGCP",
00476    .description = tdesc,
00477    .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
00478    .requester = mgcp_request,
00479    .devicestate = mgcp_devicestate,
00480    .call = mgcp_call,
00481    .hangup = mgcp_hangup,
00482    .answer = mgcp_answer,
00483    .read = mgcp_read,
00484    .write = mgcp_write,
00485    .indicate = mgcp_indicate,
00486    .fixup = mgcp_fixup,
00487    .send_digit_begin = mgcp_senddigit_begin,
00488    .send_digit_end = mgcp_senddigit_end,
00489    .func_channel_read = acf_channel_read,
00490 };
00491 
00492 static void mwi_event_cb(void *userdata, struct stasis_subscription *sub, struct stasis_message *msg)
00493 {
00494    /* This module does not handle MWI in an event-based manner.  However, it
00495     * subscribes to MWI for each mailbox that is configured so that the core
00496     * knows that we care about it.  Then, chan_mgcp will get the MWI from the
00497     * event cache instead of checking the mailbox directly. */
00498 }
00499 
00500 static int has_voicemail(struct mgcp_endpoint *p)
00501 {
00502    int new_msgs;
00503    RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
00504 
00505    msg = stasis_cache_get(ast_mwi_state_cache(), ast_mwi_state_type(), p->mailbox);
00506    if (msg) {
00507       struct ast_mwi_state *mwi_state = stasis_message_data(msg);
00508       new_msgs = mwi_state->new_msgs;
00509    } else {
00510       new_msgs = ast_app_has_voicemail(p->mailbox, NULL);
00511    }
00512 
00513    return new_msgs;
00514 }
00515 
00516 static int unalloc_sub(struct mgcp_subchannel *sub)
00517 {
00518    struct mgcp_endpoint *p = sub->parent;
00519    if (p->sub == sub) {
00520       ast_log(LOG_WARNING, "Trying to unalloc the real channel %s@%s?!?\n", p->name, p->parent->name);
00521       return -1;
00522    }
00523    ast_debug(1, "Released sub %d of channel %s@%s\n", sub->id, p->name, p->parent->name);
00524 
00525    mgcp_set_owner(sub, NULL);
00526    if (!ast_strlen_zero(sub->cxident)) {
00527       transmit_connection_del(sub);
00528    }
00529    sub->cxident[0] = '\0';
00530    sub->callid[0] = '\0';
00531    sub->cxmode = MGCP_CX_INACTIVE;
00532    sub->outgoing = 0;
00533    sub->alreadygone = 0;
00534    memset(&sub->tmpdest, 0, sizeof(sub->tmpdest));
00535    if (sub->rtp) {
00536       ast_rtp_instance_destroy(sub->rtp);
00537       sub->rtp = NULL;
00538    }
00539    dump_cmd_queues(NULL, sub);
00540    return 0;
00541 }
00542 
00543 /* modified for new transport mechanism */
00544 static int __mgcp_xmit(struct mgcp_gateway *gw, char *data, int len)
00545 {
00546    int res;
00547    if (gw->addr.sin_addr.s_addr)
00548       res=sendto(mgcpsock, data, len, 0, (struct sockaddr *)&gw->addr, sizeof(struct sockaddr_in));
00549    else
00550       res=sendto(mgcpsock, data, len, 0, (struct sockaddr *)&gw->defaddr, sizeof(struct sockaddr_in));
00551    if (res != len) {
00552       ast_log(LOG_WARNING, "mgcp_xmit returned %d: %s\n", res, strerror(errno));
00553    }
00554    return res;
00555 }
00556 
00557 static int resend_response(struct mgcp_subchannel *sub, struct mgcp_response *resp)
00558 {
00559    struct mgcp_endpoint *p = sub->parent;
00560    int res;
00561    ast_debug(1, "Retransmitting:\n%s\n to %s:%d\n", resp->buf, ast_inet_ntoa(p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
00562    res = __mgcp_xmit(p->parent, resp->buf, resp->len);
00563    if (res > 0)
00564       res = 0;
00565    return res;
00566 }
00567 
00568 static int send_response(struct mgcp_subchannel *sub, struct mgcp_request *req)
00569 {
00570    struct mgcp_endpoint *p = sub->parent;
00571    int res;
00572    ast_debug(1, "Transmitting:\n%s\n to %s:%d\n", req->data, ast_inet_ntoa(p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
00573    res = __mgcp_xmit(p->parent, req->data, req->len);
00574    if (res > 0)
00575       res = 0;
00576    return res;
00577 }
00578 
00579 /* modified for new transport framework */
00580 static void dump_queue(struct mgcp_gateway *gw, struct mgcp_endpoint *p)
00581 {
00582    struct mgcp_message *cur, *q = NULL, *w, *prev;
00583 
00584    ast_mutex_lock(&gw->msgs_lock);
00585    for (prev = NULL, cur = gw->msgs; cur; prev = cur, cur = cur->next) {
00586       if (!p || cur->owner_ep == p) {
00587          if (prev) {
00588             prev->next = cur->next;
00589          } else {
00590             gw->msgs = cur->next;
00591          }
00592 
00593          ast_log(LOG_NOTICE, "Removing message from %s transaction %u\n",
00594             gw->name, cur->seqno);
00595 
00596          w = cur;
00597          if (q) {
00598             w->next = q;
00599          } else {
00600             w->next = NULL;
00601          }
00602          q = w;
00603       }
00604    }
00605    ast_mutex_unlock(&gw->msgs_lock);
00606 
00607    while (q) {
00608       cur = q;
00609       q = q->next;
00610       ast_free(cur);
00611    }
00612 }
00613 
00614 static void mgcp_queue_frame(struct mgcp_subchannel *sub, struct ast_frame *f)
00615 {
00616    for (;;) {
00617       if (sub->owner) {
00618          if (!ast_channel_trylock(sub->owner)) {
00619             ast_queue_frame(sub->owner, f);
00620             ast_channel_unlock(sub->owner);
00621             break;
00622          } else {
00623             DEADLOCK_AVOIDANCE(&sub->lock);
00624          }
00625       } else {
00626          break;
00627       }
00628    }
00629 }
00630 
00631 static void mgcp_queue_hangup(struct mgcp_subchannel *sub)
00632 {
00633    for (;;) {
00634       if (sub->owner) {
00635          if (!ast_channel_trylock(sub->owner)) {
00636             ast_queue_hangup(sub->owner);
00637             ast_channel_unlock(sub->owner);
00638             break;
00639          } else {
00640             DEADLOCK_AVOIDANCE(&sub->lock);
00641          }
00642       } else {
00643          break;
00644       }
00645    }
00646 }
00647 
00648 static void mgcp_queue_control(struct mgcp_subchannel *sub, int control)
00649 {
00650    struct ast_frame f = { AST_FRAME_CONTROL, { control } };
00651    return mgcp_queue_frame(sub, &f);
00652 }
00653 
00654 static int retrans_pkt(const void *data)
00655 {
00656    struct mgcp_gateway *gw = (struct mgcp_gateway *)data;
00657    struct mgcp_message *cur, *exq = NULL, *w, *prev;
00658    int res = 0;
00659 
00660    /* find out expired msgs */
00661    ast_mutex_lock(&gw->msgs_lock);
00662 
00663    for (prev = NULL, cur = gw->msgs; cur; prev = cur, cur = cur->next) {
00664       if (cur->retrans < MAX_RETRANS) {
00665          cur->retrans++;
00666          ast_debug(1, "Retransmitting #%d transaction %u on [%s]\n",
00667             cur->retrans, cur->seqno, gw->name);
00668          __mgcp_xmit(gw, cur->buf, cur->len);
00669       } else {
00670          if (prev)
00671             prev->next = cur->next;
00672          else
00673             gw->msgs = cur->next;
00674 
00675          ast_log(LOG_WARNING, "Maximum retries exceeded for transaction %u on [%s]\n",
00676             cur->seqno, gw->name);
00677 
00678          w = cur;
00679 
00680          if (exq) {
00681             w->next = exq;
00682          } else {
00683             w->next = NULL;
00684          }
00685          exq = w;
00686       }
00687    }
00688 
00689    if (!gw->msgs) {
00690       gw->retransid = -1;
00691       res = 0;
00692    } else {
00693       res = 1;
00694    }
00695    ast_mutex_unlock(&gw->msgs_lock);
00696 
00697    while (exq) {
00698       cur = exq;
00699       /* time-out transaction */
00700       handle_response(cur->owner_ep, cur->owner_sub, 406, cur->seqno, NULL);
00701       exq = exq->next;
00702       ast_free(cur);
00703    }
00704 
00705    return res;
00706 }
00707 
00708 /* modified for the new transaction mechanism */
00709 static int mgcp_postrequest(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,
00710                             char *data, int len, unsigned int seqno)
00711 {
00712    struct mgcp_message *msg;
00713    struct mgcp_message *cur;
00714    struct mgcp_gateway *gw;
00715    struct timeval now;
00716 
00717    if (!(msg = ast_malloc(sizeof(*msg) + len))) {
00718       return -1;
00719    }
00720    if (!(gw = ((p && p->parent) ? p->parent : NULL))) {
00721       ast_free(msg);
00722       return -1;
00723    }
00724 
00725    msg->owner_sub = sub;
00726    msg->owner_ep = p;
00727    msg->seqno = seqno;
00728    msg->next = NULL;
00729    msg->len = len;
00730    msg->retrans = 0;
00731    memcpy(msg->buf, data, msg->len);
00732 
00733    ast_mutex_lock(&gw->msgs_lock);
00734    for (cur = gw->msgs; cur && cur->next; cur = cur->next);
00735    if (cur) {
00736       cur->next = msg;
00737    } else {
00738       gw->msgs = msg;
00739    }
00740 
00741    now = ast_tvnow();
00742    msg->expire = now.tv_sec * 1000 + now.tv_usec / 1000 + DEFAULT_RETRANS;
00743 
00744    if (gw->retransid == -1)
00745       gw->retransid = ast_sched_add(sched, DEFAULT_RETRANS, retrans_pkt, (void *)gw);
00746    ast_mutex_unlock(&gw->msgs_lock);
00747    __mgcp_xmit(gw, msg->buf, msg->len);
00748    /* XXX Should schedule retransmission XXX */
00749    return 0;
00750 }
00751 
00752 /* modified for new transport */
00753 static int send_request(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,
00754                         struct mgcp_request *req, unsigned int seqno)
00755 {
00756    int res = 0;
00757    struct mgcp_request **queue, *q, *r, *t;
00758    ast_mutex_t *l;
00759 
00760    ast_debug(1, "Slow sequence is %d\n", p->slowsequence);
00761    if (p->slowsequence) {
00762       queue = &p->cmd_queue;
00763       l = &p->cmd_queue_lock;
00764       ast_mutex_lock(l);
00765    } else {
00766       switch (req->cmd) {
00767       case MGCP_CMD_DLCX:
00768          queue = &sub->cx_queue;
00769          l = &sub->cx_queue_lock;
00770          ast_mutex_lock(l);
00771          q = sub->cx_queue;
00772          /* delete pending cx cmds */
00773          /* buggy sb5120 */
00774          if (!sub->parent->ncs) {
00775             while (q) {
00776                r = q->next;
00777                ast_free(q);
00778                q = r;
00779             }
00780             *queue = NULL;
00781          }
00782          break;
00783 
00784       case MGCP_CMD_CRCX:
00785       case MGCP_CMD_MDCX:
00786          queue = &sub->cx_queue;
00787          l = &sub->cx_queue_lock;
00788          ast_mutex_lock(l);
00789          break;
00790 
00791       case MGCP_CMD_RQNT:
00792          queue = &p->rqnt_queue;
00793          l = &p->rqnt_queue_lock;
00794          ast_mutex_lock(l);
00795          break;
00796 
00797       default:
00798          queue = &p->cmd_queue;
00799          l = &p->cmd_queue_lock;
00800          ast_mutex_lock(l);
00801          break;
00802       }
00803    }
00804 
00805    if (!(r = ast_malloc(sizeof(*r)))) {
00806       ast_log(LOG_WARNING, "Cannot post MGCP request: insufficient memory\n");
00807       ast_mutex_unlock(l);
00808       return -1;
00809    }
00810    memcpy(r, req, sizeof(*r));
00811 
00812    if (!(*queue)) {
00813       ast_debug(1, "Posting Request:\n%s to %s:%d\n", req->data,
00814          ast_inet_ntoa(p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
00815 
00816       res = mgcp_postrequest(p, sub, req->data, req->len, seqno);
00817    } else {
00818       ast_debug(1, "Queueing Request:\n%s to %s:%d\n", req->data,
00819          ast_inet_ntoa(p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
00820    }
00821 
00822    /* XXX find tail. We could also keep tail in the data struct for faster access */
00823    for (t = *queue; t && t->next; t = t->next);
00824 
00825    r->next = NULL;
00826    if (t)
00827       t->next = r;
00828    else
00829       *queue = r;
00830 
00831    ast_mutex_unlock(l);
00832 
00833    return res;
00834 }
00835 
00836 static int mgcp_call(struct ast_channel *ast, const char *dest, int timeout)
00837 {
00838    int res;
00839    struct mgcp_endpoint *p;
00840    struct mgcp_subchannel *sub;
00841    char tone[50] = "";
00842    const char *distinctive_ring = pbx_builtin_getvar_helper(ast, "ALERT_INFO");
00843 
00844    ast_debug(3, "MGCP mgcp_call(%s)\n", ast_channel_name(ast));
00845    sub = ast_channel_tech_pvt(ast);
00846    p = sub->parent;
00847 
00848    ast_mutex_lock(&sub->lock);
00849    switch (p->hookstate) {
00850    case MGCP_OFFHOOK:
00851       if (!ast_strlen_zero(distinctive_ring)) {
00852          snprintf(tone, sizeof(tone), "L/wt%s", distinctive_ring);
00853          ast_debug(3, "MGCP distinctive callwait %s\n", tone);
00854       } else {
00855          ast_copy_string(tone, (p->ncs ? "L/wt1" : "L/wt"), sizeof(tone));
00856          ast_debug(3, "MGCP normal callwait %s\n", tone);
00857       }
00858       break;
00859    case MGCP_ONHOOK:
00860    default:
00861       if (!ast_strlen_zero(distinctive_ring)) {
00862          snprintf(tone, sizeof(tone), "L/r%s", distinctive_ring);
00863          ast_debug(3, "MGCP distinctive ring %s\n", tone);
00864       } else {
00865          ast_copy_string(tone, "L/rg", sizeof(tone));
00866          ast_debug(3, "MGCP default ring\n");
00867       }
00868       break;
00869    }
00870 
00871    if ((ast_channel_state(ast) != AST_STATE_DOWN) && (ast_channel_state(ast) != AST_STATE_RESERVED)) {
00872       ast_log(LOG_WARNING, "mgcp_call called on %s, neither down nor reserved\n", ast_channel_name(ast));
00873       ast_mutex_unlock(&sub->lock);
00874       return -1;
00875    }
00876 
00877    res = 0;
00878    sub->outgoing = 1;
00879    sub->cxmode = MGCP_CX_RECVONLY;
00880    ast_setstate(ast, AST_STATE_RINGING);
00881    if (p->type == TYPE_LINE) {
00882       if (!sub->rtp) {
00883          start_rtp(sub);
00884       } else {
00885          transmit_modify_request(sub);
00886       }
00887 
00888       if (sub->next->owner && !ast_strlen_zero(sub->next->cxident) && !ast_strlen_zero(sub->next->callid)) {
00889          /* try to prevent a callwait from disturbing the other connection */
00890          sub->next->cxmode = MGCP_CX_RECVONLY;
00891          transmit_modify_request(sub->next);
00892       }
00893 
00894       transmit_notify_request_with_callerid(sub, tone,
00895          S_COR(ast_channel_connected(ast)->id.number.valid, ast_channel_connected(ast)->id.number.str, ""),
00896          S_COR(ast_channel_connected(ast)->id.name.valid, ast_channel_connected(ast)->id.name.str, ""));
00897       ast_setstate(ast, AST_STATE_RINGING);
00898 
00899       if (sub->next->owner && !ast_strlen_zero(sub->next->cxident) && !ast_strlen_zero(sub->next->callid)) {
00900          /* Put the connection back in sendrecv */
00901          sub->next->cxmode = MGCP_CX_SENDRECV;
00902          transmit_modify_request(sub->next);
00903       }
00904    } else {
00905       ast_log(LOG_NOTICE, "Don't know how to dial on trunks yet\n");
00906       res = -1;
00907    }
00908    ast_mutex_unlock(&sub->lock);
00909    return res;
00910 }
00911 
00912 static int mgcp_hangup(struct ast_channel *ast)
00913 {
00914    struct mgcp_subchannel *sub = ast_channel_tech_pvt(ast);
00915    struct mgcp_endpoint *p = sub->parent;
00916 
00917    ast_debug(1, "mgcp_hangup(%s)\n", ast_channel_name(ast));
00918    if (!ast_channel_tech_pvt(ast)) {
00919       ast_debug(1, "Asked to hangup channel not connected\n");
00920       return 0;
00921    }
00922    if (strcmp(sub->magic, MGCP_SUBCHANNEL_MAGIC)) {
00923       ast_debug(1, "Invalid magic. MGCP subchannel freed up already.\n");
00924       return 0;
00925    }
00926    ast_mutex_lock(&sub->lock);
00927    ast_debug(3, "MGCP mgcp_hangup(%s) on %s@%s\n", ast_channel_name(ast), p->name, p->parent->name);
00928 
00929    if ((p->dtmfmode & MGCP_DTMF_INBAND) && p->dsp) {
00930       /* check whether other channel is active. */
00931       if (!sub->next->owner) {
00932          if (p->dtmfmode & MGCP_DTMF_HYBRID) {
00933             p->dtmfmode &= ~MGCP_DTMF_INBAND;
00934          }
00935          ast_debug(2, "MGCP free dsp on %s@%s\n", p->name, p->parent->name);
00936          ast_dsp_free(p->dsp);
00937          p->dsp = NULL;
00938       }
00939    }
00940 
00941    mgcp_set_owner(sub, NULL);
00942 
00943    /* for deleting gate */
00944    if (p->pktcgatealloc && sub->gate) {
00945       sub->gate->gate_open = NULL;
00946       sub->gate->gate_remove = NULL;
00947       sub->gate->got_dq_gi = NULL;
00948       sub->gate->tech_pvt = NULL;
00949       if (sub->gate->state == GATE_ALLOC_PROGRESS || sub->gate->state == GATE_ALLOCATED) {
00950          ast_pktccops_gate_alloc(GATE_DEL, sub->gate, 0, 0, 0, 0, 0, 0, NULL, NULL);
00951       } else {
00952          sub->gate->deltimer = time(NULL) + 5;
00953       }
00954       sub->gate = NULL;
00955    }
00956 
00957    if (!ast_strlen_zero(sub->cxident)) {
00958       transmit_connection_del(sub);
00959    }
00960    sub->cxident[0] = '\0';
00961    if ((sub == p->sub) && sub->next->owner) {
00962       RAII_VAR(struct ast_channel *, bridged, ast_channel_bridge_peer(sub->next->owner), ast_channel_cleanup);
00963 
00964       if (p->hookstate == MGCP_OFFHOOK) {
00965          if (sub->next->owner && bridged) {
00966             /* ncs fix! */
00967             transmit_notify_request_with_callerid(p->sub, (p->ncs ? "L/wt1" : "L/wt"),
00968                S_COR(ast_channel_caller(bridged)->id.number.valid, ast_channel_caller(bridged)->id.number.str, ""),
00969                S_COR(ast_channel_caller(bridged)->id.name.valid, ast_channel_caller(bridged)->id.name.str, ""));
00970          }
00971       } else {
00972          /* set our other connection as the primary and swith over to it */
00973          p->sub = sub->next;
00974          p->sub->cxmode = MGCP_CX_RECVONLY;
00975          transmit_modify_request(p->sub);
00976          if (sub->next->owner && bridged) {
00977             transmit_notify_request_with_callerid(p->sub, "L/rg",
00978                S_COR(ast_channel_caller(bridged)->id.number.valid, ast_channel_caller(bridged)->id.number.str, ""),
00979                S_COR(ast_channel_caller(bridged)->id.name.valid, ast_channel_caller(bridged)->id.name.str, ""));
00980          }
00981       }
00982 
00983    } else if ((sub == p->sub->next) && p->hookstate == MGCP_OFFHOOK) {
00984       transmit_notify_request(sub, p->ncs ? "" : "L/v");
00985    } else if (p->hookstate == MGCP_OFFHOOK) {
00986       transmit_notify_request(sub, "L/ro");
00987    } else {
00988       transmit_notify_request(sub, "");
00989    }
00990 
00991    ast_channel_tech_pvt_set(ast, NULL);
00992    sub->alreadygone = 0;
00993    sub->outgoing = 0;
00994    sub->cxmode = MGCP_CX_INACTIVE;
00995    sub->callid[0] = '\0';
00996    if (p) {
00997       memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
00998    }
00999    /* Reset temporary destination */
01000    memset(&sub->tmpdest, 0, sizeof(sub->tmpdest));
01001    if (sub->rtp) {
01002       ast_rtp_instance_destroy(sub->rtp);
01003       sub->rtp = NULL;
01004    }
01005 
01006    ast_module_unref(ast_module_info->self);
01007 
01008    if ((p->hookstate == MGCP_ONHOOK) && (!sub->next->rtp)) {
01009       p->hidecallerid = 0;
01010       if (p->hascallwaiting && !p->callwaiting) {
01011          ast_verb(3, "Enabling call waiting on %s\n", ast_channel_name(ast));
01012          p->callwaiting = -1;
01013       }
01014       if (has_voicemail(p)) {
01015          ast_debug(3, "MGCP mgcp_hangup(%s) on %s@%s set vmwi(+)\n",
01016             ast_channel_name(ast), p->name, p->parent->name);
01017          transmit_notify_request(sub, "L/vmwi(+)");
01018       } else {
01019          ast_debug(3, "MGCP mgcp_hangup(%s) on %s@%s set vmwi(-)\n",
01020             ast_channel_name(ast), p->name, p->parent->name);
01021          transmit_notify_request(sub, "L/vmwi(-)");
01022       }
01023    }
01024    ast_mutex_unlock(&sub->lock);
01025    return 0;
01026 }
01027 
01028 static char *handle_mgcp_show_endpoints(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01029 {
01030    struct mgcp_gateway  *mg;
01031    struct mgcp_endpoint *me;
01032    int hasendpoints = 0;
01033    struct ast_variable * v = NULL;
01034 
01035    switch (cmd) {
01036    case CLI_INIT:
01037       e->command = "mgcp show endpoints";
01038       e->usage =
01039          "Usage: mgcp show endpoints\n"
01040          "       Lists all endpoints known to the MGCP (Media Gateway Control Protocol) subsystem.\n";
01041       return NULL;
01042    case CLI_GENERATE:
01043       return NULL;
01044    }
01045 
01046    if (a->argc != 3) {
01047       return CLI_SHOWUSAGE;
01048    }
01049    ast_mutex_lock(&gatelock);
01050    for (mg = gateways; mg; mg = mg->next) {
01051       ast_cli(a->fd, "Gateway '%s' at %s (%s%s)\n", mg->name, mg->addr.sin_addr.s_addr ? ast_inet_ntoa(mg->addr.sin_addr) : ast_inet_ntoa(mg->defaddr.sin_addr), mg->realtime ? "Realtime, " : "", mg->dynamic ? "Dynamic" : "Static");
01052       for (me = mg->endpoints; me; me = me->next) {
01053          ast_cli(a->fd, "   -- '%s@%s in '%s' is %s\n", me->name, mg->name, me->context, me->sub->owner ? "active" : "idle");
01054          if (me->chanvars) {
01055             ast_cli(a->fd, "  Variables:\n");
01056             for (v = me->chanvars ; v ; v = v->next) {
01057                ast_cli(a->fd, "    %s = '%s'\n", v->name, v->value);
01058             }
01059          }
01060          hasendpoints = 1;
01061       }
01062       if (!hasendpoints) {
01063          ast_cli(a->fd, "   << No Endpoints Defined >>     ");
01064       }
01065    }
01066    ast_mutex_unlock(&gatelock);
01067    return CLI_SUCCESS;
01068 }
01069 
01070 static char *handle_mgcp_audit_endpoint(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01071 {
01072    struct mgcp_gateway  *mg;
01073    struct mgcp_endpoint *me;
01074    int found = 0;
01075    char *ename,*gname, *c;
01076 
01077    switch (cmd) {
01078    case CLI_INIT:
01079       e->command = "mgcp audit endpoint";
01080       e->usage =
01081          "Usage: mgcp audit endpoint <endpointid>\n"
01082          "       Lists the capabilities of an endpoint in the MGCP (Media Gateway Control Protocol) subsystem.\n"
01083          "       mgcp debug MUST be on to see the results of this command.\n";
01084       return NULL;
01085    case CLI_GENERATE:
01086       return NULL;
01087    }
01088 
01089    if (!mgcpdebug) {
01090       return CLI_SHOWUSAGE;
01091    }
01092    if (a->argc != 4)
01093       return CLI_SHOWUSAGE;
01094    /* split the name into parts by null */
01095    ename = ast_strdupa(a->argv[3]);
01096    for (gname = ename; *gname; gname++) {
01097       if (*gname == '@') {
01098          *gname = 0;
01099          gname++;
01100          break;
01101       }
01102    }
01103    if (gname[0] == '[') {
01104       gname++;
01105    }
01106    if ((c = strrchr(gname, ']'))) {
01107       *c = '\0';
01108    }
01109    ast_mutex_lock(&gatelock);
01110    for (mg = gateways; mg; mg = mg->next) {
01111       if (!strcasecmp(mg->name, gname)) {
01112          for (me = mg->endpoints; me; me = me->next) {
01113             if (!strcasecmp(me->name, ename)) {
01114                found = 1;
01115                transmit_audit_endpoint(me);
01116                break;
01117             }
01118          }
01119          if (found) {
01120             break;
01121          }
01122       }
01123    }
01124    if (!found) {
01125       ast_cli(a->fd, "   << Could not find endpoint >>     ");
01126    }
01127    ast_mutex_unlock(&gatelock);
01128    return CLI_SUCCESS;
01129 }
01130 
01131 static char *handle_mgcp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01132 {
01133    switch (cmd) {
01134    case CLI_INIT:
01135       e->command = "mgcp set debug {on|off}";
01136       e->usage =
01137          "Usage: mgcp set debug {on|off}\n"
01138          "       Enables/Disables dumping of MGCP packets for debugging purposes\n";
01139       return NULL;
01140    case CLI_GENERATE:
01141       return NULL;
01142    }
01143 
01144    if (a->argc != e->args)
01145       return CLI_SHOWUSAGE;
01146 
01147    if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
01148       mgcpdebug = 1;
01149       ast_cli(a->fd, "MGCP Debugging Enabled\n");
01150    } else if (!strncasecmp(a->argv[3], "off", 3)) {
01151       mgcpdebug = 0;
01152       ast_cli(a->fd, "MGCP Debugging Disabled\n");
01153    } else {
01154       return CLI_SHOWUSAGE;
01155    }
01156    return CLI_SUCCESS;
01157 }
01158 
01159 static struct ast_cli_entry cli_mgcp[] = {
01160    AST_CLI_DEFINE(handle_mgcp_audit_endpoint, "Audit specified MGCP endpoint"),
01161    AST_CLI_DEFINE(handle_mgcp_show_endpoints, "List defined MGCP endpoints"),
01162    AST_CLI_DEFINE(handle_mgcp_set_debug, "Enable/Disable MGCP debugging"),
01163    AST_CLI_DEFINE(mgcp_reload, "Reload MGCP configuration"),
01164 };
01165 
01166 static int mgcp_answer(struct ast_channel *ast)
01167 {
01168    int res = 0;
01169    struct mgcp_subchannel *sub = ast_channel_tech_pvt(ast);
01170    struct mgcp_endpoint *p = sub->parent;
01171 
01172    ast_mutex_lock(&sub->lock);
01173    sub->cxmode = MGCP_CX_SENDRECV;
01174    if (!sub->rtp) {
01175       start_rtp(sub);
01176    } else {
01177       transmit_modify_request(sub);
01178    }
01179    ast_verb(3, "MGCP mgcp_answer(%s) on %s@%s-%d\n",
01180          ast_channel_name(ast), p->name, p->parent->name, sub->id);
01181    if (ast_channel_state(ast) != AST_STATE_UP) {
01182       ast_setstate(ast, AST_STATE_UP);
01183       ast_debug(1, "mgcp_answer(%s)\n", ast_channel_name(ast));
01184       transmit_notify_request(sub, "");
01185       transmit_modify_request(sub);
01186    }
01187    ast_mutex_unlock(&sub->lock);
01188    return res;
01189 }
01190 
01191 static struct ast_frame *mgcp_rtp_read(struct mgcp_subchannel *sub)
01192 {
01193    /* Retrieve audio/etc from channel.  Assumes sub->lock is already held. */
01194    struct ast_frame *f;
01195 
01196    f = ast_rtp_instance_read(sub->rtp, 0);
01197    /* Don't send RFC2833 if we're not supposed to */
01198    if (f && (f->frametype == AST_FRAME_DTMF) && !(sub->parent->dtmfmode & MGCP_DTMF_RFC2833))
01199       return &ast_null_frame;
01200    if (sub->owner) {
01201       /* We already hold the channel lock */
01202       if (f->frametype == AST_FRAME_VOICE) {
01203          if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(sub->owner), f->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
01204             struct ast_format_cap *caps;
01205 
01206             ast_debug(1, "Oooh, format changed to %s\n", ast_format_get_name(f->subclass.format));
01207 
01208             caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
01209             if (caps) {
01210                ast_format_cap_append(caps, f->subclass.format, 0);
01211                ast_channel_nativeformats_set(sub->owner, caps);
01212                ao2_ref(caps, -1);
01213             } else {
01214                return &ast_null_frame;
01215             }
01216 
01217             ast_set_read_format(sub->owner, ast_channel_readformat(sub->owner));
01218             ast_set_write_format(sub->owner, ast_channel_writeformat(sub->owner));
01219          }
01220          /* Courtesy fearnor aka alex@pilosoft.com */
01221          if ((sub->parent->dtmfmode & MGCP_DTMF_INBAND) && (sub->parent->dsp)) {
01222 #if 0
01223             ast_log(LOG_NOTICE, "MGCP ast_dsp_process\n");
01224 #endif
01225             f = ast_dsp_process(sub->owner, sub->parent->dsp, f);
01226          }
01227       }
01228    }
01229    return f;
01230 }
01231 
01232 static void mgcp_set_owner(struct mgcp_subchannel *sub, struct ast_channel *chan)
01233 {
01234    sub->owner = chan;
01235    if (sub->rtp) {
01236       ast_rtp_instance_set_channel_id(sub->rtp, sub->owner ? ast_channel_uniqueid(chan) : "");
01237    }
01238 }
01239 
01240 static struct ast_frame *mgcp_read(struct ast_channel *ast)
01241 {
01242    struct ast_frame *f;
01243    struct mgcp_subchannel *sub = ast_channel_tech_pvt(ast);
01244    ast_mutex_lock(&sub->lock);
01245    f = mgcp_rtp_read(sub);
01246    ast_mutex_unlock(&sub->lock);
01247    return f;
01248 }
01249 
01250 static int mgcp_write(struct ast_channel *ast, struct ast_frame *frame)
01251 {
01252    struct mgcp_subchannel *sub = ast_channel_tech_pvt(ast);
01253    int res = 0;
01254 
01255    if (frame->frametype != AST_FRAME_VOICE) {
01256       if (frame->frametype == AST_FRAME_IMAGE)
01257          return 0;
01258       else {
01259          ast_log(LOG_WARNING, "Can't send %u type frames with MGCP write\n", frame->frametype);
01260          return 0;
01261       }
01262    } else {
01263       if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), frame->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
01264          struct ast_str *cap_buf = ast_str_alloca(64);
01265 
01266          ast_log(LOG_WARNING, "Asked to transmit frame type %s, while native formats is %s (read/write = %s/%s)\n",
01267             ast_format_get_name(frame->subclass.format),
01268             ast_format_cap_get_names(ast_channel_nativeformats(ast), &cap_buf),
01269             ast_format_get_name(ast_channel_readformat(ast)),
01270             ast_format_get_name(ast_channel_writeformat(ast)));
01271          /* return -1; */
01272       }
01273    }
01274    if (sub) {
01275       ast_mutex_lock(&sub->lock);
01276       if (!sub->sdpsent && sub->gate) {
01277          if (sub->gate->state == GATE_ALLOCATED) {
01278             ast_debug(1, "GATE ALLOCATED, sending sdp\n");
01279             transmit_modify_with_sdp(sub, NULL, 0);
01280          }
01281       }
01282       if ((sub->parent->sub == sub) || !sub->parent->singlepath) {
01283          if (sub->rtp) {
01284             res =  ast_rtp_instance_write(sub->rtp, frame);
01285          }
01286       }
01287       ast_mutex_unlock(&sub->lock);
01288    }
01289    return res;
01290 }
01291 
01292 static int mgcp_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
01293 {
01294    struct mgcp_subchannel *sub = ast_channel_tech_pvt(newchan);
01295 
01296    ast_mutex_lock(&sub->lock);
01297    ast_log(LOG_NOTICE, "mgcp_fixup(%s, %s)\n", ast_channel_name(oldchan), ast_channel_name(newchan));
01298    if (sub->owner != oldchan) {
01299       ast_mutex_unlock(&sub->lock);
01300       ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, sub->owner);
01301       return -1;
01302    }
01303    mgcp_set_owner(sub, newchan);
01304    ast_mutex_unlock(&sub->lock);
01305    return 0;
01306 }
01307 
01308 static int mgcp_senddigit_begin(struct ast_channel *ast, char digit)
01309 {
01310    struct mgcp_subchannel *sub = ast_channel_tech_pvt(ast);
01311    struct mgcp_endpoint *p = sub->parent;
01312    int res = 0;
01313 
01314    ast_mutex_lock(&sub->lock);
01315    if (p->dtmfmode & MGCP_DTMF_INBAND || p->dtmfmode & MGCP_DTMF_HYBRID) {
01316       ast_debug(1, "Sending DTMF using inband/hybrid\n");
01317       res = -1; /* Let asterisk play inband indications */
01318    } else if (p->dtmfmode & MGCP_DTMF_RFC2833) {
01319       ast_debug(1, "Sending DTMF using RFC2833\n");
01320       ast_rtp_instance_dtmf_begin(sub->rtp, digit);
01321    } else {
01322       ast_log(LOG_ERROR, "Don't know about DTMF_MODE %d\n", p->dtmfmode);
01323    }
01324    ast_mutex_unlock(&sub->lock);
01325 
01326    return res;
01327 }
01328 
01329 static int mgcp_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
01330 {
01331    struct mgcp_subchannel *sub = ast_channel_tech_pvt(ast);
01332    struct mgcp_endpoint *p = sub->parent;
01333    int res = 0;
01334    char tmp[4];
01335 
01336    ast_mutex_lock(&sub->lock);
01337    if (p->dtmfmode & MGCP_DTMF_INBAND || p->dtmfmode & MGCP_DTMF_HYBRID) {
01338       ast_debug(1, "Stopping DTMF using inband/hybrid\n");
01339       res = -1; /* Tell Asterisk to stop inband indications */
01340    } else if (p->dtmfmode & MGCP_DTMF_RFC2833) {
01341       ast_debug(1, "Stopping DTMF using RFC2833\n");
01342       if (sub->parent->ncs) {
01343          tmp[0] = digit;
01344          tmp[1] = '\0';
01345       } else {
01346          tmp[0] = 'D';
01347          tmp[1] = '/';
01348          tmp[2] = digit;
01349          tmp[3] = '\0';
01350       }
01351       transmit_notify_request(sub, tmp);
01352       ast_rtp_instance_dtmf_end(sub->rtp, digit);
01353    } else {
01354       ast_log(LOG_ERROR, "Don't know about DTMF_MODE %d\n", p->dtmfmode);
01355    }
01356    ast_mutex_unlock(&sub->lock);
01357 
01358    return res;
01359 }
01360 
01361 /*!
01362  *  \brief  mgcp_devicestate: channel callback for device status monitoring
01363  *  \param  data tech/resource name of MGCP device to query
01364  *
01365  * Callback for device state management in channel subsystem
01366  * to obtain device status (up/down) of a specific MGCP endpoint
01367  *
01368  *  \return device status result (from devicestate.h) AST_DEVICE_INVALID (not available) or AST_DEVICE_UNKNOWN (available but unknown state)
01369  */
01370 static int mgcp_devicestate(const char *data)
01371 {
01372    struct mgcp_gateway  *g;
01373    struct mgcp_endpoint *e = NULL;
01374    char *tmp, *endpt, *gw;
01375    int ret = AST_DEVICE_INVALID;
01376 
01377    endpt = ast_strdupa(data);
01378    if ((tmp = strchr(endpt, '@'))) {
01379       *tmp++ = '\0';
01380       gw = tmp;
01381    } else
01382       goto error;
01383 
01384    ast_mutex_lock(&gatelock);
01385    for (g = gateways; g; g = g->next) {
01386       if (strcasecmp(g->name, gw) == 0) {
01387          e = g->endpoints;
01388          break;
01389       }
01390    }
01391 
01392    if (!e)
01393       goto error;
01394 
01395    for (; e; e = e->next) {
01396       if (strcasecmp(e->name, endpt) == 0) {
01397          break;
01398       }
01399    }
01400 
01401    if (!e)
01402       goto error;
01403 
01404    /*
01405     * As long as the gateway/endpoint is valid, we'll
01406     * assume that the device is available and its state
01407     * can be tracked.
01408     */
01409    ret = AST_DEVICE_UNKNOWN;
01410 
01411 error:
01412    ast_mutex_unlock(&gatelock);
01413    return ret;
01414 }
01415 
01416 static char *control2str(int ind) {
01417    switch (ind) {
01418    case AST_CONTROL_HANGUP:
01419       return "Other end has hungup";
01420    case AST_CONTROL_RING:
01421       return "Local ring";
01422    case AST_CONTROL_RINGING:
01423       return "Remote end is ringing";
01424    case AST_CONTROL_ANSWER:
01425       return "Remote end has answered";
01426    case AST_CONTROL_BUSY:
01427       return "Remote end is busy";
01428    case AST_CONTROL_TAKEOFFHOOK:
01429       return "Make it go off hook";
01430    case AST_CONTROL_OFFHOOK:
01431       return "Line is off hook";
01432    case AST_CONTROL_CONGESTION:
01433       return "Congestion (circuits busy)";
01434    case AST_CONTROL_FLASH:
01435       return "Flash hook";
01436    case AST_CONTROL_WINK:
01437       return "Wink";
01438    case AST_CONTROL_OPTION:
01439       return "Set a low-level option";
01440    case AST_CONTROL_RADIO_KEY:
01441       return "Key Radio";
01442    case AST_CONTROL_RADIO_UNKEY:
01443       return "Un-Key Radio";
01444    }
01445    return "UNKNOWN";
01446 }
01447 
01448 static int mgcp_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen)
01449 {
01450    struct mgcp_subchannel *sub = ast_channel_tech_pvt(ast);
01451    int res = 0;
01452 
01453    ast_debug(3, "MGCP asked to indicate %d '%s' condition on channel %s\n",
01454       ind, control2str(ind), ast_channel_name(ast));
01455    ast_mutex_lock(&sub->lock);
01456    switch(ind) {
01457    case AST_CONTROL_RINGING:
01458 #ifdef DLINK_BUGGY_FIRMWARE
01459       transmit_notify_request(sub, "rt");
01460 #else
01461       if (!sub->sdpsent) { /* will hide the inband progress!!! */
01462          transmit_notify_request(sub, sub->parent->ncs ? "L/rt" : "G/rt");
01463       }
01464 #endif
01465       break;
01466    case AST_CONTROL_BUSY:
01467       transmit_notify_request(sub, "L/bz");
01468       break;
01469    case AST_CONTROL_INCOMPLETE:
01470       /* We do not currently support resetting of the Interdigit Timer, so treat
01471        * Incomplete control frames as a congestion response
01472        */
01473    case AST_CONTROL_CONGESTION:
01474       transmit_notify_request(sub, sub->parent->ncs ? "L/cg" : "G/cg");
01475       break;
01476    case AST_CONTROL_HOLD:
01477       ast_moh_start(ast, data, NULL);
01478       break;
01479    case AST_CONTROL_UNHOLD:
01480       ast_moh_stop(ast);
01481       break;
01482    case AST_CONTROL_SRCUPDATE:
01483       ast_rtp_instance_update_source(sub->rtp);
01484       break;
01485    case AST_CONTROL_SRCCHANGE:
01486       ast_rtp_instance_change_source(sub->rtp);
01487       break;
01488    case AST_CONTROL_PROGRESS:
01489    case AST_CONTROL_PROCEEDING:
01490       transmit_modify_request(sub);
01491    case -1:
01492       transmit_notify_request(sub, "");
01493       break;
01494    default:
01495       ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", ind);
01496       /* fallthrough */
01497    case AST_CONTROL_PVT_CAUSE_CODE:
01498       res = -1;
01499    }
01500    ast_mutex_unlock(&sub->lock);
01501    return res;
01502 }
01503 
01504 static struct ast_channel *mgcp_new(struct mgcp_subchannel *sub, int state, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor)
01505 {
01506    struct ast_format_cap *caps = NULL;
01507    struct ast_channel *tmp;
01508    struct ast_variable *v = NULL;
01509    struct mgcp_endpoint *i = sub->parent;
01510    struct ast_format *tmpfmt;
01511 
01512    caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
01513    if (!caps) {
01514       ast_log(LOG_ERROR, "Format capabilities could not be created\n");
01515       return NULL;
01516    }
01517    tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, assignedids, requestor, i->amaflags, "MGCP/%s@%s-%d", i->name, i->parent->name, sub->id);
01518    if (!tmp) {
01519       ast_log(LOG_WARNING, "Channel could not be created\n");
01520       ao2_ref(caps, -1);
01521       return NULL;
01522    }
01523 
01524    ast_channel_stage_snapshot(tmp);
01525    ast_channel_tech_set(tmp, &mgcp_tech);
01526    if (ast_format_cap_count(i->cap)) {
01527       ast_format_cap_append_from_cap(caps, i->cap, AST_MEDIA_TYPE_UNKNOWN);
01528    } else {
01529       ast_format_cap_append_from_cap(caps, global_capability, AST_MEDIA_TYPE_UNKNOWN);
01530    }
01531    ast_channel_nativeformats_set(tmp, caps);
01532    ao2_ref(caps, -1);
01533    if (sub->rtp) {
01534       ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(sub->rtp, 0));
01535    }
01536    if (i->dtmfmode & (MGCP_DTMF_INBAND | MGCP_DTMF_HYBRID)) {
01537       i->dsp = ast_dsp_new();
01538       ast_dsp_set_features(i->dsp, DSP_FEATURE_DIGIT_DETECT);
01539       /* this is to prevent clipping of dtmf tones during dsp processing */
01540       ast_dsp_set_digitmode(i->dsp, DSP_DIGITMODE_NOQUELCH);
01541    } else {
01542       i->dsp = NULL;
01543    }
01544    if (state == AST_STATE_RING) {
01545       ast_channel_rings_set(tmp, 1);
01546    }
01547 
01548    tmpfmt = ast_format_cap_get_format(ast_channel_nativeformats(tmp), 0);
01549    ast_channel_set_writeformat(tmp, tmpfmt);
01550    ast_channel_set_rawwriteformat(tmp, tmpfmt);
01551    ast_channel_set_readformat(tmp, tmpfmt);
01552    ast_channel_set_rawreadformat(tmp, tmpfmt);
01553    ao2_ref(tmpfmt, -1);
01554    ast_channel_tech_pvt_set(tmp, sub);
01555    if (!ast_strlen_zero(i->language))
01556       ast_channel_language_set(tmp, i->language);
01557    if (!ast_strlen_zero(i->accountcode))
01558       ast_channel_accountcode_set(tmp, i->accountcode);
01559    if (i->amaflags)
01560       ast_channel_amaflags_set(tmp, i->amaflags);
01561    mgcp_set_owner(sub, tmp);
01562    ast_module_ref(ast_module_info->self);
01563    ast_channel_callgroup_set(tmp, i->callgroup);
01564    ast_channel_pickupgroup_set(tmp, i->pickupgroup);
01565    ast_channel_call_forward_set(tmp, i->call_forward);
01566    ast_channel_context_set(tmp, i->context);
01567    ast_channel_exten_set(tmp, i->exten);
01568    /* Don't use ast_set_callerid() here because it will
01569     * generate a needless NewCallerID event */
01570    if (!ast_strlen_zero(i->cid_num)) {
01571       ast_channel_caller(tmp)->ani.number.valid = 1;
01572       ast_channel_caller(tmp)->ani.number.str = ast_strdup(i->cid_num);
01573    }
01574 
01575    if (!i->adsi) {
01576       ast_channel_adsicpe_set(tmp, AST_ADSI_UNAVAILABLE);
01577    }
01578    ast_channel_priority_set(tmp, 1);
01579 
01580    /* Set channel variables for this call from configuration */
01581    for (v = i->chanvars ; v ; v = v->next) {
01582       char valuebuf[1024];
01583       pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
01584    }
01585 
01586    if (sub->rtp) {
01587       ast_jb_configure(tmp, &global_jbconf);
01588    }
01589 
01590    ast_channel_stage_snapshot_done(tmp);
01591    ast_channel_unlock(tmp);
01592 
01593    if (state != AST_STATE_DOWN) {
01594       if (ast_pbx_start(tmp)) {
01595          ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ast_channel_name(tmp));
01596          ast_hangup(tmp);
01597          tmp = NULL;
01598       }
01599    }
01600    ast_verb(3, "MGCP mgcp_new(%s) created in state: %s\n",
01601          ast_channel_name(tmp), ast_state2str(state));
01602 
01603    return tmp;
01604 }
01605 
01606 static char *get_sdp_by_line(char* line, char *name, int nameLen)
01607 {
01608    if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
01609       char *r = line + nameLen + 1;
01610       while (*r && (*r < 33)) ++r;
01611       return r;
01612    }
01613    return "";
01614 }
01615 
01616 static char *get_sdp(struct mgcp_request *req, char *name)
01617 {
01618    int x;
01619    int len = strlen(name);
01620    char *r;
01621 
01622    for (x = 0; x < req->lines; x++) {
01623       r = get_sdp_by_line(req->line[x], name, len);
01624       if (r[0] != '\0') return r;
01625    }
01626    return "";
01627 }
01628 
01629 static void sdpLineNum_iterator_init(int *iterator)
01630 {
01631    *iterator = 0;
01632 }
01633 
01634 static char *get_sdp_iterate(int* iterator, struct mgcp_request *req, char *name)
01635 {
01636    int len = strlen(name);
01637    char *r;
01638    while (*iterator < req->lines) {
01639       r = get_sdp_by_line(req->line[(*iterator)++], name, len);
01640       if (r[0] != '\0') return r;
01641    }
01642    return "";
01643 }
01644 
01645 static char *__get_header(struct mgcp_request *req, char *name, int *start, char *def)
01646 {
01647    int x;
01648    int len = strlen(name);
01649    char *r;
01650    for (x = *start; x < req->headers; x++) {
01651       if (!strncasecmp(req->header[x], name, len) &&
01652           (req->header[x][len] == ':')) {
01653          r = req->header[x] + len + 1;
01654          while (*r && (*r < 33)) {
01655             r++;
01656          }
01657          *start = x + 1;
01658          return r;
01659       }
01660    }
01661    /* Don't return NULL, so get_header is always a valid pointer */
01662    return def;
01663 }
01664 
01665 static char *get_header(struct mgcp_request *req, char *name)
01666 {
01667    int start = 0;
01668    return __get_header(req, name, &start, "");
01669 }
01670 
01671 /*! \brief get_csv: (SC:) get comma separated value */
01672 static char *get_csv(char *c, int *len, char **next)
01673 {
01674    char *s;
01675 
01676    *next = NULL, *len = 0;
01677    if (!c) return NULL;
01678 
01679    while (*c && (*c < 33 || *c == ',')) {
01680       c++;
01681    }
01682 
01683    s = c;
01684    while (*c && (*c >= 33 && *c != ',')) {
01685       c++, (*len)++;
01686    }
01687    *next = c;
01688 
01689    if (*len == 0) {
01690       s = NULL, *next = NULL;
01691    }
01692 
01693    return s;
01694 }
01695 
01696 static struct mgcp_gateway *find_realtime_gw(char *name, char *at, struct sockaddr_in *sin)
01697 {
01698    struct mgcp_gateway *g = NULL;
01699    struct ast_variable *mgcpgwconfig = NULL;
01700    struct ast_variable *gwv, *epname = NULL;
01701    struct mgcp_endpoint *e;
01702    char lines[256];
01703    int i, j;
01704 
01705    ast_debug(1, "*** find Realtime MGCPGW\n");
01706 
01707    if (!(i = ast_check_realtime("mgcpgw")) || !(j = ast_check_realtime("mgcpep"))) {
01708       return NULL;
01709    }
01710 
01711    if (ast_strlen_zero(at)) {
01712       ast_debug(1, "null gw name\n");
01713       return NULL;
01714    }
01715 
01716    if (!(mgcpgwconfig = ast_load_realtime("mgcpgw", "name", at, NULL))) {
01717       return NULL;
01718    }
01719 
01720    /*!
01721     * \note This is a fairly odd way of instantiating lines.  Instead of each
01722     * line created by virtue of being in the database (and loaded via
01723     * ast_load_realtime_multientry), this code forces a specific order with a
01724     * "lines" entry in the "mgcpgw" record.  This has benefits, because as with
01725     * chan_dahdi, values are inherited across definitions.  The downside is
01726     * that it's not as clear what the values will be simply by looking at a
01727     * single row in the database, and it's probable that the sanest configuration
01728     * should have the first column in the "mgcpep" table be "clearvars", with a
01729     * static value of "all", if any variables are set at all.  It may be worth
01730     * making this assumption explicit in the code in the future, and then just
01731     * using ast_load_realtime_multientry for the "mgcpep" records.
01732     */
01733    lines[0] = '\0';
01734    for (gwv = mgcpgwconfig; gwv; gwv = gwv->next) {
01735       if (!strcasecmp(gwv->name, "lines")) {
01736          ast_copy_string(lines, gwv->value, sizeof(lines));
01737          break;
01738       }
01739    }
01740    /* Position gwv at the end of the list */
01741    for (gwv = gwv && gwv->next ? gwv : mgcpgwconfig; gwv->next; gwv = gwv->next);
01742 
01743    if (!ast_strlen_zero(lines)) {
01744       AST_DECLARE_APP_ARGS(args,
01745          AST_APP_ARG(line)[100];
01746       );
01747       AST_STANDARD_APP_ARGS(args, lines);
01748       for (i = 0; i < args.argc; i++) {
01749          gwv->next = ast_load_realtime("mgcpep", "name", at, "line", args.line[i], NULL);
01750 
01751          /* Remove "line" AND position gwv at the end of the list. */
01752          for (epname = NULL; gwv->next; gwv = gwv->next) {
01753             if (!strcasecmp(gwv->next->name, "line")) {
01754                /* Remove it from the list */
01755                epname = gwv->next;
01756                gwv->next = gwv->next->next;
01757             }
01758          }
01759          /* Since "line" instantiates the configuration, we have to move it to the end. */
01760          if (epname) {
01761             gwv->next = epname;
01762             epname->next = NULL;
01763             gwv = gwv->next;
01764          }
01765       }
01766    }
01767    for (gwv = mgcpgwconfig; gwv; gwv = gwv->next) {
01768       ast_debug(1, "MGCP Realtime var: %s => %s\n", gwv->name, gwv->value);
01769    }
01770 
01771    if (mgcpgwconfig) {
01772       g = build_gateway(at, mgcpgwconfig);
01773       ast_variables_destroy(mgcpgwconfig);
01774    }
01775    if (g) {
01776       g->next = gateways;
01777       g->realtime = 1;
01778       gateways = g;
01779       for (e = g->endpoints; e; e = e->next) {
01780          transmit_audit_endpoint(e);
01781          e->needaudit = 0;
01782       }
01783    }
01784    return g;
01785 }
01786 
01787 static struct mgcp_subchannel *find_subchannel_and_lock(char *name, int msgid, struct sockaddr_in *sin)
01788 {
01789    struct mgcp_endpoint *p = NULL;
01790    struct mgcp_subchannel *sub = NULL;
01791    struct mgcp_gateway *g;
01792    char tmp[256] = "";
01793    char *at = NULL, *c;
01794    int found = 0;
01795    if (name) {
01796       ast_copy_string(tmp, name, sizeof(tmp));
01797       at = strchr(tmp, '@');
01798       if (!at) {
01799          ast_log(LOG_NOTICE, "Endpoint '%s' has no at sign!\n", name);
01800          return NULL;
01801       }
01802       *at++ = '\0';
01803    }
01804    ast_mutex_lock(&gatelock);
01805    if (at && (at[0] == '[')) {
01806       at++;
01807       c = strrchr(at, ']');
01808       if (c) {
01809          *c = '\0';
01810       }
01811    }
01812    for (g = gateways ? gateways : find_realtime_gw(name, at, sin); g; g = g->next ? g->next : find_realtime_gw(name, at, sin)) {
01813       if ((!name || !strcasecmp(g->name, at)) &&
01814           (sin || g->addr.sin_addr.s_addr || g->defaddr.sin_addr.s_addr)) {
01815          /* Found the gateway.  If it's dynamic, save it's address -- now for the endpoint */
01816          if (sin && g->dynamic && name) {
01817             if ((g->addr.sin_addr.s_addr != sin->sin_addr.s_addr) ||
01818                (g->addr.sin_port != sin->sin_port)) {
01819                memcpy(&g->addr, sin, sizeof(g->addr));
01820                {
01821                   struct ast_sockaddr tmp1, tmp2;
01822                   struct sockaddr_in tmp3 = {0,};
01823 
01824                   tmp3.sin_addr = g->ourip;
01825                   ast_sockaddr_from_sin(&tmp1, &g->addr);
01826                   ast_sockaddr_from_sin(&tmp2, &tmp3);
01827                   if (ast_ouraddrfor(&tmp1, &tmp2)) {
01828                      memcpy(&g->ourip, &__ourip, sizeof(g->ourip));
01829                   }
01830                   ast_sockaddr_to_sin(&tmp2, &tmp3);
01831                   g->ourip = tmp3.sin_addr;
01832                }
01833                ast_verb(3, "Registered MGCP gateway '%s' at %s port %d\n", g->name, ast_inet_ntoa(g->addr.sin_addr), ntohs(g->addr.sin_port));
01834             }
01835          /* not dynamic, check if the name matches */
01836          } else if (name) {
01837             if (strcasecmp(g->name, at)) {
01838                continue;
01839             }
01840          /* not dynamic, no name, check if the addr matches */
01841          } else if (!name && sin) {
01842             if ((g->addr.sin_addr.s_addr != sin->sin_addr.s_addr) ||
01843                 (g->addr.sin_port != sin->sin_port)) {
01844                continue;
01845             }
01846          } else {
01847             continue;
01848          }
01849          for (p = g->endpoints; p; p = p->next) {
01850             ast_debug(1, "Searching on %s@%s for subchannel\n", p->name, g->name);
01851             if (msgid) {
01852                sub = p->sub;
01853                found = 1;
01854                break;
01855             } else if (name && !strcasecmp(p->name, tmp)) {
01856                ast_debug(1, "Coundn't determine subchannel, assuming current master %s@%s-%d\n",
01857                   p->name, g->name, p->sub->id);
01858                sub = p->sub;
01859                found = 1;
01860                break;
01861             }
01862          }
01863          if (sub && found) {
01864             ast_mutex_lock(&sub->lock);
01865             break;
01866          }
01867       }
01868    }
01869    ast_mutex_unlock(&gatelock);
01870    if (!sub) {
01871       if (name) {
01872          if (g) {
01873             ast_log(LOG_NOTICE, "Endpoint '%s' not found on gateway '%s'\n", tmp, at);
01874          } else {
01875             ast_log(LOG_NOTICE, "Gateway '%s' (and thus its endpoint '%s') does not exist\n", at, tmp);
01876          }
01877       }
01878    }
01879    return sub;
01880 }
01881 
01882 static void parse(struct mgcp_request *req)
01883 {
01884    /* Divide fields by NULL's */
01885    char *c;
01886    int f = 0;
01887    c = req->data;
01888 
01889    /* First header starts immediately */
01890    req->header[f] = c;
01891    for (; *c; c++) {
01892       if (*c == '\n') {
01893          /* We've got a new header */
01894          *c = 0;
01895          ast_debug(3, "Header: %s (%d)\n", req->header[f], (int) strlen(req->header[f]));
01896          if (ast_strlen_zero(req->header[f])) {
01897             /* Line by itself means we're now in content */
01898             c++;
01899             break;
01900          }
01901          if (f >= MGCP_MAX_HEADERS - 1) {
01902             ast_log(LOG_WARNING, "Too many MGCP headers...\n");
01903          } else {
01904             f++;
01905          }
01906          req->header[f] = c + 1;
01907       } else if (*c == '\r') {
01908          /* Ignore but eliminate \r's */
01909          *c = 0;
01910       }
01911    }
01912    /* Check for last header */
01913    if (!ast_strlen_zero(req->header[f])) {
01914       f++;
01915    }
01916    req->headers = f;
01917    /* Now we process any mime content */
01918    f = 0;
01919    req->line[f] = c;
01920    for (; *c; c++) {
01921       if (*c == '\n') {
01922          /* We've got a new line */
01923          *c = 0;
01924          ast_debug(3, "Line: %s (%d)\n", req->line[f], (int) strlen(req->line[f]));
01925          if (f >= MGCP_MAX_LINES - 1) {
01926             ast_log(LOG_WARNING, "Too many SDP lines...\n");
01927          } else {
01928             f++;
01929          }
01930          req->line[f] = c + 1;
01931       } else if (*c == '\r') {
01932          /* Ignore and eliminate \r's */
01933          *c = 0;
01934       }
01935    }
01936    /* Check for last line */
01937    if (!ast_strlen_zero(req->line[f])) {
01938       f++;
01939    }
01940    req->lines = f;
01941    /* Parse up the initial header */
01942    c = req->header[0];
01943    while (*c && *c < 33) c++;
01944    /* First the verb */
01945    req->verb = c;
01946    while (*c && (*c > 32)) c++;
01947    if (*c) {
01948       *c = '\0';
01949       c++;
01950       while (*c && (*c < 33)) c++;
01951       req->identifier = c;
01952       while (*c && (*c > 32)) c++;
01953       if (*c) {
01954          *c = '\0';
01955          c++;
01956          while (*c && (*c < 33)) c++;
01957          req->endpoint = c;
01958          while (*c && (*c > 32)) c++;
01959          if (*c) {
01960             *c = '\0';
01961             c++;
01962             while (*c && (*c < 33)) c++;
01963             req->version = c;
01964             while (*c && (*c > 32)) c++;
01965             while (*c && (*c < 33)) c++;
01966             while (*c && (*c > 32)) c++;
01967             *c = '\0';
01968          }
01969       }
01970    }
01971 
01972    ast_debug(1, "Verb: '%s', Identifier: '%s', Endpoint: '%s', Version: '%s'\n",
01973          req->verb, req->identifier, req->endpoint, req->version);
01974    ast_debug(1, "%d headers, %d lines\n", req->headers, req->lines);
01975    if (*c) {
01976       ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
01977    }
01978 }
01979 
01980 static int process_sdp(struct mgcp_subchannel *sub, struct mgcp_request *req)
01981 {
01982    char *m;
01983    char *c;
01984    char *a;
01985    char host[258];
01986    int len = 0;
01987    int portno;
01988    struct ast_format_cap *peercap;
01989    int peerNonCodecCapability;
01990    struct sockaddr_in sin;
01991    struct ast_sockaddr sin_tmp;
01992    char *codecs;
01993    struct ast_hostent ahp; struct hostent *hp;
01994    int codec, codec_count=0;
01995    int iterator;
01996    struct mgcp_endpoint *p = sub->parent;
01997    struct ast_str *global_buf = ast_str_alloca(64);
01998    struct ast_str *peer_buf = ast_str_alloca(64);
01999    struct ast_str *pvt_buf = ast_str_alloca(64);
02000 
02001    /* Get codec and RTP info from SDP */
02002    m = get_sdp(req, "m");
02003    c = get_sdp(req, "c");
02004    if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
02005       ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
02006       return -1;
02007    }
02008    if (sscanf(c, "IN IP4 %256s", host) != 1) {
02009       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
02010       return -1;
02011    }
02012    /* XXX This could block for a long time, and block the main thread! XXX */
02013    hp = ast_gethostbyname(host, &ahp);
02014    if (!hp) {
02015       ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
02016       return -1;
02017    }
02018    if (sscanf(m, "audio %30d RTP/AVP %n", &portno, &len) != 1 || !len) {
02019       ast_log(LOG_WARNING, "Malformed media stream descriptor: %s\n", m);
02020       return -1;
02021    }
02022    sin.sin_family = AF_INET;
02023    memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
02024    sin.sin_port = htons(portno);
02025    ast_sockaddr_from_sin(&sin_tmp, &sin);
02026    ast_rtp_instance_set_remote_address(sub->rtp, &sin_tmp);
02027    ast_debug(3, "Peer RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
02028    /* Scan through the RTP payload types specified in a "m=" line: */
02029    ast_rtp_codecs_payloads_clear(ast_rtp_instance_get_codecs(sub->rtp), sub->rtp);
02030    codecs = ast_strdupa(m + len);
02031    while (!ast_strlen_zero(codecs)) {
02032       if (sscanf(codecs, "%30d%n", &codec, &len) != 1) {
02033          if (codec_count) {
02034             break;
02035          }
02036          ast_log(LOG_WARNING, "Error in codec string '%s' at '%s'\n", m, codecs);
02037          return -1;
02038       }
02039       ast_rtp_codecs_payloads_set_m_type(ast_rtp_instance_get_codecs(sub->rtp), sub->rtp, codec);
02040       codec_count++;
02041       codecs += len;
02042    }
02043 
02044    /* Next, scan through each "a=rtpmap:" line, noting each */
02045    /* specified RTP payload type (with corresponding MIME subtype): */
02046    sdpLineNum_iterator_init(&iterator);
02047    while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
02048       char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
02049       if (sscanf(a, "rtpmap: %30d %127[^/]/", &codec, mimeSubtype) != 2)
02050          continue;
02051       /* Note: should really look at the 'freq' and '#chans' params too */
02052       ast_rtp_codecs_payloads_set_rtpmap_type(ast_rtp_instance_get_codecs(sub->rtp), sub->rtp, codec, "audio", mimeSubtype, 0);
02053    }
02054 
02055    /* Now gather all of the codecs that were asked for: */
02056    if (!(peercap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
02057       return -1;
02058    }
02059    ast_rtp_codecs_payload_formats(ast_rtp_instance_get_codecs(sub->rtp), peercap, &peerNonCodecCapability);
02060    ast_format_cap_get_compatible(global_capability, peercap, p->cap);
02061    ast_debug(1, "Capabilities: us - %s, them - %s, combined - %s\n",
02062       ast_format_cap_get_names(global_capability, &global_buf),
02063       ast_format_cap_get_names(peercap, &peer_buf),
02064       ast_format_cap_get_names(p->cap, &pvt_buf));
02065    ao2_ref(peercap, -1);
02066 
02067    ast_debug(1, "Non-codec capabilities: us - %d, them - %d, combined - %d\n",
02068       nonCodecCapability, peerNonCodecCapability, p->nonCodecCapability);
02069    if (!ast_format_cap_count(p->cap)) {
02070       ast_log(LOG_WARNING, "No compatible codecs!\n");
02071       return -1;
02072    }
02073    return 0;
02074 }
02075 
02076 static int add_header(struct mgcp_request *req, const char *var, const char *value)
02077 {
02078    if (req->len >= sizeof(req->data) - 4) {
02079       ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
02080       return -1;
02081    }
02082    if (req->lines) {
02083       ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
02084       return -1;
02085    }
02086    req->header[req->headers] = req->data + req->len;
02087    snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s: %s\r\n", var, value);
02088    req->len += strlen(req->header[req->headers]);
02089    if (req->headers < MGCP_MAX_HEADERS) {
02090       req->headers++;
02091    } else {
02092       ast_log(LOG_WARNING, "Out of header space\n");
02093       return -1;
02094    }
02095    return 0;
02096 }
02097 
02098 static int add_line(struct mgcp_request *req, char *line)
02099 {
02100    if (req->len >= sizeof(req->data) - 4) {
02101       ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
02102       return -1;
02103    }
02104    if (!req->lines) {
02105       /* Add extra empty return */
02106       ast_copy_string(req->data + req->len, "\r\n", sizeof(req->data) - req->len);
02107       req->len += strlen(req->data + req->len);
02108    }
02109    req->line[req->lines] = req->data + req->len;
02110    snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
02111    req->len += strlen(req->line[req->lines]);
02112    if (req->lines < MGCP_MAX_LINES) {
02113       req->lines++;
02114    } else {
02115       ast_log(LOG_WARNING, "Out of line space\n");
02116       return -1;
02117    }
02118    return 0;
02119 }
02120 
02121 static int init_resp(struct mgcp_request *req, char *resp, struct mgcp_request *orig, char *resprest)
02122 {
02123    /* Initialize a response */
02124    if (req->headers || req->len) {
02125       ast_log(LOG_WARNING, "Request already initialized?!?\n");
02126       return -1;
02127    }
02128    req->header[req->headers] = req->data + req->len;
02129    snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s %s\r\n", resp, orig->identifier, resprest);
02130    req->len += strlen(req->header[req->headers]);
02131    if (req->headers < MGCP_MAX_HEADERS) {
02132       req->headers++;
02133    } else {
02134       ast_log(LOG_WARNING, "Out of header space\n");
02135    }
02136    return 0;
02137 }
02138 
02139 static int init_req(struct mgcp_endpoint *p, struct mgcp_request *req, char *verb, unsigned int oseq)
02140 {
02141    /* Initialize a response */
02142    if (req->headers || req->len) {
02143       ast_log(LOG_WARNING, "Request already initialized?!?\n");
02144       return -1;
02145    }
02146    req->header[req->headers] = req->data + req->len;
02147    /* check if we need brackets around the gw name */
02148    if (p->parent->isnamedottedip) {
02149       snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %u %s@[%s] MGCP 1.0%s\r\n", verb, oseq, p->name, p->parent->name, p->ncs ? " NCS 1.0" : "");
02150    } else {
02151 +     snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %u %s@%s MGCP 1.0%s\r\n", verb, oseq, p->name, p->parent->name, p->ncs ? " NCS 1.0" : "");
02152    }
02153    req->len += strlen(req->header[req->headers]);
02154    if (req->headers < MGCP_MAX_HEADERS) {
02155       req->headers++;
02156    } else {
02157       ast_log(LOG_WARNING, "Out of header space\n");
02158    }
02159    return 0;
02160 }
02161 
02162 
02163 static int respprep(struct mgcp_request *resp, struct mgcp_endpoint *p, char *msg, struct mgcp_request *req, char *msgrest)
02164 {
02165    memset(resp, 0, sizeof(*resp));
02166    init_resp(resp, msg, req, msgrest);
02167    return 0;
02168 }
02169 
02170 static int reqprep(struct mgcp_request *req, struct mgcp_endpoint *p, char *verb)
02171 {
02172    unsigned int oseq;
02173    memset(req, 0, sizeof(struct mgcp_request));
02174    ast_mutex_lock(&oseq_lock);
02175    oseq_global++;
02176    if (oseq_global > 999999999) {
02177       oseq_global = 1;
02178    }
02179    oseq = oseq_global;
02180    ast_mutex_unlock(&oseq_lock);
02181    init_req(p, req, verb, oseq);
02182    return oseq;
02183 }
02184 
02185 static int transmit_response(struct mgcp_subchannel *sub, char *msg, struct mgcp_request *req, char *msgrest)
02186 {
02187    struct mgcp_request resp;
02188    struct mgcp_endpoint *p = sub->parent;
02189    struct mgcp_response *mgr;
02190 
02191    if (!sub) {
02192       return -1;
02193    }
02194 
02195    respprep(&resp, p, msg, req, msgrest);
02196    if (!(mgr = ast_calloc(1, sizeof(*mgr) + resp.len + 1))) {
02197       return send_response(sub, &resp);
02198    }
02199    /* Store MGCP response in case we have to retransmit */
02200    sscanf(req->identifier, "%30d", &mgr->seqno);
02201    time(&mgr->whensent);
02202    mgr->len = resp.len;
02203    memcpy(mgr->buf, resp.data, resp.len);
02204    mgr->buf[resp.len] = '\0';
02205    mgr->next = p->parent->responses;
02206    p->parent->responses = mgr;
02207 
02208    return send_response(sub, &resp);
02209 }
02210 
02211 
02212 static int add_sdp(struct mgcp_request *resp, struct mgcp_subchannel *sub, struct ast_rtp_instance *rtp)
02213 {
02214    int len;
02215    int codec;
02216    char costr[80];
02217    struct sockaddr_in sin;
02218    struct ast_sockaddr sin_tmp;
02219    char v[256];
02220    char s[256];
02221    char o[256];
02222    char c[256];
02223    char t[256];
02224    char m[256] = "";
02225    char a[1024] = "";
02226    int x;
02227    struct sockaddr_in dest = { 0, };
02228    struct ast_sockaddr dest_tmp;
02229    struct mgcp_endpoint *p = sub->parent;
02230    /* XXX We break with the "recommendation" and send our IP, in order that our
02231           peer doesn't have to ast_gethostbyname() us XXX */
02232    len = 0;
02233    if (!sub->rtp) {
02234       ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
02235       return -1;
02236    }
02237    ast_rtp_instance_get_local_address(sub->rtp, &sin_tmp);
02238    ast_sockaddr_to_sin(&sin_tmp, &sin);
02239    if (rtp) {
02240       ast_rtp_instance_get_remote_address(sub->rtp, &dest_tmp);
02241       ast_sockaddr_to_sin(&dest_tmp, &dest);
02242    } else {
02243       if (sub->tmpdest.sin_addr.s_addr) {
02244          dest.sin_addr = sub->tmpdest.sin_addr;
02245          dest.sin_port = sub->tmpdest.sin_port;
02246          /* Reset temporary destination */
02247          memset(&sub->tmpdest, 0, sizeof(sub->tmpdest));
02248       } else {
02249          dest.sin_addr = p->parent->ourip;
02250          dest.sin_port = sin.sin_port;
02251       }
02252    }
02253    ast_debug(1, "We're at %s port %d\n", ast_inet_ntoa(p->parent->ourip), ntohs(sin.sin_port));
02254    ast_copy_string(v, "v=0\r\n", sizeof(v));
02255    snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", (int)getpid(), (int)getpid(), ast_inet_ntoa(dest.sin_addr));
02256    ast_copy_string(s, "s=session\r\n", sizeof(s));
02257    snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
02258    ast_copy_string(t, "t=0 0\r\n", sizeof(t));
02259    snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
02260 
02261    for (x = 0; x < ast_format_cap_count(p->cap); x++) {
02262       struct ast_format *format = ast_format_cap_get_format(p->cap, x);
02263 
02264       if (ast_format_get_type(format) != AST_MEDIA_TYPE_AUDIO) {
02265          ao2_ref(format, -1);
02266          continue;
02267       }
02268 
02269       ast_debug(1, "Answering with capability %s\n", ast_format_get_name(format));
02270       codec = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(sub->rtp), 1, format, 0);
02271       if (codec > -1) {
02272          snprintf(costr, sizeof(costr), " %d", codec);
02273          strncat(m, costr, sizeof(m) - strlen(m) - 1);
02274          snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype2(1, format, 0, 0));
02275          strncat(a, costr, sizeof(a) - strlen(a) - 1);
02276       }
02277 
02278       ao2_ref(format, -1);
02279    }
02280 
02281    for (x = 1LL; x <= AST_RTP_MAX; x <<= 1) {
02282       if (p->nonCodecCapability & x) {
02283          ast_debug(1, "Answering with non-codec capability %d\n", (int) x);
02284          codec = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(sub->rtp), 0, NULL, x);
02285          if (codec > -1) {
02286             snprintf(costr, sizeof(costr), " %d", codec);
02287             strncat(m, costr, sizeof(m) - strlen(m) - 1);
02288             snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype2(0, NULL, x, 0));
02289             strncat(a, costr, sizeof(a) - strlen(a) - 1);
02290             if (x == AST_RTP_DTMF) {
02291                /* Indicate we support DTMF...  Not sure about 16,
02292                   but MSN supports it so dang it, we will too... */
02293                snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n", codec);
02294                strncat(a, costr, sizeof(a) - strlen(a) - 1);
02295             }
02296          }
02297       }
02298    }
02299    strncat(m, "\r\n", sizeof(m) - strlen(m) - 1);
02300    len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
02301    snprintf(costr, sizeof(costr), "%d", len);
02302    add_line(resp, v);
02303    add_line(resp, o);
02304    add_line(resp, s);
02305    add_line(resp, c);
02306    add_line(resp, t);
02307    add_line(resp, m);
02308    add_line(resp, a);
02309    return 0;
02310 }
02311 
02312 static int transmit_modify_with_sdp(struct mgcp_subchannel *sub, struct ast_rtp_instance *rtp, const struct ast_format_cap *codecs)
02313 {
02314    struct mgcp_request resp;
02315    char local[256];
02316    char tmp[80];
02317    struct mgcp_endpoint *p = sub->parent;
02318    int i;
02319    struct ast_sockaddr sub_tmpdest_tmp;
02320    unsigned int oseq;
02321 
02322    if (ast_strlen_zero(sub->cxident) && rtp) {
02323       /* We don't have a CXident yet, store the destination and
02324          wait a bit */
02325       ast_rtp_instance_get_remote_address(rtp, &sub_tmpdest_tmp);
02326       ast_sockaddr_to_sin(&sub_tmpdest_tmp, &sub->tmpdest);
02327       return 0;
02328    }
02329    ast_copy_string(local, "e:on, s:off, p:20", sizeof(local));
02330 
02331    for (i = 0; i < ast_format_cap_count(p->cap); i++) {
02332       struct ast_format *format = ast_format_cap_get_format(p->cap, i);
02333 
02334       if (ast_format_get_type(format) != AST_MEDIA_TYPE_AUDIO) {
02335          ao2_ref(format, -1);
02336          continue;
02337       }
02338 
02339       snprintf(tmp, sizeof(tmp), ", a:%s", ast_rtp_lookup_mime_subtype2(1, format, 0, 0));
02340       strncat(local, tmp, sizeof(local) - strlen(local) - 1);
02341 
02342       ao2_ref(format, -1);
02343    }
02344 
02345    if (sub->gate) {
02346       if (sub->gate->state == GATE_ALLOCATED || sub->gate->state == GATE_OPEN) {
02347          snprintf(tmp, sizeof(tmp), ", dq-gi:%x", sub->gate->gateid);
02348          strncat(local, tmp, sizeof(local) - strlen(local) - 1);
02349          sub->sdpsent = 1;
02350       } else {
02351          /* oops wait */
02352          ast_debug(1, "Waiting for opened gate...\n");
02353          sub->sdpsent = 0;
02354          return 0;
02355       }
02356    }
02357 
02358 
02359    oseq = reqprep(&resp, p, "MDCX");
02360    add_header(&resp, "C", sub->callid);
02361    add_header(&resp, "L", local);
02362    add_header(&resp, "M", mgcp_cxmodes[sub->cxmode]);
02363    /* X header should not be sent. kept for compatibility */
02364    add_header(&resp, "X", sub->txident);
02365    add_header(&resp, "I", sub->cxident);
02366    /*add_header(&resp, "S", "");*/
02367    add_sdp(&resp, sub, rtp);
02368    /* fill in new fields */
02369    resp.cmd = MGCP_CMD_MDCX;
02370    resp.trid = oseq;
02371    return send_request(p, sub, &resp, oseq);
02372 }
02373 
02374 static int transmit_connect_with_sdp(struct mgcp_subchannel *sub, struct ast_rtp_instance *rtp)
02375 {
02376    struct mgcp_request resp;
02377    char local[256];
02378    char tmp[80];
02379    int i;
02380    struct mgcp_endpoint *p = sub->parent;
02381    unsigned int oseq;
02382 
02383    ast_debug(3, "Creating connection for %s@%s-%d in cxmode: %s callid: %s\n",
02384        p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode], sub->callid);
02385 
02386    ast_copy_string(local, "e:on, s:off, p:20", sizeof(local));
02387 
02388    for (i = 0; i < ast_format_cap_count(p->cap); i++) {
02389       struct ast_format *format = ast_format_cap_get_format(p->cap, i);
02390 
02391       if (ast_format_get_type(format) != AST_MEDIA_TYPE_AUDIO) {
02392          ao2_ref(format, -1);
02393          continue;
02394       }
02395 
02396       snprintf(tmp, sizeof(tmp), ", a:%s", ast_rtp_lookup_mime_subtype2(1, format, 0, 0));
02397       strncat(local, tmp, sizeof(local) - strlen(local) - 1);
02398 
02399       ao2_ref(format, -1);
02400    }
02401 
02402    if (sub->gate) {
02403       if(sub->gate->state == GATE_ALLOCATED) {
02404          snprintf(tmp, sizeof(tmp), ", dq-gi:%x", sub->gate->gateid);
02405          strncat(local, tmp, sizeof(local) - strlen(local) - 1);
02406       }
02407    }
02408    sub->sdpsent = 1;
02409    oseq = reqprep(&resp, p, "CRCX");
02410    add_header(&resp, "C", sub->callid);
02411    add_header(&resp, "L", local);
02412    add_header(&resp, "M", mgcp_cxmodes[sub->cxmode]);
02413    /* X header should not be sent. kept for compatibility */
02414    add_header(&resp, "X", sub->txident);
02415    /*add_header(&resp, "S", "");*/
02416    add_sdp(&resp, sub, rtp);
02417    /* fill in new fields */
02418    resp.cmd = MGCP_CMD_CRCX;
02419    resp.trid = oseq;
02420    return send_request(p, sub, &resp, oseq);
02421 }
02422 
02423 static int mgcp_pktcgate_remove(struct cops_gate *gate)
02424 {
02425    struct mgcp_subchannel *sub = gate->tech_pvt;
02426 
02427    if (!sub) {
02428       return 1;
02429    }
02430 
02431    ast_mutex_lock(&sub->lock);
02432    ast_debug(1, "Pktc: gate 0x%x deleted\n", gate->gateid);
02433    if (sub->gate->state != GATE_CLOSED && sub->parent->hangupongateremove) {
02434       sub->gate = NULL;
02435       if (sub->owner) {
02436          ast_softhangup(sub->owner, AST_CAUSE_REQUESTED_CHAN_UNAVAIL);
02437          ast_channel_unlock(sub->owner);
02438       }
02439    } else {
02440       sub->gate = NULL;
02441    }
02442    ast_mutex_unlock(&sub->lock);
02443    return 1;
02444 }
02445 
02446 static int mgcp_pktcgate_open(struct cops_gate *gate)
02447 {
02448    struct mgcp_subchannel *sub = gate->tech_pvt;
02449    if (!sub) {
02450       return 1;
02451    }
02452    ast_mutex_lock(&sub->lock);
02453    ast_debug(1, "Pktc: gate 0x%x open\n", gate->gateid);
02454    if (!sub->sdpsent) transmit_modify_with_sdp(sub, NULL, 0);
02455    ast_mutex_unlock(&sub->lock);
02456    return 1;
02457 }
02458 
02459 static int mgcp_alloc_pktcgate(struct mgcp_subchannel *sub)
02460 {
02461    struct mgcp_endpoint *p = sub->parent;
02462    sub->gate = ast_pktccops_gate_alloc(GATE_SET, NULL, ntohl(p->parent->addr.sin_addr.s_addr),
02463                8, 128000, 232, 0, 0, NULL, &mgcp_pktcgate_remove);
02464 
02465    if (!sub->gate) {
02466       return 0;
02467    }
02468    sub->gate->tech_pvt = sub;
02469    sub->gate->gate_open = &mgcp_pktcgate_open;
02470    return 1;
02471 }
02472 
02473 static int transmit_connect(struct mgcp_subchannel *sub)
02474 {
02475    struct mgcp_request resp;
02476    int x;
02477    char local[256];
02478    char tmp[80];
02479    struct ast_format *tmpfmt;
02480    struct mgcp_endpoint *p = sub->parent;
02481    unsigned int oseq;
02482 
02483    ast_copy_string(local, "p:20, s:off, e:on", sizeof(local));
02484 
02485    for (x = 0; x < ast_format_cap_count(p->cap); x++) {
02486       tmpfmt = ast_format_cap_get_format(p->cap, x);
02487 
02488       snprintf(tmp, sizeof(tmp), ", a:%s", ast_rtp_lookup_mime_subtype2(1, tmpfmt, 0, 0));
02489       strncat(local, tmp, sizeof(local) - strlen(local) - 1);
02490 
02491       ao2_ref(tmpfmt, -1);
02492    }
02493 
02494    ast_debug(3, "Creating connection for %s@%s-%d in cxmode: %s callid: %s\n",
02495           p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode], sub->callid);
02496    sub->sdpsent = 0;
02497    oseq = reqprep(&resp, p, "CRCX");
02498    add_header(&resp, "C", sub->callid);
02499    add_header(&resp, "L", local);
02500    add_header(&resp, "M", "inactive");
02501    /* X header should not be sent. kept for compatibility */
02502    add_header(&resp, "X", sub->txident);
02503    /*add_header(&resp, "S", "");*/
02504    /* fill in new fields */
02505    resp.cmd = MGCP_CMD_CRCX;
02506    resp.trid = oseq;
02507    return send_request(p, sub, &resp, oseq);
02508 }
02509 
02510 static int transmit_notify_request(struct mgcp_subchannel *sub, char *tone)
02511 {
02512    struct mgcp_request resp;
02513    struct mgcp_endpoint *p = sub->parent;
02514    unsigned int oseq;
02515 
02516    ast_debug(3, "MGCP Asked to indicate tone: %s on  %s@%s-%d in cxmode: %s\n",
02517       tone, p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode]);
02518    ast_copy_string(p->curtone, tone, sizeof(p->curtone));
02519    oseq = reqprep(&resp, p, "RQNT");
02520    add_header(&resp, "X", p->rqnt_ident);
02521    switch (p->hookstate) {
02522    case MGCP_ONHOOK:
02523       add_header(&resp, "R", "L/hd(N)");
02524       break;
02525    case MGCP_OFFHOOK:
02526       add_header_offhook(sub, &resp, tone);
02527       break;
02528    }
02529    if (!ast_strlen_zero(tone)) {
02530       add_header(&resp, "S", tone);
02531    }
02532    /* fill in new fields */
02533    resp.cmd = MGCP_CMD_RQNT;
02534    resp.trid = oseq;
02535    return send_request(p, NULL, &resp, oseq);
02536 }
02537 
02538 static int transmit_notify_request_with_callerid(struct mgcp_subchannel *sub, char *tone, char *callernum, char *callername)
02539 {
02540    struct mgcp_request resp;
02541    char tone2[256];
02542    char *l, *n;
02543    struct timeval t = ast_tvnow();
02544    struct ast_tm tm;
02545    struct mgcp_endpoint *p = sub->parent;
02546    unsigned int oseq;
02547 
02548    ast_localtime(&t, &tm, NULL);
02549    n = callername;
02550    l = callernum;
02551    if (!n)
02552       n = "";
02553    if (!l)
02554       l = "";
02555 
02556    /* Keep track of last callerid for blacklist and callreturn */
02557    ast_copy_string(p->lastcallerid, l, sizeof(p->lastcallerid));
02558 
02559    snprintf(tone2, sizeof(tone2), "%s,L/ci(%02d/%02d/%02d/%02d,%s,%s)", tone,
02560       tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, l, n);
02561    ast_copy_string(p->curtone, tone, sizeof(p->curtone));
02562    oseq = reqprep(&resp, p, "RQNT");
02563    add_header(&resp, "X", p->rqnt_ident);
02564    switch (p->hookstate) {
02565    case MGCP_ONHOOK:
02566       add_header(&resp, "R", "L/hd(N)");
02567       break;
02568    case MGCP_OFFHOOK:
02569       add_header_offhook(sub, &resp, tone);
02570       break;
02571    }
02572    if (!ast_strlen_zero(tone2)) {
02573       add_header(&resp, "S", tone2);
02574    }
02575    ast_debug(3, "MGCP Asked to indicate tone: %s on  %s@%s-%d in cxmode: %s\n",
02576       tone2, p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode]);
02577    /* fill in new fields */
02578    resp.cmd = MGCP_CMD_RQNT;
02579    resp.trid = oseq;
02580    return send_request(p, NULL, &resp, oseq);
02581 }
02582 
02583 static int transmit_modify_request(struct mgcp_subchannel *sub)
02584 {
02585    struct mgcp_request resp;
02586    struct mgcp_endpoint *p = sub->parent;
02587    int i;
02588    int fc = 1;
02589    char local[256];
02590    char tmp[80];
02591    unsigned int oseq;
02592 
02593    if (ast_strlen_zero(sub->cxident)) {
02594       /* We don't have a CXident yet, store the destination and
02595          wait a bit */
02596       return 0;
02597    }
02598    ast_debug(3, "Modified %s@%s-%d with new mode: %s on callid: %s\n",
02599       p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode], sub->callid);
02600 
02601    ast_copy_string(local, "", sizeof(local));
02602    for (i = 0; i < ast_format_cap_count(p->cap); i++) {
02603       struct ast_format *format = ast_format_cap_get_format(p->cap, i);
02604 
02605       if (p->ncs && !fc) {
02606          ast_format_cap_remove_by_type(p->cap, AST_MEDIA_TYPE_UNKNOWN);
02607          ast_format_cap_append(p->cap, format, 0); /* sb5120e bug */
02608          ao2_ref(format, -1);
02609          break;
02610       } else {
02611          fc = 0;
02612          snprintf(tmp, sizeof(tmp), ", a:%s", ast_rtp_lookup_mime_subtype2(1, format, 0, 0));
02613       }
02614       strncat(local, tmp, sizeof(local) - strlen(local) - 1);
02615 
02616       ao2_ref(format, -1);
02617    }
02618 
02619    if (!sub->sdpsent) {
02620       if (sub->gate) {
02621          if (sub->gate->state == GATE_ALLOCATED || sub->gate->state == GATE_OPEN) {
02622             snprintf(tmp, sizeof(tmp), ", dq-gi:%x", sub->gate->gateid);
02623             strncat(local, tmp, sizeof(local) - strlen(local) - 1);
02624          } else {
02625                /* we still don't have gateid wait */
02626             return 0;
02627          }
02628       }
02629    }
02630 
02631    oseq = reqprep(&resp, p, "MDCX");
02632    add_header(&resp, "C", sub->callid);
02633    if (!sub->sdpsent) {
02634       add_header(&resp, "L", local);
02635    }
02636    add_header(&resp, "M", mgcp_cxmodes[sub->cxmode]);
02637    /* X header should not be sent. kept for compatibility */
02638    add_header(&resp, "X", sub->txident);
02639    add_header(&resp, "I", sub->cxident);
02640    switch (sub->parent->hookstate) {
02641    case MGCP_ONHOOK:
02642       add_header(&resp, "R", "L/hd(N)");
02643       break;
02644    case MGCP_OFFHOOK:
02645       add_header_offhook(sub, &resp, "");
02646       break;
02647    }
02648    if (!sub->sdpsent) {
02649       add_sdp(&resp, sub, NULL);
02650       sub->sdpsent = 1;
02651    }
02652    /* fill in new fields */
02653    resp.cmd = MGCP_CMD_MDCX;
02654    resp.trid = oseq;
02655    return send_request(p, sub, &resp, oseq);
02656 }
02657 
02658 
02659 static void add_header_offhook(struct mgcp_subchannel *sub, struct mgcp_request *resp, char *tone)
02660 {
02661    struct mgcp_endpoint *p = sub->parent;
02662    char tone_indicate_end = 0;
02663 
02664    /* We also should check the tone to indicate, because it have no sense
02665       to request notify D/[0-9#*] (dtmf keys) if we are sending congestion
02666       tone for example G/cg */
02667    if (p && (!strcasecmp(tone, (p->ncs ? "L/ro" : "G/cg")))) {
02668       tone_indicate_end = 1;
02669    }
02670 
02671    if (p && p->sub && p->sub->owner &&
02672          ast_channel_state(p->sub->owner) >= AST_STATE_RINGING &&
02673          (p->dtmfmode & (MGCP_DTMF_INBAND | MGCP_DTMF_HYBRID))) {
02674        add_header(resp, "R", "L/hu(N),L/hf(N)");
02675 
02676    } else if (!tone_indicate_end){
02677        add_header(resp, "R", (p->ncs ? "L/hu(N),L/hf(N),L/[0-9#*](N)" : "L/hu(N),L/hf(N),D/[0-9#*](N)"));
02678    } else {
02679       ast_debug(1, "We don't want more digits if we will end the call\n");
02680       add_header(resp, "R", "L/hu(N),L/hf(N)");
02681    }
02682 }
02683 
02684 
02685 
02686 
02687 static int transmit_audit_endpoint(struct mgcp_endpoint *p)
02688 {
02689    struct mgcp_request resp;
02690    unsigned int oseq;
02691    oseq = reqprep(&resp, p, "AUEP");
02692    /* removed unknown param VS */
02693    /*add_header(&resp, "F", "A,R,D,S,X,N,I,T,O,ES,E,MD,M");*/
02694    add_header(&resp, "F", "A");
02695    /* fill in new fields */
02696    resp.cmd = MGCP_CMD_AUEP;
02697    resp.trid = oseq;
02698    return send_request(p, NULL, &resp, oseq);
02699 }
02700 
02701 static int transmit_connection_del(struct mgcp_subchannel *sub)
02702 {
02703    struct mgcp_endpoint *p = sub->parent;
02704    struct mgcp_request resp;
02705    unsigned int oseq;
02706 
02707    ast_debug(3, "Delete connection %s %s@%s-%d with new mode: %s on callid: %s\n",
02708       sub->cxident, p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode], sub->callid);
02709    oseq = reqprep(&resp, p, "DLCX");
02710    /* check if call id is avail */
02711    if (sub->callid[0])
02712       add_header(&resp, "C", sub->callid);
02713    /* X header should not be sent. kept for compatibility */
02714    add_header(&resp, "X", sub->txident);
02715    /* check if cxident is avail */
02716    if (sub->cxident[0])
02717       add_header(&resp, "I", sub->cxident);
02718    /* fill in new fields */
02719    resp.cmd = MGCP_CMD_DLCX;
02720    resp.trid = oseq;
02721    return send_request(p, sub, &resp, oseq);
02722 }
02723 
02724 static int transmit_connection_del_w_params(struct mgcp_endpoint *p, char *callid, char *cxident)
02725 {
02726    struct mgcp_request resp;
02727    unsigned int oseq;
02728 
02729    ast_debug(3, "Delete connection %s %s@%s on callid: %s\n",
02730       cxident ? cxident : "", p->name, p->parent->name, callid ? callid : "");
02731    oseq = reqprep(&resp, p, "DLCX");
02732    /* check if call id is avail */
02733    if (callid && *callid)
02734       add_header(&resp, "C", callid);
02735    /* check if cxident is avail */
02736    if (cxident && *cxident)
02737       add_header(&resp, "I", cxident);
02738    /* fill in new fields */
02739    resp.cmd = MGCP_CMD_DLCX;
02740    resp.trid = oseq;
02741    return send_request(p, p->sub, &resp, oseq);
02742 }
02743 
02744 /*! \brief  dump_cmd_queues: (SC:) cleanup pending commands */
02745 static void dump_cmd_queues(struct mgcp_endpoint *p, struct mgcp_subchannel *sub)
02746 {
02747    struct mgcp_request *t, *q;
02748 
02749    if (p) {
02750       ast_mutex_lock(&p->rqnt_queue_lock);
02751       for (q = p->rqnt_queue; q; t = q->next, ast_free(q), q=t);
02752       p->rqnt_queue = NULL;
02753       ast_mutex_unlock(&p->rqnt_queue_lock);
02754 
02755       ast_mutex_lock(&p->cmd_queue_lock);
02756       for (q = p->cmd_queue; q; t = q->next, ast_free(q), q=t);
02757       p->cmd_queue = NULL;
02758       ast_mutex_unlock(&p->cmd_queue_lock);
02759 
02760       ast_mutex_lock(&p->sub->cx_queue_lock);
02761       for (q = p->sub->cx_queue; q; t = q->next, ast_free(q), q=t);
02762       p->sub->cx_queue = NULL;
02763       ast_mutex_unlock(&p->sub->cx_queue_lock);
02764 
02765       ast_mutex_lock(&p->sub->next->cx_queue_lock);
02766       for (q = p->sub->next->cx_queue; q; t = q->next, ast_free(q), q=t);
02767       p->sub->next->cx_queue = NULL;
02768       ast_mutex_unlock(&p->sub->next->cx_queue_lock);
02769    } else if (sub) {
02770       ast_mutex_lock(&sub->cx_queue_lock);
02771       for (q = sub->cx_queue; q; t = q->next, ast_free(q), q=t);
02772       sub->cx_queue = NULL;
02773       ast_mutex_unlock(&sub->cx_queue_lock);
02774    }
02775 }
02776 
02777 
02778 /*! \brief  find_command: (SC:) remove command transaction from queue */
02779 static struct mgcp_request *find_command(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,
02780       struct mgcp_request **queue, ast_mutex_t *l, int ident)
02781 {
02782    struct mgcp_request *prev, *req;
02783 
02784    ast_mutex_lock(l);
02785    for (prev = NULL, req = *queue; req; prev = req, req = req->next) {
02786       if (req->trid == ident) {
02787          /* remove from queue */
02788          if (!prev)
02789             *queue = req->next;
02790          else
02791             prev->next = req->next;
02792 
02793          /* send next pending command */
02794          if (*queue) {
02795             ast_debug(1, "Posting Queued Request:\n%s to %s:%d\n", (*queue)->data,
02796                ast_inet_ntoa(p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
02797 
02798             mgcp_postrequest(p, sub, (*queue)->data, (*queue)->len, (*queue)->trid);
02799          }
02800          break;
02801       }
02802    }
02803    ast_mutex_unlock(l);
02804    return req;
02805 }
02806 
02807 /* modified for new transport mechanism */
02808 static void handle_response(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,
02809       int result, unsigned int ident, struct mgcp_request *resp)
02810 {
02811    char *c;
02812    struct mgcp_request *req;
02813    struct mgcp_gateway *gw = p->parent;
02814 
02815    if (result < 200) {
02816       /* provisional response */
02817       return;
02818    }
02819 
02820    if (p->slowsequence)
02821       req = find_command(p, sub, &p->cmd_queue, &p->cmd_queue_lock, ident);
02822    else if (sub)
02823       req = find_command(p, sub, &sub->cx_queue, &sub->cx_queue_lock, ident);
02824    else if (!(req = find_command(p, sub, &p->rqnt_queue, &p->rqnt_queue_lock, ident)))
02825       req = find_command(p, sub, &p->cmd_queue, &p->cmd_queue_lock, ident);
02826 
02827    if (!req) {
02828       ast_verb(3, "No command found on [%s] for transaction %u. Ignoring...\n",
02829             gw->name, ident);
02830       return;
02831    }
02832 
02833    if (p && (result >= 400) && (result <= 599)) {
02834       switch (result) {
02835       case 401:
02836          p->hookstate = MGCP_OFFHOOK;
02837          break;
02838       case 402:
02839          p->hookstate = MGCP_ONHOOK;
02840          break;
02841       case 406:
02842          ast_log(LOG_NOTICE, "Transaction %u timed out\n", ident);
02843          break;
02844       case 407:
02845          ast_log(LOG_NOTICE, "Transaction %u aborted\n", ident);
02846          break;
02847       }
02848       if (sub) {
02849          if (!sub->cxident[0] && (req->cmd == MGCP_CMD_CRCX)) {
02850              ast_log(LOG_NOTICE, "DLCX for all connections on %s due to error %d\n", gw->name, result);
02851              transmit_connection_del(sub);
02852          }
02853          if (sub->owner) {
02854             ast_log(LOG_NOTICE, "Terminating on result %d from %s@%s-%d\n",
02855                result, p->name, p->parent->name, sub ? sub->id:-1);
02856             mgcp_queue_hangup(sub);
02857          }
02858       } else {
02859          if (p->sub->next->owner) {
02860             ast_log(LOG_NOTICE, "Terminating on result %d from %s@%s-%d\n",
02861                result, p->name, p->parent->name, sub ? sub->id:-1);
02862             mgcp_queue_hangup(p->sub);
02863          }
02864 
02865          if (p->sub->owner) {
02866             ast_log(LOG_NOTICE, "Terminating on result %d from %s@%s-%d\n",
02867                result, p->name, p->parent->name, sub ? sub->id:-1);
02868             mgcp_queue_hangup(p->sub);
02869          }
02870 
02871          dump_cmd_queues(p, NULL);
02872       }
02873    }
02874 
02875    if (resp) {
02876       /* responseAck: */
02877       if (result == 200 && (req->cmd == MGCP_CMD_CRCX || req->cmd == MGCP_CMD_MDCX)) {
02878             if (sub) {
02879                transmit_response(sub, "000", resp, "OK");
02880                if (sub->owner && ast_channel_state(sub->owner) == AST_STATE_RINGING) {
02881                   ast_queue_control(sub->owner, AST_CONTROL_RINGING);
02882                }
02883             }
02884       }
02885       if (req->cmd == MGCP_CMD_CRCX) {
02886          if ((c = get_header(resp, "I"))) {
02887             if (!ast_strlen_zero(c) && sub) {
02888                /* if we are hanging up do not process this conn. */
02889                if (sub->owner) {
02890                   if (!ast_strlen_zero(sub->cxident)) {
02891                      if (strcasecmp(c, sub->cxident)) {
02892                         ast_log(LOG_WARNING, "Subchannel already has a cxident. sub->cxident: %s requested %s\n", sub->cxident, c);
02893                      }
02894                   }
02895                   ast_copy_string(sub->cxident, c, sizeof(sub->cxident));
02896                   if (sub->tmpdest.sin_addr.s_addr) {
02897                      transmit_modify_with_sdp(sub, NULL, 0);
02898                   }
02899                } else {
02900                   /* XXX delete this one
02901                      callid and conn id may already be lost.
02902                      so the following del conn may have a side effect of
02903                      cleaning up the next subchannel */
02904                   transmit_connection_del(sub);
02905                }
02906             }
02907          }
02908       }
02909 
02910       if (req->cmd == MGCP_CMD_AUEP) {
02911          /* check stale connection ids */
02912          if ((c = get_header(resp, "I"))) {
02913             char *v, *n;
02914             int len;
02915             while ((v = get_csv(c, &len, &n))) {
02916                if (len) {
02917                   if (strncasecmp(v, p->sub->cxident, len) &&
02918                       strncasecmp(v, p->sub->next->cxident, len)) {
02919                      /* connection id not found. delete it */
02920                      char cxident[80] = "";
02921 
02922                      if (len > (sizeof(cxident) - 1))
02923                         len = sizeof(cxident) - 1;
02924                      ast_copy_string(cxident, v, len);
02925                      ast_verb(3, "Non existing connection id %s on %s@%s \n",
02926                                cxident, p->name, gw->name);
02927                      transmit_connection_del_w_params(p, NULL, cxident);
02928                   }
02929                }
02930                c = n;
02931             }
02932          }
02933 
02934          /* Try to determine the hookstate returned from an audit endpoint command */
02935          if ((c = get_header(resp, "ES"))) {
02936             if (!ast_strlen_zero(c)) {
02937                if (strstr(c, "hu")) {
02938                   if (p->hookstate != MGCP_ONHOOK) {
02939                      /* XXX cleanup if we think we are offhook XXX */
02940                      if ((p->sub->owner || p->sub->next->owner ) &&
02941                          p->hookstate == MGCP_OFFHOOK)
02942                         mgcp_queue_hangup(sub);
02943                      p->hookstate = MGCP_ONHOOK;
02944 
02945                      /* update the requested events according to the new hookstate */
02946                      transmit_notify_request(p->sub, "");
02947 
02948                      ast_verb(3, "Setting hookstate of %s@%s to ONHOOK\n", p->name, gw->name);
02949                      }
02950                } else if (strstr(c, "hd")) {
02951                   if (p->hookstate != MGCP_OFFHOOK) {
02952                      p->hookstate = MGCP_OFFHOOK;
02953 
02954                      /* update the requested events according to the new hookstate */
02955                      transmit_notify_request(p->sub, "");
02956 
02957                      ast_verb(3, "Setting hookstate of %s@%s to OFFHOOK\n", p->name, gw->name);
02958                      }
02959                   }
02960                }
02961             }
02962          }
02963 
02964       if (resp && resp->lines) {
02965          /* do not process sdp if we are hanging up. this may be a late response */
02966          if (sub && sub->owner) {
02967             if (!sub->rtp)
02968                start_rtp(sub);
02969             if (sub->rtp)
02970                process_sdp(sub, resp);
02971          }
02972       }
02973    }
02974 
02975    ast_free(req);
02976 }
02977 
02978 static void start_rtp(struct mgcp_subchannel *sub)
02979 {
02980    struct ast_sockaddr bindaddr_tmp;
02981 
02982    ast_mutex_lock(&sub->lock);
02983    /* check again to be on the safe side */
02984    if (sub->rtp) {
02985       ast_rtp_instance_destroy(sub->rtp);
02986       sub->rtp = NULL;
02987    }
02988    /* Allocate the RTP now */
02989    ast_sockaddr_from_sin(&bindaddr_tmp, &bindaddr);
02990    sub->rtp = ast_rtp_instance_new("asterisk", sched, &bindaddr_tmp, NULL);
02991    if (sub->rtp && sub->owner)
02992       ast_channel_set_fd(sub->owner, 0, ast_rtp_instance_fd(sub->rtp, 0));
02993    if (sub->rtp) {
02994       ast_rtp_instance_set_qos(sub->rtp, qos.tos_audio, qos.cos_audio, "MGCP RTP");
02995       ast_rtp_instance_set_prop(sub->rtp, AST_RTP_PROPERTY_NAT, sub->nat);
02996    }
02997    /* Make a call*ID */
02998    snprintf(sub->callid, sizeof(sub->callid), "%08lx%s", (unsigned long)ast_random(), sub->txident);
02999    /* Transmit the connection create */
03000    if(!sub->parent->pktcgatealloc) {
03001       transmit_connect_with_sdp(sub, NULL);
03002    } else {
03003       transmit_connect(sub);
03004       sub->gate = NULL;
03005       if(!mgcp_alloc_pktcgate(sub))
03006          mgcp_queue_hangup(sub);
03007    }
03008    ast_mutex_unlock(&sub->lock);
03009 }
03010 
03011 static void *mgcp_ss(void *data)
03012 {
03013    struct ast_channel *chan = data;
03014    struct mgcp_subchannel *sub = ast_channel_tech_pvt(chan);
03015    struct mgcp_endpoint *p = sub->parent;
03016    /* char exten[AST_MAX_EXTENSION] = ""; */
03017    int len = 0;
03018    int timeout = firstdigittimeout;
03019    int res= 0;
03020    int getforward = 0;
03021    int loop_pause = 100;
03022    RAII_VAR(struct ast_features_pickup_config *, pickup_cfg, NULL, ao2_cleanup);
03023    const char *pickupexten;
03024 
03025    len = strlen(p->dtmf_buf);
03026 
03027    ast_channel_lock(chan);
03028    pickup_cfg = ast_get_chan_features_pickup_config(chan);
03029    if (!pickup_cfg) {
03030       ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension\n");
03031       pickupexten = "";
03032    } else {
03033       pickupexten = ast_strdupa(pickup_cfg->pickupexten);
03034    }
03035    ast_channel_unlock(chan);
03036 
03037    while (len < AST_MAX_EXTENSION - 1) {
03038       ast_debug(1, "Dtmf buffer '%s' for '%s@%s'\n", p->dtmf_buf, p->name, p->parent->name);
03039       res = 1;  /* Assume that we will get a digit */
03040       while (strlen(p->dtmf_buf) == len) {
03041          ast_safe_sleep(chan, loop_pause);
03042          timeout -= loop_pause;
03043          if (timeout <= 0){
03044             res = 0;
03045             break;
03046          }
03047          res = 1;
03048       }
03049 
03050       timeout = 0;
03051       len = strlen(p->dtmf_buf);
03052 
03053       if (!ast_ignore_pattern(ast_channel_context(chan), p->dtmf_buf)) {
03054          /*res = tone_zone_play_tone(p->subs[index].zfd, -1);*/
03055          ast_indicate(chan, -1);
03056       } else {
03057          /* XXX Redundant?  We should already be playing dialtone */
03058          /*tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALTONE);*/
03059          transmit_notify_request(sub, "L/dl");
03060       }
03061       if (ast_exists_extension(chan, ast_channel_context(chan), p->dtmf_buf, 1, p->cid_num)) {
03062          if (!res || !ast_matchmore_extension(chan, ast_channel_context(chan), p->dtmf_buf, 1, p->cid_num)) {
03063             if (getforward) {
03064                /* Record this as the forwarding extension */
03065                ast_copy_string(p->call_forward, p->dtmf_buf, sizeof(p->call_forward));
03066                ast_verb(3, "Setting call forward to '%s' on channel %s\n",
03067                      p->call_forward, ast_channel_name(chan));
03068                /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
03069                transmit_notify_request(sub, "L/sl");
03070                if (res)
03071                   break;
03072                usleep(500000);
03073                /*res = tone_zone_play_tone(p->subs[index].zfd, -1);*/
03074                ast_indicate(chan, -1);
03075                sleep(1);
03076                memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
03077                /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALTONE);*/
03078                transmit_notify_request(sub, "L/dl");
03079                len = 0;
03080                getforward = 0;
03081             } else {
03082                /*res = tone_zone_play_tone(p->subs[index].zfd, -1);*/
03083                ast_indicate(chan, -1);
03084                ast_channel_lock(chan);
03085                ast_channel_exten_set(chan, p->dtmf_buf);
03086                ast_channel_dialed(chan)->number.str = ast_strdup(p->dtmf_buf);
03087                memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
03088                ast_set_callerid(chan,
03089                   p->hidecallerid ? "" : p->cid_num,
03090                   p->hidecallerid ? "" : p->cid_name,
03091                   ast_channel_caller(chan)->ani.number.valid ? NULL : p->cid_num);
03092                ast_setstate(chan, AST_STATE_RING);
03093                ast_channel_unlock(chan);
03094                if (p->dtmfmode & MGCP_DTMF_HYBRID) {
03095                   p->dtmfmode |= MGCP_DTMF_INBAND;
03096                   ast_indicate(chan, -1);
03097                }
03098                res = ast_pbx_run(chan);
03099                if (res) {
03100                   ast_log(LOG_WARNING, "PBX exited non-zero\n");
03101                   /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_CONGESTION);*/
03102                   /*transmit_notify_request(p, "nbz", 1);*/
03103                   transmit_notify_request(sub, p->ncs ? "L/cg" : "G/cg");
03104                }
03105                return NULL;
03106             }
03107          } else {
03108             /* It's a match, but they just typed a digit, and there is an ambiguous match,
03109                so just set the timeout to matchdigittimeout and wait some more */
03110             timeout = matchdigittimeout;
03111          }
03112       } else if (res == 0) {
03113          ast_debug(1, "not enough digits (and no ambiguous match)...\n");
03114          /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_CONGESTION);*/
03115          transmit_notify_request(sub, p->ncs ? "L/cg" : "G/cg");
03116          /*dahdi_wait_event(p->subs[index].zfd);*/
03117          ast_hangup(chan);
03118          memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
03119          return NULL;
03120       } else if (p->hascallwaiting && p->callwaiting && !strcmp(p->dtmf_buf, "*70")) {
03121          ast_verb(3, "Disabling call waiting on %s\n", ast_channel_name(chan));
03122          /* Disable call waiting if enabled */
03123          p->callwaiting = 0;
03124          /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
03125          transmit_notify_request(sub, "L/sl");
03126          len = 0;
03127          memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
03128          timeout = firstdigittimeout;
03129       } else if (!strcmp(p->dtmf_buf, pickupexten)) {
03130          /* Scan all channels and see if any there
03131           * ringing channqels with that have call groups
03132           * that equal this channels pickup group
03133           */
03134          if (ast_pickup_call(chan)) {
03135             ast_log(LOG_WARNING, "No call pickup possible...\n");
03136             /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_CONGESTION);*/
03137             transmit_notify_request(sub, p->ncs ? "L/cg" : "G/cg");
03138          }
03139          memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
03140          ast_hangup(chan);
03141          return NULL;
03142       } else if (!p->hidecallerid && !strcmp(p->dtmf_buf, "*67")) {
03143          ast_verb(3, "Disabling Caller*ID on %s\n", ast_channel_name(chan));
03144          /* Disable Caller*ID if enabled */
03145          p->hidecallerid = 1;
03146          ast_set_callerid(chan, "", "", NULL);
03147          /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
03148          transmit_notify_request(sub, "L/sl");
03149          len = 0;
03150          memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
03151          timeout = firstdigittimeout;
03152       } else if (p->callreturn && !strcmp(p->dtmf_buf, "*69")) {
03153          res = 0;
03154          if (!ast_strlen_zero(p->lastcallerid)) {
03155             res = ast_say_digit_str(chan, p->lastcallerid, "", ast_channel_language(chan));
03156          }
03157          if (!res)
03158             /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
03159             transmit_notify_request(sub, "L/sl");
03160          break;
03161       } else if (!strcmp(p->dtmf_buf, "*78")) {
03162          /* Do not disturb */
03163          ast_verb(3, "Enabled DND on channel %s\n", ast_channel_name(chan));
03164          /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
03165          transmit_notify_request(sub, "L/sl");
03166          p->dnd = 1;
03167          getforward = 0;
03168          memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
03169          len = 0;
03170       } else if (!strcmp(p->dtmf_buf, "*79")) {
03171          /* Do not disturb */
03172          ast_verb(3, "Disabled DND on channel %s\n", ast_channel_name(chan));
03173          /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
03174          transmit_notify_request(sub, "L/sl");
03175          p->dnd = 0;
03176          getforward = 0;
03177          memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
03178          len = 0;
03179       } else if (p->cancallforward && !strcmp(p->dtmf_buf, "*72")) {
03180          /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
03181          transmit_notify_request(sub, "L/sl");
03182          getforward = 1;
03183          memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
03184          len = 0;
03185       } else if (p->cancallforward && !strcmp(p->dtmf_buf, "*73")) {
03186          ast_verb(3, "Cancelling call forwarding on channel %s\n", ast_channel_name(chan));
03187          /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
03188          transmit_notify_request(sub, "L/sl");
03189          memset(p->call_forward, 0, sizeof(p->call_forward));
03190          getforward = 0;
03191          memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
03192          len = 0;
03193       } else if (ast_parking_provider_registered() && ast_parking_is_exten_park(ast_channel_context(chan), p->dtmf_buf) &&
03194          sub->next->owner) {
03195          RAII_VAR(struct ast_bridge_channel *, bridge_channel, NULL, ao2_cleanup);
03196          /* This is a three way call, the main call being a real channel,
03197             and we're parking the first call. */
03198          ast_channel_lock(chan);
03199          bridge_channel = ast_channel_get_bridge_channel(chan);
03200          ast_channel_unlock(chan);
03201          if (bridge_channel && !ast_parking_blind_transfer_park(bridge_channel, ast_channel_context(chan), p->dtmf_buf, NULL, NULL)) {
03202             ast_verb(3, "Parking call to '%s'\n", ast_channel_name(chan));
03203          }
03204          break;
03205       } else if (!ast_strlen_zero(p->lastcallerid) && !strcmp(p->dtmf_buf, "*60")) {
03206          ast_verb(3, "Blacklisting number %s\n", p->lastcallerid);
03207          res = ast_db_put("blacklist", p->lastcallerid, "1");
03208          if (!res) {
03209             /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
03210             transmit_notify_request(sub, "L/sl");
03211             memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
03212             len = 0;
03213          }
03214       } else if (p->hidecallerid && !strcmp(p->dtmf_buf, "*82")) {
03215          ast_verb(3, "Enabling Caller*ID on %s\n", ast_channel_name(chan));
03216          /* Enable Caller*ID if enabled */
03217          p->hidecallerid = 0;
03218          ast_set_callerid(chan, p->cid_num, p->cid_name, NULL);
03219          /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
03220          transmit_notify_request(sub, "L/sl");
03221          len = 0;
03222          memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
03223          timeout = firstdigittimeout;
03224       } else if (!ast_canmatch_extension(chan, ast_channel_context(chan), p->dtmf_buf, 1,
03225          S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))
03226          && ((p->dtmf_buf[0] != '*') || (strlen(p->dtmf_buf) > 2))) {
03227          ast_debug(1, "Can't match %s from '%s' in context %s\n", p->dtmf_buf,
03228             S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, "<Unknown Caller>"),
03229             ast_channel_context(chan));
03230          break;
03231       }
03232       if (!timeout)
03233          timeout = gendigittimeout;
03234       if (len && !ast_ignore_pattern(ast_channel_context(chan), p->dtmf_buf))
03235          /*tone_zone_play_tone(p->subs[index].zfd, -1);*/
03236          ast_indicate(chan, -1);
03237    }
03238 #if 0
03239    for (;;) {
03240       res = ast_waitfordigit(chan, to);
03241       if (!res) {
03242          ast_debug(1, "Timeout...\n");
03243          break;
03244       }
03245       if (res < 0) {
03246          ast_debug(1, "Got hangup...\n");
03247          ast_hangup(chan);
03248          break;
03249       }
03250       exten[pos++] = res;
03251       if (!ast_ignore_pattern(chan->context, exten))
03252          ast_indicate(chan, -1);
03253       if (ast_matchmore_extension(chan, chan->context, exten, 1, chan->callerid)) {
03254          if (ast_exists_extension(chan, chan->context, exten, 1, chan->callerid))
03255             to = 3000;
03256          else
03257             to = 8000;
03258       } else
03259          break;
03260    }
03261    if (ast_exists_extension(chan, chan->context, exten, 1, chan->callerid)) {
03262       ast_copy_string(chan->exten, exten, sizeof(chan->exten)1);
03263       if (!p->rtp) {
03264          start_rtp(p);
03265       }
03266       ast_setstate(chan, AST_STATE_RING);
03267       chan->rings = 1;
03268       if (ast_pbx_run(chan)) {
03269          ast_log(LOG_WARNING, "Unable to launch PBX on %s\n", chan->name);
03270       } else {
03271          memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
03272          return NULL;
03273       }
03274    }
03275 #endif
03276    ast_hangup(chan);
03277    memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
03278    return NULL;
03279 }
03280 
03281 /*! \brief Complete an attended transfer
03282  *
03283  * \param p The endpoint performing the attended transfer
03284  * \param sub The sub-channel completing the attended transfer
03285  *
03286  * \note p->sub is the currently active sub-channel (the channel the phone is using)
03287  * \note p->sub->next is the sub-channel not in use, potentially on hold
03288  *
03289  * \retval 0 when channel should be hung up
03290  * \retval 1 when channel should not be hung up
03291  */
03292 static int attempt_transfer(struct mgcp_endpoint *p, struct mgcp_subchannel *sub)
03293 {
03294    enum ast_transfer_result res;
03295 
03296    /* Ensure that the other channel goes off hold and that it is indicating properly */
03297    ast_queue_unhold(sub->next->owner);
03298    if (ast_channel_state(sub->owner) == AST_STATE_RINGING) {
03299       ast_queue_control(sub->next->owner, AST_CONTROL_RINGING);
03300    }
03301 
03302    ast_mutex_unlock(&p->sub->next->lock);
03303    ast_mutex_unlock(&p->sub->lock);
03304    res = ast_bridge_transfer_attended(sub->owner, sub->next->owner);
03305 
03306    /* Subs are only freed when the endpoint itself is destroyed, so they will continue to exist
03307     * after ast_bridge_transfer_attended returns making this safe without reference counting
03308     */
03309    ast_mutex_lock(&p->sub->lock);
03310    ast_mutex_lock(&p->sub->next->lock);
03311 
03312    if (res != AST_BRIDGE_TRANSFER_SUCCESS) {
03313       /* If transferring fails hang up the other channel if present and us */
03314       if (sub->next->owner) {
03315          ast_channel_softhangup_internal_flag_add(sub->next->owner, AST_SOFTHANGUP_DEV);
03316          mgcp_queue_hangup(sub->next);
03317       }
03318       sub->next->alreadygone = 1;
03319       return 0;
03320    }
03321 
03322    unalloc_sub(sub->next);
03323 
03324    /* If the active sub is NOT the one completing the transfer change it to be, and hang up the other sub */
03325    if (p->sub != sub) {
03326       p->sub = sub;
03327       return 1;
03328    }
03329 
03330    return 0;
03331 }
03332 
03333 static void handle_hd_hf(struct mgcp_subchannel *sub, char *ev)
03334 {
03335    struct mgcp_endpoint *p = sub->parent;
03336    struct ast_channel *c;
03337    pthread_t t;
03338 
03339    /* Off hook / answer */
03340    if (sub->outgoing) {
03341       /* Answered */
03342       if (sub->owner) {
03343          ast_queue_unhold(sub->owner);
03344          sub->cxmode = MGCP_CX_SENDRECV;
03345          if (!sub->rtp) {
03346             start_rtp(sub);
03347          } else {
03348             transmit_modify_request(sub);
03349          }
03350          /*transmit_notify_request(sub, "aw");*/
03351          transmit_notify_request(sub, "");
03352          mgcp_queue_control(sub, AST_CONTROL_ANSWER);
03353       }
03354    } else {
03355       /* Start switch */
03356       /*sub->cxmode = MGCP_CX_SENDRECV;*/
03357       if (!sub->owner) {
03358          if (!sub->rtp) {
03359             start_rtp(sub);
03360          } else {
03361             transmit_modify_request(sub);
03362          }
03363          if (p->immediate) {
03364             /* The channel is immediately up. Start right away */
03365 #ifdef DLINK_BUGGY_FIRMWARE
03366             transmit_notify_request(sub, "rt");
03367 #else
03368             transmit_notify_request(sub, p->ncs ? "L/rt" : "G/rt");
03369 #endif
03370             c = mgcp_new(sub, AST_STATE_RING, NULL, NULL);
03371             if (!c) {
03372                ast_log(LOG_WARNING, "Unable to start PBX on channel %s@%s\n", p->name, p->parent->name);
03373                transmit_notify_request(sub, p->ncs ? "L/cg" : "G/cg");
03374                ast_hangup(c);
03375             }
03376          } else {
03377             if (has_voicemail(p)) {
03378                transmit_notify_request(sub, "L/sl");
03379             } else {
03380                transmit_notify_request(sub, "L/dl");
03381             }
03382             c = mgcp_new(sub, AST_STATE_DOWN, NULL, NULL);
03383             if (c) {
03384                if (ast_pthread_create_detached(&t, NULL, mgcp_ss, c)) {
03385                   ast_log(LOG_WARNING, "Unable to create switch thread: %s\n", strerror(errno));
03386                   ast_hangup(c);
03387                }
03388             } else {
03389                ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", p->name, p->parent->name);
03390             }
03391          }
03392       } else {
03393          if (p->hookstate == MGCP_OFFHOOK) {
03394             ast_log(LOG_WARNING, "Off hook, but already have owner on %s@%s\n", p->name, p->parent->name);
03395          } else {
03396             ast_log(LOG_WARNING, "On hook, but already have owner on %s@%s\n", p->name, p->parent->name);
03397             ast_log(LOG_WARNING, "If we're onhook why are we here trying to handle a hd or hf?\n");
03398          }
03399          ast_queue_unhold(sub->owner);
03400          sub->cxmode = MGCP_CX_SENDRECV;
03401          if (!sub->rtp) {
03402             start_rtp(sub);
03403          } else {
03404             transmit_modify_request(sub);
03405          }
03406          /*transmit_notify_request(sub, "aw");*/
03407          transmit_notify_request(sub, "");
03408          /*ast_queue_control(sub->owner, AST_CONTROL_ANSWER);*/
03409       }
03410    }
03411 }
03412 
03413 static int handle_request(struct mgcp_subchannel *sub, struct mgcp_request *req, struct sockaddr_in *sin)
03414 {
03415    char *ev, *s;
03416    struct ast_frame f = { 0, };
03417    struct mgcp_endpoint *p = sub->parent;
03418    struct mgcp_gateway *g = NULL;
03419    int res;
03420 
03421    ast_debug(1, "Handling request '%s' on %s@%s\n", req->verb, p->name, p->parent->name);
03422    /* Clear out potential response */
03423    if (!strcasecmp(req->verb, "RSIP")) {
03424       /* Test if this RSIP request is just a keepalive */
03425       if (!strcasecmp( get_header(req, "RM"), "X-keepalive")) {
03426          ast_verb(3, "Received keepalive request from %s@%s\n", p->name, p->parent->name);
03427          transmit_response(sub, "200", req, "OK");
03428       } else {
03429          dump_queue(p->parent, p);
03430          dump_cmd_queues(p, NULL);
03431 
03432          if ((strcmp(p->name, p->parent->wcardep) != 0)) {
03433             ast_verb(3, "Resetting interface %s@%s\n", p->name, p->parent->name);
03434          }
03435          /* For RSIP on wildcard we reset all endpoints */
03436          if (!strcmp(p->name, p->parent->wcardep)) {
03437             /* Reset all endpoints */
03438             struct mgcp_endpoint *tmp_ep;
03439 
03440             g = p->parent;
03441             for (tmp_ep = g->endpoints; tmp_ep; tmp_ep = tmp_ep->next) {
03442                /*if ((strcmp(tmp_ep->name, "*") != 0) && (strcmp(tmp_ep->name, "aaln/" "*") != 0)) {*/
03443                if (strcmp(tmp_ep->name, g->wcardep) != 0) {
03444                   struct mgcp_subchannel *tmp_sub, *first_sub;
03445                   ast_verb(3, "Resetting interface %s@%s\n", tmp_ep->name, p->parent->name);
03446 
03447                   first_sub = tmp_ep->sub;
03448                   tmp_sub = tmp_ep->sub;
03449                   while (tmp_sub) {
03450                      mgcp_queue_hangup(tmp_sub);
03451                      tmp_sub = tmp_sub->next;
03452                      if (tmp_sub == first_sub)
03453                         break;
03454                   }
03455                }
03456             }
03457          } else if (sub->owner) {
03458             mgcp_queue_hangup(sub);
03459          }
03460          transmit_response(sub, "200", req, "OK");
03461          /* We don't send NTFY or AUEP to wildcard ep */
03462          if (strcmp(p->name, p->parent->wcardep) != 0) {
03463             transmit_notify_request(sub, "");
03464             /* Audit endpoint.
03465              Idea is to prevent lost lines due to race conditions
03466             */
03467             transmit_audit_endpoint(p);
03468          }
03469       }
03470    } else if (!strcasecmp(req->verb, "NTFY")) {
03471       /* Acknowledge and be sure we keep looking for the same things */
03472       transmit_response(sub, "200", req, "OK");
03473       /* Notified of an event */
03474       ev = get_header(req, "O");
03475       s = strchr(ev, '/');
03476       if (s) ev = s + 1;
03477       ast_debug(1, "Endpoint '%s@%s-%d' observed '%s'\n", p->name, p->parent->name, sub->id, ev);
03478       /* Keep looking for events unless this was a hangup */
03479       if (strcasecmp(ev, "hu") && strcasecmp(ev, "hd") && strcasecmp(ev, "ping")) {
03480          transmit_notify_request(sub, p->curtone);
03481       }
03482       if (!strcasecmp(ev, "hd")) {
03483          p->hookstate = MGCP_OFFHOOK;
03484          sub->cxmode = MGCP_CX_SENDRECV;
03485 
03486          if (p) {
03487            /* When the endpoint have a Off hook transition we allways
03488               starts without any previous dtmfs */
03489            memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
03490          }
03491 
03492          handle_hd_hf(sub, ev);
03493       } else if (!strcasecmp(ev, "hf")) {
03494          /* We can assume we are offhook if we received a hookflash */
03495          /* First let's just do call wait and ignore threeway */
03496          /* We're currently in charge */
03497          if (p->hookstate != MGCP_OFFHOOK) {
03498             /* Cisco c7940 sends hf even if the phone is onhook */
03499             /* Thanks to point on IRC for pointing this out */
03500             return -1;
03501          }
03502          /* do not let * conference two down channels */
03503          if (sub->owner && ast_channel_state(sub->owner) == AST_STATE_DOWN && !sub->next->owner)
03504             return -1;
03505 
03506          if (p->callwaiting || p->transfer || p->threewaycalling) {
03507             ast_verb(3, "Swapping %d for %d on %s@%s\n", p->sub->id, p->sub->next->id, p->name, p->parent->name);
03508             p->sub = p->sub->next;
03509 
03510             /* transfer control to our next subchannel */
03511             if (!sub->next->owner) {
03512                /* plave the first call on hold and start up a new call */
03513                sub->cxmode = MGCP_CX_MUTE;
03514                ast_verb(3, "MGCP Muting %d on %s@%s\n", sub->id, p->name, p->parent->name);
03515                transmit_modify_request(sub);
03516                if (sub->owner) {
03517                   ast_queue_hold(sub->owner, NULL);
03518                }
03519                sub->next->cxmode = MGCP_CX_RECVONLY;
03520                handle_hd_hf(sub->next, ev);
03521             } else if (sub->owner && sub->next->owner) {
03522                /* We've got two active calls lets decide whether or not to conference or just flip flop */
03523                if ((!sub->outgoing) && (!sub->next->outgoing)) {
03524                   /* We made both calls lets conference */
03525                   ast_verb(3, "MGCP Conferencing %d and %d on %s@%s\n",
03526                         sub->id, sub->next->id, p->name, p->parent->name);
03527                   sub->cxmode = MGCP_CX_CONF;
03528                   sub->next->cxmode = MGCP_CX_CONF;
03529                   ast_queue_unhold(sub->next->owner);
03530                   transmit_modify_request(sub);
03531                   transmit_modify_request(sub->next);
03532                } else {
03533                   /* Let's flipflop between calls */
03534                   /* XXX Need to check for state up ??? */
03535                   /* XXX Need a way to indicate the current call, or maybe the call that's waiting */
03536                   ast_verb(3, "We didn't make one of the calls FLIPFLOP %d and %d on %s@%s\n",
03537                         sub->id, sub->next->id, p->name, p->parent->name);
03538                   sub->cxmode = MGCP_CX_MUTE;
03539                   ast_verb(3, "MGCP Muting %d on %s@%s\n", sub->id, p->name, p->parent->name);
03540                   transmit_modify_request(sub);
03541 
03542                   ast_queue_hold(sub->owner, NULL);
03543                   ast_queue_hold(sub->next->owner, NULL);
03544 
03545                   handle_hd_hf(sub->next, ev);
03546                }
03547             } else {
03548                /* We've most likely lost one of our calls find an active call and bring it up */
03549                if (sub->owner) {
03550                   p->sub = sub;
03551                } else if (sub->next->owner) {
03552                   p->sub = sub->next;
03553                } else {
03554                   /* We seem to have lost both our calls */
03555                   /* XXX - What do we do now? */
03556                   return -1;
03557                }
03558                ast_queue_unhold(p->sub->owner);
03559                p->sub->cxmode = MGCP_CX_SENDRECV;
03560                transmit_modify_request(p->sub);
03561             }
03562          } else {
03563             ast_log(LOG_WARNING, "Callwaiting, call transfer or threeway calling not enabled on endpoint %s@%s\n",
03564                p->name, p->parent->name);
03565          }
03566       } else if (!strcasecmp(ev, "hu")) {
03567          p->hookstate = MGCP_ONHOOK;
03568          sub->cxmode = MGCP_CX_RECVONLY;
03569          ast_debug(1, "MGCP %s@%s Went on hook\n", p->name, p->parent->name);
03570          /* Do we need to send MDCX before a DLCX ?
03571          if (sub->rtp) {
03572             transmit_modify_request(sub);
03573          }
03574          */
03575          if (p->transfer && (sub->owner && sub->next->owner) && ((!sub->outgoing) || (!sub->next->outgoing))) {
03576             /* We're allowed to transfer, we have two avtive calls and */
03577             /* we made at least one of the calls.  Let's try and transfer */
03578             ast_mutex_lock(&p->sub->next->lock);
03579             res = attempt_transfer(p, sub);
03580             if (res) {
03581                ast_log(LOG_WARNING, "Transfer attempt failed\n");
03582                ast_mutex_unlock(&p->sub->next->lock);
03583                return -1;
03584             }
03585             ast_mutex_unlock(&p->sub->next->lock);
03586          } else {
03587             /* Hangup the current call */
03588             /* If there is another active call, mgcp_hangup will ring the phone with the other call */
03589             if (sub->owner) {
03590                sub->alreadygone = 1;
03591                mgcp_queue_hangup(sub);
03592             } else {
03593                ast_verb(3, "MGCP handle_request(%s@%s-%d) ast_channel already destroyed, resending DLCX.\n",
03594                      p->name, p->parent->name, sub->id);
03595                /* Instruct the other side to remove the connection since it apparently *
03596                 * still thinks the channel is active. *
03597                 * For Cisco IAD2421 /BAK/ */
03598                transmit_connection_del(sub);
03599             }
03600          }
03601          if ((p->hookstate == MGCP_ONHOOK) && (!sub->rtp) && (!sub->next->rtp)) {
03602             p->hidecallerid = 0;
03603             if (p->hascallwaiting && !p->callwaiting) {
03604                ast_verb(3, "Enabling call waiting on MGCP/%s@%s-%d\n", p->name, p->parent->name, sub->id);
03605                p->callwaiting = -1;
03606             }
03607             if (has_voicemail(p)) {
03608                ast_verb(3, "MGCP handle_request(%s@%s) set vmwi(+)\n", p->name, p->parent->name);
03609                transmit_notify_request(sub, "L/vmwi(+)");
03610             } else {
03611                ast_verb(3, "MGCP handle_request(%s@%s) set vmwi(-)\n", p->name, p->parent->name);
03612                transmit_notify_request(sub, "L/vmwi(-)");
03613             }
03614          }
03615       } else if ((strlen(ev) == 1) &&
03616             (((ev[0] >= '0') && (ev[0] <= '9')) ||
03617              ((ev[0] >= 'A') && (ev[0] <= 'D')) ||
03618               (ev[0] == '*') || (ev[0] == '#'))) {
03619          if (sub && sub->owner && (ast_channel_state(sub->owner) >=  AST_STATE_UP)) {
03620             f.frametype = AST_FRAME_DTMF;
03621             f.subclass.integer = ev[0];
03622             f.src = "mgcp";
03623             /* XXX MUST queue this frame to all subs in threeway call if threeway call is active */
03624             mgcp_queue_frame(sub, &f);
03625             ast_mutex_lock(&sub->next->lock);
03626             if (sub->next->owner)
03627                mgcp_queue_frame(sub->next, &f);
03628             ast_mutex_unlock(&sub->next->lock);
03629             if (strstr(p->curtone, (p->ncs ? "wt1" : "wt")) && (ev[0] == 'A')) {
03630                memset(p->curtone, 0, sizeof(p->curtone));
03631             }
03632          } else {
03633             p->dtmf_buf[strlen(p->dtmf_buf)] = ev[0];
03634             p->dtmf_buf[strlen(p->dtmf_buf)] = '\0';
03635          }
03636       } else if (!strcasecmp(ev, "T")) {
03637          /* Digit timeout -- unimportant */
03638       } else if (!strcasecmp(ev, "ping")) {
03639          /* ping -- unimportant */
03640       } else {
03641          ast_log(LOG_NOTICE, "Received unknown event '%s' from %s@%s\n", ev, p->name, p->parent->name);
03642       }
03643    } else {
03644       ast_log(LOG_WARNING, "Unknown verb '%s' received from %s\n", req->verb, ast_inet_ntoa(sin->sin_addr));
03645       transmit_response(sub, "510", req, "Unknown verb");
03646    }
03647    return 0;
03648 }
03649 
03650 static int find_and_retrans(struct mgcp_subchannel *sub, struct mgcp_request *req)
03651 {
03652    int seqno=0;
03653    time_t now;
03654    struct mgcp_response *prev = NULL, *cur, *next, *answer = NULL;
03655    time(&now);
03656    if (sscanf(req->identifier, "%30d", &seqno) != 1) {
03657       seqno = 0;
03658    }
03659    for (cur = sub->parent->parent->responses, next = cur ? cur->next : NULL; cur; cur = next, next = cur ? cur->next : NULL) {
03660       if (now - cur->whensent > RESPONSE_TIMEOUT) {
03661          /* Delete this entry */
03662          if (prev)
03663             prev->next = next;
03664          else
03665             sub->parent->parent->responses = next;
03666          ast_free(cur);
03667       } else {
03668          if (seqno == cur->seqno)
03669             answer = cur;
03670          prev = cur;
03671       }
03672    }
03673    if (answer) {
03674       resend_response(sub, answer);
03675       return 1;
03676    }
03677    return 0;
03678 }
03679 
03680 static int mgcpsock_read(int *id, int fd, short events, void *ignore)
03681 {
03682    struct mgcp_request req;
03683    struct sockaddr_in sin;
03684    struct mgcp_subchannel *sub;
03685    int res;
03686    socklen_t len;
03687    int result;
03688    int ident;
03689    len = sizeof(sin);
03690    memset(&req, 0, sizeof(req));
03691    res = recvfrom(mgcpsock, req.data, sizeof(req.data) - 1, 0, (struct sockaddr *)&sin, &len);
03692    if (res < 0) {
03693       if (errno != ECONNREFUSED)
03694          ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
03695       return 1;
03696    }
03697    req.data[res] = '\0';
03698    req.len = res;
03699    ast_debug(1, "MGCP read: \n%s\nfrom %s:%d\n", req.data, ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
03700    parse(&req);
03701    if (req.headers < 1) {
03702       /* Must have at least one header */
03703       return 1;
03704    }
03705    if (ast_strlen_zero(req.identifier)) {
03706       ast_log(LOG_NOTICE, "Message from %s missing identifier\n", ast_inet_ntoa(sin.sin_addr));
03707       return 1;
03708    }
03709 
03710    if (sscanf(req.verb, "%30d", &result) && sscanf(req.identifier, "%30d", &ident)) {
03711       if (result < 200) {
03712          ast_debug(1, "Ignoring provisional response on transaction %d\n", ident);
03713          return 1;
03714       }
03715       /* Try to find who this message is for, if it's important */
03716       sub = find_subchannel_and_lock(NULL, ident, &sin);
03717       if (sub) {
03718          struct mgcp_gateway *gw = sub->parent->parent;
03719          struct mgcp_message *cur, *prev;
03720 
03721          ast_mutex_unlock(&sub->lock);
03722          ast_mutex_lock(&gw->msgs_lock);
03723          for (prev = NULL, cur = gw->msgs; cur; prev = cur, cur = cur->next) {
03724             if (cur->seqno == ident) {
03725                ast_debug(1, "Got response back on transaction %d\n", ident);
03726                if (prev)
03727                   prev->next = cur->next;
03728                else
03729                   gw->msgs = cur->next;
03730                break;
03731             }
03732          }
03733 
03734          /* stop retrans timer if the queue is empty */
03735          if (!gw->msgs) {
03736             AST_SCHED_DEL(sched, gw->retransid);
03737          }
03738 
03739          ast_mutex_unlock(&gw->msgs_lock);
03740          if (cur) {
03741             handle_response(cur->owner_ep, cur->owner_sub, result, ident, &req);
03742             ast_free(cur);
03743             return 1;
03744          }
03745 
03746          ast_log(LOG_NOTICE, "Got response back on [%s] for transaction %d we aren't sending?\n",
03747             gw->name, ident);
03748       }
03749    } else {
03750       if (ast_strlen_zero(req.endpoint) ||
03751          ast_strlen_zero(req.version) ||
03752          ast_strlen_zero(req.verb)) {
03753          ast_log(LOG_NOTICE, "Message must have a verb, an idenitifier, version, and endpoint\n");
03754          return 1;
03755       }
03756       /* Process request, with iflock held */
03757       sub = find_subchannel_and_lock(req.endpoint, 0, &sin);
03758       if (sub) {
03759          /* look first to find a matching response in the queue */
03760          if (!find_and_retrans(sub, &req))
03761             /* pass the request off to the currently mastering subchannel */
03762             handle_request(sub, &req, &sin);
03763          ast_mutex_unlock(&sub->lock);
03764       }
03765    }
03766    return 1;
03767 }
03768 
03769 static int *mgcpsock_read_id = NULL;
03770 
03771 static int mgcp_prune_realtime_gateway(struct mgcp_gateway *g)
03772 {
03773    struct mgcp_endpoint *enext, *e;
03774    struct mgcp_subchannel *s, *sub;
03775    int i, prune = 1;
03776 
03777    if (g->ha || !g->realtime || ast_mutex_trylock(&g->msgs_lock) || g->msgs) {
03778       ast_mutex_unlock(&g->msgs_lock);
03779       return 0;
03780    }
03781 
03782    for (e = g->endpoints; e; e = e->next) {
03783       ast_mutex_lock(&e->lock);
03784       if (e->dsp || ast_mutex_trylock(&e->rqnt_queue_lock) || ast_mutex_trylock(&e->cmd_queue_lock)) {
03785          prune = 0;
03786       } else if (e->rqnt_queue || e->cmd_queue) {
03787          prune = 0;
03788       }
03789       s = e->sub;
03790       for (i = 0; (i < MAX_SUBS) && s; i++) {
03791          ast_mutex_lock(&s->lock);
03792          if (!ast_strlen_zero(s->cxident) || s->rtp || ast_mutex_trylock(&s->cx_queue_lock) || s->gate) {
03793             prune = 0;
03794          } else if (s->cx_queue) {
03795             prune = 0;
03796          }
03797          s = s->next;
03798       }
03799    }
03800 
03801    for (e = g->endpoints, sub = e->sub, enext = e->next; e; e = enext, enext = e->next) {
03802       for (i = 0; (i < MAX_SUBS) && sub; i++) {
03803          s = sub;
03804          sub = sub->next;
03805          ast_mutex_unlock(&s->lock);
03806          ast_mutex_unlock(&s->cx_queue_lock);
03807          if (prune) {
03808             ast_mutex_destroy(&s->lock);
03809             ast_mutex_destroy(&s->cx_queue_lock);
03810             ast_free(s);
03811          }
03812       }
03813       ast_mutex_unlock(&e->lock);
03814       ast_mutex_unlock(&e->rqnt_queue_lock);
03815       ast_mutex_unlock(&e->cmd_queue_lock);
03816       if (prune) {
03817          ast_mutex_destroy(&e->lock);
03818          ast_mutex_destroy(&e->rqnt_queue_lock);
03819          ast_mutex_destroy(&e->cmd_queue_lock);
03820          ast_free(e);
03821       }
03822    }
03823    if (prune) {
03824       ast_debug(1, "***** MGCP REALTIME PRUNE GW: %s\n", g->name);
03825    }
03826    return prune;
03827 }
03828 
03829 static void *do_monitor(void *data)
03830 {
03831    int res;
03832    int reloading;
03833    struct mgcp_gateway *g, *gprev;
03834    /*struct mgcp_gateway *g;*/
03835    /*struct mgcp_endpoint *e;*/
03836    /*time_t thispass = 0, lastpass = 0;*/
03837    time_t lastrun = 0;
03838 
03839    /* Add an I/O event to our UDP socket */
03840    if (mgcpsock > -1) {
03841       mgcpsock_read_id = ast_io_add(io, mgcpsock, mgcpsock_read, AST_IO_IN, NULL);
03842    }
03843    /* This thread monitors all the frame relay interfaces which are not yet in use
03844       (and thus do not have a separate thread) indefinitely */
03845    /* From here on out, we die whenever asked */
03846    for (;;) {
03847       /* Check for a reload request */
03848       ast_mutex_lock(&mgcp_reload_lock);
03849       reloading = mgcp_reloading;
03850       mgcp_reloading = 0;
03851       ast_mutex_unlock(&mgcp_reload_lock);
03852       if (reloading) {
03853          ast_verb(1, "Reloading MGCP\n");
03854          reload_config(1);
03855          /* Add an I/O event to our UDP socket */
03856          if (mgcpsock > -1 && !mgcpsock_read_id) {
03857             mgcpsock_read_id = ast_io_add(io, mgcpsock, mgcpsock_read, AST_IO_IN, NULL);
03858          }
03859       }
03860 
03861       /* Check for interfaces needing to be killed */
03862       /* Don't let anybody kill us right away.  Nobody should lock the interface list
03863          and wait for the monitor list, but the other way around is okay. */
03864       ast_mutex_lock(&monlock);
03865       /* Lock the network interface */
03866       ast_mutex_lock(&netlock);
03867 
03868 #if 0
03869       /* XXX THIS IS COMPLETELY HOSED */
03870       /* The gateway goes into a state of panic */
03871       /* If the vmwi indicator is sent while it is reseting interfaces */
03872       lastpass = thispass;
03873       thispass = time(NULL);
03874       g = gateways;
03875       while(g) {
03876          if (thispass != lastpass) {
03877             e = g->endpoints;
03878             while(e) {
03879                if (e->type == TYPE_LINE) {
03880                   res = has_voicemail(e);
03881                   if ((e->msgstate != res) && (e->hookstate == MGCP_ONHOOK) && (!e->rtp)){
03882                      if (res) {
03883                         transmit_notify_request(e, "L/vmwi(+)");
03884                      } else {
03885                         transmit_notify_request(e, "L/vmwi(-)");
03886                      }
03887                      e->msgstate = res;
03888                      e->onhooktime = thispass;
03889                   }
03890                }
03891                e = e->next;
03892             }
03893          }
03894          g = g->next;
03895       }
03896 #endif
03897       /* pruning unused realtime gateways, running in every 60 seconds*/
03898       if(time(NULL) > (lastrun + 60)) {
03899          ast_mutex_lock(&gatelock);
03900          g = gateways;
03901          gprev = NULL;
03902          while(g) {
03903             if(g->realtime) {
03904                if(mgcp_prune_realtime_gateway(g)) {
03905                   if(gprev) {
03906                      gprev->next = g->next;
03907                   } else {
03908                      gateways = g->next;
03909                   }
03910                   ast_mutex_unlock(&g->msgs_lock);
03911                   ast_mutex_destroy(&g->msgs_lock);
03912                   ast_free(g);
03913                } else {
03914                   ast_mutex_unlock(&g->msgs_lock);
03915                   gprev = g;
03916                }
03917             } else {
03918                gprev = g;
03919             }
03920             g = g->next;
03921          }
03922          ast_mutex_unlock(&gatelock);
03923          lastrun = time(NULL);
03924       }
03925       /* Okay, now that we know what to do, release the network lock */
03926       ast_mutex_unlock(&netlock);
03927       /* And from now on, we're okay to be killed, so release the monitor lock as well */
03928       ast_mutex_unlock(&monlock);
03929       pthread_testcancel();
03930       /* Wait for sched or io */
03931       res = ast_sched_wait(sched);
03932       /* copied from chan_sip.c */
03933       if ((res < 0) || (res > 1000)) {
03934          res = 1000;
03935       }
03936       res = ast_io_wait(io, res);
03937       ast_mutex_lock(&monlock);
03938       if (res >= 0) {
03939          ast_sched_runq(sched);
03940       }
03941       ast_mutex_unlock(&monlock);
03942    }
03943    /* Never reached */
03944    return NULL;
03945 }
03946 
03947 static int restart_monitor(void)
03948 {
03949    /* If we're supposed to be stopped -- stay stopped */
03950    if (monitor_thread == AST_PTHREADT_STOP)
03951       return 0;
03952    if (ast_mutex_lock(&monlock)) {
03953       ast_log(LOG_WARNING, "Unable to lock monitor\n");
03954       return -1;
03955    }
03956    if (monitor_thread == pthread_self()) {
03957       ast_mutex_unlock(&monlock);
03958       ast_log(LOG_WARNING, "Cannot kill myself\n");
03959       return -1;
03960    }
03961    if (monitor_thread != AST_PTHREADT_NULL) {
03962       /* Wake up the thread */
03963       pthread_kill(monitor_thread, SIGURG);
03964    } else {
03965       /* Start a new monitor */
03966       if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
03967          ast_mutex_unlock(&monlock);
03968          ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
03969          return -1;
03970       }
03971    }
03972    ast_mutex_unlock(&monlock);
03973    return 0;
03974 }
03975 
03976 static struct ast_channel *mgcp_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *dest, int *cause)
03977 {
03978    struct mgcp_subchannel *sub;
03979    struct ast_channel *tmpc = NULL;
03980    char tmp[256];
03981 
03982    if (!(ast_format_cap_iscompatible(cap, global_capability))) {
03983       struct ast_str *cap_buf = ast_str_alloca(64);
03984       ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%s'\n",
03985          ast_format_cap_get_names(cap, &cap_buf));
03986       /*return NULL;*/
03987    }
03988    ast_copy_string(tmp, dest, sizeof(tmp));
03989    if (ast_strlen_zero(tmp)) {
03990       ast_log(LOG_NOTICE, "MGCP Channels require an endpoint\n");
03991       return NULL;
03992    }
03993    if (!(sub = find_subchannel_and_lock(tmp, 0, NULL))) {
03994       ast_log(LOG_WARNING, "Unable to find MGCP endpoint '%s'\n", tmp);
03995       *cause = AST_CAUSE_UNREGISTERED;
03996       return NULL;
03997    }
03998 
03999    ast_verb(3, "MGCP mgcp_request(%s)\n", tmp);
04000    ast_verb(3, "MGCP cw: %d, dnd: %d, so: %d, sno: %d\n",
04001          sub->parent->callwaiting, sub->parent->dnd, sub->owner ? 1 : 0, sub->next->owner ? 1: 0);
04002    /* Must be busy */
04003    if (((sub->parent->callwaiting) && ((sub->owner) && (sub->next->owner))) ||
04004       ((!sub->parent->callwaiting) && (sub->owner)) ||
04005        (sub->parent->dnd && (ast_strlen_zero(sub->parent->call_forward)))) {
04006       if (sub->parent->hookstate == MGCP_ONHOOK) {
04007          if (has_voicemail(sub->parent)) {
04008             transmit_notify_request(sub,"L/vmwi(+)");
04009          } else {
04010             transmit_notify_request(sub,"L/vmwi(-)");
04011          }
04012       }
04013       *cause = AST_CAUSE_BUSY;
04014       ast_mutex_unlock(&sub->lock);
04015       return NULL;
04016    }
04017    tmpc = mgcp_new(sub->owner ? sub->next : sub, AST_STATE_DOWN, assignedids, requestor);
04018    ast_mutex_unlock(&sub->lock);
04019    if (!tmpc)
04020       ast_log(LOG_WARNING, "Unable to make channel for '%s'\n", tmp);
04021    restart_monitor();
04022    return tmpc;
04023 }
04024 
04025 /* modified for reload support */
04026 /*! \brief  build_gateway: parse mgcp.conf and create gateway/endpoint structures */
04027 static struct mgcp_gateway *build_gateway(char *cat, struct ast_variable *v)
04028 {
04029    struct mgcp_gateway *gw;
04030    struct mgcp_endpoint *e;
04031    struct mgcp_subchannel *sub;
04032    struct ast_variable *chanvars = NULL;
04033 
04034    /*char txident[80];*/
04035    int i=0, y=0;
04036    int gw_reload = 0;
04037    int ep_reload = 0;
04038    directmedia = DIRECTMEDIA;
04039 
04040    /* locate existing gateway */
04041    for (gw = gateways; gw; gw = gw->next) {
04042       if (!strcasecmp(cat, gw->name)) {
04043          /* gateway already exists */
04044          gw->delme = 0;
04045          gw_reload = 1;
04046          break;
04047       }
04048    }
04049 
04050    if (!gw && !(gw = ast_calloc(1, sizeof(*gw)))) {
04051       return NULL;
04052    }
04053 
04054    if (!gw_reload) {
04055       gw->expire = -1;
04056       gw->realtime = 0;
04057       gw->retransid = -1;
04058       ast_mutex_init(&gw->msgs_lock);
04059       ast_copy_string(gw->name, cat, sizeof(gw->name));
04060       /* check if the name is numeric ip */
04061       if ((strchr(gw->name, '.')) && inet_addr(gw->name) != INADDR_NONE)
04062          gw->isnamedottedip = 1;
04063    }
04064    for (; v; v = v->next) {
04065       if (!strcasecmp(v->name, "host")) {
04066          if (!strcasecmp(v->value, "dynamic")) {
04067             /* They'll register with us */
04068             gw->dynamic = 1;
04069             memset(&gw->addr.sin_addr, 0, 4);
04070             if (gw->addr.sin_port) {
04071                /* If we've already got a port, make it the default rather than absolute */
04072                gw->defaddr.sin_port = gw->addr.sin_port;
04073                gw->addr.sin_port = 0;
04074             }
04075          } else {
04076             /* Non-dynamic.  Make sure we become that way if we're not */
04077             AST_SCHED_DEL(sched, gw->expire);
04078             gw->dynamic = 0;
04079             {
04080                struct ast_sockaddr tmp;
04081 
04082                ast_sockaddr_from_sin(&tmp, &gw->addr);
04083                if (ast_get_ip(&tmp, v->value)) {
04084                   if (!gw_reload) {
04085                      ast_mutex_destroy(&gw->msgs_lock);
04086                      ast_free(gw);
04087                   }
04088                   return NULL;
04089                }
04090                ast_sockaddr_to_sin(&tmp, &gw->addr);
04091             }
04092          }
04093       } else if (!strcasecmp(v->name, "defaultip")) {
04094          struct ast_sockaddr tmp;
04095 
04096          ast_sockaddr_from_sin(&tmp, &gw->defaddr);
04097          if (ast_get_ip(&tmp, v->value)) {
04098             if (!gw_reload) {
04099                ast_mutex_destroy(&gw->msgs_lock);
04100                ast_free(gw);
04101             }
04102             return NULL;
04103          }
04104          ast_sockaddr_to_sin(&tmp, &gw->defaddr);
04105       } else if (!strcasecmp(v->name, "permit") ||
04106          !strcasecmp(v->name, "deny")) {
04107          gw->ha = ast_append_ha(v->name, v->value, gw->ha, NULL);
04108       } else if (!strcasecmp(v->name, "port")) {
04109          gw->addr.sin_port = htons(atoi(v->value));
04110       } else if (!strcasecmp(v->name, "context")) {
04111          ast_copy_string(context, v->value, sizeof(context));
04112       } else if (!strcasecmp(v->name, "dtmfmode")) {
04113          if (!strcasecmp(v->value, "inband"))
04114             dtmfmode = MGCP_DTMF_INBAND;
04115          else if (!strcasecmp(v->value, "rfc2833"))
04116             dtmfmode = MGCP_DTMF_RFC2833;
04117          else if (!strcasecmp(v->value, "hybrid"))
04118             dtmfmode = MGCP_DTMF_HYBRID;
04119          else if (!strcasecmp(v->value, "none"))
04120             dtmfmode = 0;
04121          else
04122             ast_log(LOG_WARNING, "'%s' is not a valid DTMF mode at line %d\n", v->value, v->lineno);
04123       } else if (!strcasecmp(v->name, "nat")) {
04124          nat = ast_true(v->value);
04125       } else if (!strcasecmp(v->name, "ncs")) {
04126          ncs = ast_true(v->value);
04127       } else if (!strcasecmp(v->name, "hangupongateremove")) {
04128          hangupongateremove = ast_true(v->value);
04129       } else if (!strcasecmp(v->name, "pktcgatealloc")) {
04130          pktcgatealloc = ast_true(v->value);
04131       } else if (!strcasecmp(v->name, "callerid")) {
04132          if (!strcasecmp(v->value, "asreceived")) {
04133             cid_num[0] = '\0';
04134             cid_name[0] = '\0';
04135          } else {
04136             ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
04137          }
04138       } else if (!strcasecmp(v->name, "language")) {
04139          ast_copy_string(language, v->value, sizeof(language));
04140       } else if (!strcasecmp(v->name, "accountcode")) {
04141          ast_copy_string(accountcode, v->value, sizeof(accountcode));
04142       } else if (!strcasecmp(v->name, "amaflags")) {
04143          y = ast_channel_string2amaflag(v->value);
04144          if (y < 0) {
04145             ast_log(LOG_WARNING, "Invalid AMA flags: %s at line %d\n", v->value, v->lineno);
04146          } else {
04147             amaflags = y;
04148          }
04149       } else if (!strcasecmp(v->name, "setvar")) {
04150          chanvars = add_var(v->value, chanvars);
04151       } else if (!strcasecmp(v->name, "clearvars")) {
04152          if (chanvars) {
04153             ast_variables_destroy(chanvars);
04154             chanvars = NULL;
04155          }
04156       } else if (!strcasecmp(v->name, "musiconhold")) {
04157          ast_copy_string(musicclass, v->value, sizeof(musicclass));
04158       } else if (!strcasecmp(v->name, "parkinglot")) {
04159          ast_copy_string(parkinglot, v->value, sizeof(parkinglot));
04160       } else if (!strcasecmp(v->name, "callgroup")) {
04161          cur_callergroup = ast_get_group(v->value);
04162       } else if (!strcasecmp(v->name, "pickupgroup")) {
04163          cur_pickupgroup = ast_get_group(v->value);
04164       } else if (!strcasecmp(v->name, "immediate")) {
04165          immediate = ast_true(v->value);
04166       } else if (!strcasecmp(v->name, "cancallforward")) {
04167          cancallforward = ast_true(v->value);
04168       } else if (!strcasecmp(v->name, "singlepath")) {
04169          singlepath = ast_true(v->value);
04170       } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
04171          directmedia = ast_true(v->value);
04172       } else if (!strcasecmp(v->name, "mailbox")) {
04173          ast_copy_string(mailbox, v->value, sizeof(mailbox));
04174       } else if (!strcasecmp(v->name, "hasvoicemail")) {
04175          if (ast_true(v->value) && ast_strlen_zero(mailbox)) {
04176             /*
04177              * hasvoicemail is a users.conf legacy voicemail enable method.
04178              * hasvoicemail is only going to work for app_voicemail mailboxes.
04179              */
04180             if (strchr(gw->name, '@')) {
04181                ast_copy_string(mailbox, gw->name, sizeof(mailbox));
04182             } else {
04183                snprintf(mailbox, sizeof(mailbox), "%s@default", gw->name);
04184             }
04185          }
04186       } else if (!strcasecmp(v->name, "adsi")) {
04187          adsi = ast_true(v->value);
04188       } else if (!strcasecmp(v->name, "callreturn")) {
04189          callreturn = ast_true(v->value);
04190       } else if (!strcasecmp(v->name, "callwaiting")) {
04191          callwaiting = ast_true(v->value);
04192       } else if (!strcasecmp(v->name, "slowsequence")) {
04193          slowsequence = ast_true(v->value);
04194       } else if (!strcasecmp(v->name, "transfer")) {
04195          transfer = ast_true(v->value);
04196       } else if (!strcasecmp(v->name, "threewaycalling")) {
04197          threewaycalling = ast_true(v->value);
04198       } else if (!strcasecmp(v->name, "wcardep")) {
04199          /* locate existing endpoint */
04200          for (e = gw->endpoints; e; e = e->next) {
04201             if (!strcasecmp(v->value, e->name)) {
04202                /* endpoint already exists */
04203                e->delme = 0;
04204                ep_reload = 1;
04205                break;
04206             }
04207          }
04208 
04209          if (!e) {
04210             /* Allocate wildcard endpoint */
04211             e = ast_calloc(1, sizeof(*e));
04212             ep_reload = 0;
04213          }
04214 
04215          if (e) {
04216             if (!ep_reload) {
04217                memset(e, 0, sizeof(struct mgcp_endpoint));
04218                ast_mutex_init(&e->lock);
04219                ast_mutex_init(&e->rqnt_queue_lock);
04220                ast_mutex_init(&e->cmd_queue_lock);
04221                e->cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
04222                ast_copy_string(e->name, v->value, sizeof(e->name));
04223                e->needaudit = 1;
04224             }
04225             ast_copy_string(gw->wcardep, v->value, sizeof(gw->wcardep));
04226             /* XXX Should we really check for uniqueness?? XXX */
04227             ast_copy_string(e->accountcode, accountcode, sizeof(e->accountcode));
04228             ast_copy_string(e->context, context, sizeof(e->context));
04229             ast_copy_string(e->cid_num, cid_num, sizeof(e->cid_num));
04230             ast_copy_string(e->cid_name, cid_name, sizeof(e->cid_name));
04231             ast_copy_string(e->language, language, sizeof(e->language));
04232             ast_copy_string(e->musicclass, musicclass, sizeof(e->musicclass));
04233             ast_copy_string(e->mailbox, mailbox, sizeof(e->mailbox));
04234             ast_copy_string(e->parkinglot, parkinglot, sizeof(e->parkinglot));
04235             if (!ast_strlen_zero(e->mailbox)) {
04236                struct stasis_topic *mailbox_specific_topic;
04237 
04238                mailbox_specific_topic = ast_mwi_topic(e->mailbox);
04239                if (mailbox_specific_topic) {
04240                   e->mwi_event_sub = stasis_subscribe_pool(mailbox_specific_topic, mwi_event_cb, NULL);
04241                }
04242             }
04243             snprintf(e->rqnt_ident, sizeof(e->rqnt_ident), "%08lx", (unsigned long)ast_random());
04244             e->msgstate = -1;
04245             e->amaflags = amaflags;
04246             ast_format_cap_append_from_cap(e->cap, global_capability, AST_MEDIA_TYPE_UNKNOWN);
04247             e->parent = gw;
04248             e->ncs = ncs;
04249             e->dtmfmode = dtmfmode;
04250             if (!ep_reload && e->sub && e->sub->rtp) {
04251                e->dtmfmode |= MGCP_DTMF_INBAND;
04252             }
04253             e->adsi = adsi;
04254             e->type = TYPE_LINE;
04255             e->immediate = immediate;
04256             e->callgroup=cur_callergroup;
04257             e->pickupgroup=cur_pickupgroup;
04258             e->callreturn = callreturn;
04259             e->cancallforward = cancallforward;
04260             e->singlepath = singlepath;
04261             e->directmedia = directmedia;
04262             e->callwaiting = callwaiting;
04263             e->hascallwaiting = callwaiting;
04264             e->slowsequence = slowsequence;
04265             e->transfer = transfer;
04266             e->threewaycalling = threewaycalling;
04267             e->onhooktime = time(NULL);
04268             /* ASSUME we're onhook */
04269             e->hookstate = MGCP_ONHOOK;
04270             e->chanvars = copy_vars(chanvars);
04271             if (!ep_reload) {
04272                /*snprintf(txident, sizeof(txident), "%08lx", (unsigned long)ast_random());*/
04273                for (i = 0; i < MAX_SUBS; i++) {
04274                   sub = ast_calloc(1, sizeof(*sub));
04275                   if (sub) {
04276                      ast_verb(3, "Allocating subchannel '%d' on %s@%s\n", i, e->name, gw->name);
04277                      ast_mutex_init(&sub->lock);
04278                      ast_mutex_init(&sub->cx_queue_lock);
04279                      sub->parent = e;
04280                      sub->id = i;
04281                      snprintf(sub->txident, sizeof(sub->txident), "%08lx", (unsigned long)ast_random());
04282                      /*stnrcpy(sub->txident, txident, sizeof(sub->txident) - 1);*/
04283                      sub->cxmode = MGCP_CX_INACTIVE;
04284                      sub->nat = nat;
04285                      sub->gate = NULL;
04286                      sub->sdpsent = 0;
04287                      sub->next = e->sub;
04288                      e->sub = sub;
04289                   } else {
04290                      /* XXX Should find a way to clean up our memory */
04291                      ast_log(LOG_WARNING, "Out of memory allocating subchannel\n");
04292                      return NULL;
04293                   }
04294                }
04295                /* Make out subs a circular linked list so we can always sping through the whole bunch */
04296                /* find the end of the list */
04297                for (sub = e->sub; sub && sub->next; sub = sub->next);
04298                /* set the last sub->next to the first sub */
04299                sub->next = e->sub;
04300 
04301                e->next = gw->endpoints;
04302                gw->endpoints = e;
04303             }
04304          }
04305       } else if (!strcasecmp(v->name, "trunk") ||
04306                  !strcasecmp(v->name, "line")) {
04307 
04308          /* locate existing endpoint */
04309          for (e = gw->endpoints; e; e = e->next) {
04310             if (!strcasecmp(v->value, e->name)) {
04311                /* endpoint already exists */
04312                e->delme = 0;
04313                ep_reload = 1;
04314                break;
04315             }
04316          }
04317 
04318          if (!e) {
04319             e = ast_calloc(1, sizeof(*e));
04320             ep_reload = 0;
04321          }
04322 
04323          if (e) {
04324             if (!ep_reload) {
04325                ast_mutex_init(&e->lock);
04326                ast_mutex_init(&e->rqnt_queue_lock);
04327                ast_mutex_init(&e->cmd_queue_lock);
04328                e->cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
04329                ast_copy_string(e->name, v->value, sizeof(e->name));
04330                e->needaudit = 1;
04331             }
04332             /* XXX Should we really check for uniqueness?? XXX */
04333             ast_copy_string(e->accountcode, accountcode, sizeof(e->accountcode));
04334             ast_copy_string(e->context, context, sizeof(e->context));
04335             ast_copy_string(e->cid_num, cid_num, sizeof(e->cid_num));
04336             ast_copy_string(e->cid_name, cid_name, sizeof(e->cid_name));
04337             ast_copy_string(e->language, language, sizeof(e->language));
04338             ast_copy_string(e->musicclass, musicclass, sizeof(e->musicclass));
04339             ast_copy_string(e->mailbox, mailbox, sizeof(e->mailbox));
04340             ast_copy_string(e->parkinglot, parkinglot, sizeof(e->parkinglot));
04341             if (!ast_strlen_zero(mailbox)) {
04342                ast_verb(3, "Setting mailbox '%s' on %s@%s\n", mailbox, gw->name, e->name);
04343             }
04344             if (!ep_reload) {
04345                /* XXX potential issue due to reload */
04346                e->msgstate = -1;
04347                e->parent = gw;
04348             }
04349             e->amaflags = amaflags;
04350             ast_format_cap_append_from_cap(e->cap, global_capability, AST_MEDIA_TYPE_UNKNOWN);
04351             e->dtmfmode = dtmfmode;
04352             e->ncs = ncs;
04353             e->pktcgatealloc = pktcgatealloc;
04354             e->hangupongateremove = hangupongateremove;
04355             e->adsi = adsi;
04356             e->type = (!strcasecmp(v->name, "trunk")) ? TYPE_TRUNK : TYPE_LINE;
04357             e->immediate = immediate;
04358             e->callgroup=cur_callergroup;
04359             e->pickupgroup=cur_pickupgroup;
04360             e->callreturn = callreturn;
04361             e->cancallforward = cancallforward;
04362             e->directmedia = directmedia;
04363             e->singlepath = singlepath;
04364             e->callwaiting = callwaiting;
04365             e->hascallwaiting = callwaiting;
04366             e->slowsequence = slowsequence;
04367             e->transfer = transfer;
04368             e->threewaycalling = threewaycalling;
04369 
04370             /* If we already have a valid chanvars, it's not a new endpoint (it's a reload),
04371                so first, free previous mem
04372              */
04373             if (e->chanvars) {
04374                ast_variables_destroy(e->chanvars);
04375                e->chanvars = NULL;
04376             }
04377             e->chanvars = copy_vars(chanvars);
04378 
04379             if (!ep_reload) {
04380                e->onhooktime = time(NULL);
04381                /* ASSUME we're onhook */
04382                e->hookstate = MGCP_ONHOOK;
04383                snprintf(e->rqnt_ident, sizeof(e->rqnt_ident), "%08lx", (unsigned long)ast_random());
04384             }
04385 
04386             for (i = 0, sub = NULL; i < MAX_SUBS; i++) {
04387                if (!ep_reload) {
04388                   sub = ast_calloc(1, sizeof(*sub));
04389                } else {
04390                   if (!sub) {
04391                      sub = e->sub;
04392                   } else {
04393                      sub = sub->next;
04394                   }
04395                }
04396 
04397                if (sub) {
04398                   if (!ep_reload) {
04399                      ast_verb(3, "Allocating subchannel '%d' on %s@%s\n", i, e->name, gw->name);
04400                      ast_mutex_init(&sub->lock);
04401                      ast_mutex_init(&sub->cx_queue_lock);
04402                      ast_copy_string(sub->magic, MGCP_SUBCHANNEL_MAGIC, sizeof(sub->magic));
04403                      sub->parent = e;
04404                      sub->id = i;
04405                      snprintf(sub->txident, sizeof(sub->txident), "%08lx", (unsigned long)ast_random());
04406                      sub->cxmode = MGCP_CX_INACTIVE;
04407                      sub->next = e->sub;
04408                      e->sub = sub;
04409                   }
04410                   sub->nat = nat;
04411                } else {
04412                   /* XXX Should find a way to clean up our memory */
04413                   ast_log(LOG_WARNING, "Out of memory allocating subchannel\n");
04414                   return NULL;
04415                }
04416             }
04417             if (!ep_reload) {
04418                /* Make out subs a circular linked list so we can always sping through the whole bunch */
04419                /* find the end of the list */
04420                for (sub = e->sub; sub && sub->next; sub = sub->next);
04421                /* set the last sub->next to the first sub */
04422                sub->next = e->sub;
04423 
04424                e->next = gw->endpoints;
04425                gw->endpoints = e;
04426             }
04427          }
04428       } else if (!strcasecmp(v->name, "name") || !strcasecmp(v->name, "lines")) {
04429          /* just eliminate realtime warnings */
04430       } else {
04431          ast_log(LOG_WARNING, "Don't know keyword '%s' at line %d\n", v->name, v->lineno);
04432       }
04433    }
04434    if (!ntohl(gw->addr.sin_addr.s_addr) && !gw->dynamic) {
04435       ast_log(LOG_WARNING, "Gateway '%s' lacks IP address and isn't dynamic\n", gw->name);
04436       if (!gw_reload) {
04437          ast_mutex_destroy(&gw->msgs_lock);
04438          ast_free(gw);
04439       }
04440 
04441       /* Return NULL */
04442       gw_reload = 1;
04443    } else {
04444       gw->defaddr.sin_family = AF_INET;
04445       gw->addr.sin_family = AF_INET;
04446       if (gw->defaddr.sin_addr.s_addr && !ntohs(gw->defaddr.sin_port)) {
04447          gw->defaddr.sin_port = htons(DEFAULT_MGCP_GW_PORT);
04448       }
04449       if (gw->addr.sin_addr.s_addr && !ntohs(gw->addr.sin_port)) {
04450          gw->addr.sin_port = htons(DEFAULT_MGCP_GW_PORT);
04451       }
04452       {
04453          struct ast_sockaddr tmp1, tmp2;
04454          struct sockaddr_in tmp3 = {0,};
04455 
04456          tmp3.sin_addr = gw->ourip;
04457          ast_sockaddr_from_sin(&tmp1, &gw->addr);
04458          ast_sockaddr_from_sin(&tmp2, &tmp3);
04459          if (gw->addr.sin_addr.s_addr && ast_ouraddrfor(&tmp1, &tmp2)) {
04460             memcpy(&gw->ourip, &__ourip, sizeof(gw->ourip));
04461          } else {
04462             ast_sockaddr_to_sin(&tmp2, &tmp3);
04463             gw->ourip = tmp3.sin_addr;
04464          }
04465       }
04466    }
04467 
04468    if (chanvars) {
04469       ast_variables_destroy(chanvars);
04470       chanvars = NULL;
04471    }
04472    return (gw_reload ? NULL : gw);
04473 }
04474 
04475 static enum ast_rtp_glue_result mgcp_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
04476 {
04477    struct mgcp_subchannel *sub = NULL;
04478 
04479    if (!(sub = ast_channel_tech_pvt(chan)) || !(sub->rtp))
04480       return AST_RTP_GLUE_RESULT_FORBID;
04481 
04482    *instance = sub->rtp ? ao2_ref(sub->rtp, +1), sub->rtp : NULL;
04483 
04484    if (sub->parent->directmedia)
04485       return AST_RTP_GLUE_RESULT_REMOTE;
04486    else
04487       return AST_RTP_GLUE_RESULT_LOCAL;
04488 }
04489 
04490 static int mgcp_set_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance *rtp, struct ast_rtp_instance *vrtp, struct ast_rtp_instance *trtp, const struct ast_format_cap *cap, int nat_active)
04491 {
04492    /* XXX Is there such thing as video support with MGCP? XXX */
04493    struct mgcp_subchannel *sub;
04494    sub = ast_channel_tech_pvt(chan);
04495    if (sub && !sub->alreadygone) {
04496       transmit_modify_with_sdp(sub, rtp, cap);
04497       return 0;
04498    }
04499    return -1;
04500 }
04501 
04502 static void mgcp_get_codec(struct ast_channel *chan, struct ast_format_cap *result)
04503 {
04504    struct mgcp_subchannel *sub = ast_channel_tech_pvt(chan);
04505    struct mgcp_endpoint *p = sub->parent;
04506 
04507    ast_format_cap_append_from_cap(result, p->cap, AST_MEDIA_TYPE_UNKNOWN);
04508 }
04509 
04510 static struct ast_rtp_glue mgcp_rtp_glue = {
04511    .type = "MGCP",
04512    .get_rtp_info = mgcp_get_rtp_peer,
04513    .update_peer = mgcp_set_rtp_peer,
04514    .get_codec = mgcp_get_codec,
04515 };
04516 
04517 
04518 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *args, char *buf, size_t buflen)
04519 {
04520    struct mgcp_subchannel *sub = ast_channel_tech_pvt(chan);
04521    int res = 0;
04522 
04523    /* Sanity check */
04524    if (!chan || ast_channel_tech(chan) != &mgcp_tech) {
04525       ast_log(LOG_ERROR, "This function requires a valid MGCP channel\n");
04526       return -1;
04527    }
04528 
04529    if (!strcasecmp(args, "ncs")) {
04530       snprintf(buf, buflen, "%s", sub->parent->ncs ?  "yes":"no");
04531    } else {
04532       res = -1;
04533    }
04534    return res;
04535 }
04536 
04537 
04538 static void destroy_endpoint(struct mgcp_endpoint *e)
04539 {
04540    struct mgcp_subchannel *sub = e->sub->next, *s;
04541    int i;
04542 
04543    for (i = 0; i < MAX_SUBS; i++) {
04544       ast_mutex_lock(&sub->lock);
04545       if (!ast_strlen_zero(sub->cxident)) {
04546          transmit_connection_del(sub);
04547       }
04548       if (sub->rtp) {
04549          ast_rtp_instance_destroy(sub->rtp);
04550          sub->rtp = NULL;
04551       }
04552       memset(sub->magic, 0, sizeof(sub->magic));
04553       mgcp_queue_hangup(sub);
04554       dump_cmd_queues(NULL, sub);
04555       if(sub->gate) {
04556          sub->gate->tech_pvt = NULL;
04557          sub->gate->got_dq_gi = NULL;
04558          sub->gate->gate_remove = NULL;
04559          sub->gate->gate_open = NULL;
04560       }
04561       ast_mutex_unlock(&sub->lock);
04562       sub = sub->next;
04563    }
04564 
04565    if (e->dsp) {
04566       ast_dsp_free(e->dsp);
04567    }
04568 
04569    dump_queue(e->parent, e);
04570    dump_cmd_queues(e, NULL);
04571 
04572    sub = e->sub;
04573    for (i = 0; (i < MAX_SUBS) && sub; i++) {
04574       s = sub;
04575       sub = sub->next;
04576       ast_mutex_destroy(&s->lock);
04577       ast_mutex_destroy(&s->cx_queue_lock);
04578       ast_free(s);
04579    }
04580 
04581    if (e->mwi_event_sub) {
04582       e->mwi_event_sub = stasis_unsubscribe(e->mwi_event_sub);
04583    }
04584 
04585    if (e->chanvars) {
04586       ast_variables_destroy(e->chanvars);
04587       e->chanvars = NULL;
04588    }
04589 
04590    ast_mutex_destroy(&e->lock);
04591    ast_mutex_destroy(&e->rqnt_queue_lock);
04592    ast_mutex_destroy(&e->cmd_queue_lock);
04593    ao2_ref(e->cap, -1);
04594    ast_free(e);
04595 }
04596 
04597 static void destroy_gateway(struct mgcp_gateway *g)
04598 {
04599    if (g->ha)
04600       ast_free_ha(g->ha);
04601 
04602    dump_queue(g, NULL);
04603 
04604    ast_free(g);
04605 }
04606 
04607 static void prune_gateways(void)
04608 {
04609    struct mgcp_gateway *g, *z, *r;
04610    struct mgcp_endpoint *e, *p, *t;
04611 
04612    ast_mutex_lock(&gatelock);
04613 
04614    /* prune gateways */
04615    for (z = NULL, g = gateways; g;) {
04616       /* prune endpoints */
04617       for (p = NULL, e = g->endpoints; e; ) {
04618          if (!g->realtime && (e->delme || g->delme)) {
04619             t = e;
04620             e = e->next;
04621             if (!p)
04622                g->endpoints = e;
04623             else
04624                p->next = e;
04625             destroy_endpoint(t);
04626          } else {
04627             p = e;
04628             e = e->next;
04629          }
04630       }
04631 
04632       if (g->delme) {
04633          r = g;
04634          g = g->next;
04635          if (!z)
04636             gateways = g;
04637          else
04638             z->next = g;
04639 
04640          destroy_gateway(r);
04641       } else {
04642          z = g;
04643          g = g->next;
04644       }
04645    }
04646 
04647    ast_mutex_unlock(&gatelock);
04648 }
04649 
04650 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
04651 {
04652    struct ast_variable *tmpvar = NULL;
04653    char *varname = ast_strdupa(buf), *varval = NULL;
04654 
04655    if ((varval = strchr(varname, '='))) {
04656       *varval++ = '\0';
04657       if ((tmpvar = ast_variable_new(varname, varval, ""))) {
04658          tmpvar->next = list;
04659          list = tmpvar;
04660       }
04661    }
04662    return list;
04663 }
04664 
04665 /*! \brief
04666  * duplicate a list of channel variables, \return the copy.
04667  */
04668 static struct ast_variable *copy_vars(struct ast_variable *src)
04669 {
04670    struct ast_variable *res = NULL, *tmp, *v = NULL;
04671 
04672    for (v = src ; v ; v = v->next) {
04673       if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
04674          tmp->next = res;
04675          res = tmp;
04676       }
04677    }
04678    return res;
04679 }
04680 
04681 
04682 static int reload_config(int reload)
04683 {
04684    struct ast_config *cfg;
04685    struct ast_variable *v;
04686    struct mgcp_gateway *g;
04687    struct mgcp_endpoint *e;
04688    char *cat;
04689    struct ast_hostent ahp;
04690    struct hostent *hp;
04691    struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
04692 
04693    if (gethostname(ourhost, sizeof(ourhost)-1)) {
04694       ast_log(LOG_WARNING, "Unable to get hostname, MGCP disabled\n");
04695       return 0;
04696    }
04697    cfg = ast_config_load(config, config_flags);
04698 
04699    /* We *must* have a config file otherwise stop immediately */
04700    if (!cfg) {
04701       ast_log(LOG_NOTICE, "Unable to load config %s, MGCP disabled\n", config);
04702       return 0;
04703    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
04704       return 0;
04705    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
04706       ast_log(LOG_ERROR, "Config file %s is in an invalid format.  Aborting.\n", config);
04707       return 0;
04708    }
04709 
04710    memset(&bindaddr, 0, sizeof(bindaddr));
04711    dtmfmode = 0;
04712 
04713    /* Copy the default jb config over global_jbconf */
04714    memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
04715 
04716    for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
04717       /* handle jb conf */
04718       if (!ast_jb_read_conf(&global_jbconf, v->name, v->value)) {
04719          continue;
04720       }
04721 
04722       /* Create the interface list */
04723       if (!strcasecmp(v->name, "bindaddr")) {
04724          if (!(hp = ast_gethostbyname(v->value, &ahp))) {
04725             ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
04726          } else {
04727             memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
04728          }
04729       } else if (!strcasecmp(v->name, "allow")) {
04730          ast_format_cap_update_by_allow_disallow(global_capability, v->value, 1);
04731       } else if (!strcasecmp(v->name, "disallow")) {
04732          ast_format_cap_update_by_allow_disallow(global_capability, v->value, 0);
04733       } else if (!strcasecmp(v->name, "tos")) {
04734          if (ast_str2tos(v->value, &qos.tos)) {
04735              ast_log(LOG_WARNING, "Invalid tos value at line %d, refer to QoS documentation\n", v->lineno);
04736          }
04737       } else if (!strcasecmp(v->name, "tos_audio")) {
04738          if (ast_str2tos(v->value, &qos.tos_audio))
04739              ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
04740       } else if (!strcasecmp(v->name, "cos")) {
04741          if (ast_str2cos(v->value, &qos.cos))
04742              ast_log(LOG_WARNING, "Invalid cos value at line %d, refer to QoS documentation\n", v->lineno);
04743       } else if (!strcasecmp(v->name, "cos_audio")) {
04744          if (ast_str2cos(v->value, &qos.cos_audio))
04745              ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
04746       } else if (!strcasecmp(v->name, "port")) {
04747          if (sscanf(v->value, "%5d", &ourport) == 1) {
04748             bindaddr.sin_port = htons(ourport);
04749          } else {
04750             ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
04751          }
04752       } else if (!strcasecmp(v->name, "firstdigittimeout")) {
04753          firstdigittimeout = atoi(v->value);
04754       } else if (!strcasecmp(v->name, "gendigittimeout")) {
04755          gendigittimeout = atoi(v->value);
04756       } else if (!strcasecmp(v->name, "matchdigittimeout")) {
04757          matchdigittimeout = atoi(v->value);
04758       }
04759    }
04760 
04761    /* mark existing entries for deletion */
04762    ast_mutex_lock(&gatelock);
04763    for (g = gateways; g; g = g->next) {
04764       g->delme = 1;
04765       for (e = g->endpoints; e; e = e->next) {
04766          e->delme = 1;
04767       }
04768    }
04769    ast_mutex_unlock(&gatelock);
04770 
04771    for (cat = ast_category_browse(cfg, NULL); cat; cat = ast_category_browse(cfg, cat)) {
04772       if (strcasecmp(cat, "general")) {
04773          ast_mutex_lock(&gatelock);
04774          if ((g = build_gateway(cat, ast_variable_browse(cfg, cat)))) {
04775             ast_verb(3, "Added gateway '%s'\n", g->name);
04776             g->next = gateways;
04777             gateways = g;
04778          }
04779          ast_mutex_unlock(&gatelock);
04780 
04781          /* FS: process queue and IO */
04782          if (monitor_thread == pthread_self()) {
04783             if (sched) ast_sched_runq(sched);
04784             if (io) ast_io_wait(io, 10);
04785          }
04786       }
04787    }
04788 
04789    /* prune deleted entries etc. */
04790    prune_gateways();
04791 
04792    if (ntohl(bindaddr.sin_addr.s_addr)) {
04793       memcpy(&__ourip, &bindaddr.sin_addr, sizeof(__ourip));
04794    } else {
04795       hp = ast_gethostbyname(ourhost, &ahp);
04796       if (!hp) {
04797          ast_log(LOG_WARNING, "Unable to get our IP address, MGCP disabled\n");
04798          ast_config_destroy(cfg);
04799          return 0;
04800       }
04801       memcpy(&__ourip, hp->h_addr, sizeof(__ourip));
04802    }
04803    if (!ntohs(bindaddr.sin_port))
04804       bindaddr.sin_port = htons(DEFAULT_MGCP_CA_PORT);
04805    bindaddr.sin_family = AF_INET;
04806    ast_mutex_lock(&netlock);
04807    if (mgcpsock > -1)
04808       close(mgcpsock);
04809 
04810    if (mgcpsock_read_id != NULL)
04811       ast_io_remove(io, mgcpsock_read_id);
04812    mgcpsock_read_id = NULL;
04813 
04814    mgcpsock = socket(AF_INET, SOCK_DGRAM, 0);
04815    if (mgcpsock < 0) {
04816       ast_log(LOG_WARNING, "Unable to create MGCP socket: %s\n", strerror(errno));
04817    } else {
04818       if (bind(mgcpsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
04819          ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
04820             ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
04821                strerror(errno));
04822          close(mgcpsock);
04823          mgcpsock = -1;
04824       } else {
04825          ast_verb(2, "MGCP Listening on %s:%d\n",
04826                ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
04827          ast_set_qos(mgcpsock, qos.tos, qos.cos, "MGCP");
04828       }
04829    }
04830    ast_mutex_unlock(&netlock);
04831    ast_config_destroy(cfg);
04832 
04833    /* send audit only to the new endpoints */
04834    for (g = gateways; g; g = g->next) {
04835       for (e = g->endpoints; e && e->needaudit; e = e->next) {
04836          e->needaudit = 0;
04837          transmit_audit_endpoint(e);
04838          ast_verb(3, "MGCP Auditing endpoint %s@%s for hookstate\n", e->name, g->name);
04839       }
04840    }
04841 
04842    return 0;
04843 }
04844 
04845 /*!
04846  * \brief Load the module
04847  *
04848  * Module loading including tests for configuration or dependencies.
04849  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
04850  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
04851  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
04852  * configuration file or other non-critical problem return
04853  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
04854  */
04855 static int load_module(void)
04856 {
04857    if (!(global_capability = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
04858       return AST_MODULE_LOAD_FAILURE;
04859    }
04860    if (!(mgcp_tech.capabilities = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
04861       ao2_ref(global_capability, -1);
04862       return AST_MODULE_LOAD_FAILURE;
04863    }
04864    ast_format_cap_append(global_capability, ast_format_ulaw, 0);
04865    ast_format_cap_append(mgcp_tech.capabilities, ast_format_ulaw, 0);
04866    ast_format_cap_append(mgcp_tech.capabilities, ast_format_alaw, 0);
04867    if (!(sched = ast_sched_context_create())) {
04868       ast_log(LOG_WARNING, "Unable to create schedule context\n");
04869       ao2_ref(global_capability, -1);
04870       ao2_ref(mgcp_tech.capabilities, -1);
04871       return AST_MODULE_LOAD_FAILURE;
04872    }
04873 
04874    if (!(io = io_context_create())) {
04875       ast_log(LOG_WARNING, "Unable to create I/O context\n");
04876       ast_sched_context_destroy(sched);
04877       ao2_ref(global_capability, -1);
04878       ao2_ref(mgcp_tech.capabilities, -1);
04879       return AST_MODULE_LOAD_FAILURE;
04880    }
04881 
04882    if (reload_config(0)) {
04883       ao2_ref(global_capability, -1);
04884       ao2_ref(mgcp_tech.capabilities, -1);
04885       return AST_MODULE_LOAD_DECLINE;
04886    }
04887 
04888    /* Make sure we can register our mgcp channel type */
04889    if (ast_channel_register(&mgcp_tech)) {
04890       ast_log(LOG_ERROR, "Unable to register channel class 'MGCP'\n");
04891       io_context_destroy(io);
04892       ast_sched_context_destroy(sched);
04893       ao2_ref(global_capability, -1);
04894       ao2_ref(mgcp_tech.capabilities, -1);
04895       return AST_MODULE_LOAD_FAILURE;
04896    }
04897 
04898    ast_rtp_glue_register(&mgcp_rtp_glue);
04899    ast_cli_register_multiple(cli_mgcp, sizeof(cli_mgcp) / sizeof(struct ast_cli_entry));
04900 
04901    /* And start the monitor for the first time */
04902    restart_monitor();
04903 
04904    return AST_MODULE_LOAD_SUCCESS;
04905 }
04906 
04907 static char *mgcp_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
04908 {
04909    static int deprecated = 0;
04910 
04911    if (e) {
04912       switch (cmd) {
04913       case CLI_INIT:
04914          e->command = "mgcp reload";
04915          e->usage =
04916             "Usage: mgcp reload\n"
04917             "       'mgcp reload' is deprecated.  Please use 'reload chan_mgcp.so' instead.\n";
04918          return NULL;
04919       case CLI_GENERATE:
04920          return NULL;
04921       }
04922    }
04923 
04924    if (!deprecated && a && a->argc > 0) {
04925       ast_log(LOG_WARNING, "'mgcp reload' is deprecated.  Please use 'reload chan_mgcp.so' instead.\n");
04926       deprecated = 1;
04927    }
04928 
04929    ast_mutex_lock(&mgcp_reload_lock);
04930    if (mgcp_reloading) {
04931       ast_verbose("Previous mgcp reload not yet done\n");
04932    } else {
04933       mgcp_reloading = 1;
04934    }
04935    ast_mutex_unlock(&mgcp_reload_lock);
04936    restart_monitor();
04937    return CLI_SUCCESS;
04938 }
04939 
04940 static int reload(void)
04941 {
04942    mgcp_reload(NULL, 0, NULL);
04943    return 0;
04944 }
04945 
04946 static int unload_module(void)
04947 {
04948    struct mgcp_endpoint *e;
04949    struct mgcp_gateway *g;
04950 
04951    /* Check to see if we're reloading */
04952    if (ast_mutex_trylock(&mgcp_reload_lock)) {
04953       ast_log(LOG_WARNING, "MGCP is currently reloading.  Unable to remove module.\n");
04954       return -1;
04955    } else {
04956       mgcp_reloading = 1;
04957       ast_mutex_unlock(&mgcp_reload_lock);
04958    }
04959 
04960    /* First, take us out of the channel loop */
04961    ast_channel_unregister(&mgcp_tech);
04962 
04963    /* Shut down the monitoring thread */
04964    if (!ast_mutex_lock(&monlock)) {
04965       if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP)) {
04966          pthread_cancel(monitor_thread);
04967          pthread_kill(monitor_thread, SIGURG);
04968          pthread_join(monitor_thread, NULL);
04969       }
04970       monitor_thread = AST_PTHREADT_STOP;
04971       ast_mutex_unlock(&monlock);
04972    } else {
04973       ast_log(LOG_WARNING, "Unable to lock the monitor\n");
04974       /* We always want to leave this in a consistent state */
04975       ast_channel_register(&mgcp_tech);
04976       mgcp_reloading = 0;
04977       mgcp_reload(NULL, 0, NULL);
04978       return -1;
04979    }
04980 
04981    if (!ast_mutex_lock(&gatelock)) {
04982       for (g = gateways; g; g = g->next) {
04983          g->delme = 1;
04984          for (e = g->endpoints; e; e = e->next) {
04985             e->delme = 1;
04986          }
04987       }
04988 
04989       prune_gateways();
04990       ast_mutex_unlock(&gatelock);
04991    } else {
04992       ast_log(LOG_WARNING, "Unable to lock the gateways list.\n");
04993       /* We always want to leave this in a consistent state */
04994       ast_channel_register(&mgcp_tech);
04995       /* Allow the monitor to restart */
04996       monitor_thread = AST_PTHREADT_NULL;
04997       mgcp_reloading = 0;
04998       mgcp_reload(NULL, 0, NULL);
04999       return -1;
05000    }
05001 
05002    close(mgcpsock);
05003    ast_rtp_glue_unregister(&mgcp_rtp_glue);
05004    ast_cli_unregister_multiple(cli_mgcp, sizeof(cli_mgcp) / sizeof(struct ast_cli_entry));
05005    ast_sched_context_destroy(sched);
05006 
05007    ao2_ref(global_capability, -1);
05008    global_capability = NULL;
05009    ao2_ref(mgcp_tech.capabilities, -1);
05010    mgcp_tech.capabilities = NULL;
05011 
05012    return 0;
05013 }
05014 
05015 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Media Gateway Control Protocol (MGCP)",
05016       .support_level = AST_MODULE_SUPPORT_EXTENDED,
05017       .load = load_module,
05018       .unload = unload_module,
05019       .reload = reload,
05020       .load_pri = AST_MODPRI_CHANNEL_DRIVER,
05021       .nonoptreq = "res_pktccops",
05022           );

Generated on Thu Apr 16 06:27:22 2015 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.6