git migration: Refactor the ASTERISK_FILE_VERSION macro
[asterisk/asterisk.git] / channels / chan_mgcp.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Implementation of Media Gateway Control Protocol
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  * \ingroup channel_drivers
26  */
27
28 /*! \li \ref chan_mgcp.c uses the configuration file \ref mgcp.conf
29  * \addtogroup configuration_file
30  */
31
32 /*! \page mgcp.conf mgcp.conf
33  * \verbinclude mgcp.conf.sample
34  */
35
36 /*** MODULEINFO
37         <use type="module">res_pktccops</use>
38         <support_level>extended</support_level>
39  ***/
40
41 #include "asterisk.h"
42
43 ASTERISK_REGISTER_FILE()
44
45 #include <sys/socket.h>
46 #include <sys/ioctl.h>
47 #include <net/if.h>
48 #include <fcntl.h>
49 #include <netdb.h>
50 #include <sys/signal.h>
51 #include <signal.h>
52 #include <netinet/in.h>
53 #include <netinet/in_systm.h>
54 #include <netinet/ip.h>
55 #include <arpa/inet.h>
56 #include <ctype.h>
57
58 #include "asterisk/lock.h"
59 #include "asterisk/channel.h"
60 #include "asterisk/config.h"
61 #include "asterisk/module.h"
62 #include "asterisk/pickup.h"
63 #include "asterisk/pbx.h"
64 #include "asterisk/sched.h"
65 #include "asterisk/io.h"
66 #include "asterisk/rtp_engine.h"
67 #include "asterisk/acl.h"
68 #include "asterisk/callerid.h"
69 #include "asterisk/cli.h"
70 #include "asterisk/say.h"
71 #include "asterisk/astdb.h"
72 #include "asterisk/features.h"
73 #include "asterisk/app.h"
74 #include "asterisk/musiconhold.h"
75 #include "asterisk/utils.h"
76 #include "asterisk/netsock2.h"
77 #include "asterisk/causes.h"
78 #include "asterisk/dsp.h"
79 #include "asterisk/devicestate.h"
80 #include "asterisk/stringfields.h"
81 #include "asterisk/abstract_jb.h"
82 #include "asterisk/chanvars.h"
83 #include "asterisk/pktccops.h"
84 #include "asterisk/stasis.h"
85 #include "asterisk/bridge.h"
86 #include "asterisk/features_config.h"
87 #include "asterisk/parking.h"
88 #include "asterisk/stasis_channels.h"
89 #include "asterisk/format_cache.h"
90
91 /*
92  * Define to work around buggy dlink MGCP phone firmware which
93  * appears not to know that "rt" is part of the "G" package.
94  */
95 /* #define DLINK_BUGGY_FIRMWARE */
96
97 #define MGCPDUMPER
98 #define DEFAULT_EXPIRY  120
99 #define MAX_EXPIRY      3600
100 #define DIRECTMEDIA     1
101
102 #ifndef INADDR_NONE
103 #define INADDR_NONE (in_addr_t)(-1)
104 #endif
105
106 /*! Global jitterbuffer configuration - by default, jb is disabled
107  *  \note Values shown here match the defaults shown in mgcp.conf.sample */
108 static struct ast_jb_conf default_jbconf =
109 {
110         .flags = 0,
111         .max_size = 200,
112         .resync_threshold = 1000,
113         .impl = "fixed",
114         .target_extra = 40,
115 };
116 static struct ast_jb_conf global_jbconf;
117
118 static const char tdesc[] = "Media Gateway Control Protocol (MGCP)";
119 static const char config[] = "mgcp.conf";
120
121 #define MGCP_DTMF_RFC2833       (1 << 0)
122 #define MGCP_DTMF_INBAND        (1 << 1)
123 #define MGCP_DTMF_HYBRID        (1 << 2)
124
125 #define DEFAULT_MGCP_GW_PORT    2427 /*!< From RFC 2705 */
126 #define DEFAULT_MGCP_CA_PORT    2727 /*!< From RFC 2705 */
127 #define MGCP_MAX_PACKET         1500 /*!< Also from RFC 2543, should sub headers tho */
128 #define DEFAULT_RETRANS         1000 /*!< How frequently to retransmit */
129 #define MAX_RETRANS             5    /*!< Try only 5 times for retransmissions */
130
131 /*! MGCP rtp stream modes { */
132 #define MGCP_CX_SENDONLY        0
133 #define MGCP_CX_RECVONLY        1
134 #define MGCP_CX_SENDRECV        2
135 #define MGCP_CX_CONF            3
136 #define MGCP_CX_CONFERENCE      3
137 #define MGCP_CX_MUTE            4
138 #define MGCP_CX_INACTIVE        4
139 /*! } */
140
141 static const char * const mgcp_cxmodes[] = {
142         "sendonly",
143         "recvonly",
144         "sendrecv",
145         "confrnce",
146         "inactive"
147 };
148
149 enum {
150         MGCP_CMD_EPCF,
151         MGCP_CMD_CRCX,
152         MGCP_CMD_MDCX,
153         MGCP_CMD_DLCX,
154         MGCP_CMD_RQNT,
155         MGCP_CMD_NTFY,
156         MGCP_CMD_AUEP,
157         MGCP_CMD_AUCX,
158         MGCP_CMD_RSIP
159 };
160
161 static char context[AST_MAX_EXTENSION] = "default";
162
163 static char language[MAX_LANGUAGE] = "";
164 static char musicclass[MAX_MUSICCLASS] = "";
165 static char parkinglot[AST_MAX_CONTEXT];
166 static char cid_num[AST_MAX_EXTENSION] = "";
167 static char cid_name[AST_MAX_EXTENSION] = "";
168
169 static int dtmfmode = 0;
170 static int nat = 0;
171 static int ncs = 0;
172 static int pktcgatealloc = 0;
173 static int hangupongateremove = 0;
174
175 static ast_group_t cur_callergroup = 0;
176 static ast_group_t cur_pickupgroup = 0;
177
178 static struct {
179         unsigned int tos;
180         unsigned int tos_audio;
181         unsigned int cos;
182         unsigned int cos_audio;
183 } qos = { 0, 0, 0, 0 };
184
185 static int immediate = 0;
186
187 static int callwaiting = 0;
188
189 static int callreturn = 0;
190
191 static int slowsequence = 0;
192
193 static int threewaycalling = 0;
194
195 /*! This is for flashhook transfers */
196 static int transfer = 0;
197
198 static int cancallforward = 0;
199
200 static int singlepath = 0;
201
202 static int directmedia = DIRECTMEDIA;
203
204 static char accountcode[AST_MAX_ACCOUNT_CODE] = "";
205
206 static char mailbox[AST_MAX_MAILBOX_UNIQUEID];
207
208 static int amaflags = 0;
209
210 static int adsi = 0;
211
212 static unsigned int oseq_global = 0;
213 AST_MUTEX_DEFINE_STATIC(oseq_lock);
214
215 /*! Wait up to 16 seconds for first digit (FXO logic) */
216 static int firstdigittimeout = 16000;
217
218 /*! How long to wait for following digits (FXO logic) */
219 static int gendigittimeout = 8000;
220
221 /*! How long to wait for an extra digit, if there is an ambiguous match */
222 static int matchdigittimeout = 3000;
223
224 /*! Protect the monitoring thread, so only one process can kill or start it, and not
225     when it's doing something critical. */
226 AST_MUTEX_DEFINE_STATIC(netlock);
227
228 AST_MUTEX_DEFINE_STATIC(monlock);
229
230 /*! This is the thread for the monitor which checks for input on the channels
231  *  which are not currently in use.
232  */
233 static pthread_t monitor_thread = AST_PTHREADT_NULL;
234
235 static int restart_monitor(void);
236
237 static struct ast_format_cap *global_capability;
238 static int nonCodecCapability = AST_RTP_DTMF;
239
240 static char ourhost[MAXHOSTNAMELEN];
241 static struct in_addr __ourip;
242 static int ourport;
243
244 static int mgcpdebug = 0;
245
246 static struct ast_sched_context *sched;
247 static struct io_context *io;
248 /*! The private structures of the mgcp channels are linked for
249  * selecting outgoing channels
250  */
251
252 #define MGCP_MAX_HEADERS        64
253 #define MGCP_MAX_LINES          64
254
255 struct mgcp_request {
256         int len;
257         char *verb;
258         char *identifier;
259         char *endpoint;
260         char *version;
261         int headers;                    /*!< MGCP Headers */
262         char *header[MGCP_MAX_HEADERS];
263         int lines;                      /*!< SDP Content */
264         char *line[MGCP_MAX_LINES];
265         char data[MGCP_MAX_PACKET];
266         int cmd;                        /*!< int version of verb = command */
267         unsigned int trid;              /*!< int version of identifier = transaction id */
268         struct mgcp_request *next;      /*!< next in the queue */
269 };
270
271 /*! \brief mgcp_message: MGCP message for queuing up */
272 struct mgcp_message {
273         struct mgcp_endpoint *owner_ep;
274         struct mgcp_subchannel *owner_sub;
275         int retrans;
276         unsigned long expire;
277         unsigned int seqno;
278         int len;
279         struct mgcp_message *next;
280         char buf[0];
281 };
282
283 #define RESPONSE_TIMEOUT 30     /*!< in seconds */
284
285 struct mgcp_response {
286         time_t whensent;
287         int len;
288         int seqno;
289         struct mgcp_response *next;
290         char buf[0];
291 };
292
293 #define MAX_SUBS 2
294
295 #define SUB_REAL 0
296 #define SUB_ALT  1
297
298 struct mgcp_subchannel {
299         /*! subchannel magic string.
300            Needed to prove that any subchannel pointer passed by asterisk
301            really points to a valid subchannel memory area.
302            Ugly.. But serves the purpose for the time being.
303          */
304 #define MGCP_SUBCHANNEL_MAGIC "!978!"
305         char magic[6];
306         ast_mutex_t lock;
307         int id;
308         struct ast_channel *owner;
309         struct mgcp_endpoint *parent;
310         struct ast_rtp_instance *rtp;
311         struct sockaddr_in tmpdest;
312         char txident[80]; /*! \todo FIXME txident is replaced by rqnt_ident in endpoint.
313                         This should be obsoleted */
314         char cxident[80];
315         char callid[80];
316         int cxmode;
317         struct mgcp_request *cx_queue; /*!< pending CX commands */
318         ast_mutex_t cx_queue_lock;     /*!< CX queue lock */
319         int nat;
320         int iseq;                      /*!< Not used? RTP? */
321         int outgoing;
322         int alreadygone;
323         int sdpsent;
324         struct cops_gate *gate;
325         struct mgcp_subchannel *next;  /*!< for out circular linked list */
326 };
327
328 #define MGCP_ONHOOK  1
329 #define MGCP_OFFHOOK 2
330
331 #define TYPE_TRUNK 1
332 #define TYPE_LINE  2
333
334 struct mgcp_endpoint {
335         ast_mutex_t lock;
336         char name[80];
337         struct mgcp_subchannel *sub;            /*!< Pointer to our current connection, channel and stuff */
338         char accountcode[AST_MAX_ACCOUNT_CODE];
339         char exten[AST_MAX_EXTENSION];          /*!< Extention where to start */
340         char context[AST_MAX_EXTENSION];
341         char language[MAX_LANGUAGE];
342         char cid_num[AST_MAX_EXTENSION];        /*!< Caller*ID number */
343         char cid_name[AST_MAX_EXTENSION];       /*!< Caller*ID name */
344         char lastcallerid[AST_MAX_EXTENSION];   /*!< Last Caller*ID */
345         char dtmf_buf[AST_MAX_EXTENSION];       /*!< place to collect digits be */
346         char call_forward[AST_MAX_EXTENSION];   /*!< Last Caller*ID */
347         char musicclass[MAX_MUSICCLASS];
348         char curtone[80];                       /*!< Current tone */
349         char mailbox[AST_MAX_EXTENSION];
350         char parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
351         struct stasis_subscription *mwi_event_sub;
352         ast_group_t callgroup;
353         ast_group_t pickupgroup;
354         int callwaiting;
355         int hascallwaiting;
356         int transfer;
357         int threewaycalling;
358         int singlepath;
359         int cancallforward;
360         int directmedia;
361         int callreturn;
362         int dnd; /* How does this affect callwait? Do we just deny a mgcp_request if we're dnd? */
363         int hascallerid;
364         int hidecallerid;
365         int dtmfmode;
366         int amaflags;
367         int ncs;
368         int pktcgatealloc;
369         int hangupongateremove;
370         int type;
371         int slowsequence;                       /*!< MS: Sequence the endpoint as a whole */
372         int group;
373         int iseq; /*!< Not used? */
374         int lastout; /*!< tracking this on the subchannels.  Is it needed here? */
375         int needdestroy; /*!< Not used? */
376         struct ast_format_cap *cap;
377         int nonCodecCapability;
378         int onhooktime;
379         int msgstate; /*!< voicemail message state */
380         int immediate;
381         int hookstate;
382         int adsi;
383         char rqnt_ident[80];             /*!< request identifier */
384         struct mgcp_request *rqnt_queue; /*!< pending RQNT commands */
385         ast_mutex_t rqnt_queue_lock;
386         struct mgcp_request *cmd_queue;  /*!< pending commands other than RQNT */
387         ast_mutex_t cmd_queue_lock;
388         int delme;                       /*!< needed for reload */
389         int needaudit;                   /*!< needed for reload */
390         struct ast_dsp *dsp; /*!< XXX Should there be a dsp/subchannel? XXX */
391         /* owner is tracked on the subchannels, and the *sub indicates whos in charge */
392         /* struct ast_channel *owner; */
393         /* struct ast_rtp *rtp; */
394         /* struct sockaddr_in tmpdest; */
395         /* message go the the endpoint and not the channel so they stay here */
396         struct ast_variable *chanvars;          /*!< Variables to set for channel created by user */
397         struct mgcp_endpoint *next;
398         struct mgcp_gateway *parent;
399 };
400
401 static struct mgcp_gateway {
402         /* A gateway containing one or more endpoints */
403         char name[80];
404         int isnamedottedip; /*!< is the name FQDN or dotted ip */
405         struct sockaddr_in addr;
406         struct sockaddr_in defaddr;
407         struct in_addr ourip;
408         int dynamic;
409         int expire;             /*!< XXX Should we ever expire dynamic registrations? XXX */
410         struct mgcp_endpoint *endpoints;
411         struct ast_ha *ha;
412 /* obsolete
413         time_t lastouttime;
414         int lastout;
415         int messagepending;
416 */
417 /* Wildcard endpoint name */
418         char wcardep[30];
419         struct mgcp_message *msgs; /*!< gw msg queue */
420         ast_mutex_t msgs_lock;     /*!< queue lock */
421         int retransid;             /*!< retrans timer id */
422         int delme;                 /*!< needed for reload */
423         int realtime;
424         struct mgcp_response *responses;
425         struct mgcp_gateway *next;
426 } *gateways = NULL;
427
428 AST_MUTEX_DEFINE_STATIC(mgcp_reload_lock);
429 static int mgcp_reloading = 0;
430
431 /*! \brief gatelock: mutex for gateway/endpoint lists */
432 AST_MUTEX_DEFINE_STATIC(gatelock);
433
434 static int mgcpsock  = -1;
435
436 static struct sockaddr_in bindaddr;
437
438 static void mgcp_set_owner(struct mgcp_subchannel *sub, struct ast_channel *chan);
439 static struct ast_frame  *mgcp_read(struct ast_channel *ast);
440 static int transmit_response(struct mgcp_subchannel *sub, char *msg, struct mgcp_request *req, char *msgrest);
441 static int transmit_notify_request(struct mgcp_subchannel *sub, char *tone);
442 static int transmit_modify_request(struct mgcp_subchannel *sub);
443 static int transmit_connect(struct mgcp_subchannel *sub);
444 static int transmit_notify_request_with_callerid(struct mgcp_subchannel *sub, char *tone, char *callernum, char *callername);
445 static int transmit_modify_with_sdp(struct mgcp_subchannel *sub, struct ast_rtp_instance *rtp, const struct ast_format_cap *codecs);
446 static int transmit_connection_del(struct mgcp_subchannel *sub);
447 static int transmit_audit_endpoint(struct mgcp_endpoint *p);
448 static void start_rtp(struct mgcp_subchannel *sub);
449 static void handle_response(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,
450                             int result, unsigned int ident, struct mgcp_request *resp);
451 static void dump_cmd_queues(struct mgcp_endpoint *p, struct mgcp_subchannel *sub);
452 static char *mgcp_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
453 static int reload_config(int reload);
454
455 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);
456 static int mgcp_call(struct ast_channel *ast, const char *dest, int timeout);
457 static int mgcp_hangup(struct ast_channel *ast);
458 static int mgcp_answer(struct ast_channel *ast);
459 static struct ast_frame *mgcp_read(struct ast_channel *ast);
460 static int mgcp_write(struct ast_channel *ast, struct ast_frame *frame);
461 static int mgcp_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen);
462 static int mgcp_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
463 static int mgcp_senddigit_begin(struct ast_channel *ast, char digit);
464 static int mgcp_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
465 static int mgcp_devicestate(const char *data);
466 static void add_header_offhook(struct mgcp_subchannel *sub, struct mgcp_request *resp, char *tone);
467 static int transmit_connect_with_sdp(struct mgcp_subchannel *sub, struct ast_rtp_instance *rtp);
468 static struct mgcp_gateway *build_gateway(char *cat, struct ast_variable *v);
469 static int mgcp_alloc_pktcgate(struct mgcp_subchannel *sub);
470 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
471 static struct ast_variable *add_var(const char *buf, struct ast_variable *list);
472 static struct ast_variable *copy_vars(struct ast_variable *src);
473
474 static struct ast_channel_tech mgcp_tech = {
475         .type = "MGCP",
476         .description = tdesc,
477         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
478         .requester = mgcp_request,
479         .devicestate = mgcp_devicestate,
480         .call = mgcp_call,
481         .hangup = mgcp_hangup,
482         .answer = mgcp_answer,
483         .read = mgcp_read,
484         .write = mgcp_write,
485         .indicate = mgcp_indicate,
486         .fixup = mgcp_fixup,
487         .send_digit_begin = mgcp_senddigit_begin,
488         .send_digit_end = mgcp_senddigit_end,
489         .func_channel_read = acf_channel_read,
490 };
491
492 static void mwi_event_cb(void *userdata, struct stasis_subscription *sub, struct stasis_message *msg)
493 {
494         /* This module does not handle MWI in an event-based manner.  However, it
495          * subscribes to MWI for each mailbox that is configured so that the core
496          * knows that we care about it.  Then, chan_mgcp will get the MWI from the
497          * event cache instead of checking the mailbox directly. */
498 }
499
500 static int has_voicemail(struct mgcp_endpoint *p)
501 {
502         int new_msgs;
503         RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
504
505         msg = stasis_cache_get(ast_mwi_state_cache(), ast_mwi_state_type(), p->mailbox);
506         if (msg) {
507                 struct ast_mwi_state *mwi_state = stasis_message_data(msg);
508                 new_msgs = mwi_state->new_msgs;
509         } else {
510                 new_msgs = ast_app_has_voicemail(p->mailbox, NULL);
511         }
512
513         return new_msgs;
514 }
515
516 static int unalloc_sub(struct mgcp_subchannel *sub)
517 {
518         struct mgcp_endpoint *p = sub->parent;
519         if (p->sub == sub) {
520                 ast_log(LOG_WARNING, "Trying to unalloc the real channel %s@%s?!?\n", p->name, p->parent->name);
521                 return -1;
522         }
523         ast_debug(1, "Released sub %d of channel %s@%s\n", sub->id, p->name, p->parent->name);
524
525         mgcp_set_owner(sub, NULL);
526         if (!ast_strlen_zero(sub->cxident)) {
527                 transmit_connection_del(sub);
528         }
529         sub->cxident[0] = '\0';
530         sub->callid[0] = '\0';
531         sub->cxmode = MGCP_CX_INACTIVE;
532         sub->outgoing = 0;
533         sub->alreadygone = 0;
534         memset(&sub->tmpdest, 0, sizeof(sub->tmpdest));
535         if (sub->rtp) {
536                 ast_rtp_instance_destroy(sub->rtp);
537                 sub->rtp = NULL;
538         }
539         dump_cmd_queues(NULL, sub);
540         return 0;
541 }
542
543 /* modified for new transport mechanism */
544 static int __mgcp_xmit(struct mgcp_gateway *gw, char *data, int len)
545 {
546         int res;
547         if (gw->addr.sin_addr.s_addr)
548                 res=sendto(mgcpsock, data, len, 0, (struct sockaddr *)&gw->addr, sizeof(struct sockaddr_in));
549         else
550                 res=sendto(mgcpsock, data, len, 0, (struct sockaddr *)&gw->defaddr, sizeof(struct sockaddr_in));
551         if (res != len) {
552                 ast_log(LOG_WARNING, "mgcp_xmit returned %d: %s\n", res, strerror(errno));
553         }
554         return res;
555 }
556
557 static int resend_response(struct mgcp_subchannel *sub, struct mgcp_response *resp)
558 {
559         struct mgcp_endpoint *p = sub->parent;
560         int res;
561         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));
562         res = __mgcp_xmit(p->parent, resp->buf, resp->len);
563         if (res > 0)
564                 res = 0;
565         return res;
566 }
567
568 static int send_response(struct mgcp_subchannel *sub, struct mgcp_request *req)
569 {
570         struct mgcp_endpoint *p = sub->parent;
571         int res;
572         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));
573         res = __mgcp_xmit(p->parent, req->data, req->len);
574         if (res > 0)
575                 res = 0;
576         return res;
577 }
578
579 /* modified for new transport framework */
580 static void dump_queue(struct mgcp_gateway *gw, struct mgcp_endpoint *p)
581 {
582         struct mgcp_message *cur, *q = NULL, *w, *prev;
583
584         ast_mutex_lock(&gw->msgs_lock);
585         for (prev = NULL, cur = gw->msgs; cur; prev = cur, cur = cur->next) {
586                 if (!p || cur->owner_ep == p) {
587                         if (prev) {
588                                 prev->next = cur->next;
589                         } else {
590                                 gw->msgs = cur->next;
591                         }
592
593                         ast_log(LOG_NOTICE, "Removing message from %s transaction %u\n",
594                                 gw->name, cur->seqno);
595
596                         w = cur;
597                         if (q) {
598                                 w->next = q;
599                         } else {
600                                 w->next = NULL;
601                         }
602                         q = w;
603                 }
604         }
605         ast_mutex_unlock(&gw->msgs_lock);
606
607         while (q) {
608                 cur = q;
609                 q = q->next;
610                 ast_free(cur);
611         }
612 }
613
614 static void mgcp_queue_frame(struct mgcp_subchannel *sub, struct ast_frame *f)
615 {
616         for (;;) {
617                 if (sub->owner) {
618                         if (!ast_channel_trylock(sub->owner)) {
619                                 ast_queue_frame(sub->owner, f);
620                                 ast_channel_unlock(sub->owner);
621                                 break;
622                         } else {
623                                 DEADLOCK_AVOIDANCE(&sub->lock);
624                         }
625                 } else {
626                         break;
627                 }
628         }
629 }
630
631 static void mgcp_queue_hangup(struct mgcp_subchannel *sub)
632 {
633         for (;;) {
634                 if (sub->owner) {
635                         if (!ast_channel_trylock(sub->owner)) {
636                                 ast_queue_hangup(sub->owner);
637                                 ast_channel_unlock(sub->owner);
638                                 break;
639                         } else {
640                                 DEADLOCK_AVOIDANCE(&sub->lock);
641                         }
642                 } else {
643                         break;
644                 }
645         }
646 }
647
648 static void mgcp_queue_control(struct mgcp_subchannel *sub, int control)
649 {
650         struct ast_frame f = { AST_FRAME_CONTROL, { control } };
651         return mgcp_queue_frame(sub, &f);
652 }
653
654 static int retrans_pkt(const void *data)
655 {
656         struct mgcp_gateway *gw = (struct mgcp_gateway *)data;
657         struct mgcp_message *cur, *exq = NULL, *w, *prev;
658         int res = 0;
659
660         /* find out expired msgs */
661         ast_mutex_lock(&gw->msgs_lock);
662
663         for (prev = NULL, cur = gw->msgs; cur; prev = cur, cur = cur->next) {
664                 if (cur->retrans < MAX_RETRANS) {
665                         cur->retrans++;
666                         ast_debug(1, "Retransmitting #%d transaction %u on [%s]\n",
667                                 cur->retrans, cur->seqno, gw->name);
668                         __mgcp_xmit(gw, cur->buf, cur->len);
669                 } else {
670                         if (prev)
671                                 prev->next = cur->next;
672                         else
673                                 gw->msgs = cur->next;
674
675                         ast_log(LOG_WARNING, "Maximum retries exceeded for transaction %u on [%s]\n",
676                                 cur->seqno, gw->name);
677
678                         w = cur;
679
680                         if (exq) {
681                                 w->next = exq;
682                         } else {
683                                 w->next = NULL;
684                         }
685                         exq = w;
686                 }
687         }
688
689         if (!gw->msgs) {
690                 gw->retransid = -1;
691                 res = 0;
692         } else {
693                 res = 1;
694         }
695         ast_mutex_unlock(&gw->msgs_lock);
696
697         while (exq) {
698                 cur = exq;
699                 /* time-out transaction */
700                 handle_response(cur->owner_ep, cur->owner_sub, 406, cur->seqno, NULL);
701                 exq = exq->next;
702                 ast_free(cur);
703         }
704
705         return res;
706 }
707
708 /* modified for the new transaction mechanism */
709 static int mgcp_postrequest(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,
710                             char *data, int len, unsigned int seqno)
711 {
712         struct mgcp_message *msg;
713         struct mgcp_message *cur;
714         struct mgcp_gateway *gw;
715         struct timeval now;
716
717         if (!(msg = ast_malloc(sizeof(*msg) + len))) {
718                 return -1;
719         }
720         if (!(gw = ((p && p->parent) ? p->parent : NULL))) {
721                 ast_free(msg);
722                 return -1;
723         }
724
725         msg->owner_sub = sub;
726         msg->owner_ep = p;
727         msg->seqno = seqno;
728         msg->next = NULL;
729         msg->len = len;
730         msg->retrans = 0;
731         memcpy(msg->buf, data, msg->len);
732
733         ast_mutex_lock(&gw->msgs_lock);
734         for (cur = gw->msgs; cur && cur->next; cur = cur->next);
735         if (cur) {
736                 cur->next = msg;
737         } else {
738                 gw->msgs = msg;
739         }
740
741         now = ast_tvnow();
742         msg->expire = now.tv_sec * 1000 + now.tv_usec / 1000 + DEFAULT_RETRANS;
743
744         if (gw->retransid == -1)
745                 gw->retransid = ast_sched_add(sched, DEFAULT_RETRANS, retrans_pkt, (void *)gw);
746         ast_mutex_unlock(&gw->msgs_lock);
747         __mgcp_xmit(gw, msg->buf, msg->len);
748         /* XXX Should schedule retransmission XXX */
749         return 0;
750 }
751
752 /* modified for new transport */
753 static int send_request(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,
754                         struct mgcp_request *req, unsigned int seqno)
755 {
756         int res = 0;
757         struct mgcp_request **queue, *q, *r, *t;
758         ast_mutex_t *l;
759
760         ast_debug(1, "Slow sequence is %d\n", p->slowsequence);
761         if (p->slowsequence) {
762                 queue = &p->cmd_queue;
763                 l = &p->cmd_queue_lock;
764                 ast_mutex_lock(l);
765         } else {
766                 switch (req->cmd) {
767                 case MGCP_CMD_DLCX:
768                         queue = &sub->cx_queue;
769                         l = &sub->cx_queue_lock;
770                         ast_mutex_lock(l);
771                         q = sub->cx_queue;
772                         /* delete pending cx cmds */
773                         /* buggy sb5120 */
774                         if (!sub->parent->ncs) {
775                                 while (q) {
776                                         r = q->next;
777                                         ast_free(q);
778                                         q = r;
779                                 }
780                                 *queue = NULL;
781                         }
782                         break;
783
784                 case MGCP_CMD_CRCX:
785                 case MGCP_CMD_MDCX:
786                         queue = &sub->cx_queue;
787                         l = &sub->cx_queue_lock;
788                         ast_mutex_lock(l);
789                         break;
790
791                 case MGCP_CMD_RQNT:
792                         queue = &p->rqnt_queue;
793                         l = &p->rqnt_queue_lock;
794                         ast_mutex_lock(l);
795                         break;
796
797                 default:
798                         queue = &p->cmd_queue;
799                         l = &p->cmd_queue_lock;
800                         ast_mutex_lock(l);
801                         break;
802                 }
803         }
804
805         if (!(r = ast_malloc(sizeof(*r)))) {
806                 ast_log(LOG_WARNING, "Cannot post MGCP request: insufficient memory\n");
807                 ast_mutex_unlock(l);
808                 return -1;
809         }
810         memcpy(r, req, sizeof(*r));
811
812         if (!(*queue)) {
813                 ast_debug(1, "Posting Request:\n%s to %s:%d\n", req->data,
814                         ast_inet_ntoa(p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
815
816                 res = mgcp_postrequest(p, sub, req->data, req->len, seqno);
817         } else {
818                 ast_debug(1, "Queueing Request:\n%s to %s:%d\n", req->data,
819                         ast_inet_ntoa(p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
820         }
821
822         /* XXX find tail. We could also keep tail in the data struct for faster access */
823         for (t = *queue; t && t->next; t = t->next);
824
825         r->next = NULL;
826         if (t)
827                 t->next = r;
828         else
829                 *queue = r;
830
831         ast_mutex_unlock(l);
832
833         return res;
834 }
835
836 static int mgcp_call(struct ast_channel *ast, const char *dest, int timeout)
837 {
838         int res;
839         struct mgcp_endpoint *p;
840         struct mgcp_subchannel *sub;
841         char tone[50] = "";
842         const char *distinctive_ring = pbx_builtin_getvar_helper(ast, "ALERT_INFO");
843
844         ast_debug(3, "MGCP mgcp_call(%s)\n", ast_channel_name(ast));
845         sub = ast_channel_tech_pvt(ast);
846         p = sub->parent;
847
848         ast_mutex_lock(&sub->lock);
849         switch (p->hookstate) {
850         case MGCP_OFFHOOK:
851                 if (!ast_strlen_zero(distinctive_ring)) {
852                         snprintf(tone, sizeof(tone), "L/wt%s", distinctive_ring);
853                         ast_debug(3, "MGCP distinctive callwait %s\n", tone);
854                 } else {
855                         ast_copy_string(tone, (p->ncs ? "L/wt1" : "L/wt"), sizeof(tone));
856                         ast_debug(3, "MGCP normal callwait %s\n", tone);
857                 }
858                 break;
859         case MGCP_ONHOOK:
860         default:
861                 if (!ast_strlen_zero(distinctive_ring)) {
862                         snprintf(tone, sizeof(tone), "L/r%s", distinctive_ring);
863                         ast_debug(3, "MGCP distinctive ring %s\n", tone);
864                 } else {
865                         ast_copy_string(tone, "L/rg", sizeof(tone));
866                         ast_debug(3, "MGCP default ring\n");
867                 }
868                 break;
869         }
870
871         if ((ast_channel_state(ast) != AST_STATE_DOWN) && (ast_channel_state(ast) != AST_STATE_RESERVED)) {
872                 ast_log(LOG_WARNING, "mgcp_call called on %s, neither down nor reserved\n", ast_channel_name(ast));
873                 ast_mutex_unlock(&sub->lock);
874                 return -1;
875         }
876
877         res = 0;
878         sub->outgoing = 1;
879         sub->cxmode = MGCP_CX_RECVONLY;
880         ast_setstate(ast, AST_STATE_RINGING);
881         if (p->type == TYPE_LINE) {
882                 if (!sub->rtp) {
883                         start_rtp(sub);
884                 } else {
885                         transmit_modify_request(sub);
886                 }
887
888                 if (sub->next->owner && !ast_strlen_zero(sub->next->cxident) && !ast_strlen_zero(sub->next->callid)) {
889                         /* try to prevent a callwait from disturbing the other connection */
890                         sub->next->cxmode = MGCP_CX_RECVONLY;
891                         transmit_modify_request(sub->next);
892                 }
893
894                 transmit_notify_request_with_callerid(sub, tone,
895                         S_COR(ast_channel_connected(ast)->id.number.valid, ast_channel_connected(ast)->id.number.str, ""),
896                         S_COR(ast_channel_connected(ast)->id.name.valid, ast_channel_connected(ast)->id.name.str, ""));
897                 ast_setstate(ast, AST_STATE_RINGING);
898
899                 if (sub->next->owner && !ast_strlen_zero(sub->next->cxident) && !ast_strlen_zero(sub->next->callid)) {
900                         /* Put the connection back in sendrecv */
901                         sub->next->cxmode = MGCP_CX_SENDRECV;
902                         transmit_modify_request(sub->next);
903                 }
904         } else {
905                 ast_log(LOG_NOTICE, "Don't know how to dial on trunks yet\n");
906                 res = -1;
907         }
908         ast_mutex_unlock(&sub->lock);
909         return res;
910 }
911
912 static int mgcp_hangup(struct ast_channel *ast)
913 {
914         struct mgcp_subchannel *sub = ast_channel_tech_pvt(ast);
915         struct mgcp_endpoint *p = sub->parent;
916
917         ast_debug(1, "mgcp_hangup(%s)\n", ast_channel_name(ast));
918         if (!ast_channel_tech_pvt(ast)) {
919                 ast_debug(1, "Asked to hangup channel not connected\n");
920                 return 0;
921         }
922         if (strcmp(sub->magic, MGCP_SUBCHANNEL_MAGIC)) {
923                 ast_debug(1, "Invalid magic. MGCP subchannel freed up already.\n");
924                 return 0;
925         }
926         ast_mutex_lock(&sub->lock);
927         ast_debug(3, "MGCP mgcp_hangup(%s) on %s@%s\n", ast_channel_name(ast), p->name, p->parent->name);
928
929         if ((p->dtmfmode & MGCP_DTMF_INBAND) && p->dsp) {
930                 /* check whether other channel is active. */
931                 if (!sub->next->owner) {
932                         if (p->dtmfmode & MGCP_DTMF_HYBRID) {
933                                 p->dtmfmode &= ~MGCP_DTMF_INBAND;
934                         }
935                         ast_debug(2, "MGCP free dsp on %s@%s\n", p->name, p->parent->name);
936                         ast_dsp_free(p->dsp);
937                         p->dsp = NULL;
938                 }
939         }
940
941         mgcp_set_owner(sub, NULL);
942
943         /* for deleting gate */
944         if (p->pktcgatealloc && sub->gate) {
945                 sub->gate->gate_open = NULL;
946                 sub->gate->gate_remove = NULL;
947                 sub->gate->got_dq_gi = NULL;
948                 sub->gate->tech_pvt = NULL;
949                 if (sub->gate->state == GATE_ALLOC_PROGRESS || sub->gate->state == GATE_ALLOCATED) {
950                         ast_pktccops_gate_alloc(GATE_DEL, sub->gate, 0, 0, 0, 0, 0, 0, NULL, NULL);
951                 } else {
952                         sub->gate->deltimer = time(NULL) + 5;
953                 }
954                 sub->gate = NULL;
955         }
956
957         if (!ast_strlen_zero(sub->cxident)) {
958                 transmit_connection_del(sub);
959         }
960         sub->cxident[0] = '\0';
961         if ((sub == p->sub) && sub->next->owner) {
962                 RAII_VAR(struct ast_channel *, bridged, ast_channel_bridge_peer(sub->next->owner), ast_channel_cleanup);
963
964                 if (p->hookstate == MGCP_OFFHOOK) {
965                         if (sub->next->owner && bridged) {
966                                 /* ncs fix! */
967                                 transmit_notify_request_with_callerid(p->sub, (p->ncs ? "L/wt1" : "L/wt"),
968                                         S_COR(ast_channel_caller(bridged)->id.number.valid, ast_channel_caller(bridged)->id.number.str, ""),
969                                         S_COR(ast_channel_caller(bridged)->id.name.valid, ast_channel_caller(bridged)->id.name.str, ""));
970                         }
971                 } else {
972                         /* set our other connection as the primary and swith over to it */
973                         p->sub = sub->next;
974                         p->sub->cxmode = MGCP_CX_RECVONLY;
975                         transmit_modify_request(p->sub);
976                         if (sub->next->owner && bridged) {
977                                 transmit_notify_request_with_callerid(p->sub, "L/rg",
978                                         S_COR(ast_channel_caller(bridged)->id.number.valid, ast_channel_caller(bridged)->id.number.str, ""),
979                                         S_COR(ast_channel_caller(bridged)->id.name.valid, ast_channel_caller(bridged)->id.name.str, ""));
980                         }
981                 }
982
983         } else if ((sub == p->sub->next) && p->hookstate == MGCP_OFFHOOK) {
984                 transmit_notify_request(sub, p->ncs ? "" : "L/v");
985         } else if (p->hookstate == MGCP_OFFHOOK) {
986                 transmit_notify_request(sub, "L/ro");
987         } else {
988                 transmit_notify_request(sub, "");
989         }
990
991         ast_channel_tech_pvt_set(ast, NULL);
992         sub->alreadygone = 0;
993         sub->outgoing = 0;
994         sub->cxmode = MGCP_CX_INACTIVE;
995         sub->callid[0] = '\0';
996         if (p) {
997                 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
998         }
999         /* Reset temporary destination */
1000         memset(&sub->tmpdest, 0, sizeof(sub->tmpdest));
1001         if (sub->rtp) {
1002                 ast_rtp_instance_destroy(sub->rtp);
1003                 sub->rtp = NULL;
1004         }
1005
1006         ast_module_unref(ast_module_info->self);
1007
1008         if ((p->hookstate == MGCP_ONHOOK) && (!sub->next->rtp)) {
1009                 p->hidecallerid = 0;
1010                 if (p->hascallwaiting && !p->callwaiting) {
1011                         ast_verb(3, "Enabling call waiting on %s\n", ast_channel_name(ast));
1012                         p->callwaiting = -1;
1013                 }
1014                 if (has_voicemail(p)) {
1015                         ast_debug(3, "MGCP mgcp_hangup(%s) on %s@%s set vmwi(+)\n",
1016                                 ast_channel_name(ast), p->name, p->parent->name);
1017                         transmit_notify_request(sub, "L/vmwi(+)");
1018                 } else {
1019                         ast_debug(3, "MGCP mgcp_hangup(%s) on %s@%s set vmwi(-)\n",
1020                                 ast_channel_name(ast), p->name, p->parent->name);
1021                         transmit_notify_request(sub, "L/vmwi(-)");
1022                 }
1023         }
1024         ast_mutex_unlock(&sub->lock);
1025         return 0;
1026 }
1027
1028 static char *handle_mgcp_show_endpoints(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1029 {
1030         struct mgcp_gateway  *mg;
1031         struct mgcp_endpoint *me;
1032         int hasendpoints = 0;
1033         struct ast_variable * v = NULL;
1034
1035         switch (cmd) {
1036         case CLI_INIT:
1037                 e->command = "mgcp show endpoints";
1038                 e->usage =
1039                         "Usage: mgcp show endpoints\n"
1040                         "       Lists all endpoints known to the MGCP (Media Gateway Control Protocol) subsystem.\n";
1041                 return NULL;
1042         case CLI_GENERATE:
1043                 return NULL;
1044         }
1045
1046         if (a->argc != 3) {
1047                 return CLI_SHOWUSAGE;
1048         }
1049         ast_mutex_lock(&gatelock);
1050         for (mg = gateways; mg; mg = mg->next) {
1051                 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");
1052                 for (me = mg->endpoints; me; me = me->next) {
1053                         ast_cli(a->fd, "   -- '%s@%s in '%s' is %s\n", me->name, mg->name, me->context, me->sub->owner ? "active" : "idle");
1054                         if (me->chanvars) {
1055                                 ast_cli(a->fd, "  Variables:\n");
1056                                 for (v = me->chanvars ; v ; v = v->next) {
1057                                         ast_cli(a->fd, "    %s = '%s'\n", v->name, v->value);
1058                                 }
1059                         }
1060                         hasendpoints = 1;
1061                 }
1062                 if (!hasendpoints) {
1063                         ast_cli(a->fd, "   << No Endpoints Defined >>     ");
1064                 }
1065         }
1066         ast_mutex_unlock(&gatelock);
1067         return CLI_SUCCESS;
1068 }
1069
1070 static char *handle_mgcp_audit_endpoint(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1071 {
1072         struct mgcp_gateway  *mg;
1073         struct mgcp_endpoint *me;
1074         int found = 0;
1075         char *ename,*gname, *c;
1076
1077         switch (cmd) {
1078         case CLI_INIT:
1079                 e->command = "mgcp audit endpoint";
1080                 e->usage =
1081                         "Usage: mgcp audit endpoint <endpointid>\n"
1082                         "       Lists the capabilities of an endpoint in the MGCP (Media Gateway Control Protocol) subsystem.\n"
1083                         "       mgcp debug MUST be on to see the results of this command.\n";
1084                 return NULL;
1085         case CLI_GENERATE:
1086                 return NULL;
1087         }
1088
1089         if (!mgcpdebug) {
1090                 return CLI_SHOWUSAGE;
1091         }
1092         if (a->argc != 4)
1093                 return CLI_SHOWUSAGE;
1094         /* split the name into parts by null */
1095         ename = ast_strdupa(a->argv[3]);
1096         for (gname = ename; *gname; gname++) {
1097                 if (*gname == '@') {
1098                         *gname = 0;
1099                         gname++;
1100                         break;
1101                 }
1102         }
1103         if (gname[0] == '[') {
1104                 gname++;
1105         }
1106         if ((c = strrchr(gname, ']'))) {
1107                 *c = '\0';
1108         }
1109         ast_mutex_lock(&gatelock);
1110         for (mg = gateways; mg; mg = mg->next) {
1111                 if (!strcasecmp(mg->name, gname)) {
1112                         for (me = mg->endpoints; me; me = me->next) {
1113                                 if (!strcasecmp(me->name, ename)) {
1114                                         found = 1;
1115                                         transmit_audit_endpoint(me);
1116                                         break;
1117                                 }
1118                         }
1119                         if (found) {
1120                                 break;
1121                         }
1122                 }
1123         }
1124         if (!found) {
1125                 ast_cli(a->fd, "   << Could not find endpoint >>     ");
1126         }
1127         ast_mutex_unlock(&gatelock);
1128         return CLI_SUCCESS;
1129 }
1130
1131 static char *handle_mgcp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1132 {
1133         switch (cmd) {
1134         case CLI_INIT:
1135                 e->command = "mgcp set debug {on|off}";
1136                 e->usage =
1137                         "Usage: mgcp set debug {on|off}\n"
1138                         "       Enables/Disables dumping of MGCP packets for debugging purposes\n";
1139                 return NULL;
1140         case CLI_GENERATE:
1141                 return NULL;
1142         }
1143
1144         if (a->argc != e->args)
1145                 return CLI_SHOWUSAGE;
1146
1147         if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
1148                 mgcpdebug = 1;
1149                 ast_cli(a->fd, "MGCP Debugging Enabled\n");
1150         } else if (!strncasecmp(a->argv[3], "off", 3)) {
1151                 mgcpdebug = 0;
1152                 ast_cli(a->fd, "MGCP Debugging Disabled\n");
1153         } else {
1154                 return CLI_SHOWUSAGE;
1155         }
1156         return CLI_SUCCESS;
1157 }
1158
1159 static struct ast_cli_entry cli_mgcp[] = {
1160         AST_CLI_DEFINE(handle_mgcp_audit_endpoint, "Audit specified MGCP endpoint"),
1161         AST_CLI_DEFINE(handle_mgcp_show_endpoints, "List defined MGCP endpoints"),
1162         AST_CLI_DEFINE(handle_mgcp_set_debug, "Enable/Disable MGCP debugging"),
1163         AST_CLI_DEFINE(mgcp_reload, "Reload MGCP configuration"),
1164 };
1165
1166 static int mgcp_answer(struct ast_channel *ast)
1167 {
1168         int res = 0;
1169         struct mgcp_subchannel *sub = ast_channel_tech_pvt(ast);
1170         struct mgcp_endpoint *p = sub->parent;
1171
1172         ast_mutex_lock(&sub->lock);
1173         sub->cxmode = MGCP_CX_SENDRECV;
1174         if (!sub->rtp) {
1175                 start_rtp(sub);
1176         } else {
1177                 transmit_modify_request(sub);
1178         }
1179         ast_verb(3, "MGCP mgcp_answer(%s) on %s@%s-%d\n",
1180                         ast_channel_name(ast), p->name, p->parent->name, sub->id);
1181         if (ast_channel_state(ast) != AST_STATE_UP) {
1182                 ast_setstate(ast, AST_STATE_UP);
1183                 ast_debug(1, "mgcp_answer(%s)\n", ast_channel_name(ast));
1184                 transmit_notify_request(sub, "");
1185                 transmit_modify_request(sub);
1186         }
1187         ast_mutex_unlock(&sub->lock);
1188         return res;
1189 }
1190
1191 static struct ast_frame *mgcp_rtp_read(struct mgcp_subchannel *sub)
1192 {
1193         /* Retrieve audio/etc from channel.  Assumes sub->lock is already held. */
1194         struct ast_frame *f;
1195
1196         f = ast_rtp_instance_read(sub->rtp, 0);
1197         /* Don't send RFC2833 if we're not supposed to */
1198         if (f && (f->frametype == AST_FRAME_DTMF) && !(sub->parent->dtmfmode & MGCP_DTMF_RFC2833))
1199                 return &ast_null_frame;
1200         if (sub->owner) {
1201                 /* We already hold the channel lock */
1202                 if (f->frametype == AST_FRAME_VOICE) {
1203                         if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(sub->owner), f->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
1204                                 struct ast_format_cap *caps;
1205
1206                                 ast_debug(1, "Oooh, format changed to %s\n", ast_format_get_name(f->subclass.format));
1207
1208                                 caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1209                                 if (caps) {
1210                                         ast_format_cap_append(caps, f->subclass.format, 0);
1211                                         ast_channel_nativeformats_set(sub->owner, caps);
1212                                         ao2_ref(caps, -1);
1213                                 } else {
1214                                         return &ast_null_frame;
1215                                 }
1216
1217                                 ast_set_read_format(sub->owner, ast_channel_readformat(sub->owner));
1218                                 ast_set_write_format(sub->owner, ast_channel_writeformat(sub->owner));
1219                         }
1220                         /* Courtesy fearnor aka alex@pilosoft.com */
1221                         if ((sub->parent->dtmfmode & MGCP_DTMF_INBAND) && (sub->parent->dsp)) {
1222 #if 0
1223                                 ast_log(LOG_NOTICE, "MGCP ast_dsp_process\n");
1224 #endif
1225                                 f = ast_dsp_process(sub->owner, sub->parent->dsp, f);
1226                         }
1227                 }
1228         }
1229         return f;
1230 }
1231
1232 static void mgcp_set_owner(struct mgcp_subchannel *sub, struct ast_channel *chan)
1233 {
1234         sub->owner = chan;
1235         if (sub->rtp) {
1236                 ast_rtp_instance_set_channel_id(sub->rtp, sub->owner ? ast_channel_uniqueid(chan) : "");
1237         }
1238 }
1239
1240 static struct ast_frame *mgcp_read(struct ast_channel *ast)
1241 {
1242         struct ast_frame *f;
1243         struct mgcp_subchannel *sub = ast_channel_tech_pvt(ast);
1244         ast_mutex_lock(&sub->lock);
1245         f = mgcp_rtp_read(sub);
1246         ast_mutex_unlock(&sub->lock);
1247         return f;
1248 }
1249
1250 static int mgcp_write(struct ast_channel *ast, struct ast_frame *frame)
1251 {
1252         struct mgcp_subchannel *sub = ast_channel_tech_pvt(ast);
1253         int res = 0;
1254
1255         if (frame->frametype != AST_FRAME_VOICE) {
1256                 if (frame->frametype == AST_FRAME_IMAGE)
1257                         return 0;
1258                 else {
1259                         ast_log(LOG_WARNING, "Can't send %u type frames with MGCP write\n", frame->frametype);
1260                         return 0;
1261                 }
1262         } else {
1263                 if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), frame->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
1264                         struct ast_str *cap_buf = ast_str_alloca(64);
1265
1266                         ast_log(LOG_WARNING, "Asked to transmit frame type %s, while native formats is %s (read/write = %s/%s)\n",
1267                                 ast_format_get_name(frame->subclass.format),
1268                                 ast_format_cap_get_names(ast_channel_nativeformats(ast), &cap_buf),
1269                                 ast_format_get_name(ast_channel_readformat(ast)),
1270                                 ast_format_get_name(ast_channel_writeformat(ast)));
1271                         /* return -1; */
1272                 }
1273         }
1274         if (sub) {
1275                 ast_mutex_lock(&sub->lock);
1276                 if (!sub->sdpsent && sub->gate) {
1277                         if (sub->gate->state == GATE_ALLOCATED) {
1278                                 ast_debug(1, "GATE ALLOCATED, sending sdp\n");
1279                                 transmit_modify_with_sdp(sub, NULL, 0);
1280                         }
1281                 }
1282                 if ((sub->parent->sub == sub) || !sub->parent->singlepath) {
1283                         if (sub->rtp) {
1284                                 res =  ast_rtp_instance_write(sub->rtp, frame);
1285                         }
1286                 }
1287                 ast_mutex_unlock(&sub->lock);
1288         }
1289         return res;
1290 }
1291
1292 static int mgcp_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1293 {
1294         struct mgcp_subchannel *sub = ast_channel_tech_pvt(newchan);
1295
1296         ast_mutex_lock(&sub->lock);
1297         ast_log(LOG_NOTICE, "mgcp_fixup(%s, %s)\n", ast_channel_name(oldchan), ast_channel_name(newchan));
1298         if (sub->owner != oldchan) {
1299                 ast_mutex_unlock(&sub->lock);
1300                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, sub->owner);
1301                 return -1;
1302         }
1303         mgcp_set_owner(sub, newchan);
1304         ast_mutex_unlock(&sub->lock);
1305         return 0;
1306 }
1307
1308 static int mgcp_senddigit_begin(struct ast_channel *ast, char digit)
1309 {
1310         struct mgcp_subchannel *sub = ast_channel_tech_pvt(ast);
1311         struct mgcp_endpoint *p = sub->parent;
1312         int res = 0;
1313
1314         ast_mutex_lock(&sub->lock);
1315         if (p->dtmfmode & MGCP_DTMF_INBAND || p->dtmfmode & MGCP_DTMF_HYBRID) {
1316                 ast_debug(1, "Sending DTMF using inband/hybrid\n");
1317                 res = -1; /* Let asterisk play inband indications */
1318         } else if (p->dtmfmode & MGCP_DTMF_RFC2833) {
1319                 ast_debug(1, "Sending DTMF using RFC2833\n");
1320                 ast_rtp_instance_dtmf_begin(sub->rtp, digit);
1321         } else {
1322                 ast_log(LOG_ERROR, "Don't know about DTMF_MODE %d\n", p->dtmfmode);
1323         }
1324         ast_mutex_unlock(&sub->lock);
1325
1326         return res;
1327 }
1328
1329 static int mgcp_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
1330 {
1331         struct mgcp_subchannel *sub = ast_channel_tech_pvt(ast);
1332         struct mgcp_endpoint *p = sub->parent;
1333         int res = 0;
1334         char tmp[4];
1335
1336         ast_mutex_lock(&sub->lock);
1337         if (p->dtmfmode & MGCP_DTMF_INBAND || p->dtmfmode & MGCP_DTMF_HYBRID) {
1338                 ast_debug(1, "Stopping DTMF using inband/hybrid\n");
1339                 res = -1; /* Tell Asterisk to stop inband indications */
1340         } else if (p->dtmfmode & MGCP_DTMF_RFC2833) {
1341                 ast_debug(1, "Stopping DTMF using RFC2833\n");
1342                 if (sub->parent->ncs) {
1343                         tmp[0] = digit;
1344                         tmp[1] = '\0';
1345                 } else {
1346                         tmp[0] = 'D';
1347                         tmp[1] = '/';
1348                         tmp[2] = digit;
1349                         tmp[3] = '\0';
1350                 }
1351                 transmit_notify_request(sub, tmp);
1352                 ast_rtp_instance_dtmf_end(sub->rtp, digit);
1353         } else {
1354                 ast_log(LOG_ERROR, "Don't know about DTMF_MODE %d\n", p->dtmfmode);
1355         }
1356         ast_mutex_unlock(&sub->lock);
1357
1358         return res;
1359 }
1360
1361 /*!
1362  *  \brief  mgcp_devicestate: channel callback for device status monitoring
1363  *  \param  data tech/resource name of MGCP device to query
1364  *
1365  * Callback for device state management in channel subsystem
1366  * to obtain device status (up/down) of a specific MGCP endpoint
1367  *
1368  *  \return device status result (from devicestate.h) AST_DEVICE_INVALID (not available) or AST_DEVICE_UNKNOWN (available but unknown state)
1369  */
1370 static int mgcp_devicestate(const char *data)
1371 {
1372         struct mgcp_gateway  *g;
1373         struct mgcp_endpoint *e = NULL;
1374         char *tmp, *endpt, *gw;
1375         int ret = AST_DEVICE_INVALID;
1376
1377         endpt = ast_strdupa(data);
1378         if ((tmp = strchr(endpt, '@'))) {
1379                 *tmp++ = '\0';
1380                 gw = tmp;
1381         } else
1382                 goto error;
1383
1384         ast_mutex_lock(&gatelock);
1385         for (g = gateways; g; g = g->next) {
1386                 if (strcasecmp(g->name, gw) == 0) {
1387                         e = g->endpoints;
1388                         break;
1389                 }
1390         }
1391
1392         if (!e)
1393                 goto error;
1394
1395         for (; e; e = e->next) {
1396                 if (strcasecmp(e->name, endpt) == 0) {
1397                         break;
1398                 }
1399         }
1400
1401         if (!e)
1402                 goto error;
1403
1404         /*
1405          * As long as the gateway/endpoint is valid, we'll
1406          * assume that the device is available and its state
1407          * can be tracked.
1408          */
1409         ret = AST_DEVICE_UNKNOWN;
1410
1411 error:
1412         ast_mutex_unlock(&gatelock);
1413         return ret;
1414 }
1415
1416 static char *control2str(int ind) {
1417         switch (ind) {
1418         case AST_CONTROL_HANGUP:
1419                 return "Other end has hungup";
1420         case AST_CONTROL_RING:
1421                 return "Local ring";
1422         case AST_CONTROL_RINGING:
1423                 return "Remote end is ringing";
1424         case AST_CONTROL_ANSWER:
1425                 return "Remote end has answered";
1426         case AST_CONTROL_BUSY:
1427                 return "Remote end is busy";
1428         case AST_CONTROL_TAKEOFFHOOK:
1429                 return "Make it go off hook";
1430         case AST_CONTROL_OFFHOOK:
1431                 return "Line is off hook";
1432         case AST_CONTROL_CONGESTION:
1433                 return "Congestion (circuits busy)";
1434         case AST_CONTROL_FLASH:
1435                 return "Flash hook";
1436         case AST_CONTROL_WINK:
1437                 return "Wink";
1438         case AST_CONTROL_OPTION:
1439                 return "Set a low-level option";
1440         case AST_CONTROL_RADIO_KEY:
1441                 return "Key Radio";
1442         case AST_CONTROL_RADIO_UNKEY:
1443                 return "Un-Key Radio";
1444         }
1445         return "UNKNOWN";
1446 }
1447
1448 static int mgcp_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen)
1449 {
1450         struct mgcp_subchannel *sub = ast_channel_tech_pvt(ast);
1451         int res = 0;
1452
1453         ast_debug(3, "MGCP asked to indicate %d '%s' condition on channel %s\n",
1454                 ind, control2str(ind), ast_channel_name(ast));
1455         ast_mutex_lock(&sub->lock);
1456         switch(ind) {
1457         case AST_CONTROL_RINGING:
1458 #ifdef DLINK_BUGGY_FIRMWARE
1459                 transmit_notify_request(sub, "rt");
1460 #else
1461                 if (!sub->sdpsent) { /* will hide the inband progress!!! */
1462                         transmit_notify_request(sub, sub->parent->ncs ? "L/rt" : "G/rt");
1463                 }
1464 #endif
1465                 break;
1466         case AST_CONTROL_BUSY:
1467                 transmit_notify_request(sub, "L/bz");
1468                 break;
1469         case AST_CONTROL_INCOMPLETE:
1470                 /* We do not currently support resetting of the Interdigit Timer, so treat
1471                  * Incomplete control frames as a congestion response
1472                  */
1473         case AST_CONTROL_CONGESTION:
1474                 transmit_notify_request(sub, sub->parent->ncs ? "L/cg" : "G/cg");
1475                 break;
1476         case AST_CONTROL_HOLD:
1477                 ast_moh_start(ast, data, NULL);
1478                 break;
1479         case AST_CONTROL_UNHOLD:
1480                 ast_moh_stop(ast);
1481                 break;
1482         case AST_CONTROL_SRCUPDATE:
1483                 ast_rtp_instance_update_source(sub->rtp);
1484                 break;
1485         case AST_CONTROL_SRCCHANGE:
1486                 ast_rtp_instance_change_source(sub->rtp);
1487                 break;
1488         case AST_CONTROL_PROGRESS:
1489         case AST_CONTROL_PROCEEDING:
1490                 transmit_modify_request(sub);
1491         case -1:
1492                 transmit_notify_request(sub, "");
1493                 break;
1494         default:
1495                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", ind);
1496                 /* fallthrough */
1497         case AST_CONTROL_PVT_CAUSE_CODE:
1498                 res = -1;
1499         }
1500         ast_mutex_unlock(&sub->lock);
1501         return res;
1502 }
1503
1504 static struct ast_channel *mgcp_new(struct mgcp_subchannel *sub, int state, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor)
1505 {
1506         struct ast_format_cap *caps = NULL;
1507         struct ast_channel *tmp;
1508         struct ast_variable *v = NULL;
1509         struct mgcp_endpoint *i = sub->parent;
1510         struct ast_format *tmpfmt;
1511
1512         caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1513         if (!caps) {
1514                 ast_log(LOG_ERROR, "Format capabilities could not be created\n");
1515                 return NULL;
1516         }
1517         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);
1518         if (!tmp) {
1519                 ast_log(LOG_WARNING, "Channel could not be created\n");
1520                 ao2_ref(caps, -1);
1521                 return NULL;
1522         }
1523
1524         ast_channel_stage_snapshot(tmp);
1525         ast_channel_tech_set(tmp, &mgcp_tech);
1526         if (ast_format_cap_count(i->cap)) {
1527                 ast_format_cap_append_from_cap(caps, i->cap, AST_MEDIA_TYPE_UNKNOWN);
1528         } else {
1529                 ast_format_cap_append_from_cap(caps, global_capability, AST_MEDIA_TYPE_UNKNOWN);
1530         }
1531         ast_channel_nativeformats_set(tmp, caps);
1532         ao2_ref(caps, -1);
1533         if (sub->rtp) {
1534                 ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(sub->rtp, 0));
1535         }
1536         if (i->dtmfmode & (MGCP_DTMF_INBAND | MGCP_DTMF_HYBRID)) {
1537                 i->dsp = ast_dsp_new();
1538                 ast_dsp_set_features(i->dsp, DSP_FEATURE_DIGIT_DETECT);
1539                 /* this is to prevent clipping of dtmf tones during dsp processing */
1540                 ast_dsp_set_digitmode(i->dsp, DSP_DIGITMODE_NOQUELCH);
1541         } else {
1542                 i->dsp = NULL;
1543         }
1544         if (state == AST_STATE_RING) {
1545                 ast_channel_rings_set(tmp, 1);
1546         }
1547
1548         tmpfmt = ast_format_cap_get_format(ast_channel_nativeformats(tmp), 0);
1549         ast_channel_set_writeformat(tmp, tmpfmt);
1550         ast_channel_set_rawwriteformat(tmp, tmpfmt);
1551         ast_channel_set_readformat(tmp, tmpfmt);
1552         ast_channel_set_rawreadformat(tmp, tmpfmt);
1553         ao2_ref(tmpfmt, -1);
1554         ast_channel_tech_pvt_set(tmp, sub);
1555         if (!ast_strlen_zero(i->language))
1556                 ast_channel_language_set(tmp, i->language);
1557         if (!ast_strlen_zero(i->accountcode))
1558                 ast_channel_accountcode_set(tmp, i->accountcode);
1559         if (i->amaflags)
1560                 ast_channel_amaflags_set(tmp, i->amaflags);
1561         mgcp_set_owner(sub, tmp);
1562         ast_module_ref(ast_module_info->self);
1563         ast_channel_callgroup_set(tmp, i->callgroup);
1564         ast_channel_pickupgroup_set(tmp, i->pickupgroup);
1565         ast_channel_call_forward_set(tmp, i->call_forward);
1566         ast_channel_context_set(tmp, i->context);
1567         ast_channel_exten_set(tmp, i->exten);
1568         /* Don't use ast_set_callerid() here because it will
1569          * generate a needless NewCallerID event */
1570         if (!ast_strlen_zero(i->cid_num)) {
1571                 ast_channel_caller(tmp)->ani.number.valid = 1;
1572                 ast_channel_caller(tmp)->ani.number.str = ast_strdup(i->cid_num);
1573         }
1574
1575         if (!i->adsi) {
1576                 ast_channel_adsicpe_set(tmp, AST_ADSI_UNAVAILABLE);
1577         }
1578         ast_channel_priority_set(tmp, 1);
1579
1580         /* Set channel variables for this call from configuration */
1581         for (v = i->chanvars ; v ; v = v->next) {
1582                 char valuebuf[1024];
1583                 pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
1584         }
1585
1586         if (sub->rtp) {
1587                 ast_jb_configure(tmp, &global_jbconf);
1588         }
1589
1590         ast_channel_stage_snapshot_done(tmp);
1591         ast_channel_unlock(tmp);
1592
1593         if (state != AST_STATE_DOWN) {
1594                 if (ast_pbx_start(tmp)) {
1595                         ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ast_channel_name(tmp));
1596                         ast_hangup(tmp);
1597                         tmp = NULL;
1598                 }
1599         }
1600         ast_verb(3, "MGCP mgcp_new(%s) created in state: %s\n",
1601                         ast_channel_name(tmp), ast_state2str(state));
1602
1603         return tmp;
1604 }
1605
1606 static char *get_sdp_by_line(char* line, char *name, int nameLen)
1607 {
1608         if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1609                 char *r = line + nameLen + 1;
1610                 while (*r && (*r < 33)) ++r;
1611                 return r;
1612         }
1613         return "";
1614 }
1615
1616 static char *get_sdp(struct mgcp_request *req, char *name)
1617 {
1618         int x;
1619         int len = strlen(name);
1620         char *r;
1621
1622         for (x = 0; x < req->lines; x++) {
1623                 r = get_sdp_by_line(req->line[x], name, len);
1624                 if (r[0] != '\0') return r;
1625         }
1626         return "";
1627 }
1628
1629 static void sdpLineNum_iterator_init(int *iterator)
1630 {
1631         *iterator = 0;
1632 }
1633
1634 static char *get_sdp_iterate(int* iterator, struct mgcp_request *req, char *name)
1635 {
1636         int len = strlen(name);
1637         char *r;
1638         while (*iterator < req->lines) {
1639                 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1640                 if (r[0] != '\0') return r;
1641         }
1642         return "";
1643 }
1644
1645 static char *__get_header(struct mgcp_request *req, char *name, int *start, char *def)
1646 {
1647         int x;
1648         int len = strlen(name);
1649         char *r;
1650         for (x = *start; x < req->headers; x++) {
1651                 if (!strncasecmp(req->header[x], name, len) &&
1652                     (req->header[x][len] == ':')) {
1653                         r = req->header[x] + len + 1;
1654                         while (*r && (*r < 33)) {
1655                                 r++;
1656                         }
1657                         *start = x + 1;
1658                         return r;
1659                 }
1660         }
1661         /* Don't return NULL, so get_header is always a valid pointer */
1662         return def;
1663 }
1664
1665 static char *get_header(struct mgcp_request *req, char *name)
1666 {
1667         int start = 0;
1668         return __get_header(req, name, &start, "");
1669 }
1670
1671 /*! \brief get_csv: (SC:) get comma separated value */
1672 static char *get_csv(char *c, int *len, char **next)
1673 {
1674         char *s;
1675
1676         *next = NULL, *len = 0;
1677         if (!c) return NULL;
1678
1679         while (*c && (*c < 33 || *c == ',')) {
1680                 c++;
1681         }
1682
1683         s = c;
1684         while (*c && (*c >= 33 && *c != ',')) {
1685                 c++, (*len)++;
1686         }
1687         *next = c;
1688
1689         if (*len == 0) {
1690                 s = NULL, *next = NULL;
1691         }
1692
1693         return s;
1694 }
1695
1696 static struct mgcp_gateway *find_realtime_gw(char *name, char *at, struct sockaddr_in *sin)
1697 {
1698         struct mgcp_gateway *g = NULL;
1699         struct ast_variable *mgcpgwconfig = NULL;
1700         struct ast_variable *gwv, *epname = NULL;
1701         struct mgcp_endpoint *e;
1702         char lines[256];
1703         int i, j;
1704
1705         ast_debug(1, "*** find Realtime MGCPGW\n");
1706
1707         if (!(i = ast_check_realtime("mgcpgw")) || !(j = ast_check_realtime("mgcpep"))) {
1708                 return NULL;
1709         }
1710
1711         if (ast_strlen_zero(at)) {
1712                 ast_debug(1, "null gw name\n");
1713                 return NULL;
1714         }
1715
1716         if (!(mgcpgwconfig = ast_load_realtime("mgcpgw", "name", at, NULL))) {
1717                 return NULL;
1718         }
1719
1720         /*!
1721          * \note This is a fairly odd way of instantiating lines.  Instead of each
1722          * line created by virtue of being in the database (and loaded via
1723          * ast_load_realtime_multientry), this code forces a specific order with a
1724          * "lines" entry in the "mgcpgw" record.  This has benefits, because as with
1725          * chan_dahdi, values are inherited across definitions.  The downside is
1726          * that it's not as clear what the values will be simply by looking at a
1727          * single row in the database, and it's probable that the sanest configuration
1728          * should have the first column in the "mgcpep" table be "clearvars", with a
1729          * static value of "all", if any variables are set at all.  It may be worth
1730          * making this assumption explicit in the code in the future, and then just
1731          * using ast_load_realtime_multientry for the "mgcpep" records.
1732          */
1733         lines[0] = '\0';
1734         for (gwv = mgcpgwconfig; gwv; gwv = gwv->next) {
1735                 if (!strcasecmp(gwv->name, "lines")) {
1736                         ast_copy_string(lines, gwv->value, sizeof(lines));
1737                         break;
1738                 }
1739         }
1740         /* Position gwv at the end of the list */
1741         for (gwv = gwv && gwv->next ? gwv : mgcpgwconfig; gwv->next; gwv = gwv->next);
1742
1743         if (!ast_strlen_zero(lines)) {
1744                 AST_DECLARE_APP_ARGS(args,
1745                         AST_APP_ARG(line)[100];
1746                 );
1747                 AST_STANDARD_APP_ARGS(args, lines);
1748                 for (i = 0; i < args.argc; i++) {
1749                         gwv->next = ast_load_realtime("mgcpep", "name", at, "line", args.line[i], NULL);
1750
1751                         /* Remove "line" AND position gwv at the end of the list. */
1752                         for (epname = NULL; gwv->next; gwv = gwv->next) {
1753                                 if (!strcasecmp(gwv->next->name, "line")) {
1754                                         /* Remove it from the list */
1755                                         epname = gwv->next;
1756                                         gwv->next = gwv->next->next;
1757                                 }
1758                         }
1759                         /* Since "line" instantiates the configuration, we have to move it to the end. */
1760                         if (epname) {
1761                                 gwv->next = epname;
1762                                 epname->next = NULL;
1763                                 gwv = gwv->next;
1764                         }
1765                 }
1766         }
1767         for (gwv = mgcpgwconfig; gwv; gwv = gwv->next) {
1768                 ast_debug(1, "MGCP Realtime var: %s => %s\n", gwv->name, gwv->value);
1769         }
1770
1771         if (mgcpgwconfig) {
1772                 g = build_gateway(at, mgcpgwconfig);
1773                 ast_variables_destroy(mgcpgwconfig);
1774         }
1775         if (g) {
1776                 g->next = gateways;
1777                 g->realtime = 1;
1778                 gateways = g;
1779                 for (e = g->endpoints; e; e = e->next) {
1780                         transmit_audit_endpoint(e);
1781                         e->needaudit = 0;
1782                 }
1783         }
1784         return g;
1785 }
1786
1787 static struct mgcp_subchannel *find_subchannel_and_lock(char *name, int msgid, struct sockaddr_in *sin)
1788 {
1789         struct mgcp_endpoint *p = NULL;
1790         struct mgcp_subchannel *sub = NULL;
1791         struct mgcp_gateway *g;
1792         char tmp[256] = "";
1793         char *at = NULL, *c;
1794         int found = 0;
1795         if (name) {
1796                 ast_copy_string(tmp, name, sizeof(tmp));
1797                 at = strchr(tmp, '@');
1798                 if (!at) {
1799                         ast_log(LOG_NOTICE, "Endpoint '%s' has no at sign!\n", name);
1800                         return NULL;
1801                 }
1802                 *at++ = '\0';
1803         }
1804         ast_mutex_lock(&gatelock);
1805         if (at && (at[0] == '[')) {
1806                 at++;
1807                 c = strrchr(at, ']');
1808                 if (c) {
1809                         *c = '\0';
1810                 }
1811         }
1812         for (g = gateways ? gateways : find_realtime_gw(name, at, sin); g; g = g->next ? g->next : find_realtime_gw(name, at, sin)) {
1813                 if ((!name || !strcasecmp(g->name, at)) &&
1814                     (sin || g->addr.sin_addr.s_addr || g->defaddr.sin_addr.s_addr)) {
1815                         /* Found the gateway.  If it's dynamic, save it's address -- now for the endpoint */
1816                         if (sin && g->dynamic && name) {
1817                                 if ((g->addr.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1818                                         (g->addr.sin_port != sin->sin_port)) {
1819                                         memcpy(&g->addr, sin, sizeof(g->addr));
1820                                         {
1821                                                 struct ast_sockaddr tmp1, tmp2;
1822                                                 struct sockaddr_in tmp3 = {0,};
1823
1824                                                 tmp3.sin_addr = g->ourip;
1825                                                 ast_sockaddr_from_sin(&tmp1, &g->addr);
1826                                                 ast_sockaddr_from_sin(&tmp2, &tmp3);
1827                                                 if (ast_ouraddrfor(&tmp1, &tmp2)) {
1828                                                         memcpy(&g->ourip, &__ourip, sizeof(g->ourip));
1829                                                 }
1830                                                 ast_sockaddr_to_sin(&tmp2, &tmp3);
1831                                                 g->ourip = tmp3.sin_addr;
1832                                         }
1833                                         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));
1834                                 }
1835                         /* not dynamic, check if the name matches */
1836                         } else if (name) {
1837                                 if (strcasecmp(g->name, at)) {
1838                                         continue;
1839                                 }
1840                         /* not dynamic, no name, check if the addr matches */
1841                         } else if (!name && sin) {
1842                                 if ((g->addr.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1843                                     (g->addr.sin_port != sin->sin_port)) {
1844                                         continue;
1845                                 }
1846                         } else {
1847                                 continue;
1848                         }
1849                         for (p = g->endpoints; p; p = p->next) {
1850                                 ast_debug(1, "Searching on %s@%s for subchannel\n", p->name, g->name);
1851                                 if (msgid) {
1852                                         sub = p->sub;
1853                                         found = 1;
1854                                         break;
1855                                 } else if (name && !strcasecmp(p->name, tmp)) {
1856                                         ast_debug(1, "Coundn't determine subchannel, assuming current master %s@%s-%d\n",
1857                                                 p->name, g->name, p->sub->id);
1858                                         sub = p->sub;
1859                                         found = 1;
1860                                         break;
1861                                 }
1862                         }
1863                         if (sub && found) {
1864                                 ast_mutex_lock(&sub->lock);
1865                                 break;
1866                         }
1867                 }
1868         }
1869         ast_mutex_unlock(&gatelock);
1870         if (!sub) {
1871                 if (name) {
1872                         if (g) {
1873                                 ast_log(LOG_NOTICE, "Endpoint '%s' not found on gateway '%s'\n", tmp, at);
1874                         } else {
1875                                 ast_log(LOG_NOTICE, "Gateway '%s' (and thus its endpoint '%s') does not exist\n", at, tmp);
1876                         }
1877                 }
1878         }
1879         return sub;
1880 }
1881
1882 static void parse(struct mgcp_request *req)
1883 {
1884         /* Divide fields by NULL's */
1885         char *c;
1886         int f = 0;
1887         c = req->data;
1888
1889         /* First header starts immediately */
1890         req->header[f] = c;
1891         for (; *c; c++) {
1892                 if (*c == '\n') {
1893                         /* We've got a new header */
1894                         *c = 0;
1895                         ast_debug(3, "Header: %s (%d)\n", req->header[f], (int) strlen(req->header[f]));
1896                         if (ast_strlen_zero(req->header[f])) {
1897                                 /* Line by itself means we're now in content */
1898                                 c++;
1899                                 break;
1900                         }
1901                         if (f >= MGCP_MAX_HEADERS - 1) {
1902                                 ast_log(LOG_WARNING, "Too many MGCP headers...\n");
1903                         } else {
1904                                 f++;
1905                         }
1906                         req->header[f] = c + 1;
1907                 } else if (*c == '\r') {
1908                         /* Ignore but eliminate \r's */
1909                         *c = 0;
1910                 }
1911         }
1912         /* Check for last header */
1913         if (!ast_strlen_zero(req->header[f])) {
1914                 f++;
1915         }
1916         req->headers = f;
1917         /* Now we process any mime content */
1918         f = 0;
1919         req->line[f] = c;
1920         for (; *c; c++) {
1921                 if (*c == '\n') {
1922                         /* We've got a new line */
1923                         *c = 0;
1924                         ast_debug(3, "Line: %s (%d)\n", req->line[f], (int) strlen(req->line[f]));
1925                         if (f >= MGCP_MAX_LINES - 1) {
1926                                 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1927                         } else {
1928                                 f++;
1929                         }
1930                         req->line[f] = c + 1;
1931                 } else if (*c == '\r') {
1932                         /* Ignore and eliminate \r's */
1933                         *c = 0;
1934                 }
1935         }
1936         /* Check for last line */
1937         if (!ast_strlen_zero(req->line[f])) {
1938                 f++;
1939         }
1940         req->lines = f;
1941         /* Parse up the initial header */
1942         c = req->header[0];
1943         while (*c && *c < 33) c++;
1944         /* First the verb */
1945         req->verb = c;
1946         while (*c && (*c > 32)) c++;
1947         if (*c) {
1948                 *c = '\0';
1949                 c++;
1950                 while (*c && (*c < 33)) c++;
1951                 req->identifier = c;
1952                 while (*c && (*c > 32)) c++;
1953                 if (*c) {
1954                         *c = '\0';
1955                         c++;
1956                         while (*c && (*c < 33)) c++;
1957                         req->endpoint = c;
1958                         while (*c && (*c > 32)) c++;
1959                         if (*c) {
1960                                 *c = '\0';
1961                                 c++;
1962                                 while (*c && (*c < 33)) c++;
1963                                 req->version = c;
1964                                 while (*c && (*c > 32)) c++;
1965                                 while (*c && (*c < 33)) c++;
1966                                 while (*c && (*c > 32)) c++;
1967                                 *c = '\0';
1968                         }
1969                 }
1970         }
1971
1972         ast_debug(1, "Verb: '%s', Identifier: '%s', Endpoint: '%s', Version: '%s'\n",
1973                         req->verb, req->identifier, req->endpoint, req->version);
1974         ast_debug(1, "%d headers, %d lines\n", req->headers, req->lines);
1975         if (*c) {
1976                 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1977         }
1978 }
1979
1980 static int process_sdp(struct mgcp_subchannel *sub, struct mgcp_request *req)
1981 {
1982         char *m;
1983         char *c;
1984         char *a;
1985         char host[258];
1986         int len = 0;
1987         int portno;
1988         struct ast_format_cap *peercap;
1989         int peerNonCodecCapability;
1990         struct sockaddr_in sin;
1991         struct ast_sockaddr sin_tmp;
1992         char *codecs;
1993         struct ast_hostent ahp; struct hostent *hp;
1994         int codec, codec_count=0;
1995         int iterator;
1996         struct mgcp_endpoint *p = sub->parent;
1997         struct ast_str *global_buf = ast_str_alloca(64);
1998         struct ast_str *peer_buf = ast_str_alloca(64);
1999         struct ast_str *pvt_buf = ast_str_alloca(64);
2000
2001         /* Get codec and RTP info from SDP */
2002         m = get_sdp(req, "m");
2003         c = get_sdp(req, "c");
2004         if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
2005                 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
2006                 return -1;
2007         }
2008         if (sscanf(c, "IN IP4 %256s", host) != 1) {
2009                 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
2010                 return -1;
2011         }
2012         /* XXX This could block for a long time, and block the main thread! XXX */
2013         hp = ast_gethostbyname(host, &ahp);
2014         if (!hp) {
2015                 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
2016                 return -1;
2017         }
2018         if (sscanf(m, "audio %30d RTP/AVP %n", &portno, &len) != 1 || !len) {
2019                 ast_log(LOG_WARNING, "Malformed media stream descriptor: %s\n", m);
2020                 return -1;
2021         }
2022         sin.sin_family = AF_INET;
2023         memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
2024         sin.sin_port = htons(portno);
2025         ast_sockaddr_from_sin(&sin_tmp, &sin);
2026         ast_rtp_instance_set_remote_address(sub->rtp, &sin_tmp);
2027         ast_debug(3, "Peer RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
2028         /* Scan through the RTP payload types specified in a "m=" line: */
2029         ast_rtp_codecs_payloads_clear(ast_rtp_instance_get_codecs(sub->rtp), sub->rtp);
2030         codecs = ast_strdupa(m + len);
2031         while (!ast_strlen_zero(codecs)) {
2032                 if (sscanf(codecs, "%30d%n", &codec, &len) != 1) {
2033                         if (codec_count) {
2034                                 break;
2035                         }
2036                         ast_log(LOG_WARNING, "Error in codec string '%s' at '%s'\n", m, codecs);
2037                         return -1;
2038                 }
2039                 ast_rtp_codecs_payloads_set_m_type(ast_rtp_instance_get_codecs(sub->rtp), sub->rtp, codec);
2040                 codec_count++;
2041                 codecs += len;
2042         }
2043
2044         /* Next, scan through each "a=rtpmap:" line, noting each */
2045         /* specified RTP payload type (with corresponding MIME subtype): */
2046         sdpLineNum_iterator_init(&iterator);
2047         while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
2048                 char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
2049                 if (sscanf(a, "rtpmap: %30d %127[^/]/", &codec, mimeSubtype) != 2)
2050                         continue;
2051                 /* Note: should really look at the 'freq' and '#chans' params too */
2052                 ast_rtp_codecs_payloads_set_rtpmap_type(ast_rtp_instance_get_codecs(sub->rtp), sub->rtp, codec, "audio", mimeSubtype, 0);
2053         }
2054
2055         /* Now gather all of the codecs that were asked for: */
2056         if (!(peercap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
2057                 return -1;
2058         }
2059         ast_rtp_codecs_payload_formats(ast_rtp_instance_get_codecs(sub->rtp), peercap, &peerNonCodecCapability);
2060         ast_format_cap_get_compatible(global_capability, peercap, p->cap);
2061         ast_debug(1, "Capabilities: us - %s, them - %s, combined - %s\n",
2062                 ast_format_cap_get_names(global_capability, &global_buf),
2063                 ast_format_cap_get_names(peercap, &peer_buf),
2064                 ast_format_cap_get_names(p->cap, &pvt_buf));
2065         ao2_ref(peercap, -1);
2066
2067         ast_debug(1, "Non-codec capabilities: us - %d, them - %d, combined - %d\n",
2068                 nonCodecCapability, peerNonCodecCapability, p->nonCodecCapability);
2069         if (!ast_format_cap_count(p->cap)) {
2070                 ast_log(LOG_WARNING, "No compatible codecs!\n");
2071                 return -1;
2072         }
2073         return 0;
2074 }
2075
2076 static int add_header(struct mgcp_request *req, const char *var, const char *value)
2077 {
2078         if (req->len >= sizeof(req->data) - 4) {
2079                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2080                 return -1;
2081         }
2082         if (req->lines) {
2083                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
2084                 return -1;
2085         }
2086         req->header[req->headers] = req->data + req->len;
2087         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s: %s\r\n", var, value);
2088         req->len += strlen(req->header[req->headers]);
2089         if (req->headers < MGCP_MAX_HEADERS) {
2090                 req->headers++;
2091         } else {
2092                 ast_log(LOG_WARNING, "Out of header space\n");
2093                 return -1;
2094         }
2095         return 0;
2096 }
2097
2098 static int add_line(struct mgcp_request *req, char *line)
2099 {
2100         if (req->len >= sizeof(req->data) - 4) {
2101                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2102                 return -1;
2103         }
2104         if (!req->lines) {
2105                 /* Add extra empty return */
2106                 ast_copy_string(req->data + req->len, "\r\n", sizeof(req->data) - req->len);
2107                 req->len += strlen(req->data + req->len);
2108         }
2109         req->line[req->lines] = req->data + req->len;
2110         snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
2111         req->len += strlen(req->line[req->lines]);
2112         if (req->lines < MGCP_MAX_LINES) {
2113                 req->lines++;
2114         } else {
2115                 ast_log(LOG_WARNING, "Out of line space\n");
2116                 return -1;
2117         }
2118         return 0;
2119 }
2120
2121 static int init_resp(struct mgcp_request *req, char *resp, struct mgcp_request *orig, char *resprest)
2122 {
2123         /* Initialize a response */
2124         if (req->headers || req->len) {
2125                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2126                 return -1;
2127         }
2128         req->header[req->headers] = req->data + req->len;
2129         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s %s\r\n", resp, orig->identifier, resprest);
2130         req->len += strlen(req->header[req->headers]);
2131         if (req->headers < MGCP_MAX_HEADERS) {
2132                 req->headers++;
2133         } else {
2134                 ast_log(LOG_WARNING, "Out of header space\n");
2135         }
2136         return 0;
2137 }
2138
2139 static int init_req(struct mgcp_endpoint *p, struct mgcp_request *req, char *verb, unsigned int oseq)
2140 {
2141         /* Initialize a response */
2142         if (req->headers || req->len) {
2143                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2144                 return -1;
2145         }
2146         req->header[req->headers] = req->data + req->len;
2147         /* check if we need brackets around the gw name */
2148         if (p->parent->isnamedottedip) {
2149                 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" : "");
2150         } else {
2151 +               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" : "");
2152         }
2153         req->len += strlen(req->header[req->headers]);
2154         if (req->headers < MGCP_MAX_HEADERS) {
2155                 req->headers++;
2156         } else {
2157                 ast_log(LOG_WARNING, "Out of header space\n");
2158         }
2159         return 0;
2160 }
2161
2162
2163 static int respprep(struct mgcp_request *resp, struct mgcp_endpoint *p, char *msg, struct mgcp_request *req, char *msgrest)
2164 {
2165         memset(resp, 0, sizeof(*resp));
2166         init_resp(resp, msg, req, msgrest);
2167         return 0;
2168 }
2169
2170 static int reqprep(struct mgcp_request *req, struct mgcp_endpoint *p, char *verb)
2171 {
2172         unsigned int oseq;
2173         memset(req, 0, sizeof(struct mgcp_request));
2174         ast_mutex_lock(&oseq_lock);
2175         oseq_global++;
2176         if (oseq_global > 999999999) {
2177                 oseq_global = 1;
2178         }
2179         oseq = oseq_global;
2180         ast_mutex_unlock(&oseq_lock);
2181         init_req(p, req, verb, oseq);
2182         return oseq;
2183 }
2184
2185 static int transmit_response(struct mgcp_subchannel *sub, char *msg, struct mgcp_request *req, char *msgrest)
2186 {
2187         struct mgcp_request resp;
2188         struct mgcp_endpoint *p = sub->parent;
2189         struct mgcp_response *mgr;
2190
2191         if (!sub) {
2192                 return -1;
2193         }
2194
2195         respprep(&resp, p, msg, req, msgrest);
2196         if (!(mgr = ast_calloc(1, sizeof(*mgr) + resp.len + 1))) {
2197                 return send_response(sub, &resp);
2198         }
2199         /* Store MGCP response in case we have to retransmit */
2200         sscanf(req->identifier, "%30d", &mgr->seqno);
2201         time(&mgr->whensent);
2202         mgr->len = resp.len;
2203         memcpy(mgr->buf, resp.data, resp.len);
2204         mgr->buf[resp.len] = '\0';
2205         mgr->next = p->parent->responses;
2206         p->parent->responses = mgr;
2207
2208         return send_response(sub, &resp);
2209 }
2210
2211
2212 static int add_sdp(struct mgcp_request *resp, struct mgcp_subchannel *sub, struct ast_rtp_instance *rtp)
2213 {
2214         int len;
2215         int codec;
2216         char costr[80];
2217         struct sockaddr_in sin;
2218         struct ast_sockaddr sin_tmp;
2219         char v[256];
2220         char s[256];
2221         char o[256];
2222         char c[256];
2223         char t[256];
2224         char m[256] = "";
2225         char a[1024] = "";
2226         int x;
2227         struct sockaddr_in dest = { 0, };
2228         struct ast_sockaddr dest_tmp;
2229         struct mgcp_endpoint *p = sub->parent;
2230         /* XXX We break with the "recommendation" and send our IP, in order that our
2231                peer doesn't have to ast_gethostbyname() us XXX */
2232         len = 0;
2233         if (!sub->rtp) {
2234                 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2235                 return -1;
2236         }
2237         ast_rtp_instance_get_local_address(sub->rtp, &sin_tmp);
2238         ast_sockaddr_to_sin(&sin_tmp, &sin);
2239         if (rtp) {
2240                 ast_rtp_instance_get_remote_address(sub->rtp, &dest_tmp);
2241                 ast_sockaddr_to_sin(&dest_tmp, &dest);
2242         } else {
2243                 if (sub->tmpdest.sin_addr.s_addr) {
2244                         dest.sin_addr = sub->tmpdest.sin_addr;
2245                         dest.sin_port = sub->tmpdest.sin_port;
2246                         /* Reset temporary destination */
2247                         memset(&sub->tmpdest, 0, sizeof(sub->tmpdest));
2248                 } else {
2249                         dest.sin_addr = p->parent->ourip;
2250                         dest.sin_port = sin.sin_port;
2251                 }
2252         }
2253         ast_debug(1, "We're at %s port %d\n", ast_inet_ntoa(p->parent->ourip), ntohs(sin.sin_port));
2254         ast_copy_string(v, "v=0\r\n", sizeof(v));
2255         snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", (int)getpid(), (int)getpid(), ast_inet_ntoa(dest.sin_addr));
2256         ast_copy_string(s, "s=session\r\n", sizeof(s));
2257         snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
2258         ast_copy_string(t, "t=0 0\r\n", sizeof(t));
2259         snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2260
2261         for (x = 0; x < ast_format_cap_count(p->cap); x++) {
2262                 struct ast_format *format = ast_format_cap_get_format(p->cap, x);
2263
2264                 if (ast_format_get_type(format) != AST_MEDIA_TYPE_AUDIO) {
2265                         ao2_ref(format, -1);
2266                         continue;
2267                 }
2268
2269                 ast_debug(1, "Answering with capability %s\n", ast_format_get_name(format));
2270                 codec = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(sub->rtp), 1, format, 0);
2271                 if (codec > -1) {
2272                         snprintf(costr, sizeof(costr), " %d", codec);
2273                         strncat(m, costr, sizeof(m) - strlen(m) - 1);
2274                         snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype2(1, format, 0, 0));
2275                         strncat(a, costr, sizeof(a) - strlen(a) - 1);
2276                 }
2277
2278                 ao2_ref(format, -1);
2279         }
2280
2281         for (x = 1LL; x <= AST_RTP_MAX; x <<= 1) {
2282                 if (p->nonCodecCapability & x) {
2283                         ast_debug(1, "Answering with non-codec capability %d\n", (int) x);
2284                         codec = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(sub->rtp), 0, NULL, x);
2285                         if (codec > -1) {
2286                                 snprintf(costr, sizeof(costr), " %d", codec);
2287                                 strncat(m, costr, sizeof(m) - strlen(m) - 1);
2288                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype2(0, NULL, x, 0));
2289                                 strncat(a, costr, sizeof(a) - strlen(a) - 1);
2290                                 if (x == AST_RTP_DTMF) {
2291                                         /* Indicate we support DTMF...  Not sure about 16,
2292                                            but MSN supports it so dang it, we will too... */
2293                                         snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n", codec);
2294                                         strncat(a, costr, sizeof(a) - strlen(a) - 1);
2295                                 }
2296                         }
2297                 }
2298         }
2299         strncat(m, "\r\n", sizeof(m) - strlen(m) - 1);
2300         len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2301         snprintf(costr, sizeof(costr), "%d", len);
2302         add_line(resp, v);
2303         add_line(resp, o);
2304         add_line(resp, s);
2305         add_line(resp, c);
2306         add_line(resp, t);
2307         add_line(resp, m);
2308         add_line(resp, a);
2309         return 0;
2310 }
2311
2312 static int transmit_modify_with_sdp(struct mgcp_subchannel *sub, struct ast_rtp_instance *rtp, const struct ast_format_cap *codecs)
2313 {
2314         struct mgcp_request resp;
2315         char local[256];
2316         char tmp[80];
2317         struct mgcp_endpoint *p = sub->parent;
2318         int i;
2319         struct ast_sockaddr sub_tmpdest_tmp;
2320         unsigned int oseq;
2321
2322         if (ast_strlen_zero(sub->cxident) && rtp) {
2323                 /* We don't have a CXident yet, store the destination and
2324                    wait a bit */
2325                 ast_rtp_instance_get_remote_address(rtp, &sub_tmpdest_tmp);
2326                 ast_sockaddr_to_sin(&sub_tmpdest_tmp, &sub->tmpdest);
2327                 return 0;
2328         }
2329         ast_copy_string(local, "e:on, s:off, p:20", sizeof(local));
2330
2331         for (i = 0; i < ast_format_cap_count(p->cap); i++) {
2332                 struct ast_format *format = ast_format_cap_get_format(p->cap, i);
2333
2334                 if (ast_format_get_type(format) != AST_MEDIA_TYPE_AUDIO) {
2335                         ao2_ref(format, -1);
2336                         continue;
2337                 }
2338
2339                 snprintf(tmp, sizeof(tmp), ", a:%s", ast_rtp_lookup_mime_subtype2(1, format, 0, 0));
2340                 strncat(local, tmp, sizeof(local) - strlen(local) - 1);
2341
2342                 ao2_ref(format, -1);
2343         }
2344
2345         if (sub->gate) {
2346                 if (sub->gate->state == GATE_ALLOCATED || sub->gate->state == GATE_OPEN) {
2347                         snprintf(tmp, sizeof(tmp), ", dq-gi:%x", sub->gate->gateid);
2348                         strncat(local, tmp, sizeof(local) - strlen(local) - 1);
2349                         sub->sdpsent = 1;
2350                 } else {
2351                         /* oops wait */
2352                         ast_debug(1, "Waiting for opened gate...\n");
2353                         sub->sdpsent = 0;
2354                         return 0;
2355                 }
2356         }
2357
2358
2359         oseq = reqprep(&resp, p, "MDCX");
2360         add_header(&resp, "C", sub->callid);
2361         add_header(&resp, "L", local);
2362         add_header(&resp, "M", mgcp_cxmodes[sub->cxmode]);
2363         /* X header should not be sent. kept for compatibility */
2364         add_header(&resp, "X", sub->txident);
2365         add_header(&resp, "I", sub->cxident);
2366         /*add_header(&resp, "S", "");*/
2367         add_sdp(&resp, sub, rtp);
2368         /* fill in new fields */
2369         resp.cmd = MGCP_CMD_MDCX;
2370         resp.trid = oseq;
2371         return send_request(p, sub, &resp, oseq);
2372 }
2373
2374 static int transmit_connect_with_sdp(struct mgcp_subchannel *sub, struct ast_rtp_instance *rtp)
2375 {
2376         struct mgcp_request resp;
2377         char local[256];
2378         char tmp[80];
2379         int i;
2380         struct mgcp_endpoint *p = sub->parent;
2381         unsigned int oseq;
2382
2383         ast_debug(3, "Creating connection for %s@%s-%d in cxmode: %s callid: %s\n",
2384                  p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode], sub->callid);
2385
2386         ast_copy_string(local, "e:on, s:off, p:20", sizeof(local));
2387
2388         for (i = 0; i < ast_format_cap_count(p->cap); i++) {
2389                 struct ast_format *format = ast_format_cap_get_format(p->cap, i);
2390
2391                 if (ast_format_get_type(format) != AST_MEDIA_TYPE_AUDIO) {
2392                         ao2_ref(format, -1);
2393                         continue;
2394                 }
2395
2396                 snprintf(tmp, sizeof(tmp), ", a:%s", ast_rtp_lookup_mime_subtype2(1, format, 0, 0));
2397                 strncat(local, tmp, sizeof(local) - strlen(local) - 1);
2398
2399                 ao2_ref(format, -1);
2400         }
2401
2402         if (sub->gate) {
2403                 if(sub->gate->state == GATE_ALLOCATED) {
2404                         snprintf(tmp, sizeof(tmp), ", dq-gi:%x", sub->gate->gateid);
2405                         strncat(local, tmp, sizeof(local) - strlen(local) - 1);
2406                 }
2407         }
2408         sub->sdpsent = 1;
2409         oseq = reqprep(&resp, p, "CRCX");
2410         add_header(&resp, "C", sub->callid);
2411         add_header(&resp, "L", local);
2412         add_header(&resp, "M", mgcp_cxmodes[sub->cxmode]);
2413         /* X header should not be sent. kept for compatibility */
2414         add_header(&resp, "X", sub->txident);
2415         /*add_header(&resp, "S", "");*/
2416         add_sdp(&resp, sub, rtp);
2417         /* fill in new fields */
2418         resp.cmd = MGCP_CMD_CRCX;
2419         resp.trid = oseq;
2420         return send_request(p, sub, &resp, oseq);
2421 }
2422
2423 static int mgcp_pktcgate_remove(struct cops_gate *gate)
2424 {
2425         struct mgcp_subchannel *sub = gate->tech_pvt;
2426
2427         if (!sub) {
2428                 return 1;
2429         }
2430
2431         ast_mutex_lock(&sub->lock);
2432         ast_debug(1, "Pktc: gate 0x%x deleted\n", gate->gateid);
2433         if (sub->gate->state != GATE_CLOSED && sub->parent->hangupongateremove) {
2434                 sub->gate = NULL;
2435                 if (sub->owner) {
2436                         ast_softhangup(sub->owner, AST_CAUSE_REQUESTED_CHAN_UNAVAIL);
2437                         ast_channel_unlock(sub->owner);
2438                 }
2439         } else {
2440                 sub->gate = NULL;
2441         }
2442         ast_mutex_unlock(&sub->lock);
2443         return 1;
2444 }
2445
2446 static int mgcp_pktcgate_open(struct cops_gate *gate)
2447 {
2448         struct mgcp_subchannel *sub = gate->tech_pvt;
2449         if (!sub) {
2450                 return 1;
2451         }
2452         ast_mutex_lock(&sub->lock);
2453         ast_debug(1, "Pktc: gate 0x%x open\n", gate->gateid);
2454         if (!sub->sdpsent) transmit_modify_with_sdp(sub, NULL, 0);
2455         ast_mutex_unlock(&sub->lock);
2456         return 1;
2457 }
2458
2459 static int mgcp_alloc_pktcgate(struct mgcp_subchannel *sub)
2460 {
2461         struct mgcp_endpoint *p = sub->parent;
2462         sub->gate = ast_pktccops_gate_alloc(GATE_SET, NULL, ntohl(p->parent->addr.sin_addr.s_addr),
2463                                         8, 128000, 232, 0, 0, NULL, &mgcp_pktcgate_remove);
2464
2465         if (!sub->gate) {
2466                 return 0;
2467         }
2468         sub->gate->tech_pvt = sub;
2469         sub->gate->gate_open = &mgcp_pktcgate_open;
2470         return 1;
2471 }
2472
2473 static int transmit_connect(struct mgcp_subchannel *sub)
2474 {
2475         struct mgcp_request resp;
2476         int x;
2477         char local[256];
2478         char tmp[80];
2479         struct ast_format *tmpfmt;
2480         struct mgcp_endpoint *p = sub->parent;
2481         unsigned int oseq;
2482
2483         ast_copy_string(local, "p:20, s:off, e:on", sizeof(local));
2484
2485         for (x = 0; x < ast_format_cap_count(p->cap); x++) {
2486                 tmpfmt = ast_format_cap_get_format(p->cap, x);
2487
2488                 snprintf(tmp, sizeof(tmp), ", a:%s", ast_rtp_lookup_mime_subtype2(1, tmpfmt, 0, 0));
2489                 strncat(local, tmp, sizeof(local) - strlen(local) - 1);
2490
2491                 ao2_ref(tmpfmt, -1);
2492         }
2493
2494         ast_debug(3, "Creating connection for %s@%s-%d in cxmode: %s callid: %s\n",
2495                     p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode], sub->callid);
2496         sub->sdpsent = 0;
2497         oseq = reqprep(&resp, p, "CRCX");
2498         add_header(&resp, "C", sub->callid);
2499         add_header(&resp, "L", local);
2500         add_header(&resp, "M", "inactive");
2501         /* X header should not be sent. kept for compatibility */
2502         add_header(&resp, "X", sub->txident);
2503         /*add_header(&resp, "S", "");*/
2504         /* fill in new fields */
2505         resp.cmd = MGCP_CMD_CRCX;
2506         resp.trid = oseq;
2507         return send_request(p, sub, &resp, oseq);
2508 }
2509
2510 static int transmit_notify_request(struct mgcp_subchannel *sub, char *tone)
2511 {
2512         struct mgcp_request resp;
2513         struct mgcp_endpoint *p = sub->parent;
2514         unsigned int oseq;
2515
2516         ast_debug(3, "MGCP Asked to indicate tone: %s on  %s@%s-%d in cxmode: %s\n",
2517                 tone, p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode]);
2518         ast_copy_string(p->curtone, tone, sizeof(p->curtone));
2519         oseq = reqprep(&resp, p, "RQNT");
2520         add_header(&resp, "X", p->rqnt_ident);
2521         switch (p->hookstate) {
2522         case MGCP_ONHOOK:
2523                 add_header(&resp, "R", "L/hd(N)");
2524                 break;
2525         case MGCP_OFFHOOK:
2526                 add_header_offhook(sub, &resp, tone);
2527                 break;
2528         }
2529         if (!ast_strlen_zero(tone)) {
2530                 add_header(&resp, "S", tone);
2531         }
2532         /* fill in new fields */
2533         resp.cmd = MGCP_CMD_RQNT;
2534         resp.trid = oseq;
2535         return send_request(p, NULL, &resp, oseq);
2536 }
2537
2538 static int transmit_notify_request_with_callerid(struct mgcp_subchannel *sub, char *tone, char *callernum, char *callername)
2539 {
2540         struct mgcp_request resp;
2541         char tone2[256];
2542         char *l, *n;
2543         struct timeval t = ast_tvnow();
2544         struct ast_tm tm;
2545         struct mgcp_endpoint *p = sub->parent;
2546         unsigned int oseq;
2547
2548         ast_localtime(&t, &tm, NULL);
2549         n = callername;
2550         l = callernum;
2551         if (!n)
2552                 n = "";
2553         if (!l)
2554                 l = "";
2555
2556         /* Keep track of last callerid for blacklist and callreturn */
2557         ast_copy_string(p->lastcallerid, l, sizeof(p->lastcallerid));
2558
2559         snprintf(tone2, sizeof(tone2), "%s,L/ci(%02d/%02d/%02d/%02d,%s,%s)", tone,
2560                 tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, l, n);
2561         ast_copy_string(p->curtone, tone, sizeof(p->curtone));
2562         oseq = reqprep(&resp, p, "RQNT");
2563         add_header(&resp, "X", p->rqnt_ident);
2564         switch (p->hookstate) {
2565         case MGCP_ONHOOK:
2566                 add_header(&resp, "R", "L/hd(N)");
2567                 break;
2568         case MGCP_OFFHOOK:
2569                 add_header_offhook(sub, &resp, tone);
2570                 break;
2571         }
2572         if (!ast_strlen_zero(tone2)) {
2573                 add_header(&resp, "S", tone2);
2574         }
2575         ast_debug(3, "MGCP Asked to indicate tone: %s on  %s@%s-%d in cxmode: %s\n",
2576                 tone2, p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode]);
2577         /* fill in new fields */
2578         resp.cmd = MGCP_CMD_RQNT;
2579         resp.trid = oseq;
2580         return send_request(p, NULL, &resp, oseq);
2581 }
2582
2583 static int transmit_modify_request(struct mgcp_subchannel *sub)
2584 {
2585         struct mgcp_request resp;
2586         struct mgcp_endpoint *p = sub->parent;
2587         int i;
2588         int fc = 1;
2589         char local[256];
2590         char tmp[80];
2591         unsigned int oseq;
2592
2593         if (ast_strlen_zero(sub->cxident)) {
2594                 /* We don't have a CXident yet, store the destination and
2595                    wait a bit */
2596                 return 0;
2597         }
2598         ast_debug(3, "Modified %s@%s-%d with new mode: %s on callid: %s\n",
2599                 p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode], sub->callid);
2600
2601         ast_copy_string(local, "", sizeof(local));
2602         for (i = 0; i < ast_format_cap_count(p->cap); i++) {
2603                 struct ast_format *format = ast_format_cap_get_format(p->cap, i);
2604
2605                 if (p->ncs && !fc) {
2606                         ast_format_cap_remove_by_type(p->cap, AST_MEDIA_TYPE_UNKNOWN);
2607                         ast_format_cap_append(p->cap, format, 0); /* sb5120e bug */
2608                         ao2_ref(format, -1);
2609                         break;
2610                 } else {
2611                         fc = 0;
2612                         snprintf(tmp, sizeof(tmp), ", a:%s", ast_rtp_lookup_mime_subtype2(1, format, 0, 0));
2613                 }
2614                 strncat(local, tmp, sizeof(local) - strlen(local) - 1);
2615
2616                 ao2_ref(format, -1);
2617         }
2618
2619         if (!sub->sdpsent) {
2620                 if (sub->gate) {
2621                         if (sub->gate->state == GATE_ALLOCATED || sub->gate->state == GATE_OPEN) {
2622                                 snprintf(tmp, sizeof(tmp), ", dq-gi:%x", sub->gate->gateid);
2623                                 strncat(local, tmp, sizeof(local) - strlen(local) - 1);
2624                         } else {
2625                                         /* we still don't have gateid wait */
2626                                 return 0;
2627                         }
2628                 }
2629         }
2630
2631         oseq = reqprep(&resp, p, "MDCX");
2632         add_header(&resp, "C", sub->callid);
2633         if (!sub->sdpsent) {
2634                 add_header(&resp, "L", local);
2635         }
2636         add_header(&resp, "M", mgcp_cxmodes[sub->cxmode]);
2637         /* X header should not be sent. kept for compatibility */
2638         add_header(&resp, "X", sub->txident);
2639         add_header(&resp, "I", sub->cxident);
2640         switch (sub->parent->hookstate) {
2641         case MGCP_ONHOOK:
2642                 add_header(&resp, "R", "L/hd(N)");
2643                 break;
2644         case MGCP_OFFHOOK:
2645                 add_header_offhook(sub, &resp, "");
2646                 break;
2647         }
2648         if (!sub->sdpsent) {
2649                 add_sdp(&resp, sub, NULL);
2650                 sub->sdpsent = 1;
2651         }
2652         /* fill in new fields */
2653         resp.cmd = MGCP_CMD_MDCX;
2654         resp.trid = oseq;
2655         return send_request(p, sub, &resp, oseq);
2656 }
2657
2658
2659 static void add_header_offhook(struct mgcp_subchannel *sub, struct mgcp_request *resp, char *tone)
2660 {
2661         struct mgcp_endpoint *p = sub->parent;
2662         char tone_indicate_end = 0;
2663
2664         /* We also should check the tone to indicate, because it have no sense
2665            to request notify D/[0-9#*] (dtmf keys) if we are sending congestion
2666            tone for example G/cg */
2667         if (p && (!strcasecmp(tone, (p->ncs ? "L/ro" : "G/cg")))) {
2668                 tone_indicate_end = 1;
2669         }
2670
2671         if (p && p->sub && p->sub->owner &&
2672                         ast_channel_state(p->sub->owner) >= AST_STATE_RINGING &&
2673                         (p->dtmfmode & (MGCP_DTMF_INBAND | MGCP_DTMF_HYBRID))) {
2674             add_header(resp, "R", "L/hu(N),L/hf(N)");
2675
2676         } else if (!tone_indicate_end){
2677             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)"));
2678         } else {
2679                 ast_debug(1, "We don't want more digits if we will end the call\n");
2680                 add_header(resp, "R", "L/hu(N),L/hf(N)");
2681         }
2682 }
2683
2684
2685
2686
2687 static int transmit_audit_endpoint(struct mgcp_endpoint *p)
2688 {
2689         struct mgcp_request resp;
2690         unsigned int oseq;
2691         oseq = reqprep(&resp, p, "AUEP");
2692         /* removed unknown param VS */
2693         /*add_header(&resp, "F", "A,R,D,S,X,N,I,T,O,ES,E,MD,M");*/
2694         add_header(&resp, "F", "A");
2695         /* fill in new fields */
2696         resp.cmd = MGCP_CMD_AUEP;
2697         resp.trid = oseq;
2698         return send_request(p, NULL, &resp, oseq);
2699 }
2700
2701 static int transmit_connection_del(struct mgcp_subchannel *sub)
2702 {
2703         struct mgcp_endpoint *p = sub->parent;
2704         struct mgcp_request resp;
2705         unsigned int oseq;
2706
2707         ast_debug(3, "Delete connection %s %s@%s-%d with new mode: %s on callid: %s\n",
2708                 sub->cxident, p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode], sub->callid);
2709         oseq = reqprep(&resp, p, "DLCX");
2710         /* check if call id is avail */
2711         if (sub->callid[0])
2712                 add_header(&resp, "C", sub->callid);
2713         /* X header should not be sent. kept for compatibility */
2714         add_header(&resp, "X", sub->txident);
2715         /* check if cxident is avail */
2716         if (sub->cxident[0])
2717                 add_header(&resp, "I", sub->cxident);
2718         /* fill in new fields */
2719         resp.cmd = MGCP_CMD_DLCX;
2720         resp.trid = oseq;
2721         return send_request(p, sub, &resp, oseq);
2722 }
2723
2724 static int transmit_connection_del_w_params(struct mgcp_endpoint *p, char *callid, char *cxident)
2725 {
2726         struct mgcp_request resp;
2727         unsigned int oseq;
2728
2729         ast_debug(3, "Delete connection %s %s@%s on callid: %s\n",
2730                 cxident ? cxident : "", p->name, p->parent->name, callid ? callid : "");
2731         oseq = reqprep(&resp, p, "DLCX");
2732         /* check if call id is avail */
2733         if (callid && *callid)
2734                 add_header(&resp, "C", callid);
2735         /* check if cxident is avail */
2736         if (cxident && *cxident)
2737                 add_header(&resp, "I", cxident);
2738         /* fill in new fields */
2739         resp.cmd = MGCP_CMD_DLCX;
2740         resp.trid = oseq;
2741         return send_request(p, p->sub, &resp, oseq);
2742 }
2743
2744 /*! \brief  dump_cmd_queues: (SC:) cleanup pending commands */
2745 static void dump_cmd_queues(struct mgcp_endpoint *p, struct mgcp_subchannel *sub)
2746 {
2747         struct mgcp_request *t, *q;
2748
2749         if (p) {
2750                 ast_mutex_lock(&p->rqnt_queue_lock);
2751                 for (q = p->rqnt_queue; q; t = q->next, ast_free(q), q=t);
2752                 p->rqnt_queue = NULL;
2753                 ast_mutex_unlock(&p->rqnt_queue_lock);
2754
2755                 ast_mutex_lock(&p->cmd_queue_lock);
2756                 for (q = p->cmd_queue; q; t = q->next, ast_free(q), q=t);
2757                 p->cmd_queue = NULL;
2758                 ast_mutex_unlock(&p->cmd_queue_lock);
2759
2760                 ast_mutex_lock(&p->sub->cx_queue_lock);
2761                 for (q = p->sub->cx_queue; q; t = q->next, ast_free(q), q=t);
2762                 p->sub->cx_queue = NULL;
2763                 ast_mutex_unlock(&p->sub->cx_queue_lock);
2764
2765                 ast_mutex_lock(&p->sub->next->cx_queue_lock);
2766                 for (q = p->sub->next->cx_queue; q; t = q->next, ast_free(q), q=t);
2767                 p->sub->next->cx_queue = NULL;
2768                 ast_mutex_unlock(&p->sub->next->cx_queue_lock);
2769         } else if (sub) {
2770                 ast_mutex_lock(&sub->cx_queue_lock);
2771                 for (q = sub->cx_queue; q; t = q->next, ast_free(q), q=t);
2772                 sub->cx_queue = NULL;
2773                 ast_mutex_unlock(&sub->cx_queue_lock);
2774         }
2775 }
2776
2777
2778 /*! \brief  find_command: (SC:) remove command transaction from queue */
2779 static struct mgcp_request *find_command(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,
2780                 struct mgcp_request **queue, ast_mutex_t *l, int ident)
2781 {
2782         struct mgcp_request *prev, *req;
2783
2784         ast_mutex_lock(l);
2785         for (prev = NULL, req = *queue; req; prev = req, req = req->next) {
2786                 if (req->trid == ident) {
2787                         /* remove from queue */
2788                         if (!prev)
2789                                 *queue = req->next;
2790                         else
2791                                 prev->next = req->next;
2792
2793                         /* send next pending command */
2794                         if (*queue) {
2795                                 ast_debug(1, "Posting Queued Request:\n%s to %s:%d\n", (*queue)->data,
2796                                         ast_inet_ntoa(p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
2797
2798                                 mgcp_postrequest(p, sub, (*queue)->data, (*queue)->len, (*queue)->trid);
2799                         }
2800                         break;
2801                 }
2802         }
2803         ast_mutex_unlock(l);
2804         return req;
2805 }
2806
2807 /* modified for new transport mechanism */
2808 static void handle_response(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,
2809                 int result, unsigned int ident, struct mgcp_request *resp)
2810 {
2811         char *c;
2812         struct mgcp_request *req;
2813         struct mgcp_gateway *gw = p->parent;
2814
2815         if (result < 200) {
2816                 /* provisional response */
2817                 return;
2818         }
2819
2820         if (p->slowsequence)
2821                 req = find_command(p, sub, &p->cmd_queue, &p->cmd_queue_lock, ident);
2822         else if (sub)
2823                 req = find_command(p, sub, &sub->cx_queue, &sub->cx_queue_lock, ident);
2824         else if (!(req = find_command(p, sub, &p->rqnt_queue, &p->rqnt_queue_lock, ident)))
2825                 req = find_command(p, sub, &p->cmd_queue, &p->cmd_queue_lock, ident);
2826
2827         if (!req) {
2828                 ast_verb(3, "No command found on [%s] for transaction %u. Ignoring...\n",
2829                                 gw->name, ident);
2830                 return;
2831         }
2832
2833         if (p && (result >= 400) && (result <= 599)) {
2834                 switch (result) {
2835                 case 401:
2836                         p->hookstate = MGCP_OFFHOOK;
2837                         break;
2838                 case 402:
2839                         p->hookstate = MGCP_ONHOOK;
2840                         break;
2841                 case 406:
2842                         ast_log(LOG_NOTICE, "Transaction %u timed out\n", ident);
2843                         break;
2844                 case 407:
2845                         ast_log(LOG_NOTICE, "Transaction %u aborted\n", ident);
2846                         break;
2847                 }
2848                 if (sub) {
2849                         if (!sub->cxident[0] && (req->cmd == MGCP_CMD_CRCX)) {
2850                             ast_log(LOG_NOTICE, "DLCX for all connections on %s due to error %d\n", gw->name, result);
2851                             transmit_connection_del(sub);
2852                         }
2853                         if (sub->owner) {
2854                                 ast_log(LOG_NOTICE, "Terminating on result %d from %s@%s-%d\n",
2855                                         result, p->name, p->parent->name, sub ? sub->id:-1);
2856                                 mgcp_queue_hangup(sub);
2857                         }
2858                 } else {
2859                         if (p->sub->next->owner) {
2860                                 ast_log(LOG_NOTICE, "Terminating on result %d from %s@%s-%d\n",
2861                                         result, p->name, p->parent->name, sub ? sub->id:-1);
2862                                 mgcp_queue_hangup(p->sub);
2863                         }
2864
2865                         if (p->sub->owner) {
2866                                 ast_log(LOG_NOTICE, "Terminating on result %d from %s@%s-%d\n",
2867                                         result, p->name, p->parent->name, sub ? sub->id:-1);
2868                                 mgcp_queue_hangup(p->sub);
2869                         }
2870
2871                         dump_cmd_queues(p, NULL);
2872                 }
2873         }
2874
2875         if (resp) {
2876                 /* responseAck: */
2877                 if (result == 200 && (req->cmd == MGCP_CMD_CRCX || req->cmd == MGCP_CMD_MDCX)) {
2878                                 if (sub) {
2879                                         transmit_response(sub, "000", resp, "OK");
2880                                         if (sub->owner && ast_channel_state(sub->owner) == AST_STATE_RINGING) {
2881                                                 ast_queue_control(sub->owner, AST_CONTROL_RINGING);
2882                                         }
2883                                 }
2884                 }
2885                 if (req->cmd == MGCP_CMD_CRCX) {
2886                         if ((c = get_header(resp, "I"))) {
2887                                 if (!ast_strlen_zero(c) && sub) {
2888                                         /* if we are hanging up do not process this conn. */
2889                                         if (sub->owner) {
2890                                                 if (!ast_strlen_zero(sub->cxident)) {
2891                                                         if (strcasecmp(c, sub->cxident)) {
2892                                                                 ast_log(LOG_WARNING, "Subchannel already has a cxident. sub->cxident: %s requested %s\n", sub->cxident, c);
2893                                                         }
2894                                                 }
2895                                                 ast_copy_string(sub->cxident, c, sizeof(sub->cxident));
2896                                                 if (sub->tmpdest.sin_addr.s_addr) {
2897                                                         transmit_modify_with_sdp(sub, NULL, 0);
2898                                                 }
2899                                         } else {
2900                                                 /* XXX delete this one
2901                                                    callid and conn id may already be lost.
2902                                                    so the following del conn may have a side effect of
2903                                                    cleaning up the next subchannel */
2904                                                 transmit_connection_del(sub);
2905                                         }
2906                                 }
2907                         }
2908                 }
2909
2910                 if (req->cmd == MGCP_CMD_AUEP) {
2911                         /* check stale connection ids */
2912                         if ((c = get_header(resp, "I"))) {
2913                                 char *v, *n;
2914                                 int len;
2915                                 while ((v = get_csv(c, &len, &n))) {
2916                                         if (len) {
2917                                                 if (strncasecmp(v, p->sub->cxident, len) &&
2918                                                     strncasecmp(v, p->sub->next->cxident, len)) {
2919                                                         /* connection id not found. delete it */
2920                                                         char cxident[80] = "";
2921
2922                                                         if (len > (sizeof(cxident) - 1))
2923                                                                 len = sizeof(cxident) - 1;
2924                                                         ast_copy_string(cxident, v, len);
2925                                                         ast_verb(3, "Non existing connection id %s on %s@%s \n",
2926                                                                             cxident, p->name, gw->name);
2927                                                         transmit_connection_del_w_params(p, NULL, cxident);
2928                                                 }
2929                                         }
2930                                         c = n;
2931                                 }
2932                         }
2933
2934                         /* Try to determine the hookstate returned from an audit endpoint command */
2935                         if ((c = get_header(resp, "ES"))) {
2936                                 if (!ast_strlen_zero(c)) {
2937                                         if (strstr(c, "hu")) {
2938                                                 if (p->hookstate != MGCP_ONHOOK) {
2939                                                         /* XXX cleanup if we think we are offhook XXX */
2940                                                         if ((p->sub->owner || p->sub->next->owner ) &&
2941                                                             p->hookstate == MGCP_OFFHOOK)
2942                                                                 mgcp_queue_hangup(sub);
2943                                                         p->hookstate = MGCP_ONHOOK;
2944
2945                                                         /* update the requested events according to the new hookstate */
2946                                                         transmit_notify_request(p->sub, "");
2947
2948                                                         ast_verb(3, "Setting hookstate of %s@%s to ONHOOK\n", p->name, gw->name);
2949                                                         }
2950                                         } else if (strstr(c, "hd")) {
2951                                                 if (p->hookstate != MGCP_OFFHOOK) {
2952                                                         p->hookstate = MGCP_OFFHOOK;
2953
2954                                                         /* update the requested events according to the new hookstate */
2955                                                         transmit_notify_request(p->sub, "");
2956
2957                                                         ast_verb(3, "Setting hookstate of %s@%s to OFFHOOK\n", p->name, gw->name);
2958                                                         }
2959                                                 }
2960                                         }
2961                                 }
2962                         }
2963
2964                 if (resp && resp->lines) {
2965                         /* do not process sdp if we are hanging up. this may be a late response */
2966                         if (sub && sub->owner) {
2967                                 if (!sub->rtp)
2968                                         start_rtp(sub);
2969                                 if (sub->rtp)
2970                                         process_sdp(sub, resp);
2971                         }
2972                 }
2973         }
2974
2975         ast_free(req);
2976 }
2977
2978 static void start_rtp(struct mgcp_subchannel *sub)
2979 {
2980         struct ast_sockaddr bindaddr_tmp;
2981
2982         ast_mutex_lock(&sub->lock);
2983         /* check again to be on the safe side */
2984         if (sub->rtp) {
2985                 ast_rtp_instance_destroy(sub->rtp);
2986                 sub->rtp = NULL;
2987         }
2988         /* Allocate the RTP now */
2989         ast_sockaddr_from_sin(&bindaddr_tmp, &bindaddr);
2990         sub->rtp = ast_rtp_instance_new("asterisk", sched, &bindaddr_tmp, NULL);
2991         if (sub->rtp && sub->owner)
2992                 ast_channel_set_fd(sub->owner, 0, ast_rtp_instance_fd(sub->rtp, 0));
2993         if (sub->rtp) {
2994                 ast_rtp_instance_set_qos(sub->rtp, qos.tos_audio, qos.cos_audio, "MGCP RTP");
2995                 ast_rtp_instance_set_prop(sub->rtp, AST_RTP_PROPERTY_NAT, sub->nat);
2996         }
2997         /* Make a call*ID */
2998         snprintf(sub->callid, sizeof(sub->callid), "%08lx%s", (unsigned long)ast_random(), sub->txident);
2999         /* Transmit the connection create */
3000         if(!sub->parent->pktcgatealloc) {
3001                 transmit_connect_with_sdp(sub, NULL);
3002         } else {
3003                 transmit_connect(sub);
3004                 sub->gate = NULL;
3005                 if(!mgcp_alloc_pktcgate(sub))
3006                         mgcp_queue_hangup(sub);
3007         }
3008         ast_mutex_unlock(&sub->lock);
3009 }
3010
3011 static void *mgcp_ss(void *data)
3012 {
3013         struct ast_channel *chan = data;
3014         struct mgcp_subchannel *sub = ast_channel_tech_pvt(chan);
3015         struct mgcp_endpoint *p = sub->parent;
3016         /* char exten[AST_MAX_EXTENSION] = ""; */
3017         int len = 0;
3018         int timeout = firstdigittimeout;
3019         int res= 0;
3020         int getforward = 0;
3021         int loop_pause = 100;
3022         RAII_VAR(struct ast_features_pickup_config *, pickup_cfg, NULL, ao2_cleanup);
3023         const char *pickupexten;
3024
3025         len = strlen(p->dtmf_buf);
3026
3027         ast_channel_lock(chan);
3028         pickup_cfg = ast_get_chan_features_pickup_config(chan);
3029         if (!pickup_cfg) {
3030                 ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension\n");
3031                 pickupexten = "";
3032         } else {
3033                 pickupexten = ast_strdupa(pickup_cfg->pickupexten);
3034         }
3035         ast_channel_unlock(chan);
3036
3037         while (len < AST_MAX_EXTENSION - 1) {
3038                 ast_debug(1, "Dtmf buffer '%s' for '%s@%s'\n", p->dtmf_buf, p->name, p->parent->name);
3039                 res = 1;  /* Assume that we will get a digit */
3040                 while (strlen(p->dtmf_buf) == len) {
3041                         ast_safe_sleep(chan, loop_pause);
3042                         timeout -= loop_pause;
3043                         if (timeout <= 0){
3044                                 res = 0;
3045                                 break;
3046                         }
3047                         res = 1;
3048                 }
3049
3050                 timeout = 0;
3051                 len = strlen(p->dtmf_buf);
3052
3053                 if (!ast_ignore_pattern(ast_channel_context(chan), p->dtmf_buf)) {
3054                         /*res = tone_zone_play_tone(p->subs[index].zfd, -1);*/
3055                         ast_indicate(chan, -1);
3056                 } else {
3057                         /* XXX Redundant?  We should already be playing dialtone */
3058                         /*tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALTONE);*/
3059                         transmit_notify_request(sub, "L/dl");
3060                 }
3061                 if (ast_exists_extension(chan, ast_channel_context(chan), p->dtmf_buf, 1, p->cid_num)) {
3062                         if (!res || !ast_matchmore_extension(chan, ast_channel_context(chan), p->dtmf_buf, 1, p->cid_num)) {
3063                                 if (getforward) {
3064                                         /* Record this as the forwarding extension */
3065                                         ast_copy_string(p->call_forward, p->dtmf_buf, sizeof(p->call_forward));
3066                                         ast_verb(3, "Setting call forward to '%s' on channel %s\n",
3067                                                         p->call_forward, ast_channel_name(chan));
3068                                         /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
3069                                         transmit_notify_request(sub, "L/sl");
3070                                         if (res)
3071                                                 break;
3072                                         usleep(500000);
3073                                         /*res = tone_zone_play_tone(p->subs[index].zfd, -1);*/
3074                                         ast_indicate(chan, -1);
3075                                         sleep(1);
3076                                         memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
3077                                         /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALTONE);*/
3078                                         transmit_notify_request(sub, "L/dl");
3079                                         len = 0;
3080                                         getforward = 0;
3081                                 } else {
3082                                         /*res = tone_zone_play_tone(p->subs[index].zfd, -1);*/
3083                                         ast_indicate(chan, -1);
3084                                         ast_channel_lock(chan);
3085                                         ast_channel_exten_set(chan, p->dtmf_buf);
3086                                         ast_channel_dialed(chan)->number.str = ast_strdup(p->dtmf_buf);
3087                                         memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
3088                                         ast_set_callerid(chan,
3089                                                 p->hidecallerid ? "" : p->cid_num,
3090                                                 p->hidecallerid ? "" : p->cid_name,
3091                                                 ast_channel_caller(chan)->ani.number.valid ? NULL : p->cid_num);
3092                                         ast_setstate(chan, AST_STATE_RING);
3093                                         ast_channel_unlock(chan);
3094                                         if (p->dtmfmode & MGCP_DTMF_HYBRID) {
3095             &nbs