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