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