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