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