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