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