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