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