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