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