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