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