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