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