f4e443cdd9045ad3e9d7014a4cae1a924d5d0fa7
[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 ast_group_t cur_callergroup = 0;
176 static ast_group_t cur_pickupgroup = 0;
177
178 /* XXX Is this needed? */
179 /*     Doesn't look like the dsp stuff for */
180 /*     dtmfmode is actually hooked up.   */
181 /*static int relaxdtmf = 0;*/
182
183 static int tos = 0;
184
185 static int immediate = 0;
186
187 static int callwaiting = 0;
188
189 /* Not used. Dosn't hurt for us to always send cid  */
190 /* to the mgcp box. */
191 /*static int callwaitingcallerid = 0;*/
192
193 /*static int hidecallerid = 0;*/
194
195 static int callreturn = 0;
196
197 static int slowsequence = 0;
198
199 static int threewaycalling = 0;
200
201 /* This is for flashhook transfers */
202 static int transfer = 0;
203
204 static int cancallforward = 0;
205
206 static int singlepath = 0;
207
208 static int canreinvite = CANREINVITE;
209
210 /*static int busycount = 3;*/
211
212 /*static int callprogress = 0;*/
213
214 static char accountcode[20] = "";
215
216 static char mailbox[AST_MAX_EXTENSION];
217
218 static int amaflags = 0;
219
220 static int adsi = 0;
221
222 static int usecnt =0;
223 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
224 /* SC: transaction id should always be positive */
225 static unsigned int oseq;
226
227 /* Wait up to 16 seconds for first digit (FXO logic) */
228 static int firstdigittimeout = 16000;
229
230 /* How long to wait for following digits (FXO logic) */
231 static int gendigittimeout = 8000;
232
233 /* How long to wait for an extra digit, if there is an ambiguous match */
234 static int matchdigittimeout = 3000;
235
236 /* Protect the monitoring thread, so only one process can kill or start it, and not
237    when it's doing something critical. */
238 AST_MUTEX_DEFINE_STATIC(netlock);
239
240 AST_MUTEX_DEFINE_STATIC(monlock);
241
242 /* This is the thread for the monitor which checks for input on the channels
243    which are not currently in use. */
244 static pthread_t monitor_thread = AST_PTHREADT_NULL;
245
246 static int restart_monitor(void);
247
248 /* 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         ast_group_t callgroup;
377         ast_group_t 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                 if (distinctive_ring && !ast_strlen_zero(distinctive_ring)) {
876                         snprintf(tone, sizeof(tone), "L/wt%s", distinctive_ring);
877                         if (mgcpdebug) {
878                                 ast_verbose(VERBOSE_PREFIX_3 "MGCP distinctive callwait %s\n", tone);
879                         }
880                 } else {
881                         snprintf(tone, sizeof(tone), "L/wt");
882                         if (mgcpdebug) {
883                                 ast_verbose(VERBOSE_PREFIX_3 "MGCP normal callwait %s\n", tone);
884                         }
885                 }
886                 break;
887         case MGCP_ONHOOK:
888         default:
889                 if (distinctive_ring && !ast_strlen_zero(distinctive_ring)) {
890                         snprintf(tone, sizeof(tone), "L/r%s", distinctive_ring);
891                         if (mgcpdebug) {
892                                 ast_verbose(VERBOSE_PREFIX_3 "MGCP distinctive ring %s\n", tone);
893                         }
894                 } else {
895                         snprintf(tone, sizeof(tone), "L/rg");
896                         if (mgcpdebug) {
897                                 ast_verbose(VERBOSE_PREFIX_3 "MGCP default ring\n");
898                         }
899                 }
900                 break;
901         }
902
903         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
904                 ast_log(LOG_WARNING, "mgcp_call called on %s, neither down nor reserved\n", ast->name);
905                 ast_mutex_unlock(&sub->lock);
906                 return -1;
907         }
908
909         res = 0;
910         sub->outgoing = 1;
911         sub->cxmode = MGCP_CX_RECVONLY;
912         if (p->type == TYPE_LINE) {
913                 if (!sub->rtp) {
914                         start_rtp(sub);
915                 } else {
916                         transmit_modify_request(sub);
917                 }
918
919                 if (sub->next->owner && strlen(sub->next->cxident) && strlen(sub->next->callid)) {
920                         /* try to prevent a callwait from disturbing the other connection */
921                         sub->next->cxmode = MGCP_CX_RECVONLY;
922                         transmit_modify_request(sub->next);
923                 }
924
925                 transmit_notify_request_with_callerid(sub, tone, ast->cid.cid_num, ast->cid.cid_name);
926                 ast_setstate(ast, AST_STATE_RINGING);
927
928                 if (sub->next->owner && strlen(sub->next->cxident) && strlen(sub->next->callid)) {
929                         /* Put the connection back in sendrecv */
930                         sub->next->cxmode = MGCP_CX_SENDRECV;
931                         transmit_modify_request(sub->next);
932                 }
933         } else {
934                 ast_log(LOG_NOTICE, "Don't know how to dial on trunks yet\n");
935                 res = -1;
936         }
937         ast_mutex_unlock(&sub->lock);
938         ast_queue_control(ast, AST_CONTROL_RINGING);
939         return res;
940 }
941
942 static int mgcp_hangup(struct ast_channel *ast)
943 {
944         struct mgcp_subchannel *sub = ast->pvt->pvt;
945         struct mgcp_endpoint *p = sub->parent;
946
947         if (option_debug) {
948                 ast_log(LOG_DEBUG, "mgcp_hangup(%s)\n", ast->name);
949         }
950         if (!ast->pvt->pvt) {
951                 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
952                 return 0;
953         }
954         if (strcmp(sub->magic, MGCP_SUBCHANNEL_MAGIC)) {
955                 ast_log(LOG_DEBUG, "Invalid magic. MGCP subchannel freed up already.\n");
956                 return 0;
957         }
958         ast_mutex_lock(&sub->lock);
959         if (mgcpdebug) {
960                 ast_verbose(VERBOSE_PREFIX_3 "MGCP mgcp_hangup(%s) on %s@%s\n", ast->name, p->name, p->parent->name);
961         }
962
963         if ((p->dtmfmode & MGCP_DTMF_INBAND) && p->dsp) {
964                 /* SC: check whether other channel is active. */
965                 if (!sub->next->owner) {
966                         if (mgcpdebug) {
967                                 ast_verbose(VERBOSE_PREFIX_2 "MGCP free dsp on %s@%s\n", p->name, p->parent->name);
968                         }
969                         ast_dsp_free(p->dsp);
970                         p->dsp = NULL;
971                 }
972         }
973
974         sub->owner = NULL;
975         if (strlen(sub->cxident)) {
976                 transmit_connection_del(sub);
977         }
978         sub->cxident[0] = '\0';
979         if ((sub == p->sub) && sub->next->owner) {
980                 if (p->hookstate == MGCP_OFFHOOK) {
981                         if (sub->next->owner && ast_bridged_channel(sub->next->owner)) {
982                                 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);
983                         }
984                 } else {
985                         /* set our other connection as the primary and swith over to it */
986                         p->sub = sub->next;
987                         p->sub->cxmode = MGCP_CX_RECVONLY;
988                         transmit_modify_request(p->sub);
989                         if (sub->next->owner && ast_bridged_channel(sub->next->owner)) {
990                                 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);
991                         }
992                 }
993
994         } else if ((sub == p->sub->next) && p->hookstate == MGCP_OFFHOOK) {
995                 transmit_notify_request(sub, "L/v");
996         } else if (p->hookstate == MGCP_OFFHOOK) {
997                 transmit_notify_request(sub, "L/ro");
998         } else {
999                 transmit_notify_request(sub, "");
1000         }
1001
1002         ast->pvt->pvt = NULL;
1003         sub->alreadygone = 0;
1004         sub->outgoing = 0;
1005         sub->cxmode = MGCP_CX_INACTIVE;
1006         sub->callid[0] = '\0';
1007         /* Reset temporary destination */
1008         memset(&sub->tmpdest, 0, sizeof(sub->tmpdest));
1009         if (sub->rtp) {
1010                 ast_rtp_destroy(sub->rtp);
1011                 sub->rtp = NULL;
1012         }
1013
1014         /* SC: Decrement use count */
1015         ast_mutex_lock(&usecnt_lock);
1016         usecnt--;
1017         ast_mutex_unlock(&usecnt_lock);
1018         ast_update_use_count();
1019         /* SC: Decrement use count */
1020
1021         if ((p->hookstate == MGCP_ONHOOK) && (!sub->next->rtp)) {
1022                 if (has_voicemail(p)) {
1023                         if (mgcpdebug) {
1024                                 ast_verbose(VERBOSE_PREFIX_3 "MGCP mgcp_hangup(%s) on %s@%s set vmwi(+)\n", 
1025                                         ast->name, p->name, p->parent->name);
1026                         }
1027                         transmit_notify_request(sub, "L/vmwi(+)");
1028                 } else {
1029                         if (mgcpdebug) {
1030                                 ast_verbose(VERBOSE_PREFIX_3 "MGCP mgcp_hangup(%s) on %s@%s set vmwi(-)\n", 
1031                                         ast->name, p->name, p->parent->name);
1032                         }
1033                         transmit_notify_request(sub, "L/vmwi(-)");
1034                 }
1035         }
1036         ast_mutex_unlock(&sub->lock);
1037         return 0;
1038 }
1039
1040 static int mgcp_show_endpoints(int fd, int argc, char *argv[])
1041 {
1042         struct mgcp_gateway  *g;
1043         struct mgcp_endpoint *e;
1044         int hasendpoints = 0;
1045         char iabuf[INET_ADDRSTRLEN];
1046
1047         if (argc != 3) 
1048                 return RESULT_SHOWUSAGE;
1049         ast_mutex_lock(&gatelock);
1050         g = gateways;
1051         while(g) {
1052                 e = g->endpoints;
1053                 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");
1054                 while(e) {
1055                         /* JS: Don't show wilcard endpoint */
1056                         if (strcmp(e->name, g->wcardep) !=0)
1057                                 ast_cli(fd, "   -- '%s@%s in '%s' is %s\n", e->name, g->name, e->context, e->sub->owner ? "active" : "idle");
1058                         hasendpoints = 1;
1059                         e = e->next;
1060                 }
1061                 if (!hasendpoints) {
1062                         ast_cli(fd, "   << No Endpoints Defined >>     ");
1063                 }
1064                 g = g->next;
1065         }
1066         ast_mutex_unlock(&gatelock);
1067         return RESULT_SUCCESS;
1068 }
1069
1070 static char show_endpoints_usage[] = 
1071 "Usage: mgcp show endpoints\n"
1072 "       Lists all endpoints known to the MGCP (Media Gateway Control Protocol) subsystem.\n";
1073
1074 static struct ast_cli_entry  cli_show_endpoints = 
1075         { { "mgcp", "show", "endpoints", NULL }, mgcp_show_endpoints, "Show defined MGCP endpoints", show_endpoints_usage };
1076
1077 static int mgcp_audit_endpoint(int fd, int argc, char *argv[])
1078 {
1079         struct mgcp_gateway  *g;
1080         struct mgcp_endpoint *e;
1081         int found = 0;
1082         char *ename,*gname, *c;
1083
1084         if (!mgcpdebug) {
1085                 return RESULT_SHOWUSAGE;
1086         }
1087         if (argc != 4) 
1088                 return RESULT_SHOWUSAGE;
1089         /* split the name into parts by null */
1090         ename = argv[3];
1091         gname = ename;
1092         while (*gname) {
1093                 if (*gname == '@') {
1094                         *gname = 0;
1095                         gname++;
1096                         break;
1097                 }
1098                 gname++;
1099         }
1100         if (gname[0] == '[')
1101                 gname++;
1102         if ((c = strrchr(gname, ']')))
1103                 *c = '\0';
1104         ast_mutex_lock(&gatelock);
1105         g = gateways;
1106         while(g) {
1107                 if (!strcasecmp(g->name, gname)) {
1108                         e = g->endpoints;
1109                         while(e) {
1110                                 if (!strcasecmp(e->name, ename)) {
1111                                         found = 1;
1112                                         transmit_audit_endpoint(e);
1113                                         break;
1114                                 }
1115                                 e = e->next;
1116                         }
1117                         if (found) {
1118                                 break;
1119                         }
1120                 }
1121                 g = g->next;
1122         }
1123         if (!found) {
1124                 ast_cli(fd, "   << Could not find endpoint >>     ");
1125         }
1126         ast_mutex_unlock(&gatelock);
1127         return RESULT_SUCCESS;
1128 }
1129
1130 static char audit_endpoint_usage[] = 
1131 "Usage: mgcp audit endpoint <endpointid>\n"
1132 "       Lists the capabilities of an endpoint in the MGCP (Media Gateway Control Protocol) subsystem.\n"
1133 "       mgcp debug MUST be on to see the results of this command.\n";
1134
1135 static struct ast_cli_entry  cli_audit_endpoint = 
1136         { { "mgcp", "audit", "endpoint", NULL }, mgcp_audit_endpoint, "Audit specified MGCP endpoint", audit_endpoint_usage };
1137
1138 static int mgcp_answer(struct ast_channel *ast)
1139 {
1140         int res = 0;
1141         struct mgcp_subchannel *sub = ast->pvt->pvt;
1142         struct mgcp_endpoint *p = sub->parent;
1143
1144         ast_mutex_lock(&sub->lock);
1145         sub->cxmode = MGCP_CX_SENDRECV;
1146         if (!sub->rtp) {
1147                 start_rtp(sub);
1148         } else {
1149                 transmit_modify_request(sub);
1150         }
1151         /* SC: verbose level check */
1152         if (option_verbose > 2) {
1153                 ast_verbose(VERBOSE_PREFIX_3 "MGCP mgcp_answer(%s) on %s@%s-%d\n", 
1154                         ast->name, p->name, p->parent->name, sub->id);
1155         }
1156         if (ast->_state != AST_STATE_UP) {
1157                 ast_setstate(ast, AST_STATE_UP);
1158                 if (option_debug)
1159                         ast_log(LOG_DEBUG, "mgcp_answer(%s)\n", ast->name);
1160                 transmit_notify_request(sub, "");
1161                 transmit_modify_request(sub);
1162         }
1163         ast_mutex_unlock(&sub->lock);
1164         return res;
1165 }
1166
1167 static struct ast_frame *mgcp_rtp_read(struct mgcp_subchannel *sub)
1168 {
1169         /* Retrieve audio/etc from channel.  Assumes sub->lock is already held. */
1170         struct ast_frame *f;
1171         static struct ast_frame null_frame = { AST_FRAME_NULL, };
1172
1173         f = ast_rtp_read(sub->rtp);
1174         /* Don't send RFC2833 if we're not supposed to */
1175         if (f && (f->frametype == AST_FRAME_DTMF) && !(sub->parent->dtmfmode & MGCP_DTMF_RFC2833))
1176                 return &null_frame;
1177         if (sub->owner) {
1178                 /* We already hold the channel lock */
1179                 if (f->frametype == AST_FRAME_VOICE) {
1180                         if (f->subclass != sub->owner->nativeformats) {
1181                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1182                                 sub->owner->nativeformats = f->subclass;
1183                                 ast_set_read_format(sub->owner, sub->owner->readformat);
1184                                 ast_set_write_format(sub->owner, sub->owner->writeformat);
1185                         }
1186                         /* Courtesy fearnor aka alex@pilosoft.com */
1187                         if ((sub->parent->dtmfmode & MGCP_DTMF_INBAND) && (sub->parent->dsp)) {
1188 #if 0
1189                                 ast_log(LOG_NOTICE, "MGCP ast_dsp_process\n");
1190 #endif
1191                                 f = ast_dsp_process(sub->owner, sub->parent->dsp, f);
1192                         }
1193                 }
1194         }
1195         return f;
1196 }
1197
1198
1199 static struct ast_frame *mgcp_read(struct ast_channel *ast)
1200 {
1201         struct ast_frame *f;
1202         struct mgcp_subchannel *sub = ast->pvt->pvt;
1203         ast_mutex_lock(&sub->lock);
1204         f = mgcp_rtp_read(sub);
1205         ast_mutex_unlock(&sub->lock);
1206         return f;
1207 }
1208
1209 static int mgcp_write(struct ast_channel *ast, struct ast_frame *frame)
1210 {
1211         struct mgcp_subchannel *sub = ast->pvt->pvt;
1212         int res = 0;
1213         if (frame->frametype != AST_FRAME_VOICE) {
1214                 if (frame->frametype == AST_FRAME_IMAGE)
1215                         return 0;
1216                 else {
1217                         ast_log(LOG_WARNING, "Can't send %d type frames with MGCP write\n", frame->frametype);
1218                         return 0;
1219                 }
1220         } else {
1221                 if (!(frame->subclass & ast->nativeformats)) {
1222                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1223                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
1224                         return -1;
1225                 }
1226         }
1227         if (sub) {
1228                 ast_mutex_lock(&sub->lock);
1229                 if ((sub->parent->sub == sub) || !sub->parent->singlepath) {
1230                         if (sub->rtp) {
1231                                 res =  ast_rtp_write(sub->rtp, frame);
1232                         }
1233                 }
1234                 ast_mutex_unlock(&sub->lock);
1235         }
1236         return res;
1237 }
1238
1239 static int mgcp_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1240 {
1241         struct mgcp_subchannel *sub = newchan->pvt->pvt;
1242
1243         ast_mutex_lock(&sub->lock);
1244         ast_log(LOG_NOTICE, "mgcp_fixup(%s, %s)\n", oldchan->name, newchan->name);
1245         if (sub->owner != oldchan) {
1246                 ast_mutex_unlock(&sub->lock);
1247                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, sub->owner);
1248                 return -1;
1249         }
1250         sub->owner = newchan;
1251         ast_mutex_unlock(&sub->lock);
1252         return 0;
1253 }
1254
1255 static int mgcp_senddigit(struct ast_channel *ast, char digit)
1256 {
1257         struct mgcp_subchannel *sub = ast->pvt->pvt;
1258         char tmp[4];
1259
1260         tmp[0] = 'D';
1261         tmp[1] = '/';
1262         tmp[2] = digit;
1263         tmp[3] = '\0';
1264         ast_mutex_lock(&sub->lock);
1265         transmit_notify_request(sub, tmp);
1266         ast_mutex_unlock(&sub->lock);
1267         return -1;
1268 }
1269
1270 static char *control2str(int ind) {
1271         switch (ind) {
1272         case AST_CONTROL_HANGUP:
1273                 return "Other end has hungup";
1274         case AST_CONTROL_RING:
1275                 return "Local ring";
1276         case AST_CONTROL_RINGING:
1277                 return "Remote end is ringing";
1278         case AST_CONTROL_ANSWER:
1279                 return "Remote end has answered";
1280         case AST_CONTROL_BUSY:
1281                 return "Remote end is busy";
1282         case AST_CONTROL_TAKEOFFHOOK:
1283                 return "Make it go off hook";
1284         case AST_CONTROL_OFFHOOK:
1285                 return "Line is off hook";
1286         case AST_CONTROL_CONGESTION:
1287                 return "Congestion (circuits busy)";
1288         case AST_CONTROL_FLASH:
1289                 return "Flash hook";
1290         case AST_CONTROL_WINK:
1291                 return "Wink";
1292         case AST_CONTROL_OPTION:
1293                 return "Set a low-level option";
1294         case AST_CONTROL_RADIO_KEY:
1295                 return "Key Radio";
1296         case AST_CONTROL_RADIO_UNKEY:
1297                 return "Un-Key Radio";
1298         }
1299         return "UNKNOWN";
1300 }
1301
1302 static int mgcp_indicate(struct ast_channel *ast, int ind)
1303 {
1304         struct mgcp_subchannel *sub = ast->pvt->pvt;
1305         int res = 0;
1306
1307         if (mgcpdebug) {
1308                 ast_verbose(VERBOSE_PREFIX_3 "MGCP asked to indicate %d '%s' condition on channel %s\n",
1309                         ind, control2str(ind), ast->name);
1310         }
1311         ast_mutex_lock(&sub->lock);
1312         switch(ind) {
1313         case AST_CONTROL_RINGING:
1314 #ifdef DLINK_BUGGY_FIRMWARE     
1315                 transmit_notify_request(sub, "rt");
1316 #else
1317                 transmit_notify_request(sub, "G/rt");
1318 #endif          
1319                 break;
1320         case AST_CONTROL_BUSY:
1321                 transmit_notify_request(sub, "L/bz");
1322                 break;
1323         case AST_CONTROL_CONGESTION:
1324                 transmit_notify_request(sub, "G/cg");
1325                 break;
1326         case -1:
1327                 transmit_notify_request(sub, "");
1328                 break;          
1329         default:
1330                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", ind);
1331                 res = -1;
1332         }
1333         ast_mutex_unlock(&sub->lock);
1334         return res;
1335 }
1336
1337 static struct ast_channel *mgcp_new(struct mgcp_subchannel *sub, int state)
1338 {
1339         struct ast_channel *tmp;
1340         struct mgcp_endpoint *i = sub->parent;
1341         int fmt;
1342
1343         i = sub->parent;
1344         tmp = ast_channel_alloc(1);
1345         if (tmp) {
1346                 tmp->nativeformats = i->capability;
1347                 if (!tmp->nativeformats)
1348                         tmp->nativeformats = capability;
1349                 fmt = ast_best_codec(tmp->nativeformats);
1350                 snprintf(tmp->name, sizeof(tmp->name), "MGCP/%s@%s-%d", i->name, i->parent->name, sub->id);
1351                 if (sub->rtp)
1352                         tmp->fds[0] = ast_rtp_fd(sub->rtp);
1353                 tmp->type = type;
1354                 if (i->dtmfmode & MGCP_DTMF_INBAND) {
1355                         i->dsp = ast_dsp_new();
1356                         ast_dsp_set_features(i->dsp,DSP_FEATURE_DTMF_DETECT);
1357                         /* SC: this is to prevent clipping of dtmf tones during dsp processing */
1358                         ast_dsp_digitmode(i->dsp, DSP_DIGITMODE_NOQUELCH);
1359                 } else {
1360                         i->dsp = NULL;
1361                 }
1362                 ast_setstate(tmp, state);
1363                 if (state == AST_STATE_RING)
1364                         tmp->rings = 1;
1365                 tmp->writeformat = fmt;
1366                 tmp->pvt->rawwriteformat = fmt;
1367                 tmp->readformat = fmt;
1368                 tmp->pvt->rawreadformat = fmt;
1369                 tmp->pvt->pvt = sub;
1370                 tmp->pvt->call = mgcp_call;
1371                 tmp->pvt->hangup = mgcp_hangup;
1372                 tmp->pvt->answer = mgcp_answer;
1373                 tmp->pvt->read = mgcp_read;
1374                 tmp->pvt->write = mgcp_write;
1375                 tmp->pvt->indicate = mgcp_indicate;
1376                 tmp->pvt->fixup = mgcp_fixup;
1377                 tmp->pvt->send_digit = mgcp_senddigit;
1378                 tmp->pvt->bridge = ast_rtp_bridge;
1379                 if (strlen(i->language))
1380                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1381                 if (strlen(i->accountcode))
1382                         strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
1383                 if (i->amaflags)
1384                         tmp->amaflags = i->amaflags;
1385                 sub->owner = tmp;
1386                 ast_mutex_lock(&usecnt_lock);
1387                 usecnt++;
1388                 ast_mutex_unlock(&usecnt_lock);
1389                 ast_update_use_count();
1390                 tmp->callgroup = i->callgroup;
1391                 tmp->pickupgroup = i->pickupgroup;
1392                 strncpy(tmp->call_forward, i->call_forward, sizeof(tmp->call_forward) - 1);
1393                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1394                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1395                 if (!ast_strlen_zero(i->cid_num))
1396                         tmp->cid.cid_num = strdup(i->cid_num);
1397                 if (!ast_strlen_zero(i->cid_name))
1398                         tmp->cid.cid_name = strdup(i->cid_name);
1399                 if (!i->adsi)
1400                         tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1401                 tmp->priority = 1;
1402                 if (state != AST_STATE_DOWN) {
1403                         if (ast_pbx_start(tmp)) {
1404                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1405                                 ast_hangup(tmp);
1406                                 tmp = NULL;
1407                         }
1408                 }
1409                 /* SC: verbose level check */
1410                 if (option_verbose > 2) {
1411                         ast_verbose(VERBOSE_PREFIX_3 "MGCP mgcp_new(%s) created in state: %s\n",
1412                                 tmp->name, ast_state2str(state));
1413                 }
1414         } else {
1415                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1416         }
1417         return tmp;
1418 }
1419
1420 static char* get_sdp_by_line(char* line, char *name, int nameLen)
1421 {
1422         if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1423                 char* r = line + nameLen + 1;
1424                 while (*r && (*r < 33)) ++r;
1425                 return r;
1426         }
1427         return "";
1428 }
1429
1430 static char *get_sdp(struct mgcp_request *req, char *name)
1431 {
1432         int x;
1433         int len = strlen(name);
1434         char *r;
1435
1436         for (x=0; x<req->lines; x++) {
1437                 r = get_sdp_by_line(req->line[x], name, len);
1438                 if (r[0] != '\0') return r;
1439         }
1440         return "";
1441 }
1442
1443 static void sdpLineNum_iterator_init(int* iterator)
1444 {
1445         *iterator = 0;
1446 }
1447
1448 static char* get_sdp_iterate(int* iterator, struct mgcp_request *req, char *name)
1449 {
1450         int len = strlen(name);
1451         char *r;
1452         while (*iterator < req->lines) {
1453                 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1454                 if (r[0] != '\0') return r;
1455         }
1456         return "";
1457 }
1458
1459 static char *__get_header(struct mgcp_request *req, char *name, int *start)
1460 {
1461         int x;
1462         int len = strlen(name);
1463         char *r;
1464         for (x=*start;x<req->headers;x++) {
1465                 if (!strncasecmp(req->header[x], name, len) && 
1466                     (req->header[x][len] == ':')) {
1467                         r = req->header[x] + len + 1;
1468                         while(*r && (*r < 33))
1469                                 r++;
1470                         *start = x+1;
1471                         return r;
1472                 }
1473         }
1474         /* Don't return NULL, so get_header is always a valid pointer */
1475         return "";
1476 }
1477
1478 static char *get_header(struct mgcp_request *req, char *name)
1479 {
1480         int start = 0;
1481         return __get_header(req, name, &start);
1482 }
1483
1484 /* SC: get comma separated value */
1485 static char *get_csv(char *c, int *len, char **next) 
1486 {
1487         char *s;
1488
1489         *next = NULL, *len = 0;
1490         if (!c) return NULL;
1491
1492         while (*c && (*c < 33 || *c == ','))
1493                 c++;
1494
1495         s = c;
1496         while (*c && (*c >= 33 && *c != ','))
1497                 c++, (*len)++;
1498         *next = c;
1499
1500         if (*len == 0)
1501                 s = NULL, *next = NULL;
1502
1503         return s;
1504 }
1505
1506 static struct mgcp_subchannel *find_subchannel_and_lock(char *name, int msgid, struct sockaddr_in *sin)
1507 {
1508         struct mgcp_endpoint *p = NULL;
1509         struct mgcp_subchannel *sub = NULL;
1510         struct mgcp_gateway *g;
1511         char iabuf[INET_ADDRSTRLEN];
1512         char tmp[256] = "";
1513         char *at = NULL, *c;
1514         int found = 0;
1515         if (name) {
1516                 strncpy(tmp, name, sizeof(tmp) - 1);
1517                 at = strchr(tmp, '@');
1518                 if (!at) {
1519                         ast_log(LOG_NOTICE, "Endpoint '%s' has no at sign!\n", name);
1520                         return NULL;
1521                 }
1522                 *at = '\0';
1523                 at++;
1524         }
1525         ast_mutex_lock(&gatelock);
1526         if (at && (at[0] == '[')) {
1527                 at++;
1528                 c = strrchr(at, ']');
1529                 if (c)
1530                         *c = '\0';
1531         }
1532         g = gateways;
1533         while(g) {
1534                 if ((!name || !strcasecmp(g->name, at)) && 
1535                     (sin || g->addr.sin_addr.s_addr || g->defaddr.sin_addr.s_addr)) {
1536                         /* Found the gateway.  If it's dynamic, save it's address -- now for the endpoint */
1537                         if (sin && g->dynamic && name) {
1538                                 if ((g->addr.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1539                                         (g->addr.sin_port != sin->sin_port)) {
1540                                         memcpy(&g->addr, sin, sizeof(g->addr));
1541                                         if (ast_ouraddrfor(&g->addr.sin_addr, &g->ourip))
1542                                                 memcpy(&g->ourip, &__ourip, sizeof(g->ourip));
1543                                         if (option_verbose > 2)
1544                                                 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));
1545                                 }
1546                         }
1547                         /* SC: not dynamic, check if the name matches */
1548                         else if (name) {
1549                                 if (strcasecmp(g->name, at)) {
1550                                         g = g->next;
1551                                         continue;
1552                                 }
1553                         }
1554                         /* SC: not dynamic, no name, check if the addr matches */
1555                         else if (!name && sin) {
1556                                 if ((g->addr.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1557                                     (g->addr.sin_port != sin->sin_port)) {
1558                                         g = g->next;
1559                                         continue;
1560                                 }
1561                         } else {
1562                                 g = g->next;
1563                                 continue;
1564                         }
1565                         /* SC */
1566                         p = g->endpoints;
1567                         while(p) {
1568                                 if (option_debug)
1569                                         ast_log(LOG_DEBUG, "Searching on %s@%s for subchannel\n",
1570                                                 p->name, g->name);
1571                                 if (msgid) {
1572 #if 0 /* SC: new transport mech */
1573                                         sub = p->sub;
1574                                         do {
1575                                                 if (option_debug)
1576                                                         ast_log(LOG_DEBUG, "Searching on %s@%s-%d for subchannel with lastout: %d\n",
1577                                                                 p->name, g->name, sub->id, msgid);
1578                                                 if (sub->lastout == msgid) {
1579                                                         if (option_debug)
1580                                                                 ast_log(LOG_DEBUG, "Found subchannel sub%d to handle request %d sub->lastout: %d\n",
1581                                                                         sub->id, msgid, sub->lastout);
1582                                                         found = 1;
1583                                                         break;
1584                                                 }
1585                                                 sub = sub->next;
1586                                         } while (sub != p->sub);
1587                                         if (found) {
1588                                                 break;
1589                                         }
1590 #endif
1591                                         /* SC */
1592                                         sub = p->sub;
1593                                         found = 1;
1594                                         /* SC */
1595                                         break;
1596                                 } else if (name && !strcasecmp(p->name, tmp)) {
1597                                         ast_log(LOG_DEBUG, "Coundn't determine subchannel, assuming current master %s@%s-%d\n", 
1598                                                 p->name, g->name, p->sub->id);
1599                                         sub = p->sub;
1600                                         found = 1;
1601                                         break;
1602                                 }
1603                                 p = p->next;
1604                         }
1605                         if (sub && found) {
1606                                 ast_mutex_lock(&sub->lock);
1607                                 break;
1608                         }
1609                 }
1610                 g = g->next;
1611         }
1612         ast_mutex_unlock(&gatelock);
1613         if (!sub) {
1614                 if (name) {
1615                         if (g)
1616                                 ast_log(LOG_NOTICE, "Endpoint '%s' not found on gateway '%s'\n", tmp, at);
1617                         else
1618                                 ast_log(LOG_NOTICE, "Gateway '%s' (and thus its endpoint '%s') does not exist\n", at, tmp);
1619                 } 
1620         }
1621         return sub;
1622 }
1623
1624 static void parse(struct mgcp_request *req)
1625 {
1626         /* Divide fields by NULL's */
1627         char *c;
1628         int f = 0;
1629         c = req->data;
1630
1631         /* First header starts immediately */
1632         req->header[f] = c;
1633         while(*c) {
1634                 if (*c == '\n') {
1635                         /* We've got a new header */
1636                         *c = 0;
1637 #if 0
1638                         printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1639 #endif                  
1640                         if (!strlen(req->header[f])) {
1641                                 /* Line by itself means we're now in content */
1642                                 c++;
1643                                 break;
1644                         }
1645                         if (f >= MGCP_MAX_HEADERS - 1) {
1646                                 ast_log(LOG_WARNING, "Too many MGCP headers...\n");
1647                         } else
1648                                 f++;
1649                         req->header[f] = c + 1;
1650                 } else if (*c == '\r') {
1651                         /* Ignore but eliminate \r's */
1652                         *c = 0;
1653                 }
1654                 c++;
1655         }
1656         /* Check for last header */
1657         if (strlen(req->header[f])) 
1658                 f++;
1659         req->headers = f;
1660         /* Now we process any mime content */
1661         f = 0;
1662         req->line[f] = c;
1663         while(*c) {
1664                 if (*c == '\n') {
1665                         /* We've got a new line */
1666                         *c = 0;
1667 #if 0
1668                         printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1669 #endif                  
1670                         if (f >= MGCP_MAX_LINES - 1) {
1671                                 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1672                         } else
1673                                 f++;
1674                         req->line[f] = c + 1;
1675                 } else if (*c == '\r') {
1676                         /* Ignore and eliminate \r's */
1677                         *c = 0;
1678                 }
1679                 c++;
1680         }
1681         /* Check for last line */
1682         if (strlen(req->line[f])) 
1683                 f++;
1684         req->lines = f;
1685         /* Parse up the initial header */
1686         c = req->header[0];
1687         while(*c && *c < 33) c++;
1688         /* First the verb */
1689         req->verb = c;
1690         while(*c && (*c > 32)) c++;
1691         if (*c) {
1692                 *c = '\0';
1693                 c++;
1694                 while(*c && (*c < 33)) c++;
1695                 req->identifier = c;
1696                 while(*c && (*c > 32)) c++;
1697                 if (*c) {
1698                         *c = '\0';
1699                         c++;
1700                         while(*c && (*c < 33)) c++;
1701                         req->endpoint = c;
1702                         while(*c && (*c > 32)) c++;
1703                         if (*c) {
1704                                 *c = '\0';
1705                                 c++;
1706                                 while(*c && (*c < 33)) c++;
1707                                 req->version = c;
1708                                 while(*c && (*c > 32)) c++;
1709                                 while(*c && (*c < 33)) c++;
1710                                 while(*c && (*c > 32)) c++;
1711                                 *c = '\0';
1712                         }
1713                 }
1714         }
1715                 
1716         if (mgcpdebug) {
1717                 ast_verbose("Verb: '%s', Identifier: '%s', Endpoint: '%s', Version: '%s'\n",
1718                         req->verb, req->identifier, req->endpoint, req->version);
1719                 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1720         }
1721         if (*c) 
1722                 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1723 }
1724
1725 static int process_sdp(struct mgcp_subchannel *sub, struct mgcp_request *req)
1726 {
1727         char *m;
1728         char *c;
1729         char *a;
1730         char host[258];
1731         int len;
1732         int portno;
1733         int peercapability, peerNonCodecCapability;
1734         struct sockaddr_in sin;
1735         char *codecs;
1736         struct ast_hostent ahp; struct hostent *hp;
1737         int codec;
1738         int iterator;
1739         struct mgcp_endpoint *p = sub->parent;
1740
1741         /* Get codec and RTP info from SDP */
1742         m = get_sdp(req, "m");
1743         c = get_sdp(req, "c");
1744         if (!strlen(m) || !strlen(c)) {
1745                 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1746                 return -1;
1747         }
1748         if (sscanf(c, "IN IP4 %256s", host) != 1) {
1749                 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1750                 return -1;
1751         }
1752         /* XXX This could block for a long time, and block the main thread! XXX */
1753         hp = ast_gethostbyname(host, &ahp);
1754         if (!hp) {
1755                 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1756                 return -1;
1757         }
1758         if (sscanf(m, "audio %d RTP/AVP %n", &portno, &len) != 1) {
1759                 ast_log(LOG_WARNING, "Unable to determine port number for RTP in '%s'\n", m); 
1760                 return -1;
1761         }
1762         sin.sin_family = AF_INET;
1763         memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1764         sin.sin_port = htons(portno);
1765         ast_rtp_set_peer(sub->rtp, &sin);
1766 #if 0
1767         printf("Peer RTP is at port %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
1768 #endif  
1769         /* Scan through the RTP payload types specified in a "m=" line: */
1770         ast_rtp_pt_clear(sub->rtp);
1771         codecs = m + len;
1772         while(strlen(codecs)) {
1773                 if (sscanf(codecs, "%d %n", &codec, &len) != 1) {
1774                         ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1775                         return -1;
1776                 }
1777                 ast_rtp_set_m_type(sub->rtp, codec);
1778                 codecs += len;
1779         }
1780
1781         /* Next, scan through each "a=rtpmap:" line, noting each */
1782         /* specified RTP payload type (with corresponding MIME subtype): */
1783         sdpLineNum_iterator_init(&iterator);
1784         while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
1785                 char* mimeSubtype = strdup(a); /* ensures we have enough space */
1786                 if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2)
1787                         continue;
1788                 /* Note: should really look at the 'freq' and '#chans' params too */
1789                 ast_rtp_set_rtpmap_type(sub->rtp, codec, "audio", mimeSubtype);
1790                 free(mimeSubtype);
1791         }
1792
1793         /* Now gather all of the codecs that were asked for: */
1794         ast_rtp_get_current_formats(sub->rtp, &peercapability, &peerNonCodecCapability);
1795         p->capability = capability & peercapability;
1796         if (mgcpdebug) {
1797                 ast_verbose("Capabilities: us - %d, them - %d, combined - %d\n",
1798                         capability, peercapability, p->capability);
1799                 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
1800                         nonCodecCapability, peerNonCodecCapability, p->nonCodecCapability);
1801         }
1802         if (!p->capability) {
1803                 ast_log(LOG_WARNING, "No compatible codecs!\n");
1804                 return -1;
1805         }
1806         return 0;
1807 }
1808
1809 static int add_header(struct mgcp_request *req, char *var, char *value)
1810 {
1811         if (req->len >= sizeof(req->data) - 4) {
1812                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1813                 return -1;
1814         }
1815         if (req->lines) {
1816                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1817                 return -1;
1818         }
1819         req->header[req->headers] = req->data + req->len;
1820         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s: %s\r\n", var, value);
1821         req->len += strlen(req->header[req->headers]);
1822         if (req->headers < MGCP_MAX_HEADERS)
1823                 req->headers++;
1824         else {
1825                 ast_log(LOG_WARNING, "Out of header space\n");
1826                 return -1;
1827         }
1828         return 0;       
1829 }
1830
1831 static int add_line(struct mgcp_request *req, char *line)
1832 {
1833         if (req->len >= sizeof(req->data) - 4) {
1834                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1835                 return -1;
1836         }
1837         if (!req->lines) {
1838                 /* Add extra empty return */
1839                 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
1840                 req->len += strlen(req->data + req->len);
1841         }
1842         req->line[req->lines] = req->data + req->len;
1843         snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1844         req->len += strlen(req->line[req->lines]);
1845         if (req->lines < MGCP_MAX_LINES)
1846                 req->lines++;
1847         else {
1848                 ast_log(LOG_WARNING, "Out of line space\n");
1849                 return -1;
1850         }
1851         return 0;       
1852 }
1853
1854 static int init_resp(struct mgcp_request *req, char *resp, struct mgcp_request *orig, char *resprest)
1855 {
1856         /* Initialize a response */
1857         if (req->headers || req->len) {
1858                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1859                 return -1;
1860         }
1861         req->header[req->headers] = req->data + req->len;
1862         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s %s\r\n", resp, orig->identifier, resprest);
1863         req->len += strlen(req->header[req->headers]);
1864         if (req->headers < MGCP_MAX_HEADERS)
1865                 req->headers++;
1866         else
1867                 ast_log(LOG_WARNING, "Out of header space\n");
1868         return 0;
1869 }
1870
1871 static int init_req(struct mgcp_endpoint *p, struct mgcp_request *req, char *verb)
1872 {
1873         /* Initialize a response */
1874         if (req->headers || req->len) {
1875                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1876                 return -1;
1877         }
1878         req->header[req->headers] = req->data + req->len;
1879         /* SC: check if we need brackets around the gw name */
1880         if (p->parent->isnamedottedip)
1881                 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);
1882         else
1883                 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);
1884         req->len += strlen(req->header[req->headers]);
1885         if (req->headers < MGCP_MAX_HEADERS)
1886                 req->headers++;
1887         else
1888                 ast_log(LOG_WARNING, "Out of header space\n");
1889         return 0;
1890 }
1891
1892
1893 static int respprep(struct mgcp_request *resp, struct mgcp_endpoint *p, char *msg, struct mgcp_request *req, char *msgrest)
1894 {
1895         memset(resp, 0, sizeof(*resp));
1896         init_resp(resp, msg, req, msgrest);
1897         return 0;
1898 }
1899
1900 static int reqprep(struct mgcp_request *req, struct mgcp_endpoint *p, char *verb)
1901 {
1902         memset(req, 0, sizeof(struct mgcp_request));
1903         oseq++;
1904         if (oseq > 999999999)
1905                 oseq = 1;
1906         init_req(p, req, verb);
1907         return 0;
1908 }
1909
1910 static int transmit_response(struct mgcp_subchannel *sub, char *msg, struct mgcp_request *req, char *msgrest)
1911 {
1912         struct mgcp_request resp;
1913         struct mgcp_endpoint *p = sub->parent;
1914         struct mgcp_response *mgr;
1915
1916         respprep(&resp, p, msg, req, msgrest);
1917         mgr = malloc(sizeof(struct mgcp_response) + resp.len + 1);
1918         if (mgr) {
1919                 /* Store MGCP response in case we have to retransmit */
1920                 memset(mgr, 0, sizeof(struct mgcp_response));
1921                 sscanf(req->identifier, "%d", &mgr->seqno);
1922                 time(&mgr->whensent);
1923                 mgr->len = resp.len;
1924                 memcpy(mgr->buf, resp.data, resp.len);
1925                 mgr->buf[resp.len] = '\0';
1926                 mgr->next = p->parent->responses;
1927                 p->parent->responses = mgr;
1928         }
1929         return send_response(sub, &resp);
1930 }
1931
1932
1933 static int add_sdp(struct mgcp_request *resp, struct mgcp_subchannel *sub, struct ast_rtp *rtp)
1934 {
1935         int len;
1936         int codec;
1937         char costr[80];
1938         struct sockaddr_in sin;
1939         char v[256];
1940         char s[256];
1941         char o[256];
1942         char c[256];
1943         char t[256];
1944         char m[256] = "";
1945         char a[1024] = "";
1946         char iabuf[INET_ADDRSTRLEN];
1947         int x;
1948         struct sockaddr_in dest;
1949         struct mgcp_endpoint *p = sub->parent;
1950         /* XXX We break with the "recommendation" and send our IP, in order that our
1951                peer doesn't have to ast_gethostbyname() us XXX */
1952         len = 0;
1953         if (!sub->rtp) {
1954                 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
1955                 return -1;
1956         }
1957         ast_rtp_get_us(sub->rtp, &sin);
1958         if (rtp) {
1959                 ast_rtp_get_peer(rtp, &dest);
1960         } else {
1961                 if (sub->tmpdest.sin_addr.s_addr) {
1962                         dest.sin_addr = sub->tmpdest.sin_addr;
1963                         dest.sin_port = sub->tmpdest.sin_port;
1964                         /* Reset temporary destination */
1965                         memset(&sub->tmpdest, 0, sizeof(sub->tmpdest));
1966                 } else {
1967                         dest.sin_addr = p->parent->ourip;
1968                         dest.sin_port = sin.sin_port;
1969                 }
1970         }
1971         if (mgcpdebug) {
1972                 ast_verbose("We're at %s port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), p->parent->ourip), ntohs(sin.sin_port));
1973         }
1974         snprintf(v, sizeof(v), "v=0\r\n");
1975         snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), ast_inet_ntoa(iabuf, sizeof(iabuf), dest.sin_addr));
1976         snprintf(s, sizeof(s), "s=session\r\n");
1977         snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", ast_inet_ntoa(iabuf, sizeof(iabuf), dest.sin_addr));
1978         snprintf(t, sizeof(t), "t=0 0\r\n");
1979         snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
1980         for (x = 1; x <= AST_FORMAT_MAX_AUDIO; x <<= 1) {
1981                 if (p->capability & x) {
1982                         if (mgcpdebug) {
1983                                 ast_verbose("Answering with capability %d\n", x);
1984                         }
1985                         codec = ast_rtp_lookup_code(sub->rtp, 1, x);
1986                         if (codec > -1) {
1987                                 snprintf(costr, sizeof(costr), " %d", codec);
1988                                 strncat(m, costr, sizeof(m) - strlen(m) - 1);
1989                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
1990                                 strncat(a, costr, sizeof(a) - strlen(a) - 1);
1991                         }
1992                 }
1993         }
1994         for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
1995                 if (p->nonCodecCapability & x) {
1996                         if (mgcpdebug) {
1997                                 ast_verbose("Answering with non-codec capability %d\n", x);
1998                         }
1999                         codec = ast_rtp_lookup_code(sub->rtp, 0, x);
2000                         if (codec > -1) {
2001                                 snprintf(costr, sizeof(costr), " %d", codec);
2002                                 strncat(m, costr, sizeof(m) - strlen(m) - 1);
2003                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
2004                                 strncat(a, costr, sizeof(a) - strlen(a) - 1);
2005                                 if (x == AST_RTP_DTMF) {
2006                                         /* Indicate we support DTMF...  Not sure about 16,
2007                                            but MSN supports it so dang it, we will too... */
2008                                         snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n", codec);
2009                                         strncat(a, costr, sizeof(a) - strlen(a) - 1);
2010                                 }
2011                         }
2012                 }
2013         }
2014         strncat(m, "\r\n", sizeof(m) - strlen(m) - 1);
2015         len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2016         snprintf(costr, sizeof(costr), "%d", len);
2017         add_line(resp, v);
2018         add_line(resp, o);
2019         add_line(resp, s);
2020         add_line(resp, c);
2021         add_line(resp, t);
2022         add_line(resp, m);
2023         add_line(resp, a);
2024         return 0;
2025 }
2026
2027 static int transmit_modify_with_sdp(struct mgcp_subchannel *sub, struct ast_rtp *rtp, int codecs)
2028 {
2029         struct mgcp_request resp;
2030         char local[256];
2031         char tmp[80];
2032         int x;
2033         int capability;
2034         struct mgcp_endpoint *p = sub->parent;
2035
2036         capability = p->capability;
2037         if (codecs)
2038                 capability = codecs;
2039         if (!strlen(sub->cxident) && rtp) {
2040                 /* We don't have a CXident yet, store the destination and
2041                    wait a bit */
2042                 ast_rtp_get_peer(rtp, &sub->tmpdest);
2043                 return 0;
2044         }
2045         snprintf(local, sizeof(local), "p:20");
2046         for (x=1;x<= AST_FORMAT_MAX_AUDIO; x <<= 1) {
2047                 if (p->capability & x) {
2048                         snprintf(tmp, sizeof(tmp), ", a:%s", ast_rtp_lookup_mime_subtype(1, x));
2049                         strncat(local, tmp, sizeof(local) - strlen(local) - 1);
2050                 }
2051         }
2052         reqprep(&resp, p, "MDCX");
2053         add_header(&resp, "C", sub->callid);
2054         add_header(&resp, "L", local);
2055         add_header(&resp, "M", mgcp_cxmodes[sub->cxmode]);
2056         /* SC: X header should not be sent. kept for compatibility */
2057         add_header(&resp, "X", sub->txident);
2058         add_header(&resp, "I", sub->cxident);
2059         /*add_header(&resp, "S", "");*/
2060         ast_rtp_offered_from_local(sub->rtp, 0);
2061         add_sdp(&resp, sub, rtp);
2062         /* SC: fill in new fields */
2063         resp.cmd = MGCP_CMD_MDCX;
2064         resp.trid = oseq;
2065         return send_request(p, sub, &resp, oseq); /* SC */
2066 }
2067
2068 static int transmit_connect_with_sdp(struct mgcp_subchannel *sub, struct ast_rtp *rtp)
2069 {
2070         struct mgcp_request resp;
2071         char local[256];
2072         char tmp[80];
2073         int x;
2074         struct mgcp_endpoint *p = sub->parent;
2075
2076         snprintf(local, sizeof(local), "p:20");
2077         for (x=1;x<= AST_FORMAT_MAX_AUDIO; x <<= 1) {
2078                 if (p->capability & x) {
2079                         snprintf(tmp, sizeof(tmp), ", a:%s", ast_rtp_lookup_mime_subtype(1, x));
2080                         strncat(local, tmp, sizeof(local) - strlen(local) - 1);
2081                 }
2082         }
2083         if (mgcpdebug) {
2084                 ast_verbose(VERBOSE_PREFIX_3 "Creating connection for %s@%s-%d in cxmode: %s callid: %s\n", 
2085                         p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode], sub->callid);
2086         }
2087         reqprep(&resp, p, "CRCX");
2088         add_header(&resp, "C", sub->callid);
2089         add_header(&resp, "L", local);
2090         add_header(&resp, "M", mgcp_cxmodes[sub->cxmode]);
2091         /* SC: X header should not be sent. kept for compatibility */
2092         add_header(&resp, "X", sub->txident);
2093         /*add_header(&resp, "S", "");*/
2094         ast_rtp_offered_from_local(sub->rtp, 1);
2095         add_sdp(&resp, sub, rtp);
2096         /* SC: fill in new fields */
2097         resp.cmd = MGCP_CMD_CRCX;
2098         resp.trid = oseq;
2099         return send_request(p, sub, &resp, oseq);  /* SC */
2100 }
2101
2102 static int transmit_notify_request(struct mgcp_subchannel *sub, char *tone)
2103 {
2104         struct mgcp_request resp;
2105         struct mgcp_endpoint *p = sub->parent;
2106
2107         if (mgcpdebug) {
2108                 ast_verbose(VERBOSE_PREFIX_3 "MGCP Asked to indicate tone: %s on  %s@%s-%d in cxmode: %s\n", 
2109                         tone, p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode]);
2110         }
2111         strncpy(p->curtone, tone, sizeof(p->curtone) - 1);
2112         reqprep(&resp, p, "RQNT");
2113         add_header(&resp, "X", p->rqnt_ident); /* SC */
2114         switch (p->hookstate) {
2115         case MGCP_ONHOOK:
2116                 add_header(&resp, "R", "L/hd(N)");
2117                 break;
2118         case MGCP_OFFHOOK:
2119                 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)");
2120                 break;
2121         }
2122         if (strlen(tone)) {
2123                 add_header(&resp, "S", tone);
2124         }
2125         /* SC: fill in new fields */
2126         resp.cmd = MGCP_CMD_RQNT;
2127         resp.trid = oseq;
2128         return send_request(p, NULL, &resp, oseq); /* SC */
2129 }
2130
2131 static int transmit_notify_request_with_callerid(struct mgcp_subchannel *sub, char *tone, char *callernum, char *callername)
2132 {
2133         struct mgcp_request resp;
2134         char tone2[256];
2135         char *l, *n;
2136         time_t t;
2137         struct tm tm;
2138         struct mgcp_endpoint *p = sub->parent;
2139         
2140         time(&t);
2141         localtime_r(&t,&tm);
2142         n = callername;
2143         l = callernum;
2144         if (!n)
2145                 n = "";
2146         if (!l)
2147                 l = "";
2148
2149         /* Keep track of last callerid for blacklist and callreturn */
2150         strncpy(p->lastcallerid, l, sizeof(p->lastcallerid) - 1);
2151
2152         snprintf(tone2, sizeof(tone2), "%s,L/ci(%02d/%02d/%02d/%02d,%s,%s)", tone, 
2153                 tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, l, n);
2154         strncpy(p->curtone, tone, sizeof(p->curtone) - 1);
2155         reqprep(&resp, p, "RQNT");
2156         add_header(&resp, "X", p->rqnt_ident); /* SC */
2157         switch (p->hookstate) {
2158         case MGCP_ONHOOK:
2159                 add_header(&resp, "R", "L/hd(N)");
2160                 break;
2161         case MGCP_OFFHOOK:
2162                 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)");
2163                 break;
2164         }
2165         if (strlen(tone2)) {
2166                 add_header(&resp, "S", tone2);
2167         }
2168         if (mgcpdebug) {
2169                 ast_verbose(VERBOSE_PREFIX_3 "MGCP Asked to indicate tone: %s on  %s@%s-%d in cxmode: %s\n", 
2170                         tone2, p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode]);
2171         }
2172         /* SC: fill in new fields */
2173         resp.cmd = MGCP_CMD_RQNT;
2174         resp.trid = oseq;
2175         return send_request(p, NULL, &resp, oseq);  /* SC */
2176 }
2177
2178 static int transmit_modify_request(struct mgcp_subchannel *sub)
2179 {
2180         struct mgcp_request resp;
2181         struct mgcp_endpoint *p = sub->parent;
2182
2183         if (!strlen(sub->cxident)) {
2184                 /* We don't have a CXident yet, store the destination and
2185                    wait a bit */
2186                 return 0;
2187         }
2188         if (mgcpdebug) {
2189                 ast_verbose(VERBOSE_PREFIX_3 "Modified %s@%s-%d with new mode: %s on callid: %s\n", 
2190                         p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode], sub->callid);
2191         }
2192         reqprep(&resp, p, "MDCX");
2193         add_header(&resp, "C", sub->callid);
2194         add_header(&resp, "M", mgcp_cxmodes[sub->cxmode]);
2195         /* SC: X header should not be sent. kept for compatibility */
2196         add_header(&resp, "X", sub->txident);
2197         add_header(&resp, "I", sub->cxident);
2198         switch (sub->parent->hookstate) {
2199         case MGCP_ONHOOK:
2200                 add_header(&resp, "R", "L/hd(N)");
2201                 break;
2202         case MGCP_OFFHOOK:
2203                 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)");
2204                 break;
2205         }
2206         /* SC: fill in new fields */
2207         resp.cmd = MGCP_CMD_MDCX;
2208         resp.trid = oseq;
2209         return send_request(p, sub, &resp, oseq); /* SC */
2210 }
2211
2212
2213 static int transmit_audit_endpoint(struct mgcp_endpoint *p)
2214 {
2215         struct mgcp_request resp;
2216         reqprep(&resp, p, "AUEP");
2217         /* SC: removed unknown param VS */
2218         /*add_header(&resp, "F", "A,R,D,S,X,N,I,T,O,ES,E,MD,M");*/
2219         add_header(&resp, "F", "A");
2220         /* SC: fill in new fields */
2221         resp.cmd = MGCP_CMD_AUEP;
2222         resp.trid = oseq;
2223         return send_request(p, NULL, &resp, oseq);  /* SC */
2224 }
2225
2226 static int transmit_connection_del(struct mgcp_subchannel *sub)
2227 {
2228         struct mgcp_endpoint *p = sub->parent;
2229         struct mgcp_request resp;
2230
2231         if (mgcpdebug) {
2232                 ast_verbose(VERBOSE_PREFIX_3 "Delete connection %s %s@%s-%d with new mode: %s on callid: %s\n", 
2233                         sub->cxident, p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode], sub->callid);
2234         }
2235         reqprep(&resp, p, "DLCX");
2236         /* SC: check if call id is avail */
2237         if (sub->callid[0])
2238                 add_header(&resp, "C", sub->callid);
2239         /* SC: X header should not be sent. kept for compatibility */
2240         add_header(&resp, "X", sub->txident);
2241         /* SC: check if cxident is avail */
2242         if (sub->cxident[0])
2243                 add_header(&resp, "I", sub->cxident);
2244         /* SC: fill in new fields */
2245         resp.cmd = MGCP_CMD_DLCX;
2246         resp.trid = oseq;
2247         return send_request(p, sub, &resp, oseq);  /* SC */
2248 }
2249
2250 static int transmit_connection_del_w_params(struct mgcp_endpoint *p, char *callid, char *cxident)
2251 {
2252         struct mgcp_request resp;
2253
2254         if (mgcpdebug) {
2255                 ast_verbose(VERBOSE_PREFIX_3 "Delete connection %s %s@%s on callid: %s\n", 
2256                         cxident ? cxident : "", p->name, p->parent->name, callid ? callid : "");
2257         }
2258         reqprep(&resp, p, "DLCX");
2259         /* SC: check if call id is avail */
2260         if (callid && *callid)
2261                 add_header(&resp, "C", callid);
2262         /* SC: check if cxident is avail */
2263         if (cxident && *cxident)
2264                 add_header(&resp, "I", cxident);
2265         /* SC: fill in new fields */
2266         resp.cmd = MGCP_CMD_DLCX;
2267         resp.trid = oseq;
2268         return send_request(p, p->sub, &resp, oseq);
2269 }
2270
2271 /* SC: cleanup pending commands */
2272 static void dump_cmd_queues(struct mgcp_endpoint *p, struct mgcp_subchannel *sub) 
2273 {
2274         struct mgcp_request *t, *q;
2275
2276         if (p) {
2277                 ast_mutex_lock(&p->rqnt_queue_lock);
2278                 for (q = p->rqnt_queue; q; t = q->next, free(q), q=t);
2279                 p->rqnt_queue = NULL;
2280                 ast_mutex_unlock(&p->rqnt_queue_lock);
2281
2282                 ast_mutex_lock(&p->cmd_queue_lock);
2283                 for (q = p->cmd_queue; q; t = q->next, free(q), q=t);
2284                 p->cmd_queue = NULL;
2285                 ast_mutex_unlock(&p->cmd_queue_lock);
2286
2287                 ast_mutex_lock(&p->sub->cx_queue_lock);
2288                 for (q = p->sub->cx_queue; q; t = q->next, free(q), q=t);
2289                 p->sub->cx_queue = NULL;
2290                 ast_mutex_unlock(&p->sub->cx_queue_lock);
2291
2292                 ast_mutex_lock(&p->sub->next->cx_queue_lock);
2293                 for (q = p->sub->next->cx_queue; q; t = q->next, free(q), q=t);
2294                 p->sub->next->cx_queue = NULL;
2295                 ast_mutex_unlock(&p->sub->next->cx_queue_lock);
2296         } else if (sub) {
2297                 ast_mutex_lock(&sub->cx_queue_lock);
2298                 for (q = sub->cx_queue; q; t = q->next, free(q), q=t);
2299                 sub->cx_queue = NULL;
2300                 ast_mutex_unlock(&sub->cx_queue_lock);
2301         }
2302 }
2303
2304
2305 /* SC: remove command transaction from queue */
2306 static struct mgcp_request *find_command(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,
2307                                          struct mgcp_request **queue, ast_mutex_t *l, int ident)
2308 {
2309         struct mgcp_request *prev, *req;
2310         char iabuf[INET_ADDRSTRLEN];
2311
2312         ast_mutex_lock(l);
2313         for (prev = NULL, req = *queue; req; prev = req, req = req->next) {
2314                 if (req->trid == ident) {
2315                         /* remove from queue */
2316                         if (!prev)
2317                                 *queue = req->next;
2318                         else
2319                                 prev->next = req->next;
2320
2321                         /* send next pending command */
2322                         if (*queue) {
2323                                 if (mgcpdebug) {
2324                                         ast_verbose("Posting Queued Request:\n%s to %s:%d\n", (*queue)->data, 
2325                                                 ast_inet_ntoa(iabuf, sizeof(iabuf), p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
2326                                 }
2327
2328                                 mgcp_postrequest(p, sub, (*queue)->data, (*queue)->len, (*queue)->trid);
2329                         }
2330                         break;
2331                 }
2332         }
2333         ast_mutex_unlock(l);
2334         return req;
2335 }
2336
2337 /* SC: modified for new transport mechanism */
2338 static void handle_response(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,  
2339                             int result, unsigned int ident, struct mgcp_request *resp)
2340 {
2341         char *c;
2342         struct mgcp_request *req;
2343         struct mgcp_gateway *gw = p->parent;
2344
2345         if (result < 200) {
2346                 /* provisional response */
2347                 return;
2348         }
2349
2350         if (p->slowsequence) 
2351                 req = find_command(p, sub, &p->cmd_queue, &p->cmd_queue_lock, ident);
2352         else if (sub)
2353                 req = find_command(p, sub, &sub->cx_queue, &sub->cx_queue_lock, ident);
2354         else if (!(req = find_command(p, sub, &p->rqnt_queue, &p->rqnt_queue_lock, ident)))
2355                 req = find_command(p, sub, &p->cmd_queue, &p->cmd_queue_lock, ident);
2356
2357         if (!req) {
2358                 if (option_verbose > 2) {
2359                         ast_verbose(VERBOSE_PREFIX_3 "No command found on [%s] for transaction %d. Ignoring...\n", 
2360                                 gw->name, ident);
2361                 }
2362                 return;
2363         }
2364
2365         if (p && (result >= 400) && (result <= 599)) {
2366                 switch (result) {
2367                 case 401:
2368                         p->hookstate = MGCP_OFFHOOK;
2369                         break;
2370                 case 402:
2371                         p->hookstate = MGCP_ONHOOK;
2372                         break;
2373                 case 406:
2374                         ast_log(LOG_NOTICE, "Transaction %d timed out\n", ident);
2375                         break;
2376                 case 407:
2377                         ast_log(LOG_NOTICE, "Transaction %d aborted\n", ident);
2378                         break;
2379                 }
2380                 if (sub) {
2381                         if (sub->owner) {
2382                                 ast_log(LOG_NOTICE, "Terminating on result %d from %s@%s-%d\n", 
2383                                         result, p->name, p->parent->name, sub ? sub->id:-1);
2384                                 mgcp_queue_hangup(sub);
2385                         }
2386                 } else {
2387                         if (p->sub->next->owner) {
2388                                 ast_log(LOG_NOTICE, "Terminating on result %d from %s@%s-%d\n", 
2389                                         result, p->name, p->parent->name, sub ? sub->id:-1);
2390                                 mgcp_queue_hangup(p->sub);
2391                         }
2392
2393                         if (p->sub->owner) {
2394                                 ast_log(LOG_NOTICE, "Terminating on result %d from %s@%s-%d\n", 
2395                                         result, p->name, p->parent->name, sub ? sub->id:-1);
2396                                 mgcp_queue_hangup(p->sub);
2397                         }
2398
2399                         dump_cmd_queues(p, NULL);
2400                 }
2401         }
2402
2403         if (resp) {
2404                 if (req->cmd == MGCP_CMD_CRCX) {
2405                         if ((c = get_header(resp, "I"))) {
2406                                 if (strlen(c) && sub) {
2407                                         /* SC: if we are hanging up do not process this conn. */
2408                                         if (sub->owner) {
2409                                                 if (strlen(sub->cxident)) {
2410                                                         if (strcasecmp(c, sub->cxident)) {
2411                                                                 ast_log(LOG_WARNING, "Subchannel already has a cxident. sub->cxident: %s requested %s\n", sub->cxident, c);
2412                                                         }
2413                                                 }
2414                                                 strncpy(sub->cxident, c, sizeof(sub->cxident) - 1);
2415                                                 if (sub->tmpdest.sin_addr.s_addr) {
2416                                                         transmit_modify_with_sdp(sub, NULL, 0);
2417                                                 }
2418                                         } else {
2419                                                 /* XXX SC: delete this one
2420                                                    callid and conn id may already be lost. 
2421                                                    so the following del conn may have a side effect of 
2422                                                    cleaning up the next subchannel */
2423                                                 transmit_connection_del(sub);
2424                                         }
2425                                 }
2426                         }
2427                 }
2428
2429                 if (req->cmd == MGCP_CMD_AUEP) {
2430                         /* SC: check stale connection ids */
2431                         if ((c = get_header(resp, "I"))) {
2432                                 char *v, *n;
2433                                 int len;
2434                                 while ((v = get_csv(c, &len, &n))) {
2435                                         if (len) {
2436                                                 if (strncasecmp(v, p->sub->cxident, len) &&
2437                                                     strncasecmp(v, p->sub->next->cxident, len)) {
2438                                                         /* connection id not found. delete it */
2439                                                         char cxident[80];
2440                                                         memcpy(cxident, v, len);
2441                                                         cxident[len] = '\0';
2442                                                         if (option_verbose > 2) {
2443                                                                 ast_verbose(VERBOSE_PREFIX_3 "Non existing connection id %s on %s@%s \n", 
2444                                                                         cxident, p->name, gw->name);
2445                                                         }
2446                                                         transmit_connection_del_w_params(p, NULL, cxident);
2447                                                 }
2448                                         }
2449                                         c = n;
2450                                 }
2451                         }
2452
2453                         /* Try to determine the hookstate returned from an audit endpoint command */
2454                         if ((c = get_header(resp, "ES"))) {
2455                                 if (strlen(c)) {
2456                                         if (strstr(c, "hu")) {
2457                                                 if (p->hookstate != MGCP_ONHOOK) {
2458                                                         /* SC: XXX cleanup if we think we are offhook XXX */
2459                                                         if ((p->sub->owner || p->sub->next->owner ) && 
2460                                                             p->hookstate == MGCP_OFFHOOK)
2461                                                                 mgcp_queue_hangup(sub);
2462                                                         p->hookstate = MGCP_ONHOOK;
2463
2464                                                         /* SC: update the requested events according to the new hookstate */
2465                                                         transmit_notify_request(p->sub, "");
2466
2467                                                         /* SC: verbose level check */
2468                                                         if (option_verbose > 2) {
2469                                                                 ast_verbose(VERBOSE_PREFIX_3 "Setting hookstate of %s@%s to ONHOOK\n", p->name, gw->name);
2470                                                         }
2471                                                 }
2472                                         } else if (strstr(c, "hd")) {
2473                                                 if (p->hookstate != MGCP_OFFHOOK) {
2474                                                         p->hookstate = MGCP_OFFHOOK;
2475
2476                                                         /* SC: update the requested events according to the new hookstate */
2477                                                         transmit_notify_request(p->sub, "");
2478
2479                                                         /* SC: verbose level check */
2480                                                         if (option_verbose > 2) {
2481                                                                 ast_verbose(VERBOSE_PREFIX_3 "Setting hookstate of %s@%s to OFFHOOK\n", p->name, gw->name);
2482                                                         }
2483                                                 }
2484                                         }
2485                                 }
2486                         }
2487                 }
2488
2489                 if (resp && resp->lines) {
2490                         /* SC: do not process sdp if we are hanging up. this may be a late response */
2491                         if (sub && sub->owner) {
2492                                 if (!sub->rtp)
2493                                         start_rtp(sub);
2494                                 if (sub->rtp)
2495                                         process_sdp(sub, resp);
2496                         }
2497                 }
2498         }
2499
2500         free(req);
2501 }
2502
2503 static void start_rtp(struct mgcp_subchannel *sub)
2504 {
2505         ast_mutex_lock(&sub->lock);
2506         /* SC: check again to be on the safe side */
2507         if (sub->rtp) {
2508                 ast_rtp_destroy(sub->rtp);
2509                 sub->rtp = NULL;
2510         }
2511         /* Allocate the RTP now */
2512         sub->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
2513         if (sub->rtp && sub->owner)
2514                 sub->owner->fds[0] = ast_rtp_fd(sub->rtp);
2515         if (sub->rtp)
2516                 ast_rtp_setnat(sub->rtp, sub->nat);
2517 #if 0
2518         ast_rtp_set_callback(p->rtp, rtpready);
2519         ast_rtp_set_data(p->rtp, p);
2520 #endif          
2521         /* Make a call*ID */
2522         snprintf(sub->callid, sizeof(sub->callid), "%08x%s", rand(), sub->txident);
2523         /* Transmit the connection create */
2524         transmit_connect_with_sdp(sub, NULL);
2525         ast_mutex_unlock(&sub->lock);
2526 }
2527
2528 static void *mgcp_ss(void *data)
2529 {
2530         struct ast_channel *chan = data;
2531         struct mgcp_subchannel *sub = chan->pvt->pvt;
2532         struct mgcp_endpoint *p = sub->parent;
2533         char exten[AST_MAX_EXTENSION] = "";
2534         int len = 0;
2535         int timeout = firstdigittimeout;
2536         int res;
2537         int getforward = 0;
2538
2539         while(len < AST_MAX_EXTENSION-1) {
2540                 res = ast_waitfordigit(chan, timeout);
2541                 timeout = 0;
2542                 if (res < 0) {
2543                         ast_log(LOG_DEBUG, "waitfordigit returned < 0...\n");
2544                         /*res = tone_zone_play_tone(p->subs[index].zfd, -1);*/
2545                         ast_indicate(chan, -1);
2546                         ast_hangup(chan);
2547                         return NULL;
2548                 } else if (res) {
2549                         exten[len++]=res;
2550                         exten[len] = '\0';
2551                 }
2552                 if (!ast_ignore_pattern(chan->context, exten)) {
2553                         /*res = tone_zone_play_tone(p->subs[index].zfd, -1);*/
2554                         ast_indicate(chan, -1);
2555                 } else {
2556                         /* XXX Redundant?  We should already be playing dialtone */
2557                         /*tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALTONE);*/
2558                         transmit_notify_request(sub, "L/dl");
2559                 }
2560                 if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num)) {
2561                         if (!res || !ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
2562                                 if (getforward) {
2563                                         /* Record this as the forwarding extension */
2564                                         strncpy(p->call_forward, exten, sizeof(p->call_forward) - 1); 
2565                                         if (option_verbose > 2) {
2566                                                 ast_verbose(VERBOSE_PREFIX_3 "Setting call forward to '%s' on channel %s\n", 
2567                                                         p->call_forward, chan->name);
2568                                         }
2569                                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2570                                         transmit_notify_request(sub, "L/sl");
2571                                         if (res)
2572                                                 break;
2573                                         usleep(500000);
2574                                         /*res = tone_zone_play_tone(p->subs[index].zfd, -1);*/
2575                                         ast_indicate(chan, -1);
2576                                         sleep(1);
2577                                         memset(exten, 0, sizeof(exten));
2578                                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALTONE);*/
2579                                         transmit_notify_request(sub, "L/dl");
2580                                         len = 0;
2581                                         getforward = 0;
2582                                 } else {
2583                                         /*res = tone_zone_play_tone(p->subs[index].zfd, -1);*/
2584                                         ast_indicate(chan, -1);
2585                                         strncpy(chan->exten, exten, sizeof(chan->exten)-1);
2586                                         if (!ast_strlen_zero(p->cid_num)) {
2587                                                 if (!p->hidecallerid) {
2588                                                         /* SC: free existing chan->callerid */
2589                                                         if (chan->cid.cid_num)
2590                                                                 free(chan->cid.cid_num);
2591                                                         chan->cid.cid_num = strdup(p->cid_num);
2592                                                         /* SC: free existing chan->callerid */
2593                                                         if (chan->cid.cid_name)
2594                                                                 free(chan->cid.cid_name);
2595                                                         chan->cid.cid_name = strdup(p->cid_name);
2596                                                 }
2597                                                 if (chan->cid.cid_ani)
2598                                                         free(chan->cid.cid_ani);
2599                                                 chan->cid.cid_ani = strdup(p->cid_num);
2600                                         }
2601                                         ast_setstate(chan, AST_STATE_RING);
2602                                         /*zt_enable_ec(p);*/
2603                                         res = ast_pbx_run(chan);
2604                                         if (res) {
2605                                                 ast_log(LOG_WARNING, "PBX exited non-zero\n");
2606                                                 /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);*/
2607                                                 /*transmit_notify_request(p, "nbz", 1);*/
2608                                                 transmit_notify_request(sub, "G/cg");
2609                                         }
2610                                         return NULL;
2611                                 }
2612                         } else {
2613                                 /* It's a match, but they just typed a digit, and there is an ambiguous match,
2614                                    so just set the timeout to matchdigittimeout and wait some more */
2615                                 timeout = matchdigittimeout;
2616                         }
2617                 } else if (res == 0) {
2618                         ast_log(LOG_DEBUG, "not enough digits (and no ambiguous match)...\n");
2619                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);*/
2620                         transmit_notify_request(sub, "G/cg");
2621                         /*zt_wait_event(p->subs[index].zfd);*/
2622                         ast_hangup(chan);
2623                         return NULL;
2624                 } else if (p->callwaiting && !strcmp(exten, "*70")) {
2625                         if (option_verbose > 2) {
2626                                 ast_verbose(VERBOSE_PREFIX_3 "Disabling call waiting on %s\n", chan->name);
2627                         }
2628                         /* Disable call waiting if enabled */
2629                         p->callwaiting = 0;
2630                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2631                         transmit_notify_request(sub, "L/sl");
2632                         len = 0;
2633                         memset(exten, 0, sizeof(exten));
2634                         timeout = firstdigittimeout;
2635                 } else if (!strcmp(exten,ast_pickup_ext())) {
2636                         /* Scan all channels and see if any there
2637                          * ringing channqels with that have call groups
2638                          * that equal this channels pickup group  
2639                          */
2640                         if (ast_pickup_call(chan)) {
2641                                 ast_log(LOG_WARNING, "No call pickup possible...\n");
2642                                 /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);*/
2643                                 transmit_notify_request(sub, "G/cg");
2644                         }
2645                         ast_hangup(chan);
2646                         return NULL;
2647                 } else if (!p->hidecallerid && !strcmp(exten, "*67")) {
2648                         if (option_verbose > 2) {
2649                                 ast_verbose(VERBOSE_PREFIX_3 "Disabling Caller*ID on %s\n", chan->name);
2650                         }
2651                         /* Disable Caller*ID if enabled */
2652                         p->hidecallerid = 1;
2653                         if (chan->cid.cid_num)
2654                                 free(chan->cid.cid_num);
2655                         chan->cid.cid_num = NULL;
2656                         if (chan->cid.cid_name)
2657                                 free(chan->cid.cid_name);
2658                         chan->cid.cid_name = NULL;
2659                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2660                         transmit_notify_request(sub, "L/sl");
2661                         len = 0;
2662                         memset(exten, 0, sizeof(exten));
2663                         timeout = firstdigittimeout;
2664                 } else if (p->callreturn && !strcmp(exten, "*69")) {
2665                         res = 0;
2666                         if (strlen(p->lastcallerid)) {
2667                                 res = ast_say_digit_str(chan, p->lastcallerid, "", chan->language);
2668                         }
2669                         if (!res)
2670                                 /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2671                                 transmit_notify_request(sub, "L/sl");
2672                         break;
2673                 } else if (!strcmp(exten, "*78")) {
2674                         /* Do not disturb */
2675                         if (option_verbose > 2) {
2676                                 ast_verbose(VERBOSE_PREFIX_3 "Enabled DND on channel %s\n", chan->name);
2677                         }
2678                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2679                         transmit_notify_request(sub, "L/sl");
2680                         p->dnd = 1;
2681                         getforward = 0;
2682                         memset(exten, 0, sizeof(exten));
2683                         len = 0;
2684                 } else if (!strcmp(exten, "*79")) {
2685                         /* Do not disturb */
2686                         if (option_verbose > 2) {
2687                                 ast_verbose(VERBOSE_PREFIX_3 "Disabled DND on channel %s\n", chan->name);
2688                         }
2689                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2690                         transmit_notify_request(sub, "L/sl");
2691                         p->dnd = 0;
2692                         getforward = 0;
2693                         memset(exten, 0, sizeof(exten));
2694                         len = 0;
2695                 } else if (p->cancallforward && !strcmp(exten, "*72")) {
2696                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2697                         transmit_notify_request(sub, "L/sl");
2698                         getforward = 1;
2699                         memset(exten, 0, sizeof(exten));
2700                         len = 0;
2701                 } else if (p->cancallforward && !strcmp(exten, "*73")) {
2702                         if (option_verbose > 2) {
2703                                 ast_verbose(VERBOSE_PREFIX_3 "Cancelling call forwarding on channel %s\n", chan->name);
2704                         }
2705                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2706                         transmit_notify_request(sub, "L/sl");
2707                         memset(p->call_forward, 0, sizeof(p->call_forward));
2708                         getforward = 0;
2709                         memset(exten, 0, sizeof(exten));
2710                         len = 0;
2711                 } else if (!strcmp(exten, ast_parking_ext()) && 
2712                         sub->next->owner && ast_bridged_channel(sub->next->owner)) {
2713                         /* This is a three way call, the main call being a real channel, 
2714                            and we're parking the first call. */
2715                         ast_masq_park_call(ast_bridged_channel(sub->next->owner), chan, 0, NULL);
2716                         if (option_verbose > 2) {
2717                                 ast_verbose(VERBOSE_PREFIX_3 "Parking call to '%s'\n", chan->name);
2718                         }
2719                         break;
2720                 } else if (strlen(p->lastcallerid) && !strcmp(exten, "*60")) {
2721                         if (option_verbose > 2) {
2722                                 ast_verbose(VERBOSE_PREFIX_3 "Blacklisting number %s\n", p->lastcallerid);
2723                         }
2724                         res = ast_db_put("blacklist", p->lastcallerid, "1");
2725                         if (!res) {
2726                                 /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2727                                 transmit_notify_request(sub, "L/sl");
2728                                 memset(exten, 0, sizeof(exten));
2729                                 len = 0;
2730                         }
2731                 } else if (p->hidecallerid && !strcmp(exten, "*82")) {
2732                         if (option_verbose > 2) {
2733                                 ast_verbose(VERBOSE_PREFIX_3 "Enabling Caller*ID on %s\n", chan->name);
2734                         }
2735                         /* Enable Caller*ID if enabled */
2736                         p->hidecallerid = 0;
2737                         if (chan->cid.cid_num)
2738                                 free(chan->cid.cid_num);
2739                         if (!ast_strlen_zero(p->cid_num))
2740                                 chan->cid.cid_num = strdup(p->cid_num);
2741                         if (chan->cid.cid_name)
2742                                 free(chan->cid.cid_name);
2743                         if (!ast_strlen_zero(p->cid_name))
2744                                 chan->cid.cid_name = strdup(p->cid_name);
2745                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2746                         transmit_notify_request(sub, "L/sl");
2747                         len = 0;
2748                         memset(exten, 0, sizeof(exten));
2749                         timeout = firstdigittimeout;
2750                 } else if (!ast_canmatch_extension(chan, chan->context, exten, 1, chan->cid.cid_num) &&
2751                                 ((exten[0] != '*') || (strlen(exten) > 2))) {
2752                         if (option_debug)
2753                                 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);
2754                         break;
2755                 }
2756                 if (!timeout)
2757                         timeout = gendigittimeout;
2758                 if (len && !ast_ignore_pattern(chan->context, exten))
2759                         /*tone_zone_play_tone(p->subs[index].zfd, -1);*/
2760                         ast_indicate(chan, -1);
2761         }
2762 #if 0
2763         for (;;) {
2764                 res = ast_waitfordigit(chan, to);
2765                 if (!res) {
2766                         ast_log(LOG_DEBUG, "Timeout...\n");
2767                         break;
2768                 }
2769                 if (res < 0) {
2770                         ast_log(LOG_DEBUG, "Got hangup...\n");
2771                         ast_hangup(chan);
2772                         break;
2773                 }
2774                 exten[pos++] = res;
2775                 if (!ast_ignore_pattern(chan->context, exten))
2776                         ast_indicate(chan, -1);
2777                 if (ast_matchmore_extension(chan, chan->context, exten, 1, chan->callerid)) {
2778                         if (ast_exists_extension(chan, chan->context, exten, 1, chan->callerid)) 
2779                                 to = 3000;
2780                         else
2781                                 to = 8000;
2782                 } else
2783                         break;
2784         }
2785         if (ast_exists_extension(chan, chan->context, exten, 1, chan->callerid)) {
2786                 strncpy(chan->exten, exten, sizeof(chan->exten) - 1);
2787                 if (!p->rtp) {
2788                         start_rtp(p);
2789                 }
2790                 ast_setstate(chan, AST_STATE_RING);
2791                 chan->rings = 1;
2792                 if (ast_pbx_run(chan)) {
2793                         ast_log(LOG_WARNING, "Unable to launch PBX on %s\n", chan->name);
2794                 } else
2795                         return NULL;
2796         }
2797 #endif
2798         ast_hangup(chan);
2799         return NULL;
2800 }
2801
2802 static int attempt_transfer(struct mgcp_endpoint *p)
2803 {
2804         /* *************************
2805          * I hope this works.
2806          * Copied out of chan_zap
2807          * Cross your fingers
2808          * *************************/
2809
2810         /* In order to transfer, we need at least one of the channels to
2811            actually be in a call bridge.  We can't conference two applications
2812            together (but then, why would we want to?) */
2813         if (ast_bridged_channel(p->sub->owner)) {
2814                 /* The three-way person we're about to transfer to could still be in MOH, so
2815                    stop if now if appropriate */
2816                 if (ast_bridged_channel(p->sub->next->owner))
2817                         ast_moh_stop(ast_bridged_channel(p->sub->next->owner));
2818                 if (p->sub->owner->_state == AST_STATE_RINGING) {
2819                         ast_indicate(ast_bridged_channel(p->sub->next->owner), AST_CONTROL_RINGING);
2820                 }
2821                 if (ast_channel_masquerade(p->sub->next->owner, ast_bridged_channel(p->sub->owner))) {
2822                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
2823                                 ast_bridged_channel(p->sub->owner)->name, p->sub->next->owner->name);
2824                         return -1;
2825                 }
2826                 /* Orphan the channel */
2827                 unalloc_sub(p->sub->next);
2828         } else if (ast_bridged_channel(p->sub->next->owner)) {
2829                 if (p->sub->owner->_state == AST_STATE_RINGING) {
2830                         ast_indicate(ast_bridged_channel(p->sub->next->owner), AST_CONTROL_RINGING);
2831                 }
2832                 ast_moh_stop(ast_bridged_channel(p->sub->next->owner));
2833                 if (ast_channel_masquerade(p->sub->owner, ast_bridged_channel(p->sub->next->owner))) {
2834                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
2835                                 ast_bridged_channel(p->sub->next->owner)->name, p->sub->owner->name);
2836                         return -1;
2837                 }
2838                 /*swap_subs(p, SUB_THREEWAY, SUB_REAL);*/
2839                 if (option_verbose > 2) {
2840                         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);
2841                 }
2842                 p->sub = p->sub->next;
2843                 unalloc_sub(p->sub->next);
2844                 /* Tell the caller not to hangup */
2845                 return 1;
2846         } else {
2847                 ast_log(LOG_DEBUG, "Neither %s nor %s are in a bridge, nothing to transfer\n",
2848                         p->sub->owner->name, p->sub->next->owner->name);
2849                 p->sub->next->owner->_softhangup |= AST_SOFTHANGUP_DEV;
2850                 if (p->sub->next->owner) {
2851                         p->sub->next->alreadygone = 1;
2852                         mgcp_queue_hangup(p->sub->next);
2853                 }
2854         }
2855         return 0;
2856 }
2857
2858 static void handle_hd_hf(struct mgcp_subchannel *sub, char *ev) 
2859 {
2860         struct mgcp_endpoint *p = sub->parent;
2861         struct ast_channel *c;
2862         pthread_t t;
2863         pthread_attr_t attr;
2864         pthread_attr_init(&attr);
2865         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);    
2866
2867         /* Off hook / answer */
2868         if (sub->outgoing) {
2869                 /* Answered */
2870                 if (sub->owner) {
2871                         if (ast_bridged_channel(sub->owner)) {
2872                                 ast_moh_stop(ast_bridged_channel(sub->owner));
2873                         }
2874                         sub->cxmode = MGCP_CX_SENDRECV;
2875                         if (!sub->rtp) {
2876                                 start_rtp(sub);
2877                         } else {
2878                                 transmit_modify_request(sub);
2879                         }
2880                         /*transmit_notify_request(sub, "aw");*/
2881                         transmit_notify_request(sub, "");
2882                         mgcp_queue_control(sub, AST_CONTROL_ANSWER);
2883                 }
2884         } else {
2885                 /* Start switch */
2886                 /*sub->cxmode = MGCP_CX_SENDRECV;*/
2887                 if (!sub->owner) {
2888                         if (!sub->rtp) {
2889                                 start_rtp(sub);
2890                         } else {
2891                                 transmit_modify_request(sub);
2892                         }
2893                         if (p->immediate) {
2894                                 /* The channel is immediately up. Start right away */
2895 #ifdef DLINK_BUGGY_FIRMWARE     
2896                                 transmit_notify_request(sub, "rt");
2897 #else
2898                                 transmit_notify_request(sub, "G/rt");
2899 #endif          
2900                                 c = mgcp_new(sub, AST_STATE_RING);
2901                                 if (!c) {
2902                                         ast_log(LOG_WARNING, "Unable to start PBX on channel %s@%s\n", p->name, p->parent->name);
2903                                         transmit_notify_request(sub, "G/cg");
2904                                         ast_hangup(c);
2905                                 }
2906                         } else {
2907                                 if (has_voicemail(p)) {
2908                                         transmit_notify_request(sub, "L/sl");
2909                                 } else {
2910                                         transmit_notify_request(sub, "L/dl");
2911                                 }
2912                                 c = mgcp_new(sub, AST_STATE_DOWN);
2913                                 if (c) {
2914                                         if (ast_pthread_create(&t, &attr, mgcp_ss, c)) {
2915                                                 ast_log(LOG_WARNING, "Unable to create switch thread: %s\n", strerror(errno));
2916                                                 ast_hangup(c);
2917                                         }
2918                                 } else {
2919                                         ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", p->name, p->parent->name);
2920                                 }
2921                         }
2922                 } else {
2923                         if (p->hookstate == MGCP_OFFHOOK) {
2924                                 ast_log(LOG_WARNING, "Off hook, but already have owner on %s@%s\n", p->name, p->parent->name);
2925                         } else {
2926                                 ast_log(LOG_WARNING, "On hook, but already have owner on %s@%s\n", p->name, p->parent->name);
2927                                 ast_log(LOG_WARNING, "If we're onhook why are we here trying to handle a hd or hf?");
2928                         }
2929                         if (ast_bridged_channel(sub->owner)) {
2930                                 ast_moh_stop(ast_bridged_channel(sub->owner));
2931                         }
2932                         sub->cxmode = MGCP_CX_SENDRECV;
2933                         if (!sub->rtp) {
2934                                 start_rtp(sub);
2935                         } else {
2936                                 transmit_modify_request(sub);
2937                         }
2938                         /*transmit_notify_request(sub, "aw");*/
2939                         transmit_notify_request(sub, "");
2940                         /*ast_queue_control(sub->owner, AST_CONTROL_ANSWER);*/
2941                 }
2942         }
2943 }
2944
2945 static int handle_request(struct mgcp_subchannel *sub, struct mgcp_request *req, struct sockaddr_in *sin)
2946 {
2947         char *ev, *s;
2948         struct ast_frame f = { 0, };
2949         struct mgcp_endpoint *p = sub->parent;
2950         struct mgcp_gateway *g = NULL;
2951         char iabuf[INET_ADDRSTRLEN];
2952         int res;
2953
2954         if (mgcpdebug) {
2955                 ast_verbose("Handling request '%s' on %s@%s\n", req->verb, p->name, p->parent->name);
2956         }
2957         /* Clear out potential response */
2958         if (!strcasecmp(req->verb, "RSIP")) {
2959                 /* Test if this RSIP request is just a keepalive */
2960                 if(!strcasecmp( get_header(req, "RM"), "X-keepalive")) {
2961                         if (option_verbose > 2)
2962                                 ast_verbose(VERBOSE_PREFIX_3 "Received keepalive request from %s@%s\n", p->name, p->parent->name);
2963                         transmit_response(sub, "200", req, "OK");
2964                 } else {
2965                         dump_queue(p->parent, p);
2966                         dump_cmd_queues(p, NULL);
2967                         
2968                         if (option_verbose > 2 && (strcmp(p->name, p->parent->wcardep) != 0)) {
2969                                 ast_verbose(VERBOSE_PREFIX_3 "Resetting interface %s@%s\n", p->name, p->parent->name);
2970                         }
2971                         /* JS: For RSIP on wildcard we reset all endpoints */
2972                         if (!strcmp(p->name, p->parent->wcardep)) {
2973                                 /* Reset all endpoints */
2974                                 struct mgcp_endpoint *tmp_ep;
2975                                 
2976                                 g = p->parent;
2977                                 tmp_ep = g->endpoints;
2978                                 while (tmp_ep) {
2979                                         /*if ((strcmp(tmp_ep->name, "*") != 0) && (strcmp(tmp_ep->name, "aaln/" "*") != 0)) {*/
2980                                         if (strcmp(tmp_ep->name, g->wcardep) != 0) {
2981                                                 struct mgcp_subchannel *tmp_sub, *first_sub;
2982                                                 if (option_verbose > 2) {
2983                                                         ast_verbose(VERBOSE_PREFIX_3 "Resetting interface %s@%s\n", tmp_ep->name, p->parent->name);
2984                                                 }
2985                                                 
2986                                                 first_sub = tmp_ep->sub;
2987                                                 tmp_sub = tmp_ep->sub;
2988                                                 while (tmp_sub) {
2989                                                         mgcp_queue_hangup(tmp_sub);
2990                                                         tmp_sub = tmp_sub->next;
2991                                                         if (tmp_sub == first_sub)
2992                                                                 break;
2993                                                 }
2994                                         }
2995                                         tmp_ep = tmp_ep->next;
2996                                 }
2997                         } else if (sub->owner) {
2998                                 mgcp_queue_hangup(sub);
2999                         }
3000                         transmit_response(sub, "200", req, "OK");
3001                         /* JS: We dont send NTFY or AUEP to wildcard ep */
3002                         if (strcmp(p->name, p->parent->wcardep) != 0) {
3003                                 transmit_notify_request(sub, "");
3004                                 /* SC: Audit endpoint. 
3005                                  Idea is to prevent lost lines due to race conditions 
3006                                 */
3007                                 transmit_audit_endpoint(p);
3008                         }
3009                 }
3010         } else if (!strcasecmp(req->verb, "NTFY")) {
3011                 /* Acknowledge and be sure we keep looking for the same things */
3012                 transmit_response(sub, "200", req, "OK");
3013                 /* Notified of an event */
3014                 ev = get_header(req, "O");
3015                 s = strchr(ev, '/');
3016                 if (s) ev = s + 1;
3017                 if (option_verbose > 2) {
3018                         ast_verbose(VERBOSE_PREFIX_3 "Endpoint '%s@%s-%d' observed '%s'\n", p->name, p->parent->name, sub->id, ev);
3019                 }
3020                 /* Keep looking for events unless this was a hangup */
3021                 if (strcasecmp(ev, "hu") && strcasecmp(ev, "hd") && strcasecmp(ev, "ping")) {
3022                         transmit_notify_request(sub, p->curtone);
3023                 }
3024                 if (!strcasecmp(ev, "hd")) {
3025                         p->hookstate = MGCP_OFFHOOK;
3026                         sub->cxmode = MGCP_CX_SENDRECV;
3027                         handle_hd_hf(sub, ev);
3028                 } else if (!strcasecmp(ev, "hf")) {
3029                         /* We can assume we are offhook if we received a hookflash */
3030                         /* First let's just do call wait and ignore threeway */
3031                         /* We're currently in charge */
3032                         if (p->hookstate != MGCP_OFFHOOK) {
3033                                 /* Cisco c7940 sends hf even if the phone is onhook */
3034                                 /* Thanks to point on IRC for pointing this out */
3035                                 return -1;
3036                         }
3037                         /* do not let * conference two down channels */  
3038                         if (sub->owner && sub->owner->_state == AST_STATE_DOWN && !sub->next->owner)
3039                                 return -1;
3040
3041                         if (p->callwaiting || p->transfer || p->threewaycalling) {
3042                                 if (option_verbose > 2) {
3043                                         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);
3044                                 }
3045                                 p->sub = p->sub->next;
3046
3047                                 /* transfer control to our next subchannel */
3048                                 if (!sub->next->owner) {
3049                                         /* plave the first call on hold and start up a new call */
3050                                         sub->cxmode = MGCP_CX_MUTE;
3051                                         if (option_verbose > 2) {
3052                                                 ast_verbose(VERBOSE_PREFIX_3 "MGCP Muting %d on %s@%s\n", sub->id, p->name, p->parent->name);
3053                                         }
3054                                         transmit_modify_request(sub);
3055                                         if (sub->owner && ast_bridged_channel(sub->owner)) {
3056                                                 ast_moh_start(ast_bridged_channel(sub->owner), NULL);
3057                                         }
3058                                         sub->next->cxmode = MGCP_CX_RECVONLY;
3059                                         handle_hd_hf(sub->next, ev);
3060                                 } else if (sub->owner && sub->next->owner) {
3061                                         /* We've got two active calls lets decide whether or not to conference or just flip flop */
3062                                         if ((!sub->outgoing) && (!sub->next->outgoing)) {
3063                                                 /* We made both calls lets conferenct */
3064                                                 if (option_verbose > 2) {
3065                                                         ast_verbose(VERBOSE_PREFIX_3 "MGCP Conferencing %d and %d on %s@%s\n", 
3066                                                                 sub->id, sub->next->id, p->name, p->parent->name);
3067                                                 }
3068                                                 sub->cxmode = MGCP_CX_CONF;
3069                                                 sub->next->cxmode = MGCP_CX_CONF;
3070                                                 if (ast_bridged_channel(sub->next->owner)) 
3071                                                         ast_moh_stop(ast_bridged_channel(sub->next->owner));
3072                                                 transmit_modify_request(sub);
3073                                                 transmit_modify_request(sub->next);
3074                                         } else {
3075                                                 /* Let's flipflop between calls */
3076                                                 /* XXX Need to check for state up ??? */
3077                                                 /* XXX Need a way to indicate the current call, or maybe the call that's waiting */
3078                                                 if (option_verbose > 2) {
3079                                                         ast_verbose(VERBOSE_PREFIX_3 "We didn't make one of the calls FLIPFLOP %d and %d on %s@%s\n", 
3080                                                                 sub->id, sub->next->id, p->name, p->parent->name);
3081                                                 }
3082                                                 sub->cxmode = MGCP_CX_MUTE;
3083                                                 if (option_verbose > 2) {
3084                                                         ast_verbose(VERBOSE_PREFIX_3 "MGCP Muting %d on %s@%s\n", sub->id, p->name, p->parent->name);
3085                                                 }
3086                                                 transmit_modify_request(sub);
3087                                                 if (ast_bridged_channel(sub->owner)) 
3088                                                         ast_moh_start(ast_bridged_channel(sub->owner), NULL);
3089                         
3090                                                 if (ast_bridged_channel(sub->next->owner)) 
3091                                                         ast_moh_stop(ast_bridged_channel(sub->next->owner));
3092                         
3093                                                 handle_hd_hf(sub->next, ev);
3094 #if 0
3095                                                 if (sub->next->owner && (sub->next->owner->_state != AST_STATE_UP)) {
3096                                                         handle_hd_hf(sub->next, ev);
3097                                                 } else {
3098                                                         ast_verbose(VERBOSE_PREFIX_3 "MGCP Unmuting %d on %s@%s\n", sub->next->id, p->name, p->parent->name);
3099                                                         sub->next->cxmode = MGCP_CX_SENDRECV;
3100                                                         transmit_modify_request(sub->next);
3101                                                 }
3102 #endif
3103                                         }
3104                                 } else {
3105                                         /* We've most likely lost one of our calls find an active call and bring it up */
3106                                         if (sub->owner) {
3107                                                 p->sub = sub;
3108                                         } else if (sub->next->owner) {
3109                                                 p->sub = sub->next;
3110                                         } else {
3111                                                 /* We seem to have lost both our calls */
3112                                                 /* XXX - What do we do now? */
3113                                                 return -1;
3114                                         }
3115                                         if (ast_bridged_channel(p->sub->owner)) {
3116                                                 ast_moh_stop(ast_bridged_channel(p->sub->owner));
3117                                         }
3118                                         p->sub->cxmode = MGCP_CX_SENDRECV;
3119                                         transmit_modify_request(p->sub);
3120                                 }
3121                         } else {
3122                                 ast_log(LOG_WARNING, "Callwaiting, call transfer or threeway calling not enabled on endpoint %s@%s\n", 
3123                                         p->name, p->parent->name);
3124                         }
3125                         /*ast_moh_stop(sub->owner->bridge);*/
3126                 } else if (!strcasecmp(ev, "hu")) {
3127                         p->hookstate = MGCP_ONHOOK;
3128                         sub->cxmode = MGCP_CX_RECVONLY;
3129                         ast_log(LOG_DEBUG, "MGCP %s@%s Went on hook\n", p->name, p->parent->name);
3130                         /* JS: Do we need to send MDCX before a DLCX ?
3131                         if (sub->rtp) {
3132                                 transmit_modify_request(sub);
3133                         }
3134                         */
3135                         if (p->transfer && (sub->owner && sub->next->owner) && ((!sub->outgoing) || (!sub->next->outgoing))) {
3136                                 /* We're allowed to transfer, we have two avtive calls and */
3137                                 /* we made at least one of the calls.  Let's try and transfer */
3138                                 ast_mutex_lock(&p->sub->next->lock);
3139                                 res = attempt_transfer(p);
3140                                 if (res < 0) {
3141                                         if (p->sub->next->owner) {
3142                                                 sub->next->alreadygone = 1;
3143                                                 mgcp_queue_hangup(sub->next);
3144                                         }
3145                                 } else if (res) {
3146                                         ast_log(LOG_WARNING, "Transfer attempt failed\n");
3147                                         ast_mutex_unlock(&p->sub->next->lock);
3148                                         return -1;
3149                                 }
3150                                 ast_mutex_unlock(&p->sub->next->lock);
3151                         } else {
3152                                 /* Hangup the current call */
3153                                 /* If there is another active call, mgcp_hangup will ring the phone with the other call */
3154                                 if (sub->owner) {
3155                                         sub->alreadygone = 1;
3156                                         mgcp_queue_hangup(sub);
3157                                 } else {
3158                                         /* SC: verbose level check */
3159                                         if (option_verbose > 2) {
3160                                                 ast_verbose(VERBOSE_PREFIX_3 "MGCP handle_request(%s@%s-%d) ast_channel already destroyed, resending DLCX.\n",
3161                                                         p->name, p->parent->name, sub->id);
3162                                         }
3163                                         /* Instruct the other side to remove the connection since it apparently *
3164                                          * still thinks the channel is active. *
3165                                          * For Cisco IAD2421 /BAK/ */
3166                                         transmit_connection_del(sub);
3167                                 }
3168                         }
3169                         if ((p->hookstate == MGCP_ONHOOK) && (!sub->rtp) && (!sub->next->rtp)) {
3170                                 if (has_voicemail(p)) {
3171                                         if (option_verbose > 2) {
3172                                                 ast_verbose(VERBOSE_PREFIX_3 "MGCP handle_request(%s@%s) set vmwi(+)\n", p->name, p->parent->name);
3173                                         }
3174                                         transmit_notify_request(sub, "L/vmwi(+)");
3175                                 } else {
3176                                         if (option_verbose > 2) {
3177                                                 ast_verbose(VERBOSE_PREFIX_3 "MGCP handle_request(%s@%s) set vmwi(-)\n", p->name, p->parent->name);
3178                                         }
3179                                         transmit_notify_request(sub, "L/vmwi(-)");
3180                                 }
3181                         }
3182                 } else if ((strlen(ev) == 1) && 
3183                                 (((ev[0] >= '0') && (ev[0] <= '9')) ||
3184                                  ((ev[0] >= 'A') && (ev[0] <= 'D')) ||
3185                                   (ev[0] == '*') || (ev[0] == '#'))) {
3186                         f.frametype = AST_FRAME_DTMF;
3187                         f.subclass = ev[0];
3188                         f.src = "mgcp";
3189                         if (sub->owner) {
3190                                 /* XXX MUST queue this frame to all subs in threeway call if threeway call is active */
3191                                 mgcp_queue_frame(sub, &f);
3192                                 ast_mutex_lock(&sub->next->lock);
3193                                 if (sub->next->owner) {
3194                                         mgcp_queue_frame(sub->next, &f);
3195                                 }
3196                                 ast_mutex_unlock(&sub->next->lock);
3197                         }
3198                         if (strstr(p->curtone, "wt") && (ev[0] == 'A')) {
3199                                 memset(p->curtone, 0, sizeof(p->curtone));
3200                         }
3201                 } else if (!strcasecmp(ev, "T")) {
3202                         /* Digit timeout -- unimportant */
3203                 } else if (!strcasecmp(ev, "ping")) {
3204                         /* ping -- unimportant */
3205                 } else {
3206                         ast_log(LOG_NOTICE, "Received unknown event '%s' from %s@%s\n", ev, p->name, p->parent->name);
3207                 }
3208         } else {
3209                 ast_log(LOG_WARNING, "Unknown verb '%s' received from %s\n", req->verb, ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
3210                 transmit_response(sub, "510", req, "Unknown verb");
3211         }
3212         return 0;
3213 }
3214
3215 static int find_and_retrans(struct mgcp_subchannel *sub, struct mgcp_request *req)
3216 {
3217         int seqno=0;
3218         time_t now;
3219         struct mgcp_response *prev = NULL, *cur, *next, *answer=NULL;
3220         time(&now);
3221         if (sscanf(req->identifier, "%d", &seqno) != 1) 
3222                 seqno = 0;
3223         cur = sub->parent->parent->responses;
3224         while(cur) {
3225                 next = cur->next;
3226                 if (now - cur->whensent > RESPONSE_TIMEOUT) {
3227                         /* Delete this entry */
3228                         if (prev)
3229                                 prev->next = next;
3230                         else
3231                                 sub->parent->parent->responses = next;
3232                         free(cur);
3233                 } else {
3234                         if (seqno == cur->seqno)
3235                                 answer = cur;
3236                         prev = cur;
3237                 }
3238                 cur = next;
3239         }
3240         if (answer) {
3241                 resend_response(sub, answer);
3242                 return 1;
3243         }
3244         return 0;
3245 }
3246
3247 static int mgcpsock_read(int *id, int fd, short events, void *ignore)
3248 {
3249         struct mgcp_request req;
3250         struct sockaddr_in sin;
3251         struct mgcp_subchannel *sub;
3252         int res;
3253         int len;
3254         int result;
3255         int ident;
3256         char iabuf[INET_ADDRSTRLEN];
3257         len = sizeof(sin);
3258         memset(&req, 0, sizeof(req));
3259         res = recvfrom(mgcpsock, req.data, sizeof(req.data) - 1, 0, (struct sockaddr *)&sin, &len);
3260         if (res < 0) {
3261                 if (errno != ECONNREFUSED)
3262                         ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
3263                 return 1;
3264         }
3265         req.data[res] = '\0';
3266         req.len = res;
3267         if (mgcpdebug) {
3268                 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));
3269         }
3270         parse(&req);
3271         if (req.headers < 1) {
3272                 /* Must have at least one header */
3273                 return 1;
3274         }
3275         if (!req.identifier || !strlen(req.identifier)) {
3276                 ast_log(LOG_NOTICE, "Message from %s missing identifier\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr));
3277                 return 1;
3278         }
3279
3280         if (sscanf(req.verb, "%d", &result) && sscanf(req.identifier, "%d", &ident)) {
3281                 /* Try to find who this message is for, if it's important */
3282                 sub = find_subchannel_and_lock(NULL, ident, &sin);
3283                 if (sub) {
3284                         struct mgcp_gateway *gw = sub->parent->parent;
3285                         struct mgcp_message *cur, *prev;
3286
3287                         ast_mutex_unlock(&sub->lock);
3288                         ast_mutex_lock(&gw->msgs_lock);
3289                         for (prev = NULL, cur = gw->msgs; cur; prev = cur, cur = cur->next) {
3290                                 if (cur->seqno == ident) {
3291                                         ast_log(LOG_DEBUG, "Got response back on transaction %d\n", ident);
3292                                         if (prev)
3293                                                 prev->next = cur->next;
3294                                         else
3295                                                 gw->msgs = cur->next;
3296                                         break;
3297                                 }
3298                         }
3299
3300                         /* stop retrans timer if the queue is empty */
3301                         if (!gw->msgs && (gw->retransid != -1)) {
3302                                 ast_sched_del(sched, gw->retransid);
3303                                 gw->retransid = -1;
3304                         }
3305
3306                         ast_mutex_unlock(&gw->msgs_lock);
3307                         if (cur) {
3308                                 handle_response(cur->owner_ep, cur->owner_sub, result, ident, &req);
3309                                 free(cur);
3310                                 return 1;
3311                         }
3312
3313                         ast_log(LOG_NOTICE, "Got response back on [%s] for transaction %d we aren't sending?\n", 
3314                                 gw->name, ident);
3315                 }
3316         } else {
3317                 if (!req.endpoint || !strlen(req.endpoint) || 
3318