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