Merged revisions 100465 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         /* Reset temporary destination */
1002         memset(&sub->tmpdest, 0, sizeof(sub->tmpdest));
1003         if (sub->rtp) {
1004                 ast_rtp_destroy(sub->rtp);
1005                 sub->rtp = NULL;
1006         }
1007
1008         ast_module_unref(ast_module_info->self);
1009
1010         if ((p->hookstate == MGCP_ONHOOK) && (!sub->next->rtp)) {
1011                 p->hidecallerid = 0;
1012                 if (p->hascallwaiting && !p->callwaiting) {
1013                         ast_verb(3, "Enabling call waiting on %s\n", ast->name);
1014                         p->callwaiting = -1;
1015                 }
1016                 if (has_voicemail(p)) {
1017                         if (mgcpdebug) {
1018                                 ast_verb(3, "MGCP mgcp_hangup(%s) on %s@%s set vmwi(+)\n",
1019                                         ast->name, p->name, p->parent->name);
1020                         }
1021                         transmit_notify_request(sub, "L/vmwi(+)");
1022                 } else {
1023                         if (mgcpdebug) {
1024                                 ast_verb(3, "MGCP mgcp_hangup(%s) on %s@%s set vmwi(-)\n",
1025                                         ast->name, p->name, p->parent->name);
1026                         }
1027                         transmit_notify_request(sub, "L/vmwi(-)");
1028                 }
1029         }
1030         ast_mutex_unlock(&sub->lock);
1031         return 0;
1032 }
1033
1034 static char *handle_mgcp_show_endpoints(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1035 {
1036         struct mgcp_gateway  *mg;
1037         struct mgcp_endpoint *me;
1038         int hasendpoints = 0;
1039
1040         switch (cmd) {
1041         case CLI_INIT:
1042                 e->command = "mgcp show endpoints";
1043                 e->usage =
1044                         "Usage: mgcp show endpoints\n"
1045                         "       Lists all endpoints known to the MGCP (Media Gateway Control Protocol) subsystem.\n";
1046                 return NULL;
1047         case CLI_GENERATE:
1048                 return NULL;
1049         }
1050
1051         if (a->argc != 3) 
1052                 return CLI_SHOWUSAGE;
1053         ast_mutex_lock(&gatelock);
1054         mg = gateways;
1055         while(mg) {
1056                 me = mg->endpoints;
1057                 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");
1058                 while(me) {
1059                         /* Don't show wilcard endpoint */
1060                         if (strcmp(me->name, mg->wcardep) != 0)
1061                                 ast_cli(a->fd, "   -- '%s@%s in '%s' is %s\n", me->name, mg->name, me->context, me->sub->owner ? "active" : "idle");
1062                         hasendpoints = 1;
1063                         me = me->next;
1064                 }
1065                 if (!hasendpoints) {
1066                         ast_cli(a->fd, "   << No Endpoints Defined >>     ");
1067                 }
1068                 mg = mg->next;
1069         }
1070         ast_mutex_unlock(&gatelock);
1071         return CLI_SUCCESS;
1072 }
1073
1074 static char *handle_mgcp_audit_endpoint(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1075 {
1076         struct mgcp_gateway  *mg;
1077         struct mgcp_endpoint *me;
1078         int found = 0;
1079         char *ename,*gname, *c;
1080
1081         switch (cmd) {
1082         case CLI_INIT:
1083                 e->command = "mgcp audit endpoint";
1084                 e->usage =
1085                         "Usage: mgcp audit endpoint <endpointid>\n"
1086                         "       Lists the capabilities of an endpoint in the MGCP (Media Gateway Control Protocol) subsystem.\n"
1087                         "       mgcp debug MUST be on to see the results of this command.\n";
1088                 return NULL;
1089         case CLI_GENERATE:
1090                 return NULL;
1091         }
1092
1093         if (!mgcpdebug) {
1094                 return CLI_SHOWUSAGE;
1095         }
1096         if (a->argc != 4)
1097                 return CLI_SHOWUSAGE;
1098         /* split the name into parts by null */
1099         ename = a->argv[3];
1100         gname = ename;
1101         while (*gname) {
1102                 if (*gname == '@') {
1103                         *gname = 0;
1104                         gname++;
1105                         break;
1106                 }
1107                 gname++;
1108         }
1109         if (gname[0] == '[')
1110                 gname++;
1111         if ((c = strrchr(gname, ']')))
1112                 *c = '\0';
1113         ast_mutex_lock(&gatelock);
1114         mg = gateways;
1115         while(mg) {
1116                 if (!strcasecmp(mg->name, gname)) {
1117                         me = mg->endpoints;
1118                         while(me) {
1119                                 if (!strcasecmp(me->name, ename)) {
1120                                         found = 1;
1121                                         transmit_audit_endpoint(me);
1122                                         break;
1123                                 }
1124                                 me = me->next;
1125                         }
1126                         if (found) {
1127                                 break;
1128                         }
1129                 }
1130                 mg = mg->next;
1131         }
1132         if (!found) {
1133                 ast_cli(a->fd, "   << Could not find endpoint >>     ");
1134         }
1135         ast_mutex_unlock(&gatelock);
1136         return CLI_SUCCESS;
1137 }
1138
1139 static char *handle_mgcp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1140 {
1141         switch (cmd) {
1142         case CLI_INIT:
1143                 e->command = "mgcp set debug";
1144                 e->usage =
1145                         "Usage: mgcp set debug\n"
1146                         "       Enables dumping of MGCP packets for debugging purposes\n";      
1147                 return NULL;
1148         case CLI_GENERATE:
1149                 return NULL;
1150         }
1151
1152         if (a->argc != 3)
1153                 return CLI_SHOWUSAGE;
1154         mgcpdebug = 1;
1155         ast_cli(a->fd, "MGCP Debugging Enabled\n");
1156         return CLI_SUCCESS;
1157 }
1158
1159 static char *handle_mgcp_set_debug_off(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1160 {
1161         switch (cmd) {
1162         case CLI_INIT:
1163                 e->command = "mgcp set debug off";
1164                 e->usage =
1165                         "Usage: mgcp set debug off\n"
1166                         "       Disables dumping of MGCP packets for debugging purposes\n";
1167                 return NULL;
1168         case CLI_GENERATE:
1169                 return NULL;
1170         }
1171
1172         if (a->argc != 4)
1173                 return CLI_SHOWUSAGE;
1174         mgcpdebug = 0;
1175         ast_cli(a->fd, "MGCP Debugging Disabled\n");
1176         return CLI_SUCCESS;
1177 }
1178
1179 static struct ast_cli_entry cli_mgcp[] = {
1180         AST_CLI_DEFINE(handle_mgcp_audit_endpoint, "Audit specified MGCP endpoint"),
1181         AST_CLI_DEFINE(handle_mgcp_show_endpoints, "List defined MGCP endpoints"),
1182         AST_CLI_DEFINE(handle_mgcp_set_debug, "Enable MGCP debugging"),
1183         AST_CLI_DEFINE(handle_mgcp_set_debug_off, "Disable MGCP debugging"),
1184         AST_CLI_DEFINE(mgcp_reload, "Reload MGCP configuration"),
1185 };
1186
1187 static int mgcp_answer(struct ast_channel *ast)
1188 {
1189         int res = 0;
1190         struct mgcp_subchannel *sub = ast->tech_pvt;
1191         struct mgcp_endpoint *p = sub->parent;
1192
1193         ast_mutex_lock(&sub->lock);
1194         sub->cxmode = MGCP_CX_SENDRECV;
1195         if (!sub->rtp) {
1196                 start_rtp(sub);
1197         } else {
1198                 transmit_modify_request(sub);
1199         }
1200         ast_verb(3, "MGCP mgcp_answer(%s) on %s@%s-%d\n",
1201                         ast->name, p->name, p->parent->name, sub->id);
1202         if (ast->_state != AST_STATE_UP) {
1203                 ast_setstate(ast, AST_STATE_UP);
1204                 ast_debug(1, "mgcp_answer(%s)\n", ast->name);
1205                 transmit_notify_request(sub, "");
1206                 transmit_modify_request(sub);
1207         }
1208         ast_mutex_unlock(&sub->lock);
1209         return res;
1210 }
1211
1212 static struct ast_frame *mgcp_rtp_read(struct mgcp_subchannel *sub)
1213 {
1214         /* Retrieve audio/etc from channel.  Assumes sub->lock is already held. */
1215         struct ast_frame *f;
1216
1217         f = ast_rtp_read(sub->rtp);
1218         /* Don't send RFC2833 if we're not supposed to */
1219         if (f && (f->frametype == AST_FRAME_DTMF) && !(sub->parent->dtmfmode & MGCP_DTMF_RFC2833))
1220                 return &ast_null_frame;
1221         if (sub->owner) {
1222                 /* We already hold the channel lock */
1223                 if (f->frametype == AST_FRAME_VOICE) {
1224                         if (f->subclass != sub->owner->nativeformats) {
1225                                 ast_debug(1, "Oooh, format changed to %d\n", f->subclass);
1226                                 sub->owner->nativeformats = f->subclass;
1227                                 ast_set_read_format(sub->owner, sub->owner->readformat);
1228                                 ast_set_write_format(sub->owner, sub->owner->writeformat);
1229                         }
1230                         /* Courtesy fearnor aka alex@pilosoft.com */
1231                         if ((sub->parent->dtmfmode & MGCP_DTMF_INBAND) && (sub->parent->dsp)) {
1232 #if 0
1233                                 ast_log(LOG_NOTICE, "MGCP ast_dsp_process\n");
1234 #endif
1235                                 f = ast_dsp_process(sub->owner, sub->parent->dsp, f);
1236                         }
1237                 }
1238         }
1239         return f;
1240 }
1241
1242
1243 static struct ast_frame *mgcp_read(struct ast_channel *ast)
1244 {
1245         struct ast_frame *f;
1246         struct mgcp_subchannel *sub = ast->tech_pvt;
1247         ast_mutex_lock(&sub->lock);
1248         f = mgcp_rtp_read(sub);
1249         ast_mutex_unlock(&sub->lock);
1250         return f;
1251 }
1252
1253 static int mgcp_write(struct ast_channel *ast, struct ast_frame *frame)
1254 {
1255         struct mgcp_subchannel *sub = ast->tech_pvt;
1256         int res = 0;
1257         if (frame->frametype != AST_FRAME_VOICE) {
1258                 if (frame->frametype == AST_FRAME_IMAGE)
1259                         return 0;
1260                 else {
1261                         ast_log(LOG_WARNING, "Can't send %d type frames with MGCP write\n", frame->frametype);
1262                         return 0;
1263                 }
1264         } else {
1265                 if (!(frame->subclass & ast->nativeformats)) {
1266                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1267                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
1268                         return -1;
1269                 }
1270         }
1271         if (sub) {
1272                 ast_mutex_lock(&sub->lock);
1273                 if ((sub->parent->sub == sub) || !sub->parent->singlepath) {
1274                         if (sub->rtp) {
1275                                 res =  ast_rtp_write(sub->rtp, frame);
1276                         }
1277                 }
1278                 ast_mutex_unlock(&sub->lock);
1279         }
1280         return res;
1281 }
1282
1283 static int mgcp_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1284 {
1285         struct mgcp_subchannel *sub = newchan->tech_pvt;
1286
1287         ast_mutex_lock(&sub->lock);
1288         ast_log(LOG_NOTICE, "mgcp_fixup(%s, %s)\n", oldchan->name, newchan->name);
1289         if (sub->owner != oldchan) {
1290                 ast_mutex_unlock(&sub->lock);
1291                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, sub->owner);
1292                 return -1;
1293         }
1294         sub->owner = newchan;
1295         ast_mutex_unlock(&sub->lock);
1296         return 0;
1297 }
1298
1299 static int mgcp_senddigit_begin(struct ast_channel *ast, char digit)
1300 {
1301         struct mgcp_subchannel *sub = ast->tech_pvt;
1302         struct mgcp_endpoint *p = sub->parent;
1303         int res = 0;
1304
1305         ast_mutex_lock(&sub->lock);
1306         if (p->dtmfmode & MGCP_DTMF_INBAND || p->dtmfmode & MGCP_DTMF_HYBRID) {
1307                 ast_log(LOG_DEBUG, "Sending DTMF using inband/hybrid\n");
1308                 res = -1; /* Let asterisk play inband indications */
1309         } else if (p->dtmfmode & MGCP_DTMF_RFC2833) {
1310                 ast_log(LOG_DEBUG, "Sending DTMF using RFC2833");
1311                 ast_rtp_senddigit_begin(sub->rtp, digit);
1312         } else {
1313                 ast_log(LOG_ERROR, "Don't know about DTMF_MODE %d\n", p->dtmfmode);
1314         }
1315         ast_mutex_unlock(&sub->lock);
1316
1317         return res;
1318 }
1319
1320 static int mgcp_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
1321 {
1322         struct mgcp_subchannel *sub = ast->tech_pvt;
1323         struct mgcp_endpoint *p = sub->parent;
1324         int res = 0;
1325         char tmp[4];
1326
1327         ast_mutex_lock(&sub->lock);
1328         if (p->dtmfmode & MGCP_DTMF_INBAND || p->dtmfmode & MGCP_DTMF_HYBRID) {
1329                 ast_log(LOG_DEBUG, "Stopping DTMF using inband/hybrid\n");
1330                 res = -1; /* Tell Asterisk to stop inband indications */
1331         } else if (p->dtmfmode & MGCP_DTMF_RFC2833) {
1332                 ast_log(LOG_DEBUG, "Stopping DTMF using RFC2833\n");
1333                 tmp[0] = 'D';
1334                 tmp[1] = '/';
1335                 tmp[2] = digit;
1336                 tmp[3] = '\0';
1337                 transmit_notify_request(sub, tmp);
1338                 ast_rtp_senddigit_end(sub->rtp, digit);
1339         } else {
1340                 ast_log(LOG_ERROR, "Don't know about DTMF_MODE %d\n", p->dtmfmode);
1341         }
1342         ast_mutex_unlock(&sub->lock);
1343
1344         return res;
1345 }
1346
1347 /*!
1348  *  \brief  mgcp_devicestate: channel callback for device status monitoring
1349  *  \param  data tech/resource name of MGCP device to query
1350  *
1351  * Callback for device state management in channel subsystem
1352  * to obtain device status (up/down) of a specific MGCP endpoint
1353  *
1354  *  \return device status result (from devicestate.h) AST_DEVICE_INVALID (not available) or AST_DEVICE_UNKNOWN (available but unknown state)
1355  */
1356 static int mgcp_devicestate(void *data)
1357 {
1358         struct mgcp_gateway  *g;
1359         struct mgcp_endpoint *e = NULL;
1360         char *tmp, *endpt, *gw;
1361         int ret = AST_DEVICE_INVALID;
1362
1363         endpt = ast_strdupa(data);
1364         if ((tmp = strchr(endpt, '@'))) {
1365                 *tmp++ = '\0';
1366                 gw = tmp;
1367         } else
1368                 goto error;
1369
1370         ast_mutex_lock(&gatelock);
1371         g = gateways;
1372         while (g) {
1373                 if (strcasecmp(g->name, gw) == 0) {
1374                         e = g->endpoints;
1375                         break;
1376                 }
1377                 g = g->next;
1378         }
1379
1380         if (!e)
1381                 goto error;
1382
1383         while (e) {
1384                 if (strcasecmp(e->name, endpt) == 0)
1385                         break;
1386                 e = e->next;
1387         }
1388
1389         if (!e)
1390                 goto error;
1391
1392         /*
1393          * As long as the gateway/endpoint is valid, we'll
1394          * assume that the device is available and its state
1395          * can be tracked.
1396          */
1397         ret = AST_DEVICE_UNKNOWN;
1398
1399 error:
1400         ast_mutex_unlock(&gatelock);
1401         return ret;
1402 }
1403
1404 static char *control2str(int ind) {
1405         switch (ind) {
1406         case AST_CONTROL_HANGUP:
1407                 return "Other end has hungup";
1408         case AST_CONTROL_RING:
1409                 return "Local ring";
1410         case AST_CONTROL_RINGING:
1411                 return "Remote end is ringing";
1412         case AST_CONTROL_ANSWER:
1413                 return "Remote end has answered";
1414         case AST_CONTROL_BUSY:
1415                 return "Remote end is busy";
1416         case AST_CONTROL_TAKEOFFHOOK:
1417                 return "Make it go off hook";
1418         case AST_CONTROL_OFFHOOK:
1419                 return "Line is off hook";
1420         case AST_CONTROL_CONGESTION:
1421                 return "Congestion (circuits busy)";
1422         case AST_CONTROL_FLASH:
1423                 return "Flash hook";
1424         case AST_CONTROL_WINK:
1425                 return "Wink";
1426         case AST_CONTROL_OPTION:
1427                 return "Set a low-level option";
1428         case AST_CONTROL_RADIO_KEY:
1429                 return "Key Radio";
1430         case AST_CONTROL_RADIO_UNKEY:
1431                 return "Un-Key Radio";
1432         }
1433         return "UNKNOWN";
1434 }
1435
1436 static int mgcp_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen)
1437 {
1438         struct mgcp_subchannel *sub = ast->tech_pvt;
1439         int res = 0;
1440
1441         if (mgcpdebug) {
1442                 ast_verb(3, "MGCP asked to indicate %d '%s' condition on channel %s\n",
1443                         ind, control2str(ind), ast->name);
1444         }
1445         ast_mutex_lock(&sub->lock);
1446         switch(ind) {
1447         case AST_CONTROL_RINGING:
1448 #ifdef DLINK_BUGGY_FIRMWARE     
1449                 transmit_notify_request(sub, "rt");
1450 #else
1451                 transmit_notify_request(sub, "G/rt");
1452 #endif          
1453                 break;
1454         case AST_CONTROL_BUSY:
1455                 transmit_notify_request(sub, "L/bz");
1456                 break;
1457         case AST_CONTROL_CONGESTION:
1458                 transmit_notify_request(sub, "G/cg");
1459                 break;
1460         case AST_CONTROL_HOLD:
1461                 ast_moh_start(ast, data, NULL);
1462                 break;
1463         case AST_CONTROL_UNHOLD:
1464                 ast_moh_stop(ast);
1465                 break;
1466         case -1:
1467                 transmit_notify_request(sub, "");
1468                 break;
1469         default:
1470                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", ind);
1471                 res = -1;
1472         }
1473         ast_mutex_unlock(&sub->lock);
1474         return res;
1475 }
1476
1477 static struct ast_channel *mgcp_new(struct mgcp_subchannel *sub, int state)
1478 {
1479         struct ast_channel *tmp;
1480         struct mgcp_endpoint *i = sub->parent;
1481         int fmt;
1482
1483         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);
1484         if (tmp) {
1485                 tmp->tech = &mgcp_tech;
1486                 tmp->nativeformats = i->capability;
1487                 if (!tmp->nativeformats)
1488                         tmp->nativeformats = capability;
1489                 fmt = ast_best_codec(tmp->nativeformats);
1490                 ast_string_field_build(tmp, name, "MGCP/%s@%s-%d", i->name, i->parent->name, sub->id);
1491                 if (sub->rtp)
1492                         ast_channel_set_fd(tmp, 0, ast_rtp_fd(sub->rtp));
1493                 if (i->dtmfmode & (MGCP_DTMF_INBAND | MGCP_DTMF_HYBRID)) {
1494                         i->dsp = ast_dsp_new();
1495                         ast_dsp_set_features(i->dsp,DSP_FEATURE_DTMF_DETECT);
1496                         /* this is to prevent clipping of dtmf tones during dsp processing */
1497                         ast_dsp_digitmode(i->dsp, DSP_DIGITMODE_NOQUELCH);
1498                 } else {
1499                         i->dsp = NULL;
1500                 }
1501                 if (state == AST_STATE_RING)
1502                         tmp->rings = 1;
1503                 tmp->writeformat = fmt;
1504                 tmp->rawwriteformat = fmt;
1505                 tmp->readformat = fmt;
1506                 tmp->rawreadformat = fmt;
1507                 tmp->tech_pvt = sub;
1508                 if (!ast_strlen_zero(i->language))
1509                         ast_string_field_set(tmp, language, i->language);
1510                 if (!ast_strlen_zero(i->accountcode))
1511                         ast_string_field_set(tmp, accountcode, i->accountcode);
1512                 if (i->amaflags)
1513                         tmp->amaflags = i->amaflags;
1514                 sub->owner = tmp;
1515                 ast_module_ref(ast_module_info->self);
1516                 tmp->callgroup = i->callgroup;
1517                 tmp->pickupgroup = i->pickupgroup;
1518                 ast_string_field_set(tmp, call_forward, i->call_forward);
1519                 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
1520                 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
1521
1522                 /* Don't use ast_set_callerid() here because it will
1523                  * generate a needless NewCallerID event */
1524                 tmp->cid.cid_ani = ast_strdup(i->cid_num);
1525                 
1526                 if (!i->adsi)
1527                         tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1528                 tmp->priority = 1;
1529                 if (sub->rtp)
1530                         ast_jb_configure(tmp, &global_jbconf);
1531                 if (state != AST_STATE_DOWN) {
1532                         if (ast_pbx_start(tmp)) {
1533                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1534                                 ast_hangup(tmp);
1535                                 tmp = NULL;
1536                         }
1537                 }
1538                 ast_verb(3, "MGCP mgcp_new(%s) created in state: %s\n",
1539                                 tmp->name, ast_state2str(state));
1540         } else {
1541                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1542         }
1543         return tmp;
1544 }
1545
1546 static char* get_sdp_by_line(char* line, char *name, int nameLen)
1547 {
1548         if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1549                 char* r = line + nameLen + 1;
1550                 while (*r && (*r < 33)) ++r;
1551                 return r;
1552         }
1553         return "";
1554 }
1555
1556 static char *get_sdp(struct mgcp_request *req, char *name)
1557 {
1558         int x;
1559         int len = strlen(name);
1560         char *r;
1561
1562         for (x=0; x<req->lines; x++) {
1563                 r = get_sdp_by_line(req->line[x], name, len);
1564                 if (r[0] != '\0') return r;
1565         }
1566         return "";
1567 }
1568
1569 static void sdpLineNum_iterator_init(int* iterator)
1570 {
1571         *iterator = 0;
1572 }
1573
1574 static char* get_sdp_iterate(int* iterator, struct mgcp_request *req, char *name)
1575 {
1576         int len = strlen(name);
1577         char *r;
1578         while (*iterator < req->lines) {
1579                 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1580                 if (r[0] != '\0') return r;
1581         }
1582         return "";
1583 }
1584
1585 static char *__get_header(struct mgcp_request *req, char *name, int *start)
1586 {
1587         int x;
1588         int len = strlen(name);
1589         char *r;
1590         for (x=*start;x<req->headers;x++) {
1591                 if (!strncasecmp(req->header[x], name, len) && 
1592                     (req->header[x][len] == ':')) {
1593                         r = req->header[x] + len + 1;
1594                         while(*r && (*r < 33))
1595                                 r++;
1596                         *start = x+1;
1597                         return r;
1598                 }
1599         }
1600         /* Don't return NULL, so get_header is always a valid pointer */
1601         return "";
1602 }
1603
1604 static char *get_header(struct mgcp_request *req, char *name)
1605 {
1606         int start = 0;
1607         return __get_header(req, name, &start);
1608 }
1609
1610 /*! \brief get_csv: (SC:) get comma separated value */
1611 static char *get_csv(char *c, int *len, char **next) 
1612 {
1613         char *s;
1614
1615         *next = NULL, *len = 0;
1616         if (!c) return NULL;
1617
1618         while (*c && (*c < 33 || *c == ','))
1619                 c++;
1620
1621         s = c;
1622         while (*c && (*c >= 33 && *c != ','))
1623                 c++, (*len)++;
1624         *next = c;
1625
1626         if (*len == 0)
1627                 s = NULL, *next = NULL;
1628
1629         return s;
1630 }
1631
1632 static struct mgcp_subchannel *find_subchannel_and_lock(char *name, int msgid, struct sockaddr_in *sin)
1633 {
1634         struct mgcp_endpoint *p = NULL;
1635         struct mgcp_subchannel *sub = NULL;
1636         struct mgcp_gateway *g;
1637         char tmp[256] = "";
1638         char *at = NULL, *c;
1639         int found = 0;
1640         if (name) {
1641                 ast_copy_string(tmp, name, sizeof(tmp));
1642                 at = strchr(tmp, '@');
1643                 if (!at) {
1644                         ast_log(LOG_NOTICE, "Endpoint '%s' has no at sign!\n", name);
1645                         return NULL;
1646                 }
1647                 *at++ = '\0';
1648         }
1649         ast_mutex_lock(&gatelock);
1650         if (at && (at[0] == '[')) {
1651                 at++;
1652                 c = strrchr(at, ']');
1653                 if (c)
1654                         *c = '\0';
1655         }
1656         g = gateways;
1657         while(g) {
1658                 if ((!name || !strcasecmp(g->name, at)) && 
1659                     (sin || g->addr.sin_addr.s_addr || g->defaddr.sin_addr.s_addr)) {
1660                         /* Found the gateway.  If it's dynamic, save it's address -- now for the endpoint */
1661                         if (sin && g->dynamic && name) {
1662                                 if ((g->addr.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1663                                         (g->addr.sin_port != sin->sin_port)) {
1664                                         memcpy(&g->addr, sin, sizeof(g->addr));
1665                                         if (ast_ouraddrfor(&g->addr.sin_addr, &g->ourip))
1666                                                 memcpy(&g->ourip, &__ourip, sizeof(g->ourip));
1667                                         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));
1668                                 }
1669                         }
1670                         /* not dynamic, check if the name matches */
1671                         else if (name) {
1672                                 if (strcasecmp(g->name, at)) {
1673                                         g = g->next;
1674                                         continue;
1675                                 }
1676                         }
1677                         /* not dynamic, no name, check if the addr matches */
1678                         else if (!name && sin) {
1679                                 if ((g->addr.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1680                                     (g->addr.sin_port != sin->sin_port)) {
1681                                         g = g->next;
1682                                         continue;
1683                                 }
1684                         } else {
1685                                 g = g->next;
1686                                 continue;
1687                         }
1688                         /* SC */
1689                         p = g->endpoints;
1690                         while(p) {
1691                                 ast_debug(1, "Searching on %s@%s for subchannel\n",
1692                                         p->name, g->name);
1693                                 if (msgid) {
1694 #if 0 /* new transport mech */
1695                                         sub = p->sub;
1696                                         do {
1697                                                 ast_debug(1, "Searching on %s@%s-%d for subchannel with lastout: %d\n",
1698                                                         p->name, g->name, sub->id, msgid);
1699                                                 if (sub->lastout == msgid) {
1700                                                         ast_debug(1, "Found subchannel sub%d to handle request %d sub->lastout: %d\n",
1701                                                                 sub->id, msgid, sub->lastout);
1702                                                         found = 1;
1703                                                         break;
1704                                                 }
1705                                                 sub = sub->next;
1706                                         } while (sub != p->sub);
1707                                         if (found) {
1708                                                 break;
1709                                         }
1710 #endif
1711                                         /* SC */
1712                                         sub = p->sub;
1713                                         found = 1;
1714                                         /* SC */
1715                                         break;
1716                                 } else if (name && !strcasecmp(p->name, tmp)) {
1717                                         ast_debug(1, "Coundn't determine subchannel, assuming current master %s@%s-%d\n", 
1718                                                 p->name, g->name, p->sub->id);
1719                                         sub = p->sub;
1720                                         found = 1;
1721                                         break;
1722                                 }
1723                                 p = p->next;
1724                         }
1725                         if (sub && found) {
1726                                 ast_mutex_lock(&sub->lock);
1727                                 break;
1728                         }
1729                 }
1730                 g = g->next;
1731         }
1732         ast_mutex_unlock(&gatelock);
1733         if (!sub) {
1734                 if (name) {
1735                         if (g)
1736                                 ast_log(LOG_NOTICE, "Endpoint '%s' not found on gateway '%s'\n", tmp, at);
1737                         else
1738                                 ast_log(LOG_NOTICE, "Gateway '%s' (and thus its endpoint '%s') does not exist\n", at, tmp);
1739                 } 
1740         }
1741         return sub;
1742 }
1743
1744 static void parse(struct mgcp_request *req)
1745 {
1746         /* Divide fields by NULL's */
1747         char *c;
1748         int f = 0;
1749         c = req->data;
1750
1751         /* First header starts immediately */
1752         req->header[f] = c;
1753         while(*c) {
1754                 if (*c == '\n') {
1755                         /* We've got a new header */
1756                         *c = 0;
1757 #if 0
1758                         printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1759 #endif                  
1760                         if (ast_strlen_zero(req->header[f])) {
1761                                 /* Line by itself means we're now in content */
1762                                 c++;
1763                                 break;
1764                         }
1765                         if (f >= MGCP_MAX_HEADERS - 1) {
1766                                 ast_log(LOG_WARNING, "Too many MGCP headers...\n");
1767                         } else
1768                                 f++;
1769                         req->header[f] = c + 1;
1770                 } else if (*c == '\r') {
1771                         /* Ignore but eliminate \r's */
1772                         *c = 0;
1773                 }
1774                 c++;
1775         }
1776         /* Check for last header */
1777         if (!ast_strlen_zero(req->header[f])) 
1778                 f++;
1779         req->headers = f;
1780         /* Now we process any mime content */
1781         f = 0;
1782         req->line[f] = c;
1783         while(*c) {
1784                 if (*c == '\n') {
1785                         /* We've got a new line */
1786                         *c = 0;
1787 #if 0
1788                         printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1789 #endif                  
1790                         if (f >= MGCP_MAX_LINES - 1) {
1791                                 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1792                         } else
1793                                 f++;
1794                         req->line[f] = c + 1;
1795                 } else if (*c == '\r') {
1796                         /* Ignore and eliminate \r's */
1797                         *c = 0;
1798                 }
1799                 c++;
1800         }
1801         /* Check for last line */
1802         if (!ast_strlen_zero(req->line[f])) 
1803                 f++;
1804         req->lines = f;
1805         /* Parse up the initial header */
1806         c = req->header[0];
1807         while(*c && *c < 33) c++;
1808         /* First the verb */
1809         req->verb = c;
1810         while(*c && (*c > 32)) c++;
1811         if (*c) {
1812                 *c = '\0';
1813                 c++;
1814                 while(*c && (*c < 33)) c++;
1815                 req->identifier = c;
1816                 while(*c && (*c > 32)) c++;
1817                 if (*c) {
1818                         *c = '\0';
1819                         c++;
1820                         while(*c && (*c < 33)) c++;
1821                         req->endpoint = c;
1822                         while(*c && (*c > 32)) c++;
1823                         if (*c) {
1824                                 *c = '\0';
1825                                 c++;
1826                                 while(*c && (*c < 33)) c++;
1827                                 req->version = c;
1828                                 while(*c && (*c > 32)) c++;
1829                                 while(*c && (*c < 33)) c++;
1830                                 while(*c && (*c > 32)) c++;
1831                                 *c = '\0';
1832                         }
1833                 }
1834         }
1835                 
1836         if (mgcpdebug) {
1837                 ast_verbose("Verb: '%s', Identifier: '%s', Endpoint: '%s', Version: '%s'\n",
1838                         req->verb, req->identifier, req->endpoint, req->version);
1839                 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1840         }
1841         if (*c) 
1842                 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1843 }
1844
1845 static int process_sdp(struct mgcp_subchannel *sub, struct mgcp_request *req)
1846 {
1847         char *m;
1848         char *c;
1849         char *a;
1850         char host[258];
1851         int len;
1852         int portno;
1853         int peercapability, peerNonCodecCapability;
1854         struct sockaddr_in sin;
1855         char *codecs;
1856         struct ast_hostent ahp; struct hostent *hp;
1857         int codec, codec_count=0;
1858         int iterator;
1859         struct mgcp_endpoint *p = sub->parent;
1860
1861         /* Get codec and RTP info from SDP */
1862         m = get_sdp(req, "m");
1863         c = get_sdp(req, "c");
1864         if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
1865                 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1866                 return -1;
1867         }
1868         if (sscanf(c, "IN IP4 %256s", host) != 1) {
1869                 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1870                 return -1;
1871         }
1872         /* XXX This could block for a long time, and block the main thread! XXX */
1873         hp = ast_gethostbyname(host, &ahp);
1874         if (!hp) {
1875                 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1876                 return -1;
1877         }
1878         if (sscanf(m, "audio %d RTP/AVP %n", &portno, &len) != 1) {
1879                 ast_log(LOG_WARNING, "Unable to determine port number for RTP in '%s'\n", m); 
1880                 return -1;
1881         }
1882         sin.sin_family = AF_INET;
1883         memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1884         sin.sin_port = htons(portno);
1885         ast_rtp_set_peer(sub->rtp, &sin);
1886 #if 0
1887         printf("Peer RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1888 #endif  
1889         /* Scan through the RTP payload types specified in a "m=" line: */
1890         ast_rtp_pt_clear(sub->rtp);
1891         codecs = ast_strdupa(m + len);
1892         while (!ast_strlen_zero(codecs)) {
1893                 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
1894                         if (codec_count)
1895                                 break;
1896                         ast_log(LOG_WARNING, "Error in codec string '%s' at '%s'\n", m, codecs);
1897                         return -1;
1898                 }
1899                 ast_rtp_set_m_type(sub->rtp, codec);
1900                 codec_count++;
1901                 codecs += len;
1902         }
1903
1904         /* Next, scan through each "a=rtpmap:" line, noting each */
1905         /* specified RTP payload type (with corresponding MIME subtype): */
1906         sdpLineNum_iterator_init(&iterator);
1907         while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
1908                 char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
1909                 if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2)
1910                         continue;
1911                 /* Note: should really look at the 'freq' and '#chans' params too */
1912                 ast_rtp_set_rtpmap_type(sub->rtp, codec, "audio", mimeSubtype, 0);
1913         }
1914
1915         /* Now gather all of the codecs that were asked for: */
1916         ast_rtp_get_current_formats(sub->rtp, &peercapability, &peerNonCodecCapability);
1917         p->capability = capability & peercapability;
1918         if (mgcpdebug) {
1919                 ast_verbose("Capabilities: us - %d, them - %d, combined - %d\n",
1920                         capability, peercapability, p->capability);
1921                 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
1922                         nonCodecCapability, peerNonCodecCapability, p->nonCodecCapability);
1923         }
1924         if (!p->capability) {
1925                 ast_log(LOG_WARNING, "No compatible codecs!\n");
1926                 return -1;
1927         }
1928         return 0;
1929 }
1930
1931 static int add_header(struct mgcp_request *req, char *var, char *value)
1932 {
1933         if (req->len >= sizeof(req->data) - 4) {
1934                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1935                 return -1;
1936         }
1937         if (req->lines) {
1938                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1939                 return -1;
1940         }
1941         req->header[req->headers] = req->data + req->len;
1942         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s: %s\r\n", var, value);
1943         req->len += strlen(req->header[req->headers]);
1944         if (req->headers < MGCP_MAX_HEADERS)
1945                 req->headers++;
1946         else {
1947                 ast_log(LOG_WARNING, "Out of header space\n");
1948                 return -1;
1949         }
1950         return 0;       
1951 }
1952
1953 static int add_line(struct mgcp_request *req, char *line)
1954 {
1955         if (req->len >= sizeof(req->data) - 4) {
1956                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1957                 return -1;
1958         }
1959         if (!req->lines) {
1960                 /* Add extra empty return */
1961                 ast_copy_string(req->data + req->len, "\r\n", sizeof(req->data) - req->len);
1962                 req->len += strlen(req->data + req->len);
1963         }
1964         req->line[req->lines] = req->data + req->len;
1965         snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1966         req->len += strlen(req->line[req->lines]);
1967         if (req->lines < MGCP_MAX_LINES)
1968                 req->lines++;
1969         else {
1970                 ast_log(LOG_WARNING, "Out of line space\n");
1971                 return -1;
1972         }
1973         return 0;       
1974 }
1975
1976 static int init_resp(struct mgcp_request *req, char *resp, struct mgcp_request *orig, char *resprest)
1977 {
1978         /* Initialize a response */
1979         if (req->headers || req->len) {
1980                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1981                 return -1;
1982         }
1983         req->header[req->headers] = req->data + req->len;
1984         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s %s\r\n", resp, orig->identifier, resprest);
1985         req->len += strlen(req->header[req->headers]);
1986         if (req->headers < MGCP_MAX_HEADERS)
1987                 req->headers++;
1988         else
1989                 ast_log(LOG_WARNING, "Out of header space\n");
1990         return 0;
1991 }
1992
1993 static int init_req(struct mgcp_endpoint *p, struct mgcp_request *req, char *verb)
1994 {
1995         /* Initialize a response */
1996         if (req->headers || req->len) {
1997                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1998                 return -1;
1999         }
2000         req->header[req->headers] = req->data + req->len;
2001         /* check if we need brackets around the gw name */
2002         if (p->parent->isnamedottedip)
2003                 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);
2004         else
2005                 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);
2006         req->len += strlen(req->header[req->headers]);
2007         if (req->headers < MGCP_MAX_HEADERS)
2008                 req->headers++;
2009         else
2010                 ast_log(LOG_WARNING, "Out of header space\n");
2011         return 0;
2012 }
2013
2014
2015 static int respprep(struct mgcp_request *resp, struct mgcp_endpoint *p, char *msg, struct mgcp_request *req, char *msgrest)
2016 {
2017         memset(resp, 0, sizeof(*resp));
2018         init_resp(resp, msg, req, msgrest);
2019         return 0;
2020 }
2021
2022 static int reqprep(struct mgcp_request *req, struct mgcp_endpoint *p, char *verb)
2023 {
2024         memset(req, 0, sizeof(struct mgcp_request));
2025         oseq++;
2026         if (oseq > 999999999)
2027                 oseq = 1;
2028         init_req(p, req, verb);
2029         return 0;
2030 }
2031
2032 static int transmit_response(struct mgcp_subchannel *sub, char *msg, struct mgcp_request *req, char *msgrest)
2033 {
2034         struct mgcp_request resp;
2035         struct mgcp_endpoint *p = sub->parent;
2036         struct mgcp_response *mgr;
2037
2038         respprep(&resp, p, msg, req, msgrest);
2039         mgr = ast_calloc(1, sizeof(*mgr) + resp.len + 1);
2040         if (mgr) {
2041                 /* Store MGCP response in case we have to retransmit */
2042                 sscanf(req->identifier, "%d", &mgr->seqno);
2043                 time(&mgr->whensent);
2044                 mgr->len = resp.len;
2045                 memcpy(mgr->buf, resp.data, resp.len);
2046                 mgr->buf[resp.len] = '\0';
2047                 mgr->next = p->parent->responses;
2048                 p->parent->responses = mgr;
2049         }
2050         return send_response(sub, &resp);
2051 }
2052
2053
2054 static int add_sdp(struct mgcp_request *resp, struct mgcp_subchannel *sub, struct ast_rtp *rtp)
2055 {
2056         int len;
2057         int codec;
2058         char costr[80];
2059         struct sockaddr_in sin;
2060         char v[256];
2061         char s[256];
2062         char o[256];
2063         char c[256];
2064         char t[256];
2065         char m[256] = "";
2066         char a[1024] = "";
2067         int x;
2068         struct sockaddr_in dest;
2069         struct mgcp_endpoint *p = sub->parent;
2070         /* XXX We break with the "recommendation" and send our IP, in order that our
2071                peer doesn't have to ast_gethostbyname() us XXX */
2072         len = 0;
2073         if (!sub->rtp) {
2074                 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2075                 return -1;
2076         }
2077         ast_rtp_get_us(sub->rtp, &sin);
2078         if (rtp) {
2079                 ast_rtp_get_peer(rtp, &dest);
2080         } else {
2081                 if (sub->tmpdest.sin_addr.s_addr) {
2082                         dest.sin_addr = sub->tmpdest.sin_addr;
2083                         dest.sin_port = sub->tmpdest.sin_port;
2084                         /* Reset temporary destination */
2085                         memset(&sub->tmpdest, 0, sizeof(sub->tmpdest));
2086                 } else {
2087                         dest.sin_addr = p->parent->ourip;
2088                         dest.sin_port = sin.sin_port;
2089                 }
2090         }
2091         if (mgcpdebug) {
2092                 ast_verbose("We're at %s port %d\n", ast_inet_ntoa(p->parent->ourip), ntohs(sin.sin_port));
2093         }
2094         ast_copy_string(v, "v=0\r\n", sizeof(v));
2095         snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", (int)getpid(), (int)getpid(), ast_inet_ntoa(dest.sin_addr));
2096         ast_copy_string(s, "s=session\r\n", sizeof(s));
2097         snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
2098         ast_copy_string(t, "t=0 0\r\n", sizeof(t));
2099         snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2100         for (x = 1; x <= AST_FORMAT_AUDIO_MASK; x <<= 1) {
2101                 if (p->capability & x) {
2102                         if (mgcpdebug) {
2103                                 ast_verbose("Answering with capability %d\n", x);
2104                         }
2105                         codec = ast_rtp_lookup_code(sub->rtp, 1, x);
2106                         if (codec > -1) {
2107                                 snprintf(costr, sizeof(costr), " %d", codec);
2108                                 strncat(m, costr, sizeof(m) - strlen(m) - 1);
2109                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x, 0));
2110                                 strncat(a, costr, sizeof(a) - strlen(a) - 1);
2111                         }
2112                 }
2113         }
2114         for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
2115                 if (p->nonCodecCapability & x) {
2116                         if (mgcpdebug) {
2117                                 ast_verbose("Answering with non-codec capability %d\n", x);
2118                         }
2119                         codec = ast_rtp_lookup_code(sub->rtp, 0, x);
2120                         if (codec > -1) {
2121                                 snprintf(costr, sizeof(costr), " %d", codec);
2122                                 strncat(m, costr, sizeof(m) - strlen(m) - 1);
2123                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x, 0));
2124                                 strncat(a, costr, sizeof(a) - strlen(a) - 1);
2125                                 if (x == AST_RTP_DTMF) {
2126                                         /* Indicate we support DTMF...  Not sure about 16,
2127                                            but MSN supports it so dang it, we will too... */
2128                                         snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n", codec);
2129                                         strncat(a, costr, sizeof(a) - strlen(a) - 1);
2130                                 }
2131                         }
2132                 }
2133         }
2134         strncat(m, "\r\n", sizeof(m) - strlen(m) - 1);
2135         len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2136         snprintf(costr, sizeof(costr), "%d", len);
2137         add_line(resp, v);
2138         add_line(resp, o);
2139         add_line(resp, s);
2140         add_line(resp, c);
2141         add_line(resp, t);
2142         add_line(resp, m);
2143         add_line(resp, a);
2144         return 0;
2145 }
2146
2147 static int transmit_modify_with_sdp(struct mgcp_subchannel *sub, struct ast_rtp *rtp, int codecs)
2148 {
2149         struct mgcp_request resp;
2150         char local[256];
2151         char tmp[80];
2152         int x;
2153         int capability;
2154         struct mgcp_endpoint *p = sub->parent;
2155
2156         capability = p->capability;
2157         if (codecs)
2158                 capability = codecs;
2159         if (ast_strlen_zero(sub->cxident) && rtp) {
2160                 /* We don't have a CXident yet, store the destination and
2161                    wait a bit */
2162                 ast_rtp_get_peer(rtp, &sub->tmpdest);
2163                 return 0;
2164         }
2165         ast_copy_string(local, "p:20", sizeof(local));
2166         for (x = 1; x <= AST_FORMAT_AUDIO_MASK; x <<= 1) {
2167                 if (p->capability & x) {
2168                         snprintf(tmp, sizeof(tmp), ", a:%s", ast_rtp_lookup_mime_subtype(1, x, 0));
2169                         strncat(local, tmp, sizeof(local) - strlen(local) - 1);
2170                 }
2171         }
2172         reqprep(&resp, p, "MDCX");
2173         add_header(&resp, "C", sub->callid);
2174         add_header(&resp, "L", local);
2175         add_header(&resp, "M", mgcp_cxmodes[sub->cxmode]);
2176         /* X header should not be sent. kept for compatibility */
2177         add_header(&resp, "X", sub->txident);
2178         add_header(&resp, "I", sub->cxident);
2179         /*add_header(&resp, "S", "");*/
2180         add_sdp(&resp, sub, rtp);
2181         /* fill in new fields */
2182         resp.cmd = MGCP_CMD_MDCX;
2183         resp.trid = oseq;
2184         return send_request(p, sub, &resp, oseq); /* SC */
2185 }
2186
2187 static int transmit_connect_with_sdp(struct mgcp_subchannel *sub, struct ast_rtp *rtp)
2188 {
2189         struct mgcp_request resp;
2190         char local[256];
2191         char tmp[80];
2192         int x;
2193         struct mgcp_endpoint *p = sub->parent;
2194
2195         ast_copy_string(local, "p:20", sizeof(local));
2196         for (x = 1; x <= AST_FORMAT_AUDIO_MASK; x <<= 1) {
2197                 if (p->capability & x) {
2198                         snprintf(tmp, sizeof(tmp), ", a:%s", ast_rtp_lookup_mime_subtype(1, x, 0));
2199                         strncat(local, tmp, sizeof(local) - strlen(local) - 1);
2200                 }
2201         }
2202         if (mgcpdebug) {
2203                 ast_verb(3, "Creating connection for %s@%s-%d in cxmode: %s callid: %s\n",
2204                         p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode], sub->callid);
2205         }
2206         reqprep(&resp, p, "CRCX");
2207         add_header(&resp, "C", sub->callid);
2208         add_header(&resp, "L", local);
2209         add_header(&resp, "M", mgcp_cxmodes[sub->cxmode]);
2210         /* X header should not be sent. kept for compatibility */
2211         add_header(&resp, "X", sub->txident);
2212         /*add_header(&resp, "S", "");*/
2213         add_sdp(&resp, sub, rtp);
2214         /* fill in new fields */
2215         resp.cmd = MGCP_CMD_CRCX;
2216         resp.trid = oseq;
2217         return send_request(p, sub, &resp, oseq);  /* SC */
2218 }
2219
2220 static int transmit_notify_request(struct mgcp_subchannel *sub, char *tone)
2221 {
2222         struct mgcp_request resp;
2223         struct mgcp_endpoint *p = sub->parent;
2224
2225         if (mgcpdebug) {
2226                 ast_verb(3, "MGCP Asked to indicate tone: %s on  %s@%s-%d in cxmode: %s\n",
2227                         tone, p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode]);
2228         }
2229         ast_copy_string(p->curtone, tone, sizeof(p->curtone));
2230         reqprep(&resp, p, "RQNT");
2231         add_header(&resp, "X", p->rqnt_ident); /* SC */
2232         switch (p->hookstate) {
2233         case MGCP_ONHOOK:
2234                 add_header(&resp, "R", "L/hd(N)");
2235                 break;
2236         case MGCP_OFFHOOK:
2237                 add_header_offhook(sub, &resp);
2238                 break;
2239         }
2240         if (!ast_strlen_zero(tone)) {
2241                 add_header(&resp, "S", tone);
2242         }
2243         /* fill in new fields */
2244         resp.cmd = MGCP_CMD_RQNT;
2245         resp.trid = oseq;
2246         return send_request(p, NULL, &resp, oseq); /* SC */
2247 }
2248
2249 static int transmit_notify_request_with_callerid(struct mgcp_subchannel *sub, char *tone, char *callernum, char *callername)
2250 {
2251         struct mgcp_request resp;
2252         char tone2[256];
2253         char *l, *n;
2254         struct timeval t = ast_tvnow();
2255         struct ast_tm tm;
2256         struct mgcp_endpoint *p = sub->parent;
2257         
2258         ast_localtime(&t, &tm, NULL);
2259         n = callername;
2260         l = callernum;
2261         if (!n)
2262                 n = "";
2263         if (!l)
2264                 l = "";
2265
2266         /* Keep track of last callerid for blacklist and callreturn */
2267         ast_copy_string(p->lastcallerid, l, sizeof(p->lastcallerid));
2268
2269         snprintf(tone2, sizeof(tone2), "%s,L/ci(%02d/%02d/%02d/%02d,%s,%s)", tone, 
2270                 tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, l, n);
2271         ast_copy_string(p->curtone, tone, sizeof(p->curtone));
2272         reqprep(&resp, p, "RQNT");
2273         add_header(&resp, "X", p->rqnt_ident); /* SC */
2274         switch (p->hookstate) {
2275         case MGCP_ONHOOK:
2276                 add_header(&resp, "R", "L/hd(N)");
2277                 break;
2278         case MGCP_OFFHOOK:
2279                 add_header_offhook(sub, &resp);
2280                 break;
2281         }
2282         if (!ast_strlen_zero(tone2)) {
2283                 add_header(&resp, "S", tone2);
2284         }
2285         if (mgcpdebug) {
2286                 ast_verb(3, "MGCP Asked to indicate tone: %s on  %s@%s-%d in cxmode: %s\n",
2287                         tone2, p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode]);
2288         }
2289         /* fill in new fields */
2290         resp.cmd = MGCP_CMD_RQNT;
2291         resp.trid = oseq;
2292         return send_request(p, NULL, &resp, oseq);  /* SC */
2293 }
2294
2295 static int transmit_modify_request(struct mgcp_subchannel *sub)
2296 {
2297         struct mgcp_request resp;
2298         struct mgcp_endpoint *p = sub->parent;
2299
2300         if (ast_strlen_zero(sub->cxident)) {
2301                 /* We don't have a CXident yet, store the destination and
2302                    wait a bit */
2303                 return 0;
2304         }
2305         if (mgcpdebug) {
2306                 ast_verb(3, "Modified %s@%s-%d with new mode: %s on callid: %s\n",
2307                         p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode], sub->callid);
2308         }
2309         reqprep(&resp, p, "MDCX");
2310         add_header(&resp, "C", sub->callid);
2311         add_header(&resp, "M", mgcp_cxmodes[sub->cxmode]);
2312         /* X header should not be sent. kept for compatibility */
2313         add_header(&resp, "X", sub->txident);
2314         add_header(&resp, "I", sub->cxident);
2315         switch (sub->parent->hookstate) {
2316         case MGCP_ONHOOK:
2317                 add_header(&resp, "R", "L/hd(N)");
2318                 break;
2319         case MGCP_OFFHOOK:
2320                 add_header_offhook(sub, &resp);
2321                 break;
2322         }
2323         /* fill in new fields */
2324         resp.cmd = MGCP_CMD_MDCX;
2325         resp.trid = oseq;
2326         return send_request(p, sub, &resp, oseq); /* SC */
2327 }
2328
2329
2330 static void add_header_offhook(struct mgcp_subchannel *sub, struct mgcp_request *resp)
2331 {
2332         struct mgcp_endpoint *p = sub->parent;
2333
2334         if (p && p->sub && p->sub->owner && p->sub->owner->_state >= AST_STATE_RINGING && (p->dtmfmode & (MGCP_DTMF_INBAND | MGCP_DTMF_HYBRID)))
2335                 add_header(resp, "R", "L/hu(N),L/hf(N)");
2336         else
2337                 add_header(resp, "R", "L/hu(N),L/hf(N),D/[0-9#*](N)");
2338 }
2339
2340 static int transmit_audit_endpoint(struct mgcp_endpoint *p)
2341 {
2342         struct mgcp_request resp;
2343         reqprep(&resp, p, "AUEP");
2344         /* removed unknown param VS */
2345         /*add_header(&resp, "F", "A,R,D,S,X,N,I,T,O,ES,E,MD,M");*/
2346         add_header(&resp, "F", "A");
2347         /* fill in new fields */
2348         resp.cmd = MGCP_CMD_AUEP;
2349         resp.trid = oseq;
2350         return send_request(p, NULL, &resp, oseq);  /* SC */
2351 }
2352
2353 static int transmit_connection_del(struct mgcp_subchannel *sub)
2354 {
2355         struct mgcp_endpoint *p = sub->parent;
2356         struct mgcp_request resp;
2357
2358         if (mgcpdebug) {
2359                 ast_verb(3, "Delete connection %s %s@%s-%d with new mode: %s on callid: %s\n",
2360                         sub->cxident, p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode], sub->callid);
2361         }
2362         reqprep(&resp, p, "DLCX");
2363         /* check if call id is avail */
2364         if (sub->callid[0])
2365                 add_header(&resp, "C", sub->callid);
2366         /* X header should not be sent. kept for compatibility */
2367         add_header(&resp, "X", sub->txident);
2368         /* check if cxident is avail */
2369         if (sub->cxident[0])
2370                 add_header(&resp, "I", sub->cxident);
2371         /* fill in new fields */
2372         resp.cmd = MGCP_CMD_DLCX;
2373         resp.trid = oseq;
2374         return send_request(p, sub, &resp, oseq);  /* SC */
2375 }
2376
2377 static int transmit_connection_del_w_params(struct mgcp_endpoint *p, char *callid, char *cxident)
2378 {
2379         struct mgcp_request resp;
2380
2381         if (mgcpdebug) {
2382                 ast_verb(3, "Delete connection %s %s@%s on callid: %s\n",
2383                         cxident ? cxident : "", p->name, p->parent->name, callid ? callid : "");
2384         }
2385         reqprep(&resp, p, "DLCX");
2386         /* check if call id is avail */
2387         if (callid && *callid)
2388                 add_header(&resp, "C", callid);
2389         /* check if cxident is avail */
2390         if (cxident && *cxident)
2391                 add_header(&resp, "I", cxident);
2392         /* fill in new fields */
2393         resp.cmd = MGCP_CMD_DLCX;
2394         resp.trid = oseq;
2395         return send_request(p, p->sub, &resp, oseq);
2396 }
2397
2398 /*! \brief  dump_cmd_queues: (SC:) cleanup pending commands */
2399 static void dump_cmd_queues(struct mgcp_endpoint *p, struct mgcp_subchannel *sub) 
2400 {
2401         struct mgcp_request *t, *q;
2402
2403         if (p) {
2404                 ast_mutex_lock(&p->rqnt_queue_lock);
2405                 for (q = p->rqnt_queue; q; t = q->next, ast_free(q), q=t);
2406                 p->rqnt_queue = NULL;
2407                 ast_mutex_unlock(&p->rqnt_queue_lock);
2408
2409                 ast_mutex_lock(&p->cmd_queue_lock);
2410                 for (q = p->cmd_queue; q; t = q->next, ast_free(q), q=t);
2411                 p->cmd_queue = NULL;
2412                 ast_mutex_unlock(&p->cmd_queue_lock);
2413
2414                 ast_mutex_lock(&p->sub->cx_queue_lock);
2415                 for (q = p->sub->cx_queue; q; t = q->next, ast_free(q), q=t);
2416                 p->sub->cx_queue = NULL;
2417                 ast_mutex_unlock(&p->sub->cx_queue_lock);
2418
2419                 ast_mutex_lock(&p->sub->next->cx_queue_lock);
2420                 for (q = p->sub->next->cx_queue; q; t = q->next, ast_free(q), q=t);
2421                 p->sub->next->cx_queue = NULL;
2422                 ast_mutex_unlock(&p->sub->next->cx_queue_lock);
2423         } else if (sub) {
2424                 ast_mutex_lock(&sub->cx_queue_lock);
2425                 for (q = sub->cx_queue; q; t = q->next, ast_free(q), q=t);
2426                 sub->cx_queue = NULL;
2427                 ast_mutex_unlock(&sub->cx_queue_lock);
2428         }
2429 }
2430
2431
2432 /*! \brief  find_command: (SC:) remove command transaction from queue */
2433 static struct mgcp_request *find_command(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,
2434                                          struct mgcp_request **queue, ast_mutex_t *l, int ident)
2435 {
2436         struct mgcp_request *prev, *req;
2437
2438         ast_mutex_lock(l);
2439         for (prev = NULL, req = *queue; req; prev = req, req = req->next) {
2440                 if (req->trid == ident) {
2441                         /* remove from queue */
2442                         if (!prev)
2443                                 *queue = req->next;
2444                         else
2445                                 prev->next = req->next;
2446
2447                         /* send next pending command */
2448                         if (*queue) {
2449                                 if (mgcpdebug) {
2450                                         ast_verbose("Posting Queued Request:\n%s to %s:%d\n", (*queue)->data, 
2451                                                 ast_inet_ntoa(p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
2452                                 }
2453
2454                                 mgcp_postrequest(p, sub, (*queue)->data, (*queue)->len, (*queue)->trid);
2455                         }
2456                         break;
2457                 }
2458         }
2459         ast_mutex_unlock(l);
2460         return req;
2461 }
2462
2463 /* modified for new transport mechanism */
2464 static void handle_response(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,  
2465                             int result, unsigned int ident, struct mgcp_request *resp)
2466 {
2467         char *c;
2468         struct mgcp_request *req;
2469         struct mgcp_gateway *gw = p->parent;
2470
2471         if (result < 200) {
2472                 /* provisional response */
2473                 return;
2474         }
2475
2476         if (p->slowsequence) 
2477                 req = find_command(p, sub, &p->cmd_queue, &p->cmd_queue_lock, ident);
2478         else if (sub)
2479                 req = find_command(p, sub, &sub->cx_queue, &sub->cx_queue_lock, ident);
2480         else if (!(req = find_command(p, sub, &p->rqnt_queue, &p->rqnt_queue_lock, ident)))
2481                 req = find_command(p, sub, &p->cmd_queue, &p->cmd_queue_lock, ident);
2482
2483         if (!req) {
2484                 ast_verb(3, "No command found on [%s] for transaction %d. Ignoring...\n",
2485                                 gw->name, ident);
2486                 return;
2487         }
2488
2489         if (p && (result >= 400) && (result <= 599)) {
2490                 switch (result) {
2491                 case 401:
2492                         p->hookstate = MGCP_OFFHOOK;
2493                         break;
2494                 case 402:
2495                         p->hookstate = MGCP_ONHOOK;
2496                         break;
2497                 case 406:
2498                         ast_log(LOG_NOTICE, "Transaction %d timed out\n", ident);
2499                         break;
2500                 case 407:
2501                         ast_log(LOG_NOTICE, "Transaction %d aborted\n", ident);
2502                         break;
2503                 }
2504                 if (sub) {
2505                         if (sub->owner) {
2506                                 ast_log(LOG_NOTICE, "Terminating on result %d from %s@%s-%d\n", 
2507                                         result, p->name, p->parent->name, sub ? sub->id:-1);
2508                                 mgcp_queue_hangup(sub);
2509                         }
2510                 } else {
2511                         if (p->sub->next->owner) {
2512                                 ast_log(LOG_NOTICE, "Terminating on result %d from %s@%s-%d\n", 
2513                                         result, p->name, p->parent->name, sub ? sub->id:-1);
2514                                 mgcp_queue_hangup(p->sub);
2515                         }
2516
2517                         if (p->sub->owner) {
2518                                 ast_log(LOG_NOTICE, "Terminating on result %d from %s@%s-%d\n", 
2519                                         result, p->name, p->parent->name, sub ? sub->id:-1);
2520                                 mgcp_queue_hangup(p->sub);
2521                         }
2522
2523                         dump_cmd_queues(p, NULL);
2524                 }
2525         }
2526
2527         if (resp) {
2528                 if (req->cmd == MGCP_CMD_CRCX) {
2529                         if ((c = get_header(resp, "I"))) {
2530                                 if (!ast_strlen_zero(c) && sub) {
2531                                         /* if we are hanging up do not process this conn. */
2532                                         if (sub->owner) {
2533                                                 if (!ast_strlen_zero(sub->cxident)) {
2534                                                         if (strcasecmp(c, sub->cxident)) {
2535                                                                 ast_log(LOG_WARNING, "Subchannel already has a cxident. sub->cxident: %s requested %s\n", sub->cxident, c);
2536                                                         }
2537                                                 }
2538                                                 ast_copy_string(sub->cxident, c, sizeof(sub->cxident));
2539                                                 if (sub->tmpdest.sin_addr.s_addr) {
2540                                                         transmit_modify_with_sdp(sub, NULL, 0);
2541                                                 }
2542                                         } else {
2543                                                 /* XXX delete this one
2544                                                    callid and conn id may already be lost. 
2545                                                    so the following del conn may have a side effect of 
2546                                                    cleaning up the next subchannel */
2547                                                 transmit_connection_del(sub);
2548                                         }
2549                                 }
2550                         }
2551                 }
2552
2553                 if (req->cmd == MGCP_CMD_AUEP) {
2554                         /* check stale connection ids */
2555                         if ((c = get_header(resp, "I"))) {
2556                                 char *v, *n;
2557                                 int len;
2558                                 while ((v = get_csv(c, &len, &n))) {
2559                                         if (len) {
2560                                                 if (strncasecmp(v, p->sub->cxident, len) &&
2561                                                     strncasecmp(v, p->sub->next->cxident, len)) {
2562                                                         /* connection id not found. delete it */
2563                                                         char cxident[80] = "";
2564
2565                                                         if (len > (sizeof(cxident) - 1))
2566                                                                 len = sizeof(cxident) - 1;
2567                                                         ast_copy_string(cxident, v, len);
2568                                                         ast_verb(3, "Non existing connection id %s on %s@%s \n",
2569                                                                             cxident, p->name, gw->name);
2570                                                         transmit_connection_del_w_params(p, NULL, cxident);
2571                                                 }
2572                                         }
2573                                         c = n;
2574                                 }
2575                         }
2576
2577                         /* Try to determine the hookstate returned from an audit endpoint command */
2578                         if ((c = get_header(resp, "ES"))) {
2579                                 if (!ast_strlen_zero(c)) {
2580                                         if (strstr(c, "hu")) {
2581                                                 if (p->hookstate != MGCP_ONHOOK) {
2582                                                         /* XXX cleanup if we think we are offhook XXX */
2583                                                         if ((p->sub->owner || p->sub->next->owner ) && 
2584                                                             p->hookstate == MGCP_OFFHOOK)
2585                                                                 mgcp_queue_hangup(sub);
2586                                                         p->hookstate = MGCP_ONHOOK;
2587
2588                                                         /* update the requested events according to the new hookstate */
2589                                                         transmit_notify_request(p->sub, "");
2590
2591                                                         ast_verb(3, "Setting hookstate of %s@%s to ONHOOK\n", p->name, gw->name);
2592                                                         }
2593                                         } else if (strstr(c, "hd")) {
2594                                                 if (p->hookstate != MGCP_OFFHOOK) {
2595                                                         p->hookstate = MGCP_OFFHOOK;
2596
2597                                                         /* update the requested events according to the new hookstate */
2598                                                         transmit_notify_request(p->sub, "");
2599
2600                                                         ast_verb(3, "Setting hookstate of %s@%s to OFFHOOK\n", p->name, gw->name);
2601                                                         }
2602                                                 }
2603                                         }
2604                                 }
2605                         }
2606
2607                 if (resp && resp->lines) {
2608                         /* do not process sdp if we are hanging up. this may be a late response */
2609                         if (sub && sub->owner) {
2610                                 if (!sub->rtp)
2611                                         start_rtp(sub);
2612                                 if (sub->rtp)
2613                                         process_sdp(sub, resp);
2614                         }
2615                 }
2616         }
2617
2618         ast_free(req);
2619 }
2620
2621 static void start_rtp(struct mgcp_subchannel *sub)
2622 {
2623         ast_mutex_lock(&sub->lock);
2624         /* check again to be on the safe side */
2625         if (sub->rtp) {
2626                 ast_rtp_destroy(sub->rtp);
2627                 sub->rtp = NULL;
2628         }
2629         /* Allocate the RTP now */
2630         sub->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
2631         if (sub->rtp && sub->owner)
2632                 ast_channel_set_fd(sub->owner, 0, ast_rtp_fd(sub->rtp));
2633         if (sub->rtp) {
2634                 ast_rtp_setqos(sub->rtp, tos_audio, cos_audio, "MGCP RTP");
2635                 ast_rtp_setnat(sub->rtp, sub->nat);
2636         }
2637 #if 0
2638         ast_rtp_set_callback(p->rtp, rtpready);
2639         ast_rtp_set_data(p->rtp, p);
2640 #endif          
2641         /* Make a call*ID */
2642         snprintf(sub->callid, sizeof(sub->callid), "%08lx%s", ast_random(), sub->txident);
2643         /* Transmit the connection create */
2644         transmit_connect_with_sdp(sub, NULL);
2645         ast_mutex_unlock(&sub->lock);
2646 }
2647
2648 static void *mgcp_ss(void *data)
2649 {
2650         struct ast_channel *chan = data;
2651         struct mgcp_subchannel *sub = chan->tech_pvt;
2652         struct mgcp_endpoint *p = sub->parent;
2653         /* char exten[AST_MAX_EXTENSION] = ""; */
2654         int len = 0;
2655         int timeout = firstdigittimeout;
2656         int res= 0;
2657         int getforward = 0;
2658         int loop_pause = 100;
2659
2660         len = strlen(p->dtmf_buf);
2661
2662         while(len < AST_MAX_EXTENSION-1) {
2663                 res = 1;  /* Assume that we will get a digit */
2664                 while (strlen(p->dtmf_buf) == len){
2665                         ast_safe_sleep(chan, loop_pause);
2666                         timeout -= loop_pause;
2667                         if (timeout <= 0){
2668                                 res = 0;
2669                                 break;
2670                         }
2671                         res = 1;
2672                 }
2673
2674                 timeout = 0;
2675                 len = strlen(p->dtmf_buf);
2676
2677                 if (!ast_ignore_pattern(chan->context, p->dtmf_buf)) {
2678                         /*res = tone_zone_play_tone(p->subs[index].zfd, -1);*/
2679                         ast_indicate(chan, -1);
2680                 } else {
2681                         /* XXX Redundant?  We should already be playing dialtone */
2682                         /*tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALTONE);*/
2683                         transmit_notify_request(sub, "L/dl");
2684                 }
2685                 if (ast_exists_extension(chan, chan->context, p->dtmf_buf, 1, p->cid_num)) {
2686                         if (!res || !ast_matchmore_extension(chan, chan->context, p->dtmf_buf, 1, p->cid_num)) {
2687                                 if (getforward) {
2688                                         /* Record this as the forwarding extension */
2689                                         ast_copy_string(p->call_forward, p->dtmf_buf, sizeof(p->call_forward)); 
2690                                         ast_verb(3, "Setting call forward to '%s' on channel %s\n",
2691                                                         p->call_forward, chan->name);
2692                                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2693                                         transmit_notify_request(sub, "L/sl");
2694                                         if (res)
2695                                                 break;
2696                                         usleep(500000);
2697                                         /*res = tone_zone_play_tone(p->subs[index].zfd, -1);*/
2698                                         ast_indicate(chan, -1);
2699                                         sleep(1);
2700                                         memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2701                                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALTONE);*/
2702                                         transmit_notify_request(sub, "L/dl");
2703                                         len = 0;
2704                                         getforward = 0;
2705                                 } else {
2706                                         /*res = tone_zone_play_tone(p->subs[index].zfd, -1);*/
2707                                         ast_indicate(chan, -1);
2708                                         ast_copy_string(chan->exten, p->dtmf_buf, sizeof(chan->exten));
2709                                         memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2710                                         ast_set_callerid(chan,
2711                                                 p->hidecallerid ? "" : p->cid_num,
2712                                                 p->hidecallerid ? "" : p->cid_name,
2713                                                 chan->cid.cid_ani ? NULL : p->cid_num);
2714                                         ast_setstate(chan, AST_STATE_RING);
2715                                         /*zt_enable_ec(p);*/
2716                                         if (p->dtmfmode & MGCP_DTMF_HYBRID) {
2717                                                 p->dtmfmode |= MGCP_DTMF_INBAND;
2718                                                 ast_indicate(chan, -1);
2719                                         }
2720                                         res = ast_pbx_run(chan);
2721                                         if (res) {
2722                                                 ast_log(LOG_WARNING, "PBX exited non-zero\n");
2723                                                 /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);*/
2724                                                 /*transmit_notify_request(p, "nbz", 1);*/
2725                                                 transmit_notify_request(sub, "G/cg");
2726                                         }
2727                                         return NULL;
2728                                 }
2729                         } else {
2730                                 /* It's a match, but they just typed a digit, and there is an ambiguous match,
2731                                    so just set the timeout to matchdigittimeout and wait some more */
2732                                 timeout = matchdigittimeout;
2733                         }
2734                 } else if (res == 0) {
2735                         ast_debug(1, "not enough digits (and no ambiguous match)...\n");
2736                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);*/
2737                         transmit_notify_request(sub, "G/cg");
2738                         /*zt_wait_event(p->subs[index].zfd);*/
2739                         ast_hangup(chan);
2740                         memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2741                         return NULL;
2742                 } else if (p->hascallwaiting && p->callwaiting && !strcmp(p->dtmf_buf, "*70")) {
2743                         ast_verb(3, "Disabling call waiting on %s\n", chan->name);
2744                         /* Disable call waiting if enabled */
2745                         p->callwaiting = 0;
2746                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2747                         transmit_notify_request(sub, "L/sl");
2748                         len = 0;
2749                         memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2750                         timeout = firstdigittimeout;
2751                 } else if (!strcmp(p->dtmf_buf,ast_pickup_ext())) {
2752                         /* Scan all channels and see if any there
2753                          * ringing channqels with that have call groups
2754                          * that equal this channels pickup group  
2755                          */
2756                         if (ast_pickup_call(chan)) {
2757                                 ast_log(LOG_WARNING, "No call pickup possible...\n");
2758                                 /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);*/
2759                                 transmit_notify_request(sub, "G/cg");
2760                         }
2761                         memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2762                         ast_hangup(chan);
2763                         return NULL;
2764                 } else if (!p->hidecallerid && !strcmp(p->dtmf_buf, "*67")) {
2765                         ast_verb(3, "Disabling Caller*ID on %s\n", chan->name);
2766                         /* Disable Caller*ID if enabled */
2767                         p->hidecallerid = 1;
2768                         ast_set_callerid(chan, "", "", NULL);
2769                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2770                         transmit_notify_request(sub, "L/sl");
2771                         len = 0;
2772                         memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2773                         timeout = firstdigittimeout;
2774                 } else if (p->callreturn && !strcmp(p->dtmf_buf, "*69")) {
2775                         res = 0;
2776                         if (!ast_strlen_zero(p->lastcallerid)) {
2777                                 res = ast_say_digit_str(chan, p->lastcallerid, "", chan->language);
2778                         }
2779                         if (!res)
2780                                 /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2781                                 transmit_notify_request(sub, "L/sl");
2782                         break;
2783                 } else if (!strcmp(p->dtmf_buf, "*78")) {
2784                         /* Do not disturb */
2785                         ast_verb(3, "Enabled DND on channel %s\n", chan->name);
2786                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2787                         transmit_notify_request(sub, "L/sl");
2788                         p->dnd = 1;
2789                         getforward = 0;
2790                         memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2791                         len = 0;
2792                 } else if (!strcmp(p->dtmf_buf, "*79")) {
2793                         /* Do not disturb */
2794                         ast_verb(3, "Disabled DND on channel %s\n", chan->name);
2795                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2796                         transmit_notify_request(sub, "L/sl");
2797                         p->dnd = 0;
2798                         getforward = 0;
2799                         memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2800                         len = 0;
2801                 } else if (p->cancallforward && !strcmp(p->dtmf_buf, "*72")) {
2802                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2803                         transmit_notify_request(sub, "L/sl");
2804                         getforward = 1;
2805                         memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2806                         len = 0;
2807                 } else if (p->cancallforward && !strcmp(p->dtmf_buf, "*73")) {
2808                         ast_verb(3, "Cancelling call forwarding on channel %s\n", chan->name);
2809                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2810                         transmit_notify_request(sub, "L/sl");
2811                         memset(p->call_forward, 0, sizeof(p->call_forward));
2812                         getforward = 0;
2813                         memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2814                         len = 0;
2815                 } else if (!strcmp(p->dtmf_buf, ast_parking_ext()) && 
2816                         sub->next->owner && ast_bridged_channel(sub->next->owner)) {
2817                         /* This is a three way call, the main call being a real channel, 
2818                            and we're parking the first call. */
2819                         ast_masq_park_call(ast_bridged_channel(sub->next->owner), chan, 0, NULL);
2820                         ast_verb(3, "Parking call to '%s'\n", chan->name);
2821                         break;
2822                 } else if (!ast_strlen_zero(p->lastcallerid) && !strcmp(p->dtmf_buf, "*60")) {
2823                         ast_verb(3, "Blacklisting number %s\n", p->lastcallerid);
2824                         res = ast_db_put("blacklist", p->lastcallerid, "1");
2825                         if (!res) {
2826                                 /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2827                                 transmit_notify_request(sub, "L/sl");
2828                                 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2829                                 len = 0;
2830                         }
2831                 } else if (p->hidecallerid && !strcmp(p->dtmf_buf, "*82")) {
2832                         ast_verb(3, "Enabling Caller*ID on %s\n", chan->name);
2833                         /* Enable Caller*ID if enabled */
2834                         p->hidecallerid = 0;
2835                         ast_set_callerid(chan, p->cid_num, p->cid_name, NULL);
2836                         /*res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);*/
2837                         transmit_notify_request(sub, "L/sl");
2838                         len = 0;
2839                         memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2840                         timeout = firstdigittimeout;
2841                 } else if (!ast_canmatch_extension(chan, chan->context, p->dtmf_buf, 1, chan->cid.cid_num) &&
2842                                 ((p->dtmf_buf[0] != '*') || (strlen(p->dtmf_buf) > 2))) {
2843                         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);
2844                         break;
2845                 }
2846                 if (!timeout)
2847                         timeout = gendigittimeout;
2848                 if (len && !ast_ignore_pattern(chan->context, p->dtmf_buf))
2849                         /*tone_zone_play_tone(p->subs[index].zfd, -1);*/
2850                         ast_indicate(chan, -1);
2851         }
2852 #if 0
2853         for (;;) {
2854                 res = ast_waitfordigit(chan, to);
2855                 if (!res) {
2856                         ast_debug(1, "Timeout...\n");
2857                         break;
2858                 }
2859                 if (res < 0) {
2860                         ast_debug(1, "Got hangup...\n");
2861                         ast_hangup(chan);
2862                         break;
2863                 }
2864                 exten[pos++] = res;
2865                 if (!ast_ignore_pattern(chan->context, exten))
2866                         ast_indicate(chan, -1);
2867                 if (ast_matchmore_extension(chan, chan->context, exten, 1, chan->callerid)) {
2868                         if (ast_exists_extension(chan, chan->context, exten, 1, chan->callerid)) 
2869                                 to = 3000;
2870                         else
2871                                 to = 8000;
2872                 } else
2873                         break;
2874         }
2875         if (ast_exists_extension(chan, chan->context, exten, 1, chan->callerid)) {
2876                 ast_copy_string(chan->exten, exten, sizeof(chan->exten)1);
2877                 if (!p->rtp) {
2878                         start_rtp(p);
2879                 }
2880                 ast_setstate(chan, AST_STATE_RING);
2881                 chan->rings = 1;
2882                 if (ast_pbx_run(chan)) {
2883                         ast_log(LOG_WARNING, "Unable to launch PBX on %s\n", chan->name);
2884                 } else {
2885                         memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2886                         return NULL;
2887                 }
2888         }
2889 #endif
2890         ast_hangup(chan);
2891         memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2892         return NULL;
2893 }
2894
2895 static int attempt_transfer(struct mgcp_endpoint *p)
2896 {
2897         /* *************************
2898          * I hope this works.
2899          * Copied out of chan_zap
2900          * Cross your fingers
2901          * *************************/
2902
2903         /* In order to transfer, we need at least one of the channels to
2904            actually be in a call bridge.  We can't conference two applications
2905            together (but then, why would we want to?) */
2906         if (ast_bridged_channel(p->sub->owner)) {
2907                 /* The three-way person we're about to transfer to could still be in MOH, so
2908                    stop if now if appropriate */
2909                 if (ast_bridged_channel(p->sub->next->owner))
2910                         ast_queue_control(p->sub->next->owner, AST_CONTROL_UNHOLD);
2911                 if (p->sub->owner->_state == AST_STATE_RINGING) {
2912                         ast_indicate(ast_bridged_channel(p->sub->next->owner), AST_CONTROL_RINGING);
2913                 }
2914                 if (ast_channel_masquerade(p->sub->next->owner, ast_bridged_channel(p->sub->owner))) {
2915                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
2916                                 ast_bridged_channel(p->sub->owner)->name, p->sub->next->owner->name);
2917                         return -1;
2918                 }
2919                 /* Orphan the channel */
2920                 unalloc_sub(p->sub->next);
2921         } else if (ast_bridged_channel(p->sub->next->owner)) {
2922                 if (p->sub->owner->_state == AST_STATE_RINGING) {
2923                         ast_indicate(ast_bridged_channel(p->sub->next->owner), AST_CONTROL_RINGING);
2924                 }
2925                 ast_queue_control(p->sub->next->owner, AST_CONTROL_UNHOLD);
2926                 if (ast_channel_masquerade(p->sub->owner, ast_bridged_channel(p->sub->next->owner))) {
2927                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
2928                                 ast_bridged_channel(p->sub->next->owner)->name, p->sub->owner->name);
2929                         return -1;
2930                 }
2931                 /*swap_subs(p, SUB_THREEWAY, SUB_REAL);*/
2932                 ast_verb(3, "Swapping %d for %d on %s@%s\n", p->sub->id, p->sub->next->id, p->name, p->parent->name);
2933                 p->sub = p->sub->next;
2934                 unalloc_sub(p->sub->next);
2935                 /* Tell the caller not to hangup */
2936                 return 1;
2937         } else {
2938                 ast_debug(1, "Neither %s nor %s are in a bridge, nothing to transfer\n",
2939                         p->sub->owner->name, p->sub->next->owner->name);
2940                 p->sub->next->owner->_softhangup |= AST_SOFTHANGUP_DEV;
2941                 if (p->sub->next->owner) {
2942                         p->sub->next->alreadygone = 1;
2943                         mgcp_queue_hangup(p->sub->next);
2944                 }
2945         }
2946         return 0;
2947 }
2948
2949 static void handle_hd_hf(struct mgcp_subchannel *sub, char *ev) 
2950 {
2951         struct mgcp_endpoint *p = sub->parent;
2952         struct ast_channel *c;
2953         pthread_t t;
2954
2955         /* Off hook / answer */
2956         if (sub->outgoing) {
2957                 /* Answered */
2958                 if (sub->owner) {
2959                         if (ast_bridged_channel(sub->owner))
2960                                 ast_queue_control(sub->owner, AST_CONTROL_UNHOLD);
2961                         sub->cxmode = MGCP_CX_SENDRECV;
2962                         if (!sub->rtp) {
2963                                 start_rtp(sub);
2964                         } else {
2965                                 transmit_modify_request(sub);
2966                         }
2967                         /*transmit_notify_request(sub, "aw");*/
2968                         transmit_notify_request(sub, "");
2969                         mgcp_queue_control(sub, AST_CONTROL_ANSWER);
2970                 }
2971         } else {
2972                 /* Start switch */
2973                 /*sub->cxmode = MGCP_CX_SENDRECV;*/
2974                 if (!sub->owner) {
2975                         if (!sub->rtp) {
2976                                 start_rtp(sub);
2977                         } else {
2978                                 transmit_modify_request(sub);
2979                         }
2980                         if (p->immediate) {
2981                                 /* The channel is immediately up. Start right away */
2982 #ifdef DLINK_BUGGY_FIRMWARE     
2983                                 transmit_notify_request(sub, "rt");
2984 #else
2985                                 transmit_notify_request(sub, "G/rt");
2986 #endif          
2987                                 c = mgcp_new(sub, AST_STATE_RING);
2988                                 if (!c) {
2989                                         ast_log(LOG_WARNING, "Unable to start PBX on channel %s@%s\n", p->name, p->parent->name);
2990                                         transmit_notify_request(sub, "G/cg");
2991                                         ast_hangup(c);
2992                                 }
2993                         } else {
2994                                 if (has_voicemail(p)) {
2995                                         transmit_notify_request(sub, "L/sl");
2996                                 } else {
2997                                         transmit_notify_request(sub, "L/dl");
2998                                 }
2999                                 c = mgcp_new(sub, AST_STATE_DOWN);
3000                                 if (c) {
3001                                         if (ast_pthread_create_detached(&t, NULL, mgcp_ss, c)) {
3002                                                 ast_log(LOG_WARNING, "Unable to create switch thread: %s\n", strerror(errno));
3003                                                 ast_hangup(c);
3004                                         }
3005                                 } else {
3006                                         ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", p->name, p->parent->name);
3007                                 }
3008                         }
3009                 } else {
3010                         if (p->hookstate == MGCP_OFFHOOK) {
3011                                 ast_log(LOG_WARNING, "Off hook, but already have owner on %s@%s\n", p->name, p->parent->name);
3012                         } else {
3013                                 ast_log(LOG_WARNING, "On hook, but already have owner on %s@%s\n", p->name, p->parent->name);
3014                                 ast_log(LOG_WARNING, "If we're onhook why are we here trying to handle a hd or hf?\n");
3015                         }
3016                         if (ast_bridged_channel(sub->owner))
3017                                 ast_queue_control(sub->owner, AST_CONTROL_UNHOLD);
3018                         sub->cxmode = MGCP_CX_SENDRECV;
3019                         if (!sub->rtp) {
3020                                 start_rtp(sub);
3021                         } else {
3022                                 transmit_modify_request(sub);
3023                         }
3024                         /*transmit_notify_request(sub, "aw");*/
3025                         transmit_notify_request(sub, "");
3026                         /*ast_queue_control(sub->owner, AST_CONTROL_ANSWER);*/
3027                 }
3028         }
3029 }
3030
3031 static int handle_request(struct mgcp_subchannel *sub, struct mgcp_request *req, struct sockaddr_in *sin)
3032 {
3033         char *ev, *s;
3034         struct ast_frame f = { 0, };
3035         struct mgcp_endpoint *p = sub->parent;
3036         struct mgcp_gateway *g = NULL;
3037         int res;
3038
3039         if (mgcpdebug) {
3040                 ast_verbose("Handling request '%s' on %s@%s\n", req->verb, p->name, p->parent->name);
3041         }
3042         /* Clear out potential response */
3043         if (!strcasecmp(req->verb, "RSIP")) {
3044                 /* Test if this RSIP request is just a keepalive */
3045                 if(!strcasecmp( get_header(req, "RM"), "X-keepalive")) {
3046                         ast_verb(3, "Received keepalive request from %s@%s\n", p->name, p->parent->name);
3047                         transmit_response(sub, "200", req, "OK");
3048                 } else {
3049                         dump_queue(p->parent, p);
3050                         dump_cmd_queues(p, NULL);
3051                         
3052                         if ((strcmp(p->name, p->parent->wcardep) != 0)) {
3053                                 ast_verb(3, "Resetting interface %s@%s\n", p->name, p->parent->name);
3054                         }
3055                         /* For RSIP on wildcard we reset all endpoints */
3056                         if (!strcmp(p->name, p->parent->wcardep)) {
3057                                 /* Reset all endpoints */
3058                                 struct mgcp_endpoint *tmp_ep;
3059                                 
3060                                 g = p->parent;
3061                                 tmp_ep = g->endpoints;
3062                                 while (tmp_ep) {
3063                                         /*if ((strcmp(tmp_ep->name, "*") != 0) && (strcmp(tmp_ep->name, "aaln/" "*") != 0)) {*/
3064                                         if (strcmp(tmp_ep->name, g->wcardep) != 0) {
3065                                                 struct mgcp_subchannel *tmp_sub, *first_sub;
3066                                                 ast_verb(3, "Resetting interface %s@%s\n", tmp_ep->name, p->parent->name);
3067                                                 
3068                                                 first_sub = tmp_ep->sub;
3069                                                 tmp_sub = tmp_ep->sub;
3070                                                 while (tmp_sub) {
3071                                                         mgcp_queue_hangup(tmp_sub);
3072                                                         tmp_sub = tmp_sub->next;
3073                                                         if (tmp_sub == first_sub)
3074                                                                 break;
3075                                                 }
3076                                         }
3077                                         tmp_ep = tmp_ep->next;
3078                                 }
3079                         } else if (sub->owner) {
3080                                 mgcp_queue_hangup(sub);
3081                         }
3082                         transmit_response(sub, "200", req, "OK");
3083                         /* We dont send NTFY or AUEP to wildcard ep */
3084                         if (strcmp(p->name, p->parent->wcardep) != 0) {
3085                                 transmit_notify_request(sub, "");
3086                                 /* Audit endpoint. 
3087                                  Idea is to prevent lost lines due to race conditions 
3088                                 */
3089                                 transmit_audit_endpoint(p);
3090                         }
3091                 }
3092         } else if (!strcasecmp(req->verb, "NTFY")) {
3093                 /* Acknowledge and be sure we keep looking for the same things */
3094                 transmit_response(sub, "200", req, "OK");
3095                 /* Notified of an event */
3096                 ev = get_header(req, "O");
3097                 s = strchr(ev, '/');
3098                 if (s) ev = s + 1;
3099                 ast_debug(1, "Endpoint '%s@%s-%d' observed '%s'\n", p->name, p->parent->name, sub->id, ev);
3100                 /* Keep looking for events unless this was a hangup */
3101                 if (strcasecmp(ev, "hu") && strcasecmp(ev, "hd") && strcasecmp(ev, "ping")) {
3102                         transmit_notify_request(sub, p->curtone);
3103                 }
3104                 if (!strcasecmp(ev, "hd")) {
3105                         p->hookstate = MGCP_OFFHOOK;
3106                         sub->cxmode = MGCP_CX_SENDRECV;
3107                         handle_hd_hf(sub, ev);
3108                 } else if (!strcasecmp(ev, "hf")) {
3109                         /* We can assume we are offhook if we received a hookflash */
3110                         /* First let's just do call wait and ignore threeway */
3111                         /* We're currently in charge */
3112                         if (p->hookstate != MGCP_OFFHOOK) {
3113                                 /* Cisco c7940 sends hf even if the phone is onhook */
3114                                 /* Thanks to point on IRC for pointing this out */
3115                                 return -1;
3116                         }
3117                         /* do not let * conference two down channels */  
3118                         if (sub->owner && sub->owner->_state == AST_STATE_DOWN && !sub->next->owner)
3119                                 return -1;
3120
3121                         if (p->callwaiting || p->transfer || p->threewaycalling) {
3122                                 ast_verb(3, "Swapping %d for %d on %s@%s\n", p->sub->id, p->sub->next->id, p->name, p->parent->name);
3123                                 p->sub = p->sub->next;
3124
3125                                 /* transfer control to our next subchannel */
3126                                 if (!sub->next->owner) {
3127                                         /* plave the first call on hold and start up a new call */
3128                                         sub->cxmode = MGCP_CX_MUTE;
3129                                         ast_verb(3, "MGCP Muting %d on %s@%s\n", sub->id, p->name, p->parent->name);
3130                                         transmit_modify_request(sub);
3131                                         if (sub->owner && ast_bridged_channel(sub->owner))
3132                                                 ast_queue_control(sub->owner, AST_CONTROL_HOLD);
3133                                         sub->next->cxmode = MGCP_CX_RECVONLY;
3134                                         handle_hd_hf(sub->next, ev);
3135                                 } else if (sub->owner && sub->next->owner) {
3136                                         /* We've got two active calls lets decide whether or not to conference or just flip flop */
3137                                         if ((!sub->outgoing) && (!sub->next->outgoing)) {
3138                                                 /* We made both calls lets conferenct */
3139                                                 ast_verb(3, "MGCP Conferencing %d and %d on %s@%s\n",
3140                                                                 sub->id, sub->next->id, p->name, p->parent->name);
3141                                                 sub->cxmode = MGCP_CX_CONF;
3142                                                 sub->next->cxmode = MGCP_CX_CONF;
3143                                                 if (ast_bridged_channel(sub->next->owner))
3144                                                         ast_queue_control(sub->next->owner, AST_CONTROL_UNHOLD);
3145                                                 transmit_modify_request(sub);
3146                                                 transmit_modify_request(sub->next);
3147                                         } else {
3148                                                 /* Let's flipflop between calls */
3149                                                 /* XXX Need to check for state up ??? */
3150                                                 /* XXX Need a way to indicate the current call, or maybe the call that's waiting */
3151                                                 ast_verb(3, "We didn't make one of the calls FLIPFLOP %d and %d on %s@%s\n",
3152                                                                 sub->id, sub->next->id, p->name, p->parent->name);
3153                                                 sub->cxmode = MGCP_CX_MUTE;
3154                                                 ast_verb(3, "MGCP Muting %d on %s@%s\n", sub->id, p->name, p->parent->name);
3155                                                 transmit_modify_request(sub);
3156                                                 if (ast_bridged_channel(sub->owner))
3157                                                         ast_queue_control(sub->owner, AST_CONTROL_HOLD);
3158                         
3159                                                 if (ast_bridged_channel(sub->next->owner)) 
3160                                                         ast_queue_control(sub->next->owner, AST_CONTROL_HOLD);
3161                         
3162                                                 handle_hd_hf(sub->next, ev);
3163                                         }
3164                                 } else {
3165                                         /* We've most likely lost one of our calls find an active call and bring it up */
3166                                         if (sub->owner) {
3167                                                 p->sub = sub;
3168                                         } else if (sub->next->owner) {
3169                                                 p->sub = sub->next;
3170                                         } else {
3171                                                 /* We seem to have lost both our calls */
3172                                                 /* XXX - What do we do now? */
3173                                                 return -1;
3174                                         }
3175                                         if (ast_bridged_channel(p->sub->owner))
3176                                                 ast_queue_control(p->sub->owner, AST_CONTROL_UNHOLD);
3177                                         p->sub->cxmode = MGCP_CX_SENDRECV;
3178                                         transmit_modify_request(p->sub);
3179                                 }
3180                         } else {
3181                                 ast_log(LOG_WARNING, "Callwaiting, call transfer or threeway calling not enabled on endpoint %s@%s\n", 
3182                                         p->name, p->parent->name);
3183                         }
3184                 } else if (!strcasecmp(ev, "hu")) {
3185                         p->hookstate = MGCP_ONHOOK;
3186                         sub->cxmode = MGCP_CX_RECVONLY;
3187                         ast_debug(1, "MGCP %s@%s Went on hook\n", p->name, p->parent->name);
3188                         /* Do we need to send MDCX before a DLCX ?
3189                         if (sub->rtp) {
3190                                 transmit_modify_request(sub);
3191                         }
3192                         */
3193                         if (p->transfer && (sub->owner && sub->next->owner) && ((!sub->outgoing) || (!sub->next->outgoing))) {
3194                                 /* We're allowed to transfer, we have two avtive calls and */
3195                                 /* we made at least one of the calls.  Let's try and transfer */
3196                                 ast_mutex_lock(&p->sub->next->lock);
3197                                 res = attempt_transfer(p);
3198                                 if (res < 0) {
3199                                         if (p->sub->next->owner) {
3200                                                 sub->next->alreadygone = 1;
3201                                                 mgcp_queue_hangup(sub->next);
3202                                         }
3203                                 } else if (res) {
3204                                         ast_log(LOG_WARNING, "Transfer attempt failed\n");
3205                                         ast_mutex_unlock(&p->sub->next->lock);
3206                                         return -1;
3207                                 }
3208                                 ast_mutex_unlock(&p->sub->next->lock);
3209                         } else {
3210                                 /* Hangup the current call */
3211                                 /* If there is another active call, mgcp_hangup will ring the phone with the other call */
3212                                 if (sub->owner) {
3213                                         sub->alreadygone = 1;
3214                                         mgcp_queue_hangup(sub);
3215                                 } else {
3216                                         ast_verb(3, "MGCP handle_request(%s@%s-%d) ast_channel already destroyed, resending DLCX.\n",
3217                                                         p->name, p->parent->name, sub->id);
3218                                         /* Instruct the other side to remove the connection since it apparently *
3219                                          * still thinks the channel is active. *
3220                                          * For Cisco IAD2421 /BAK/ */
3221                                         transmit_connection_del(sub);
3222                                 }
3223                         }
3224                         if ((p->hookstate == MGCP_ONHOOK) && (!sub->rtp) && (!sub->next->rtp)) {
3225                                 p->hidecallerid = 0;
3226                                 if (p->hascallwaiting && !p->callwaiting) {
3227                                         ast_verb(3, "Enabling call waiting on MGCP/%s@%s-%d\n", p->name, p->parent->name, sub->id);
3228                                         p->callwaiting = -1;
3229                                 }
3230                                 if (has_voicemail(p)) {
3231                                         ast_verb(3, "MGCP handle_request(%s@%s) set vmwi(+)\n", p->name, p->parent->name);
3232                                         transmit_notify_request(sub, "L/vmwi(+)");
3233                                 } else {
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                                 }
3237                         }
3238                 } else if ((strlen(ev) == 1) && 
3239                                 (((ev[0] >= '0') && (ev[0] <= '9')) ||
3240                                  ((ev[0] >= 'A') && (ev[0] <= 'D')) ||
3241                                   (ev[0] == '*') || (ev[0] == '#'))) {
3242                         if (sub && sub->owner && (sub->owner->_state >=  AST_STATE_UP)) {
3243                                 f.frametype = AST_FRAME_DTMF;
3244                                 f.subclass = ev[0];
3245                                 f.src = "mgcp";
3246                                 /* XXX MUST queue this frame to all subs in threeway call if threeway call is active */
3247                                 mgcp_queue_frame(sub, &f);
3248                                 ast_mutex_lock(&sub->next->lock);
3249                                 if (sub->next->owner)
3250                                         mgcp_queue_frame(sub->next, &f);
3251                                 ast_mutex_unlock(&sub->next->lock);
3252                                 if (strstr(p->curtone, "wt") && (ev[0] == 'A')) {
3253                                         memset(p->curtone, 0, sizeof(p->curtone));
3254                                 }
3255                         } else {
3256                                 p->dtmf_buf[strlen(p->dtmf_buf)] = ev[0];
3257                                 p->dtmf_buf[strlen(p->dtmf_buf)] = '\0';
3258                         }
3259                 } else if (!strcasecmp(ev, "T")) {
3260                         /* Digit timeout -- unimportant */
3261                 } else if (!strcasecmp(ev, "ping")) {
3262                         /* ping -- unimportant */
3263                 } else {
3264                         ast_log(LOG_NOTICE, "Received unknown event '%s' from %s@%s\n", ev, p->name, p->parent->name);
3265                 }
3266         } else {
3267                 ast_log(LOG_WARNING, "Unknown verb '%s' received from %s\n", req->verb, ast_inet_ntoa(sin->sin_addr));
3268                 transmit_response(sub, "510", req, "Unknown verb");
3269         }
3270         return 0;
3271 }
3272
3273 static int find_and_retrans(struct mgcp_subchannel *sub, struct mgcp_request *req)
3274 {
3275         int seqno=0;
3276         time_t now;
3277         struct mgcp_response *prev = NULL, *cur, *next, *answer=NULL;
3278         time(&now);
3279         if (sscanf(req->identifier, "%d", &seqno) != 1) 
3280                 seqno = 0;
3281         cur = sub->parent->parent->responses;
3282         while(cur) {
3283                 next = cur->next;
3284                 if (now - cur->whensent > RESPONSE_TIMEOUT) {
3285                         /* Delete this entry */
3286                         if (prev)
3287                                 prev->next = next;
3288                         else
3289                                 sub->parent->parent->responses = next;
3290                         ast_free(cur);
3291                 } else {
3292                         if (seqno == cur->seqno)
3293                                 answer = cur;
3294                         prev = cur;
3295                 }
3296                 cur = next;
3297         }
3298         if (answer) {
3299                 resend_response(sub, answer);
3300                 return 1;
3301         }
3302         return 0;
3303 }
3304
3305 static int mgcpsock_read(int *id, int fd, short events, void *ignore)
3306 {
3307         struct mgcp_request req;
3308         struct sockaddr_in sin;
3309         struct mgcp_subchannel *sub;
3310         int res;
3311         socklen_t len;
3312         int result;
3313         int ident;
3314         len = sizeof(sin);
3315         memset(&req, 0, sizeof(req));
3316         res = recvfrom(mgcpsock, req.data, sizeof(req.data) - 1, 0, (struct sockaddr *)&sin, &len);
3317         if (res < 0) {
3318                 if (errno != ECONNREFUSED)
3319                         ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
3320                 return 1;
3321         }
3322         req.data[res] = '\0';
3323         req.len = res;
3324         if (mgcpdebug) {
3325                 ast_verbose("MGCP read: \n%s\nfrom %s:%d\n", req.data, ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
3326         }
3327         parse(&req);
3328         if (req.headers < 1) {
3329                 /* Must have at least one header */
3330                 return 1;
3331         }
3332         if (ast_strlen_zero(req.identifier)) {
3333                 ast_log(LOG_NOTICE, "Message from %s missing identifier\n", ast_inet_ntoa(sin.sin_addr));
3334                 return 1;
3335         }
3336
3337         if (sscanf(req.verb, "%d", &result) && sscanf(req.identifier, "%d", &ident)) {
3338                 /* Try to find who this message is for, if it's important */
3339                 sub = find_subchannel_and_lock(NULL, ident, &sin);
3340                 if (sub) {
3341                         struct mgcp_gateway *gw = sub->parent->parent;
3342                         struct mgcp_message *cur, *prev;
3343
3344                         ast_mutex_unlock(&sub->lock);
3345                         ast_mutex_lock(&gw->msgs_lock);
3346                         for (prev = NULL, cur = gw->msgs; cur; prev = cur, cur = cur->next) {
3347                                 if (cur->seqno == ident) {
3348                                         ast_debug(1, "Got response back on transaction %d\n", ident);
3349                                         if (prev)
3350                                                 prev->next = cur->next;
3351