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