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