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