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