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