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