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