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