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