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