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