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