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