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