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