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