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