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