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