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