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