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