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