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