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