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