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