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