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