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