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