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