2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
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.
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.
21 * \brief Implementation of Media Gateway Control Protocol
23 * \author Mark Spencer <markster@digium.com>
26 * \arg \ref Config_mgcp
28 * \ingroup channel_drivers
33 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
35 #include <sys/socket.h>
36 #include <sys/ioctl.h>
40 #include <sys/signal.h>
42 #include <netinet/in.h>
43 #include <netinet/in_systm.h>
44 #include <netinet/ip.h>
45 #include <arpa/inet.h>
48 #include "asterisk/lock.h"
49 #include "asterisk/channel.h"
50 #include "asterisk/config.h"
51 #include "asterisk/module.h"
52 #include "asterisk/pbx.h"
53 #include "asterisk/sched.h"
54 #include "asterisk/io.h"
55 #include "asterisk/rtp_engine.h"
56 #include "asterisk/acl.h"
57 #include "asterisk/callerid.h"
58 #include "asterisk/cli.h"
59 #include "asterisk/say.h"
60 #include "asterisk/cdr.h"
61 #include "asterisk/astdb.h"
62 #include "asterisk/features.h"
63 #include "asterisk/app.h"
64 #include "asterisk/musiconhold.h"
65 #include "asterisk/utils.h"
66 #include "asterisk/netsock.h"
67 #include "asterisk/causes.h"
68 #include "asterisk/dsp.h"
69 #include "asterisk/devicestate.h"
70 #include "asterisk/stringfields.h"
71 #include "asterisk/abstract_jb.h"
72 #include "asterisk/event.h"
73 #include "asterisk/chanvars.h"
74 #include "asterisk/pktccops.h"
77 * Define to work around buggy dlink MGCP phone firmware which
78 * appears not to know that "rt" is part of the "G" package.
80 /* #define DLINK_BUGGY_FIRMWARE */
83 #define DEFAULT_EXPIRY 120
84 #define MAX_EXPIRY 3600
88 #define INADDR_NONE (in_addr_t)(-1)
91 /*! Global jitterbuffer configuration - by default, jb is disabled */
92 static struct ast_jb_conf default_jbconf =
96 .resync_threshold = -1,
99 static struct ast_jb_conf global_jbconf;
101 static const char tdesc[] = "Media Gateway Control Protocol (MGCP)";
102 static const char config[] = "mgcp.conf";
104 #define MGCP_DTMF_RFC2833 (1 << 0)
105 #define MGCP_DTMF_INBAND (1 << 1)
106 #define MGCP_DTMF_HYBRID (1 << 2)
108 #define DEFAULT_MGCP_GW_PORT 2427 /*!< From RFC 2705 */
109 #define DEFAULT_MGCP_CA_PORT 2727 /*!< From RFC 2705 */
110 #define MGCP_MAX_PACKET 1500 /*!< Also from RFC 2543, should sub headers tho */
111 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit */
112 #define MAX_RETRANS 5 /*!< Try only 5 times for retransmissions */
114 /*! MGCP rtp stream modes { */
115 #define MGCP_CX_SENDONLY 0
116 #define MGCP_CX_RECVONLY 1
117 #define MGCP_CX_SENDRECV 2
118 #define MGCP_CX_CONF 3
119 #define MGCP_CX_CONFERENCE 3
120 #define MGCP_CX_MUTE 4
121 #define MGCP_CX_INACTIVE 4
124 static const char * const mgcp_cxmodes[] = {
144 static char context[AST_MAX_EXTENSION] = "default";
146 static char language[MAX_LANGUAGE] = "";
147 static char musicclass[MAX_MUSICCLASS] = "";
148 static char parkinglot[AST_MAX_CONTEXT];
149 static char cid_num[AST_MAX_EXTENSION] = "";
150 static char cid_name[AST_MAX_EXTENSION] = "";
152 static int dtmfmode = 0;
155 static int pktcgatealloc = 0;
156 static int hangupongateremove = 0;
158 static ast_group_t cur_callergroup = 0;
159 static ast_group_t cur_pickupgroup = 0;
163 unsigned int tos_audio;
165 unsigned int cos_audio;
166 } qos = { 0, 0, 0, 0 };
168 static int immediate = 0;
170 static int callwaiting = 0;
172 static int callreturn = 0;
174 static int slowsequence = 0;
176 static int threewaycalling = 0;
178 /*! This is for flashhook transfers */
179 static int transfer = 0;
181 static int cancallforward = 0;
183 static int singlepath = 0;
185 static int directmedia = DIRECTMEDIA;
187 static char accountcode[AST_MAX_ACCOUNT_CODE] = "";
189 static char mailbox[AST_MAX_EXTENSION];
191 static int amaflags = 0;
195 static unsigned int oseq;
197 /*! Wait up to 16 seconds for first digit (FXO logic) */
198 static int firstdigittimeout = 16000;
200 /*! How long to wait for following digits (FXO logic) */
201 static int gendigittimeout = 8000;
203 /*! How long to wait for an extra digit, if there is an ambiguous match */
204 static int matchdigittimeout = 3000;
206 /*! Protect the monitoring thread, so only one process can kill or start it, and not
207 when it's doing something critical. */
208 AST_MUTEX_DEFINE_STATIC(netlock);
210 AST_MUTEX_DEFINE_STATIC(monlock);
212 /*! This is the thread for the monitor which checks for input on the channels
213 * which are not currently in use.
215 static pthread_t monitor_thread = AST_PTHREADT_NULL;
217 static int restart_monitor(void);
219 static format_t capability = AST_FORMAT_ULAW;
220 static int nonCodecCapability = AST_RTP_DTMF;
222 static char ourhost[MAXHOSTNAMELEN];
223 static struct in_addr __ourip;
226 static int mgcpdebug = 0;
228 static struct sched_context *sched;
229 static struct io_context *io;
230 /*! The private structures of the mgcp channels are linked for
231 * selecting outgoing channels
234 #define MGCP_MAX_HEADERS 64
235 #define MGCP_MAX_LINES 64
237 struct mgcp_request {
243 int headers; /*!< MGCP Headers */
244 char *header[MGCP_MAX_HEADERS];
245 int lines; /*!< SDP Content */
246 char *line[MGCP_MAX_LINES];
247 char data[MGCP_MAX_PACKET];
248 int cmd; /*!< int version of verb = command */
249 unsigned int trid; /*!< int version of identifier = transaction id */
250 struct mgcp_request *next; /*!< next in the queue */
253 /*! \brief mgcp_message: MGCP message for queuing up */
254 struct mgcp_message {
255 struct mgcp_endpoint *owner_ep;
256 struct mgcp_subchannel *owner_sub;
258 unsigned long expire;
261 struct mgcp_message *next;
265 #define RESPONSE_TIMEOUT 30 /*!< in seconds */
267 struct mgcp_response {
271 struct mgcp_response *next;
280 struct mgcp_subchannel {
281 /*! subchannel magic string.
282 Needed to prove that any subchannel pointer passed by asterisk
283 really points to a valid subchannel memory area.
284 Ugly.. But serves the purpose for the time being.
286 #define MGCP_SUBCHANNEL_MAGIC "!978!"
290 struct ast_channel *owner;
291 struct mgcp_endpoint *parent;
292 struct ast_rtp_instance *rtp;
293 struct sockaddr_in tmpdest;
294 char txident[80]; /*! \todo FIXME txident is replaced by rqnt_ident in endpoint.
295 This should be obsoleted */
299 struct mgcp_request *cx_queue; /*!< pending CX commands */
300 ast_mutex_t cx_queue_lock; /*!< CX queue lock */
302 int iseq; /*!< Not used? RTP? */
306 struct cops_gate *gate;
307 struct mgcp_subchannel *next; /*!< for out circular linked list */
310 #define MGCP_ONHOOK 1
311 #define MGCP_OFFHOOK 2
316 struct mgcp_endpoint {
319 struct mgcp_subchannel *sub; /*!< Pointer to our current connection, channel and stuff */
320 char accountcode[AST_MAX_ACCOUNT_CODE];
321 char exten[AST_MAX_EXTENSION]; /*!< Extention where to start */
322 char context[AST_MAX_EXTENSION];
323 char language[MAX_LANGUAGE];
324 char cid_num[AST_MAX_EXTENSION]; /*!< Caller*ID number */
325 char cid_name[AST_MAX_EXTENSION]; /*!< Caller*ID name */
326 char lastcallerid[AST_MAX_EXTENSION]; /*!< Last Caller*ID */
327 char dtmf_buf[AST_MAX_EXTENSION]; /*!< place to collect digits be */
328 char call_forward[AST_MAX_EXTENSION]; /*!< Last Caller*ID */
329 char musicclass[MAX_MUSICCLASS];
330 char curtone[80]; /*!< Current tone */
331 char mailbox[AST_MAX_EXTENSION];
332 char parkinglot[AST_MAX_CONTEXT]; /*!< Parkinglot */
333 struct ast_event_sub *mwi_event_sub;
334 ast_group_t callgroup;
335 ast_group_t pickupgroup;
344 int dnd; /* How does this affect callwait? Do we just deny a mgcp_request if we're dnd? */
351 int hangupongateremove;
353 int slowsequence; /*!< MS: Sequence the endpoint as a whole */
355 int iseq; /*!< Not used? */
356 int lastout; /*!< tracking this on the subchannels. Is it needed here? */
357 int needdestroy; /*!< Not used? */
359 int nonCodecCapability;
361 int msgstate; /*!< voicemail message state */
365 char rqnt_ident[80]; /*!< request identifier */
366 struct mgcp_request *rqnt_queue; /*!< pending RQNT commands */
367 ast_mutex_t rqnt_queue_lock;
368 struct mgcp_request *cmd_queue; /*!< pending commands other than RQNT */
369 ast_mutex_t cmd_queue_lock;
370 int delme; /*!< needed for reload */
371 int needaudit; /*!< needed for reload */
372 struct ast_dsp *dsp; /*!< XXX Should there be a dsp/subchannel? XXX */
373 /* owner is tracked on the subchannels, and the *sub indicates whos in charge */
374 /* struct ast_channel *owner; */
375 /* struct ast_rtp *rtp; */
376 /* struct sockaddr_in tmpdest; */
377 /* message go the the endpoint and not the channel so they stay here */
378 struct ast_variable *chanvars; /*!< Variables to set for channel created by user */
379 struct mgcp_endpoint *next;
380 struct mgcp_gateway *parent;
383 static struct mgcp_gateway {
384 /* A gateway containing one or more endpoints */
386 int isnamedottedip; /*!< is the name FQDN or dotted ip */
387 struct sockaddr_in addr;
388 struct sockaddr_in defaddr;
389 struct in_addr ourip;
391 int expire; /*!< XXX Should we ever expire dynamic registrations? XXX */
392 struct mgcp_endpoint *endpoints;
399 /* Wildcard endpoint name */
401 struct mgcp_message *msgs; /*!< gw msg queue */
402 ast_mutex_t msgs_lock; /*!< queue lock */
403 int retransid; /*!< retrans timer id */
404 int delme; /*!< needed for reload */
406 struct mgcp_response *responses;
407 struct mgcp_gateway *next;
410 AST_MUTEX_DEFINE_STATIC(mgcp_reload_lock);
411 static int mgcp_reloading = 0;
413 /*! \brief gatelock: mutex for gateway/endpoint lists */
414 AST_MUTEX_DEFINE_STATIC(gatelock);
416 static int mgcpsock = -1;
418 static struct sockaddr_in bindaddr;
420 static struct ast_frame *mgcp_read(struct ast_channel *ast);
421 static int transmit_response(struct mgcp_subchannel *sub, char *msg, struct mgcp_request *req, char *msgrest);
422 static int transmit_notify_request(struct mgcp_subchannel *sub, char *tone);
423 static int transmit_modify_request(struct mgcp_subchannel *sub);
424 static int transmit_connect(struct mgcp_subchannel *sub);
425 static int transmit_notify_request_with_callerid(struct mgcp_subchannel *sub, char *tone, char *callernum, char *callername);
426 static int transmit_modify_with_sdp(struct mgcp_subchannel *sub, struct ast_rtp_instance *rtp, format_t codecs);
427 static int transmit_connection_del(struct mgcp_subchannel *sub);
428 static int transmit_audit_endpoint(struct mgcp_endpoint *p);
429 static void start_rtp(struct mgcp_subchannel *sub);
430 static void handle_response(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,
431 int result, unsigned int ident, struct mgcp_request *resp);
432 static void dump_cmd_queues(struct mgcp_endpoint *p, struct mgcp_subchannel *sub);
433 static char *mgcp_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
434 static int reload_config(int reload);
436 static struct ast_channel *mgcp_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
437 static int mgcp_call(struct ast_channel *ast, char *dest, int timeout);
438 static int mgcp_hangup(struct ast_channel *ast);
439 static int mgcp_answer(struct ast_channel *ast);
440 static struct ast_frame *mgcp_read(struct ast_channel *ast);
441 static int mgcp_write(struct ast_channel *ast, struct ast_frame *frame);
442 static int mgcp_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen);
443 static int mgcp_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
444 static int mgcp_senddigit_begin(struct ast_channel *ast, char digit);
445 static int mgcp_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
446 static int mgcp_devicestate(void *data);
447 static void add_header_offhook(struct mgcp_subchannel *sub, struct mgcp_request *resp, char *tone);
448 static int transmit_connect_with_sdp(struct mgcp_subchannel *sub, struct ast_rtp_instance *rtp);
449 static struct mgcp_gateway *build_gateway(char *cat, struct ast_variable *v);
450 static int mgcp_alloc_pktcgate(struct mgcp_subchannel *sub);
451 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
452 static struct ast_variable *add_var(const char *buf, struct ast_variable *list);
453 static struct ast_variable *copy_vars(struct ast_variable *src);
455 static const struct ast_channel_tech mgcp_tech = {
457 .description = tdesc,
458 .capabilities = AST_FORMAT_ULAW | AST_FORMAT_ALAW,
459 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
460 .requester = mgcp_request,
461 .devicestate = mgcp_devicestate,
463 .hangup = mgcp_hangup,
464 .answer = mgcp_answer,
467 .indicate = mgcp_indicate,
469 .send_digit_begin = mgcp_senddigit_begin,
470 .send_digit_end = mgcp_senddigit_end,
471 .bridge = ast_rtp_instance_bridge,
472 .func_channel_read = acf_channel_read,
475 static void mwi_event_cb(const struct ast_event *event, void *userdata)
477 /* This module does not handle MWI in an event-based manner. However, it
478 * subscribes to MWI for each mailbox that is configured so that the core
479 * knows that we care about it. Then, chan_mgcp will get the MWI from the
480 * event cache instead of checking the mailbox directly. */
483 static int has_voicemail(struct mgcp_endpoint *p)
486 struct ast_event *event;
489 cntx = mbox = ast_strdupa(p->mailbox);
491 if (ast_strlen_zero(cntx))
494 event = ast_event_get_cached(AST_EVENT_MWI,
495 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mbox,
496 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, cntx,
500 new_msgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
501 ast_event_destroy(event);
503 new_msgs = ast_app_has_voicemail(p->mailbox, NULL);
508 static int unalloc_sub(struct mgcp_subchannel *sub)
510 struct mgcp_endpoint *p = sub->parent;
512 ast_log(LOG_WARNING, "Trying to unalloc the real channel %s@%s?!?\n", p->name, p->parent->name);
515 ast_debug(1, "Released sub %d of channel %s@%s\n", sub->id, p->name, p->parent->name);
518 if (!ast_strlen_zero(sub->cxident)) {
519 transmit_connection_del(sub);
521 sub->cxident[0] = '\0';
522 sub->callid[0] = '\0';
523 sub->cxmode = MGCP_CX_INACTIVE;
525 sub->alreadygone = 0;
526 memset(&sub->tmpdest, 0, sizeof(sub->tmpdest));
528 ast_rtp_instance_destroy(sub->rtp);
531 dump_cmd_queues(NULL, sub);
535 /* modified for new transport mechanism */
536 static int __mgcp_xmit(struct mgcp_gateway *gw, char *data, int len)
539 if (gw->addr.sin_addr.s_addr)
540 res=sendto(mgcpsock, data, len, 0, (struct sockaddr *)&gw->addr, sizeof(struct sockaddr_in));
542 res=sendto(mgcpsock, data, len, 0, (struct sockaddr *)&gw->defaddr, sizeof(struct sockaddr_in));
544 ast_log(LOG_WARNING, "mgcp_xmit returned %d: %s\n", res, strerror(errno));
549 static int resend_response(struct mgcp_subchannel *sub, struct mgcp_response *resp)
551 struct mgcp_endpoint *p = sub->parent;
553 ast_debug(1, "Retransmitting:\n%s\n to %s:%d\n", resp->buf, ast_inet_ntoa(p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
554 res = __mgcp_xmit(p->parent, resp->buf, resp->len);
560 static int send_response(struct mgcp_subchannel *sub, struct mgcp_request *req)
562 struct mgcp_endpoint *p = sub->parent;
564 ast_debug(1, "Transmitting:\n%s\n to %s:%d\n", req->data, ast_inet_ntoa(p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
565 res = __mgcp_xmit(p->parent, req->data, req->len);
571 /* modified for new transport framework */
572 static void dump_queue(struct mgcp_gateway *gw, struct mgcp_endpoint *p)
574 struct mgcp_message *cur, *q = NULL, *w, *prev;
576 ast_mutex_lock(&gw->msgs_lock);
577 for (prev = NULL, cur = gw->msgs; cur; prev = cur, cur = cur->next) {
578 if (!p || cur->owner_ep == p) {
580 prev->next = cur->next;
582 gw->msgs = cur->next;
585 ast_log(LOG_NOTICE, "Removing message from %s transaction %u\n",
586 gw->name, cur->seqno);
597 ast_mutex_unlock(&gw->msgs_lock);
606 static void mgcp_queue_frame(struct mgcp_subchannel *sub, struct ast_frame *f)
610 if (!ast_channel_trylock(sub->owner)) {
611 ast_queue_frame(sub->owner, f);
612 ast_channel_unlock(sub->owner);
615 DEADLOCK_AVOIDANCE(&sub->lock);
623 static void mgcp_queue_hangup(struct mgcp_subchannel *sub)
627 if (!ast_channel_trylock(sub->owner)) {
628 ast_queue_hangup(sub->owner);
629 ast_channel_unlock(sub->owner);
632 DEADLOCK_AVOIDANCE(&sub->lock);
640 static void mgcp_queue_control(struct mgcp_subchannel *sub, int control)
642 struct ast_frame f = { AST_FRAME_CONTROL, { control } };
643 return mgcp_queue_frame(sub, &f);
646 static int retrans_pkt(const void *data)
648 struct mgcp_gateway *gw = (struct mgcp_gateway *)data;
649 struct mgcp_message *cur, *exq = NULL, *w, *prev;
652 /* find out expired msgs */
653 ast_mutex_lock(&gw->msgs_lock);
655 for (prev = NULL, cur = gw->msgs; cur; prev = cur, cur = cur->next) {
656 if (cur->retrans < MAX_RETRANS) {
658 ast_debug(1, "Retransmitting #%d transaction %u on [%s]\n",
659 cur->retrans, cur->seqno, gw->name);
660 __mgcp_xmit(gw, cur->buf, cur->len);
663 prev->next = cur->next;
665 gw->msgs = cur->next;
667 ast_log(LOG_WARNING, "Maximum retries exceeded for transaction %u on [%s]\n",
668 cur->seqno, gw->name);
687 ast_mutex_unlock(&gw->msgs_lock);
691 /* time-out transaction */
692 handle_response(cur->owner_ep, cur->owner_sub, 406, cur->seqno, NULL);
700 /* modified for the new transaction mechanism */
701 static int mgcp_postrequest(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,
702 char *data, int len, unsigned int seqno)
704 struct mgcp_message *msg;
705 struct mgcp_message *cur;
706 struct mgcp_gateway *gw;
709 if (!(msg = ast_malloc(sizeof(*msg) + len))) {
712 if (!(gw = ((p && p->parent) ? p->parent : NULL))) {
717 msg->owner_sub = sub;
723 memcpy(msg->buf, data, msg->len);
725 ast_mutex_lock(&gw->msgs_lock);
726 for (cur = gw->msgs; cur && cur->next; cur = cur->next);
734 msg->expire = now.tv_sec * 1000 + now.tv_usec / 1000 + DEFAULT_RETRANS;
736 if (gw->retransid == -1)
737 gw->retransid = ast_sched_add(sched, DEFAULT_RETRANS, retrans_pkt, (void *)gw);
738 ast_mutex_unlock(&gw->msgs_lock);
739 __mgcp_xmit(gw, msg->buf, msg->len);
740 /* XXX Should schedule retransmission XXX */
744 /* modified for new transport */
745 static int send_request(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,
746 struct mgcp_request *req, unsigned int seqno)
749 struct mgcp_request **queue, *q, *r, *t;
752 ast_debug(1, "Slow sequence is %d\n", p->slowsequence);
753 if (p->slowsequence) {
754 queue = &p->cmd_queue;
755 l = &p->cmd_queue_lock;
760 queue = &sub->cx_queue;
761 l = &sub->cx_queue_lock;
764 /* delete pending cx cmds */
766 if (!sub->parent->ncs) {
778 queue = &sub->cx_queue;
779 l = &sub->cx_queue_lock;
784 queue = &p->rqnt_queue;
785 l = &p->rqnt_queue_lock;
790 queue = &p->cmd_queue;
791 l = &p->cmd_queue_lock;
797 if (!(r = ast_malloc(sizeof(*r)))) {
798 ast_log(LOG_WARNING, "Cannot post MGCP request: insufficient memory\n");
802 memcpy(r, req, sizeof(*r));
805 ast_debug(1, "Posting Request:\n%s to %s:%d\n", req->data,
806 ast_inet_ntoa(p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
808 res = mgcp_postrequest(p, sub, req->data, req->len, seqno);
810 ast_debug(1, "Queueing Request:\n%s to %s:%d\n", req->data,
811 ast_inet_ntoa(p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
814 /* XXX find tail. We could also keep tail in the data struct for faster access */
815 for (t = *queue; t && t->next; t = t->next);
828 static int mgcp_call(struct ast_channel *ast, char *dest, int timeout)
831 struct mgcp_endpoint *p;
832 struct mgcp_subchannel *sub;
834 const char *distinctive_ring = NULL;
835 struct varshead *headp;
836 struct ast_var_t *current;
838 ast_debug(3, "MGCP mgcp_call(%s)\n", ast->name);
841 headp = &ast->varshead;
842 AST_LIST_TRAVERSE(headp,current,entries) {
843 /* Check whether there is an ALERT_INFO variable */
844 if (strcasecmp(ast_var_name(current),"ALERT_INFO") == 0) {
845 distinctive_ring = ast_var_value(current);
849 ast_mutex_lock(&sub->lock);
850 switch (p->hookstate) {
852 if (!ast_strlen_zero(distinctive_ring)) {
853 snprintf(tone, sizeof(tone), "L/wt%s", distinctive_ring);
854 ast_debug(3, "MGCP distinctive callwait %s\n", tone);
856 ast_copy_string(tone, (p->ncs ? "L/wt1" : "L/wt"), sizeof(tone));
857 ast_debug(3, "MGCP normal callwait %s\n", tone);
862 if (!ast_strlen_zero(distinctive_ring)) {
863 snprintf(tone, sizeof(tone), "L/r%s", distinctive_ring);
864 ast_debug(3, "MGCP distinctive ring %s\n", tone);
866 ast_copy_string(tone, "L/rg", sizeof(tone));
867 ast_debug(3, "MGCP default ring\n");
872 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
873 ast_log(LOG_WARNING, "mgcp_call called on %s, neither down nor reserved\n", ast->name);
874 ast_mutex_unlock(&sub->lock);
880 sub->cxmode = MGCP_CX_RECVONLY;
881 ast_setstate(ast, AST_STATE_RINGING);
882 if (p->type == TYPE_LINE) {
886 transmit_modify_request(sub);
889 if (sub->next->owner && !ast_strlen_zero(sub->next->cxident) && !ast_strlen_zero(sub->next->callid)) {
890 /* try to prevent a callwait from disturbing the other connection */
891 sub->next->cxmode = MGCP_CX_RECVONLY;
892 transmit_modify_request(sub->next);
895 transmit_notify_request_with_callerid(sub, tone, ast->connected.id.number, ast->connected.id.name);
896 ast_setstate(ast, AST_STATE_RINGING);
898 if (sub->next->owner && !ast_strlen_zero(sub->next->cxident) && !ast_strlen_zero(sub->next->callid)) {
899 /* Put the connection back in sendrecv */
900 sub->next->cxmode = MGCP_CX_SENDRECV;
901 transmit_modify_request(sub->next);
904 ast_log(LOG_NOTICE, "Don't know how to dial on trunks yet\n");
907 ast_mutex_unlock(&sub->lock);
911 static int mgcp_hangup(struct ast_channel *ast)
913 struct mgcp_subchannel *sub = ast->tech_pvt;
914 struct mgcp_endpoint *p = sub->parent;
916 ast_debug(1, "mgcp_hangup(%s)\n", ast->name);
917 if (!ast->tech_pvt) {
918 ast_debug(1, "Asked to hangup channel not connected\n");
921 if (strcmp(sub->magic, MGCP_SUBCHANNEL_MAGIC)) {
922 ast_debug(1, "Invalid magic. MGCP subchannel freed up already.\n");
925 ast_mutex_lock(&sub->lock);
926 ast_debug(3, "MGCP mgcp_hangup(%s) on %s@%s\n", ast->name, p->name, p->parent->name);
928 if ((p->dtmfmode & MGCP_DTMF_INBAND) && p->dsp) {
929 /* check whether other channel is active. */
930 if (!sub->next->owner) {
931 if (p->dtmfmode & MGCP_DTMF_HYBRID) {
932 p->dtmfmode &= ~MGCP_DTMF_INBAND;
934 ast_debug(2, "MGCP free dsp on %s@%s\n", p->name, p->parent->name);
935 ast_dsp_free(p->dsp);
942 /* for deleting gate */
943 if (p->pktcgatealloc && sub->gate) {
944 sub->gate->gate_open = NULL;
945 sub->gate->gate_remove = NULL;
946 sub->gate->got_dq_gi = NULL;
947 sub->gate->tech_pvt = NULL;
948 if (sub->gate->state == GATE_ALLOC_PROGRESS || sub->gate->state == GATE_ALLOCATED) {
949 ast_pktccops_gate_alloc(GATE_DEL, sub->gate, 0, 0, 0, 0, 0, 0, NULL, NULL);
951 sub->gate->deltimer = time(NULL) + 5;
956 if (!ast_strlen_zero(sub->cxident)) {
957 transmit_connection_del(sub);
959 sub->cxident[0] = '\0';
960 if ((sub == p->sub) && sub->next->owner) {
961 if (p->hookstate == MGCP_OFFHOOK) {
962 if (sub->next->owner && ast_bridged_channel(sub->next->owner)) {
964 transmit_notify_request_with_callerid(p->sub, (p->ncs ? "L/wt1" : "L/wt"), ast_bridged_channel(sub->next->owner)->cid.cid_num, ast_bridged_channel(sub->next->owner)->cid.cid_name);
967 /* set our other connection as the primary and swith over to it */
969 p->sub->cxmode = MGCP_CX_RECVONLY;
970 transmit_modify_request(p->sub);
971 if (sub->next->owner && ast_bridged_channel(sub->next->owner)) {
972 transmit_notify_request_with_callerid(p->sub, "L/rg", ast_bridged_channel(sub->next->owner)->cid.cid_num, ast_bridged_channel(sub->next->owner)->cid.cid_name);
976 } else if ((sub == p->sub->next) && p->hookstate == MGCP_OFFHOOK) {
977 transmit_notify_request(sub, p->ncs ? "" : "L/v");
978 } else if (p->hookstate == MGCP_OFFHOOK) {
979 transmit_notify_request(sub, "L/ro");
981 transmit_notify_request(sub, "");
984 ast->tech_pvt = NULL;
985 sub->alreadygone = 0;
987 sub->cxmode = MGCP_CX_INACTIVE;
988 sub->callid[0] = '\0';
990 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
992 /* Reset temporary destination */
993 memset(&sub->tmpdest, 0, sizeof(sub->tmpdest));
995 ast_rtp_instance_destroy(sub->rtp);
999 ast_module_unref(ast_module_info->self);
1001 if ((p->hookstate == MGCP_ONHOOK) && (!sub->next->rtp)) {
1002 p->hidecallerid = 0;
1003 if (p->hascallwaiting && !p->callwaiting) {
1004 ast_verb(3, "Enabling call waiting on %s\n", ast->name);
1005 p->callwaiting = -1;
1007 if (has_voicemail(p)) {
1008 ast_debug(3, "MGCP mgcp_hangup(%s) on %s@%s set vmwi(+)\n",
1009 ast->name, p->name, p->parent->name);
1010 transmit_notify_request(sub, "L/vmwi(+)");
1012 ast_debug(3, "MGCP mgcp_hangup(%s) on %s@%s set vmwi(-)\n",
1013 ast->name, p->name, p->parent->name);
1014 transmit_notify_request(sub, "L/vmwi(-)");
1017 ast_mutex_unlock(&sub->lock);
1021 static char *handle_mgcp_show_endpoints(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1023 struct mgcp_gateway *mg;
1024 struct mgcp_endpoint *me;
1025 int hasendpoints = 0;
1026 struct ast_variable * v = NULL;
1030 e->command = "mgcp show endpoints";
1032 "Usage: mgcp show endpoints\n"
1033 " Lists all endpoints known to the MGCP (Media Gateway Control Protocol) subsystem.\n";
1040 return CLI_SHOWUSAGE;
1042 ast_mutex_lock(&gatelock);
1043 for (mg = gateways; mg; mg = mg->next) {
1044 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");
1045 for (me = mg->endpoints; me; me = me->next) {
1046 ast_cli(a->fd, " -- '%s@%s in '%s' is %s\n", me->name, mg->name, me->context, me->sub->owner ? "active" : "idle");
1048 ast_cli(a->fd, " Variables:\n");
1049 for (v = me->chanvars ; v ; v = v->next) {
1050 ast_cli(a->fd, " %s = '%s'\n", v->name, v->value);
1055 if (!hasendpoints) {
1056 ast_cli(a->fd, " << No Endpoints Defined >> ");
1059 ast_mutex_unlock(&gatelock);
1063 static char *handle_mgcp_audit_endpoint(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1065 struct mgcp_gateway *mg;
1066 struct mgcp_endpoint *me;
1068 char *ename,*gname, *c;
1072 e->command = "mgcp audit endpoint";
1074 "Usage: mgcp audit endpoint <endpointid>\n"
1075 " Lists the capabilities of an endpoint in the MGCP (Media Gateway Control Protocol) subsystem.\n"
1076 " mgcp debug MUST be on to see the results of this command.\n";
1083 return CLI_SHOWUSAGE;
1086 return CLI_SHOWUSAGE;
1087 /* split the name into parts by null */
1088 ename = ast_strdupa(a->argv[3]);
1089 for (gname = ename; *gname; gname++) {
1090 if (*gname == '@') {
1096 if (gname[0] == '[') {
1099 if ((c = strrchr(gname, ']'))) {
1102 ast_mutex_lock(&gatelock);
1103 for (mg = gateways; mg; mg = mg->next) {
1104 if (!strcasecmp(mg->name, gname)) {
1105 for (me = mg->endpoints; me; me = me->next) {
1106 if (!strcasecmp(me->name, ename)) {
1108 transmit_audit_endpoint(me);
1118 ast_cli(a->fd, " << Could not find endpoint >> ");
1120 ast_mutex_unlock(&gatelock);
1124 static char *handle_mgcp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1128 e->command = "mgcp set debug {on|off}";
1130 "Usage: mgcp set debug {on|off}\n"
1131 " Enables/Disables dumping of MGCP packets for debugging purposes\n";
1137 if (a->argc != e->args)
1138 return CLI_SHOWUSAGE;
1140 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
1142 ast_cli(a->fd, "MGCP Debugging Enabled\n");
1143 } else if (!strncasecmp(a->argv[3], "off", 3)) {
1145 ast_cli(a->fd, "MGCP Debugging Disabled\n");
1147 return CLI_SHOWUSAGE;
1152 static struct ast_cli_entry cli_mgcp[] = {
1153 AST_CLI_DEFINE(handle_mgcp_audit_endpoint, "Audit specified MGCP endpoint"),
1154 AST_CLI_DEFINE(handle_mgcp_show_endpoints, "List defined MGCP endpoints"),
1155 AST_CLI_DEFINE(handle_mgcp_set_debug, "Enable/Disable MGCP debugging"),
1156 AST_CLI_DEFINE(mgcp_reload, "Reload MGCP configuration"),
1159 static int mgcp_answer(struct ast_channel *ast)
1162 struct mgcp_subchannel *sub = ast->tech_pvt;
1163 struct mgcp_endpoint *p = sub->parent;
1165 ast_mutex_lock(&sub->lock);
1166 sub->cxmode = MGCP_CX_SENDRECV;
1170 transmit_modify_request(sub);
1172 ast_verb(3, "MGCP mgcp_answer(%s) on %s@%s-%d\n",
1173 ast->name, p->name, p->parent->name, sub->id);
1174 if (ast->_state != AST_STATE_UP) {
1175 ast_setstate(ast, AST_STATE_UP);
1176 ast_debug(1, "mgcp_answer(%s)\n", ast->name);
1177 transmit_notify_request(sub, "");
1178 transmit_modify_request(sub);
1180 ast_mutex_unlock(&sub->lock);
1184 static struct ast_frame *mgcp_rtp_read(struct mgcp_subchannel *sub)
1186 /* Retrieve audio/etc from channel. Assumes sub->lock is already held. */
1187 struct ast_frame *f;
1189 f = ast_rtp_instance_read(sub->rtp, 0);
1190 /* Don't send RFC2833 if we're not supposed to */
1191 if (f && (f->frametype == AST_FRAME_DTMF) && !(sub->parent->dtmfmode & MGCP_DTMF_RFC2833))
1192 return &ast_null_frame;
1194 /* We already hold the channel lock */
1195 if (f->frametype == AST_FRAME_VOICE) {
1196 if (f->subclass.codec != sub->owner->nativeformats) {
1197 ast_debug(1, "Oooh, format changed to %s\n", ast_getformatname(f->subclass.codec));
1198 sub->owner->nativeformats = f->subclass.codec;
1199 ast_set_read_format(sub->owner, sub->owner->readformat);
1200 ast_set_write_format(sub->owner, sub->owner->writeformat);
1202 /* Courtesy fearnor aka alex@pilosoft.com */
1203 if ((sub->parent->dtmfmode & MGCP_DTMF_INBAND) && (sub->parent->dsp)) {
1205 ast_log(LOG_NOTICE, "MGCP ast_dsp_process\n");
1207 f = ast_dsp_process(sub->owner, sub->parent->dsp, f);
1215 static struct ast_frame *mgcp_read(struct ast_channel *ast)
1217 struct ast_frame *f;
1218 struct mgcp_subchannel *sub = ast->tech_pvt;
1219 ast_mutex_lock(&sub->lock);
1220 f = mgcp_rtp_read(sub);
1221 ast_mutex_unlock(&sub->lock);
1225 static int mgcp_write(struct ast_channel *ast, struct ast_frame *frame)
1227 struct mgcp_subchannel *sub = ast->tech_pvt;
1231 if (frame->frametype != AST_FRAME_VOICE) {
1232 if (frame->frametype == AST_FRAME_IMAGE)
1235 ast_log(LOG_WARNING, "Can't send %d type frames with MGCP write\n", frame->frametype);
1239 if (!(frame->subclass.codec & ast->nativeformats)) {
1240 ast_log(LOG_WARNING, "Asked to transmit frame type %s, while native formats is %s (read/write = %s/%s)\n",
1241 ast_getformatname(frame->subclass.codec),
1242 ast_getformatname_multiple(buf, sizeof(buf), ast->nativeformats),
1243 ast_getformatname(ast->readformat),
1244 ast_getformatname(ast->writeformat));
1249 ast_mutex_lock(&sub->lock);
1250 if (!sub->sdpsent && sub->gate) {
1251 if (sub->gate->state == GATE_ALLOCATED) {
1252 ast_debug(1, "GATE ALLOCATED, sending sdp\n");
1253 transmit_modify_with_sdp(sub, NULL, 0);
1256 if ((sub->parent->sub == sub) || !sub->parent->singlepath) {
1258 res = ast_rtp_instance_write(sub->rtp, frame);
1261 ast_mutex_unlock(&sub->lock);
1266 static int mgcp_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1268 struct mgcp_subchannel *sub = newchan->tech_pvt;
1270 ast_mutex_lock(&sub->lock);
1271 ast_log(LOG_NOTICE, "mgcp_fixup(%s, %s)\n", oldchan->name, newchan->name);
1272 if (sub->owner != oldchan) {
1273 ast_mutex_unlock(&sub->lock);
1274 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, sub->owner);
1277 sub->owner = newchan;
1278 ast_mutex_unlock(&sub->lock);
1282 static int mgcp_senddigit_begin(struct ast_channel *ast, char digit)
1284 struct mgcp_subchannel *sub = ast->tech_pvt;
1285 struct mgcp_endpoint *p = sub->parent;
1288 ast_mutex_lock(&sub->lock);
1289 if (p->dtmfmode & MGCP_DTMF_INBAND || p->dtmfmode & MGCP_DTMF_HYBRID) {
1290 ast_debug(1, "Sending DTMF using inband/hybrid\n");
1291 res = -1; /* Let asterisk play inband indications */
1292 } else if (p->dtmfmode & MGCP_DTMF_RFC2833) {
1293 ast_debug(1, "Sending DTMF using RFC2833");
1294 ast_rtp_instance_dtmf_begin(sub->rtp, digit);
1296 ast_log(LOG_ERROR, "Don't know about DTMF_MODE %d\n", p->dtmfmode);
1298 ast_mutex_unlock(&sub->lock);
1303 static int mgcp_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
1305 struct mgcp_subchannel *sub = ast->tech_pvt;
1306 struct mgcp_endpoint *p = sub->parent;
1310 ast_mutex_lock(&sub->lock);
1311 if (p->dtmfmode & MGCP_DTMF_INBAND || p->dtmfmode & MGCP_DTMF_HYBRID) {
1312 ast_debug(1, "Stopping DTMF using inband/hybrid\n");
1313 res = -1; /* Tell Asterisk to stop inband indications */
1314 } else if (p->dtmfmode & MGCP_DTMF_RFC2833) {
1315 ast_debug(1, "Stopping DTMF using RFC2833\n");
1316 if (sub->parent->ncs) {
1325 transmit_notify_request(sub, tmp);
1326 ast_rtp_instance_dtmf_end(sub->rtp, digit);
1328 ast_log(LOG_ERROR, "Don't know about DTMF_MODE %d\n", p->dtmfmode);
1330 ast_mutex_unlock(&sub->lock);
1336 * \brief mgcp_devicestate: channel callback for device status monitoring
1337 * \param data tech/resource name of MGCP device to query
1339 * Callback for device state management in channel subsystem
1340 * to obtain device status (up/down) of a specific MGCP endpoint
1342 * \return device status result (from devicestate.h) AST_DEVICE_INVALID (not available) or AST_DEVICE_UNKNOWN (available but unknown state)
1344 static int mgcp_devicestate(void *data)
1346 struct mgcp_gateway *g;
1347 struct mgcp_endpoint *e = NULL;
1348 char *tmp, *endpt, *gw;
1349 int ret = AST_DEVICE_INVALID;
1351 endpt = ast_strdupa(data);
1352 if ((tmp = strchr(endpt, '@'))) {
1358 ast_mutex_lock(&gatelock);
1359 for (g = gateways; g; g = g->next) {
1360 if (strcasecmp(g->name, gw) == 0) {
1369 for (; e; e = e->next) {
1370 if (strcasecmp(e->name, endpt) == 0) {
1379 * As long as the gateway/endpoint is valid, we'll
1380 * assume that the device is available and its state
1383 ret = AST_DEVICE_UNKNOWN;
1386 ast_mutex_unlock(&gatelock);
1390 static char *control2str(int ind) {
1392 case AST_CONTROL_HANGUP:
1393 return "Other end has hungup";
1394 case AST_CONTROL_RING:
1395 return "Local ring";
1396 case AST_CONTROL_RINGING:
1397 return "Remote end is ringing";
1398 case AST_CONTROL_ANSWER:
1399 return "Remote end has answered";
1400 case AST_CONTROL_BUSY:
1401 return "Remote end is busy";
1402 case AST_CONTROL_TAKEOFFHOOK:
1403 return "Make it go off hook";
1404 case AST_CONTROL_OFFHOOK:
1405 return "Line is off hook";
1406 case AST_CONTROL_CONGESTION:
1407 return "Congestion (circuits busy)";
1408 case AST_CONTROL_FLASH:
1409 return "Flash hook";
1410 case AST_CONTROL_WINK:
1412 case AST_CONTROL_OPTION:
1413 return "Set a low-level option";
1414 case AST_CONTROL_RADIO_KEY:
1416 case AST_CONTROL_RADIO_UNKEY:
1417 return "Un-Key Radio";
1422 static int mgcp_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen)
1424 struct mgcp_subchannel *sub = ast->tech_pvt;
1427 ast_debug(3, "MGCP asked to indicate %d '%s' condition on channel %s\n",
1428 ind, control2str(ind), ast->name);
1429 ast_mutex_lock(&sub->lock);
1431 case AST_CONTROL_RINGING:
1432 #ifdef DLINK_BUGGY_FIRMWARE
1433 transmit_notify_request(sub, "rt");
1435 if (!sub->sdpsent) { /* will hide the inband progress!!! */
1436 transmit_notify_request(sub, sub->parent->ncs ? "L/rt" : "G/rt");
1440 case AST_CONTROL_BUSY:
1441 transmit_notify_request(sub, "L/bz");
1443 case AST_CONTROL_CONGESTION:
1444 transmit_notify_request(sub, sub->parent->ncs ? "L/cg" : "G/cg");
1446 case AST_CONTROL_HOLD:
1447 ast_moh_start(ast, data, NULL);
1449 case AST_CONTROL_UNHOLD:
1452 case AST_CONTROL_SRCUPDATE:
1453 ast_rtp_instance_new_source(sub->rtp);
1455 case AST_CONTROL_PROGRESS:
1456 case AST_CONTROL_PROCEEDING:
1457 transmit_modify_request(sub);
1459 transmit_notify_request(sub, "");
1462 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", ind);
1465 ast_mutex_unlock(&sub->lock);
1469 static struct ast_channel *mgcp_new(struct mgcp_subchannel *sub, int state, const char *linkedid)
1471 struct ast_channel *tmp;
1472 struct ast_variable *v = NULL;
1473 struct mgcp_endpoint *i = sub->parent;
1476 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);
1478 tmp->tech = &mgcp_tech;
1479 tmp->nativeformats = i->capability;
1480 if (!tmp->nativeformats) {
1481 tmp->nativeformats = capability;
1483 fmt = ast_best_codec(tmp->nativeformats);
1485 ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(sub->rtp, 0));
1487 if (i->dtmfmode & (MGCP_DTMF_INBAND | MGCP_DTMF_HYBRID)) {
1488 i->dsp = ast_dsp_new();
1489 ast_dsp_set_features(i->dsp, DSP_FEATURE_DIGIT_DETECT);
1490 /* this is to prevent clipping of dtmf tones during dsp processing */
1491 ast_dsp_set_digitmode(i->dsp, DSP_DIGITMODE_NOQUELCH);
1495 if (state == AST_STATE_RING)
1497 tmp->writeformat = fmt;
1498 tmp->rawwriteformat = fmt;
1499 tmp->readformat = fmt;
1500 tmp->rawreadformat = fmt;
1501 tmp->tech_pvt = sub;
1502 if (!ast_strlen_zero(i->language))
1503 ast_string_field_set(tmp, language, i->language);
1504 if (!ast_strlen_zero(i->accountcode))
1505 ast_string_field_set(tmp, accountcode, i->accountcode);
1507 tmp->amaflags = i->amaflags;
1509 ast_module_ref(ast_module_info->self);
1510 tmp->callgroup = i->callgroup;
1511 tmp->pickupgroup = i->pickupgroup;
1512 ast_string_field_set(tmp, call_forward, i->call_forward);
1513 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
1514 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
1516 /* Don't use ast_set_callerid() here because it will
1517 * generate a needless NewCallerID event */
1518 tmp->cid.cid_ani = ast_strdup(i->cid_num);
1521 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1525 /* Set channel variables for this call from configuration */
1526 for (v = i->chanvars ; v ; v = v->next) {
1527 char valuebuf[1024];
1528 pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
1532 ast_jb_configure(tmp, &global_jbconf);
1534 if (state != AST_STATE_DOWN) {
1535 if (ast_pbx_start(tmp)) {
1536 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1541 ast_verb(3, "MGCP mgcp_new(%s) created in state: %s\n",
1542 tmp->name, ast_state2str(state));
1544 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1549 static char *get_sdp_by_line(char* line, char *name, int nameLen)
1551 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1552 char *r = line + nameLen + 1;
1553 while (*r && (*r < 33)) ++r;
1559 static char *get_sdp(struct mgcp_request *req, char *name)
1562 int len = strlen(name);
1565 for (x = 0; x < req->lines; x++) {
1566 r = get_sdp_by_line(req->line[x], name, len);
1567 if (r[0] != '\0') return r;
1572 static void sdpLineNum_iterator_init(int *iterator)
1577 static char *get_sdp_iterate(int* iterator, struct mgcp_request *req, char *name)
1579 int len = strlen(name);
1581 while (*iterator < req->lines) {
1582 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1583 if (r[0] != '\0') return r;
1588 static char *__get_header(struct mgcp_request *req, char *name, int *start, char *def)
1591 int len = strlen(name);
1593 for (x = *start; x < req->headers; x++) {
1594 if (!strncasecmp(req->header[x], name, len) &&
1595 (req->header[x][len] == ':')) {
1596 r = req->header[x] + len + 1;
1597 while (*r && (*r < 33)) {
1604 /* Don't return NULL, so get_header is always a valid pointer */
1608 static char *get_header(struct mgcp_request *req, char *name)
1611 return __get_header(req, name, &start, "");
1614 /*! \brief get_csv: (SC:) get comma separated value */
1615 static char *get_csv(char *c, int *len, char **next)
1619 *next = NULL, *len = 0;
1620 if (!c) return NULL;
1622 while (*c && (*c < 33 || *c == ',')) {
1627 while (*c && (*c >= 33 && *c != ',')) {
1633 s = NULL, *next = NULL;
1639 static struct mgcp_gateway *find_realtime_gw(char *name, char *at, struct sockaddr_in *sin)
1641 struct mgcp_gateway *g = NULL;
1642 struct ast_variable *mgcpgwconfig = NULL;
1643 struct ast_variable *mgcpepconfig = NULL;
1644 struct ast_variable *gwv, *epname = NULL;
1645 struct mgcp_endpoint *e;
1646 char *c = NULL, *line;
1651 ast_debug(1, "*** find Realtime MGCPGW\n");
1653 if (!(i = ast_check_realtime("mgcpgw")) || !(j = ast_check_realtime("mgcpep"))) {
1657 if (ast_strlen_zero(at)) {
1658 ast_debug(1, "null gw name\n");
1662 if (!(mgcpgwconfig = ast_load_realtime("mgcpgw", "name", at, NULL))) {
1667 for (gwv = mgcpgwconfig; gwv; gwv = gwv->next) {
1668 if (!strcasecmp(gwv->name, "lines")) {
1669 ast_copy_string(lines, gwv->value, sizeof(lines));
1673 for (gwv = gwv && gwv->next ? gwv : mgcpgwconfig; gwv->next; gwv = gwv->next);
1674 if (!ast_strlen_zero(lines)) {
1675 for (c = lines, line = tmp; *c; c++) {
1679 mgcpepconfig = ast_load_realtime("mgcpep", "name", at, "line", tmp, NULL);
1680 gwv->next = mgcpepconfig;
1683 if (!strcasecmp(gwv->next->name, "line")) {
1685 gwv->next = gwv->next->next;
1690 /* moving the line var to the end */
1693 epname->next = NULL;
1696 mgcpepconfig = NULL;
1703 for (gwv = mgcpgwconfig; gwv; gwv = gwv->next) {
1704 ast_debug(1, "MGCP Realtime var: %s => %s\n", gwv->name, gwv->value);
1708 g = build_gateway(at, mgcpgwconfig);
1709 ast_variables_destroy(mgcpgwconfig);
1715 for (e = g->endpoints; e; e = e->next) {
1716 transmit_audit_endpoint(e);
1723 static struct mgcp_subchannel *find_subchannel_and_lock(char *name, int msgid, struct sockaddr_in *sin)
1725 struct mgcp_endpoint *p = NULL;
1726 struct mgcp_subchannel *sub = NULL;
1727 struct mgcp_gateway *g;
1729 char *at = NULL, *c;
1732 ast_copy_string(tmp, name, sizeof(tmp));
1733 at = strchr(tmp, '@');
1735 ast_log(LOG_NOTICE, "Endpoint '%s' has no at sign!\n", name);
1740 ast_mutex_lock(&gatelock);
1741 if (at && (at[0] == '[')) {
1743 c = strrchr(at, ']');
1748 for (g = gateways ? gateways : find_realtime_gw(name, at, sin); g; g = g->next ? g->next : find_realtime_gw(name, at, sin)) {
1749 if ((!name || !strcasecmp(g->name, at)) &&
1750 (sin || g->addr.sin_addr.s_addr || g->defaddr.sin_addr.s_addr)) {
1751 /* Found the gateway. If it's dynamic, save it's address -- now for the endpoint */
1752 if (sin && g->dynamic && name) {
1753 if ((g->addr.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1754 (g->addr.sin_port != sin->sin_port)) {
1755 memcpy(&g->addr, sin, sizeof(g->addr));
1756 if (ast_ouraddrfor(&g->addr.sin_addr, &g->ourip))
1757 memcpy(&g->ourip, &__ourip, sizeof(g->ourip));
1758 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));
1760 /* not dynamic, check if the name matches */
1762 if (strcasecmp(g->name, at)) {
1766 /* not dynamic, no name, check if the addr matches */
1767 } else if (!name && sin) {
1768 if ((g->addr.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1769 (g->addr.sin_port != sin->sin_port)) {
1771 g = find_realtime_gw(name, at, sin);
1779 for (p = g->endpoints; p; p = p->next) {
1780 ast_debug(1, "Searching on %s@%s for subchannel\n", p->name, g->name);
1785 } else if (name && !strcasecmp(p->name, tmp)) {
1786 ast_debug(1, "Coundn't determine subchannel, assuming current master %s@%s-%d\n",
1787 p->name, g->name, p->sub->id);
1794 ast_mutex_lock(&sub->lock);
1799 ast_mutex_unlock(&gatelock);
1803 ast_log(LOG_NOTICE, "Endpoint '%s' not found on gateway '%s'\n", tmp, at);
1805 ast_log(LOG_NOTICE, "Gateway '%s' (and thus its endpoint '%s') does not exist\n", at, tmp);
1812 static void parse(struct mgcp_request *req)
1814 /* Divide fields by NULL's */
1819 /* First header starts immediately */
1823 /* We've got a new header */
1825 ast_debug(3, "Header: %s (%d)\n", req->header[f], (int) strlen(req->header[f]));
1826 if (ast_strlen_zero(req->header[f])) {
1827 /* Line by itself means we're now in content */
1831 if (f >= MGCP_MAX_HEADERS - 1) {
1832 ast_log(LOG_WARNING, "Too many MGCP headers...\n");
1836 req->header[f] = c + 1;
1837 } else if (*c == '\r') {
1838 /* Ignore but eliminate \r's */
1842 /* Check for last header */
1843 if (!ast_strlen_zero(req->header[f])) {
1847 /* Now we process any mime content */
1852 /* We've got a new line */
1854 ast_debug(3, "Line: %s (%d)\n", req->line[f], (int) strlen(req->line[f]));
1855 if (f >= MGCP_MAX_LINES - 1) {
1856 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1860 req->line[f] = c + 1;
1861 } else if (*c == '\r') {
1862 /* Ignore and eliminate \r's */
1866 /* Check for last line */
1867 if (!ast_strlen_zero(req->line[f])) {
1871 /* Parse up the initial header */
1873 while (*c && *c < 33) c++;
1874 /* First the verb */
1876 while (*c && (*c > 32)) c++;
1880 while (*c && (*c < 33)) c++;
1881 req->identifier = c;
1882 while (*c && (*c > 32)) c++;
1886 while (*c && (*c < 33)) c++;
1888 while (*c && (*c > 32)) c++;
1892 while (*c && (*c < 33)) c++;
1894 while (*c && (*c > 32)) c++;
1895 while (*c && (*c < 33)) c++;
1896 while (*c && (*c > 32)) c++;
1902 ast_debug(1, "Verb: '%s', Identifier: '%s', Endpoint: '%s', Version: '%s'\n",
1903 req->verb, req->identifier, req->endpoint, req->version);
1904 ast_debug(1, "%d headers, %d lines\n", req->headers, req->lines);
1906 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1910 static int process_sdp(struct mgcp_subchannel *sub, struct mgcp_request *req)
1918 format_t peercapability;
1919 int peerNonCodecCapability;
1920 struct sockaddr_in sin;
1922 struct ast_hostent ahp; struct hostent *hp;
1923 int codec, codec_count=0;
1925 struct mgcp_endpoint *p = sub->parent;
1926 char tmp1[256], tmp2[256], tmp3[256];
1928 /* Get codec and RTP info from SDP */
1929 m = get_sdp(req, "m");
1930 c = get_sdp(req, "c");
1931 if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
1932 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1935 if (sscanf(c, "IN IP4 %256s", host) != 1) {
1936 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1939 /* XXX This could block for a long time, and block the main thread! XXX */
1940 hp = ast_gethostbyname(host, &ahp);
1942 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1945 if (sscanf(m, "audio %30d RTP/AVP %n", &portno, &len) != 1) {
1946 ast_log(LOG_WARNING, "Unable to determine port number for RTP in '%s'\n", m);
1949 sin.sin_family = AF_INET;
1950 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1951 sin.sin_port = htons(portno);
1952 ast_rtp_instance_set_remote_address(sub->rtp, &sin);
1953 ast_debug(3, "Peer RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1954 /* Scan through the RTP payload types specified in a "m=" line: */
1955 ast_rtp_codecs_payloads_clear(ast_rtp_instance_get_codecs(sub->rtp), sub->rtp);
1956 codecs = ast_strdupa(m + len);
1957 while (!ast_strlen_zero(codecs)) {
1958 if (sscanf(codecs, "%30d%n", &codec, &len) != 1) {
1962 ast_log(LOG_WARNING, "Error in codec string '%s' at '%s'\n", m, codecs);
1965 ast_rtp_codecs_payloads_set_m_type(ast_rtp_instance_get_codecs(sub->rtp), sub->rtp, codec);
1970 /* Next, scan through each "a=rtpmap:" line, noting each */
1971 /* specified RTP payload type (with corresponding MIME subtype): */
1972 sdpLineNum_iterator_init(&iterator);
1973 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
1974 char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
1975 if (sscanf(a, "rtpmap: %30u %127[^/]/", &codec, mimeSubtype) != 2)
1977 /* Note: should really look at the 'freq' and '#chans' params too */
1978 ast_rtp_codecs_payloads_set_rtpmap_type(ast_rtp_instance_get_codecs(sub->rtp), sub->rtp, codec, "audio", mimeSubtype, 0);
1981 /* Now gather all of the codecs that were asked for: */
1982 ast_rtp_codecs_payload_formats(ast_rtp_instance_get_codecs(sub->rtp), &peercapability, &peerNonCodecCapability);
1983 p->capability = capability & peercapability;
1984 ast_debug(1, "Capabilities: us - %s, them - %s, combined - %s\n",
1985 ast_getformatname_multiple(tmp1, sizeof(tmp1), capability),
1986 ast_getformatname_multiple(tmp2, sizeof(tmp2), peercapability),
1987 ast_getformatname_multiple(tmp3, sizeof(tmp3), p->capability));
1988 ast_debug(1, "Non-codec capabilities: us - %d, them - %d, combined - %d\n",
1989 nonCodecCapability, peerNonCodecCapability, p->nonCodecCapability);
1990 if (!p->capability) {
1991 ast_log(LOG_WARNING, "No compatible codecs!\n");
1997 static int add_header(struct mgcp_request *req, const char *var, const char *value)
1999 if (req->len >= sizeof(req->data) - 4) {
2000 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2004 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
2007 req->header[req->headers] = req->data + req->len;
2008 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s: %s\r\n", var, value);
2009 req->len += strlen(req->header[req->headers]);
2010 if (req->headers < MGCP_MAX_HEADERS) {
2013 ast_log(LOG_WARNING, "Out of header space\n");
2019 static int add_line(struct mgcp_request *req, char *line)
2021 if (req->len >= sizeof(req->data) - 4) {
2022 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2026 /* Add extra empty return */
2027 ast_copy_string(req->data + req->len, "\r\n", sizeof(req->data) - req->len);
2028 req->len += strlen(req->data + req->len);
2030 req->line[req->lines] = req->data + req->len;
2031 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
2032 req->len += strlen(req->line[req->lines]);
2033 if (req->lines < MGCP_MAX_LINES) {
2036 ast_log(LOG_WARNING, "Out of line space\n");
2042 static int init_resp(struct mgcp_request *req, char *resp, struct mgcp_request *orig, char *resprest)
2044 /* Initialize a response */
2045 if (req->headers || req->len) {
2046 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2049 req->header[req->headers] = req->data + req->len;
2050 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s %s\r\n", resp, orig->identifier, resprest);
2051 req->len += strlen(req->header[req->headers]);
2052 if (req->headers < MGCP_MAX_HEADERS) {
2055 ast_log(LOG_WARNING, "Out of header space\n");
2060 static int init_req(struct mgcp_endpoint *p, struct mgcp_request *req, char *verb)
2062 /* Initialize a response */
2063 if (req->headers || req->len) {
2064 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2067 req->header[req->headers] = req->data + req->len;
2068 /* check if we need brackets around the gw name */
2069 if (p->parent->isnamedottedip) {
2070 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" : "");
2072 + 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" : "");
2074 req->len += strlen(req->header[req->headers]);
2075 if (req->headers < MGCP_MAX_HEADERS) {
2078 ast_log(LOG_WARNING, "Out of header space\n");
2084 static int respprep(struct mgcp_request *resp, struct mgcp_endpoint *p, char *msg, struct mgcp_request *req, char *msgrest)
2086 memset(resp, 0, sizeof(*resp));
2087 init_resp(resp, msg, req, msgrest);
2091 static int reqprep(struct mgcp_request *req, struct mgcp_endpoint *p, char *verb)
2093 memset(req, 0, sizeof(struct mgcp_request));
2095 if (oseq > 999999999) {
2098 init_req(p, req, verb);
2102 static int transmit_response(struct mgcp_subchannel *sub, char *msg, struct mgcp_request *req, char *msgrest)
2104 struct mgcp_request resp;
2105 struct mgcp_endpoint *p = sub->parent;
2106 struct mgcp_response *mgr;
2112 respprep(&resp, p, msg, req, msgrest);
2113 if (!(mgr = ast_calloc(1, sizeof(*mgr) + resp.len + 1))) {
2114 return send_response(sub, &resp);
2116 /* Store MGCP response in case we have to retransmit */
2117 sscanf(req->identifier, "%30d", &mgr->seqno);
2118 time(&mgr->whensent);
2119 mgr->len = resp.len;
2120 memcpy(mgr->buf, resp.data, resp.len);
2121 mgr->buf[resp.len] = '\0';
2122 mgr->next = p->parent->responses;
2123 p->parent->responses = mgr;
2125 return send_response(sub, &resp);
2129 static int add_sdp(struct mgcp_request *resp, struct mgcp_subchannel *sub, struct ast_rtp_instance *rtp)
2134 struct sockaddr_in sin;
2143 struct sockaddr_in dest = { 0, };
2144 struct mgcp_endpoint *p = sub->parent;
2145 /* XXX We break with the "recommendation" and send our IP, in order that our
2146 peer doesn't have to ast_gethostbyname() us XXX */
2149 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2152 ast_rtp_instance_get_local_address(sub->rtp, &sin);
2154 ast_rtp_instance_get_remote_address(sub->rtp, &dest);
2156 if (sub->tmpdest.sin_addr.s_addr) {
2157 dest.sin_addr = sub->tmpdest.sin_addr;
2158 dest.sin_port = sub->tmpdest.sin_port;
2159 /* Reset temporary destination */
2160 memset(&sub->tmpdest, 0, sizeof(sub->tmpdest));
2162 dest.sin_addr = p->parent->ourip;
2163 dest.sin_port = sin.sin_port;
2166 ast_debug(1, "We're at %s port %d\n", ast_inet_ntoa(p->parent->ourip), ntohs(sin.sin_port));
2167 ast_copy_string(v, "v=0\r\n", sizeof(v));
2168 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", (int)getpid(), (int)getpid(), ast_inet_ntoa(dest.sin_addr));
2169 ast_copy_string(s, "s=session\r\n", sizeof(s));
2170 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
2171 ast_copy_string(t, "t=0 0\r\n", sizeof(t));
2172 snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2173 for (x = 1LL; x <= AST_FORMAT_AUDIO_MASK; x <<= 1) {
2174 if (!(x & AST_FORMAT_AUDIO_MASK)) {
2175 /* Audio is now discontiguous */
2178 if (p->capability & x) {
2179 ast_debug(1, "Answering with capability %s\n", ast_getformatname(x));
2180 codec = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(sub->rtp), 1, x);
2182 snprintf(costr, sizeof(costr), " %d", codec);
2183 strncat(m, costr, sizeof(m) - strlen(m) - 1);
2184 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype2(1, x, 0));
2185 strncat(a, costr, sizeof(a) - strlen(a) - 1);
2189 for (x = 1LL; x <= AST_RTP_MAX; x <<= 1) {
2190 if (p->nonCodecCapability & x) {
2191 ast_debug(1, "Answering with non-codec capability %d\n", (int) x);
2192 codec = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(sub->rtp), 0, x);
2194 snprintf(costr, sizeof(costr), " %d", codec);
2195 strncat(m, costr, sizeof(m) - strlen(m) - 1);
2196 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype2(0, x, 0));
2197 strncat(a, costr, sizeof(a) - strlen(a) - 1);
2198 if (x == AST_RTP_DTMF) {
2199 /* Indicate we support DTMF... Not sure about 16,
2200 but MSN supports it so dang it, we will too... */
2201 snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n", codec);
2202 strncat(a, costr, sizeof(a) - strlen(a) - 1);
2207 strncat(m, "\r\n", sizeof(m) - strlen(m) - 1);
2208 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2209 snprintf(costr, sizeof(costr), "%d", len);
2220 static int transmit_modify_with_sdp(struct mgcp_subchannel *sub, struct ast_rtp_instance *rtp, format_t codecs)
2222 struct mgcp_request resp;
2225 struct mgcp_endpoint *p = sub->parent;
2228 if (ast_strlen_zero(sub->cxident) && rtp) {
2229 /* We don't have a CXident yet, store the destination and
2231 ast_rtp_instance_get_remote_address(rtp, &sub->tmpdest);
2234 ast_copy_string(local, "e:on, s:off, p:20", sizeof(local));
2235 for (x = 1; x <= AST_FORMAT_AUDIO_MASK; x <<= 1) {
2236 if (!(x & AST_FORMAT_AUDIO_MASK)) {
2237 /* No longer contiguous */
2240 if (p->capability & x) {
2241 snprintf(tmp, sizeof(tmp), ", a:%s", ast_rtp_lookup_mime_subtype2(1, x, 0));
2242 strncat(local, tmp, sizeof(local) - strlen(local) - 1);
2247 if (sub->gate->state == GATE_ALLOCATED || sub->gate->state == GATE_OPEN) {
2248 snprintf(tmp, sizeof(tmp), ", dq-gi:%x", sub->gate->gateid);
2249 strncat(local, tmp, sizeof(local) - strlen(local) - 1);
2253 ast_debug(1, "Waiting for opened gate...\n");
2260 reqprep(&resp, p, "MDCX");
2261 add_header(&resp, "C", sub->callid);
2262 add_header(&resp, "L", local);
2263 add_header(&resp, "M", mgcp_cxmodes[sub->cxmode]);
2264 /* X header should not be sent. kept for compatibility */
2265 add_header(&resp, "X", sub->txident);
2266 add_header(&resp, "I", sub->cxident);
2267 /*add_header(&resp, "S", "");*/
2268 add_sdp(&resp, sub, rtp);
2269 /* fill in new fields */
2270 resp.cmd = MGCP_CMD_MDCX;
2272 return send_request(p, sub, &resp, oseq);
2275 static int transmit_connect_with_sdp(struct mgcp_subchannel *sub, struct ast_rtp_instance *rtp)
2277 struct mgcp_request resp;
2281 struct mgcp_endpoint *p = sub->parent;
2283 ast_debug(3, "Creating connection for %s@%s-%d in cxmode: %s callid: %s\n",
2284 p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode], sub->callid);
2286 ast_copy_string(local, "e:on, s:off, p:20", sizeof(local));
2288 for (x = 1; x <= AST_FORMAT_AUDIO_MASK; x <<= 1) {
2289 if (!(x & AST_FORMAT_AUDIO_MASK)) {
2290 /* No longer contiguous */
2293 if (p->capability & x) {
2294 snprintf(tmp, sizeof(tmp), ", a:%s", ast_rtp_lookup_mime_subtype2(1, x, 0));
2295 strncat(local, tmp, sizeof(local) - strlen(local) - 1);
2300 if(sub->gate->state == GATE_ALLOCATED) {
2301 snprintf(tmp, sizeof(tmp), ", dq-gi:%x", sub->gate->gateid);
2302 strncat(local, tmp, sizeof(local) - strlen(local) - 1);
2306 reqprep(&resp, p, "CRCX");
2307 add_header(&resp, "C", sub->callid);
2308 add_header(&resp, "L", local);
2309 add_header(&resp, "M", mgcp_cxmodes[sub->cxmode]);
2310 /* X header should not be sent. kept for compatibility */
2311 add_header(&resp, "X", sub->txident);
2312 /*add_header(&resp, "S", "");*/
2313 add_sdp(&resp, sub, rtp);
2314 /* fill in new fields */
2315 resp.cmd = MGCP_CMD_CRCX;
2317 return send_request(p, sub, &resp, oseq);
2320 static int mgcp_pktcgate_remove(struct cops_gate *gate)
2322 struct mgcp_subchannel *sub = gate->tech_pvt;
2328 ast_mutex_lock(&sub->lock);
2329 ast_debug(1, "Pktc: gate 0x%x deleted\n", gate->gateid);
2330 if (sub->gate->state != GATE_CLOSED && sub->parent->hangupongateremove) {
2333 ast_softhangup(sub->owner, AST_CAUSE_REQUESTED_CHAN_UNAVAIL);
2334 ast_channel_unlock(sub->owner);
2339 ast_mutex_unlock(&sub->lock);
2343 static int mgcp_pktcgate_open(struct cops_gate *gate)
2345 struct mgcp_subchannel *sub = gate->tech_pvt;
2349 ast_mutex_lock(&sub->lock);
2350 ast_debug(1, "Pktc: gate 0x%x open\n", gate->gateid);
2351 if (!sub->sdpsent) transmit_modify_with_sdp(sub, NULL, 0);
2352 ast_mutex_unlock(&sub->lock);
2356 static int mgcp_alloc_pktcgate(struct mgcp_subchannel *sub)
2358 struct mgcp_endpoint *p = sub->parent;
2359 sub->gate = ast_pktccops_gate_alloc(GATE_SET, NULL, ntohl(p->parent->addr.sin_addr.s_addr),
2360 8, 128000, 232, 0, 0, NULL, &mgcp_pktcgate_remove);
2365 sub->gate->tech_pvt = sub;
2366 sub->gate->gate_open = &mgcp_pktcgate_open;
2370 static int transmit_connect(struct mgcp_subchannel *sub)
2372 struct mgcp_request resp;
2376 struct mgcp_endpoint *p = sub->parent;
2378 ast_copy_string(local, "p:20, s:off, e:on", sizeof(local));
2380 for (x = 1LL; x <= AST_FORMAT_AUDIO_MASK; x <<= 1) {
2381 if (p->capability & x) {
2382 snprintf(tmp, sizeof(tmp), ", a:%s", ast_rtp_lookup_mime_subtype2(1, x, 0));
2383 strncat(local, tmp, sizeof(local) - strlen(local) - 1);
2387 ast_debug(3, "Creating connection for %s@%s-%d in cxmode: %s callid: %s\n",
2388 p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode], sub->callid);
2390 reqprep(&resp, p, "CRCX");
2391 add_header(&resp, "C", sub->callid);
2392 add_header(&resp, "L", local);
2393 add_header(&resp, "M", "inactive");
2394 /* X header should not be sent. kept for compatibility */
2395 add_header(&resp, "X", sub->txident);
2396 /*add_header(&resp, "S", "");*/
2397 /* fill in new fields */
2398 resp.cmd = MGCP_CMD_CRCX;
2400 return send_request(p, sub, &resp, oseq);
2403 static int transmit_notify_request(struct mgcp_subchannel *sub, char *tone)
2405 struct mgcp_request resp;
2406 struct mgcp_endpoint *p = sub->parent;
2408 ast_debug(3, "MGCP Asked to indicate tone: %s on %s@%s-%d in cxmode: %s\n",
2409 tone, p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode]);
2410 ast_copy_string(p->curtone, tone, sizeof(p->curtone));
2411 reqprep(&resp, p, "RQNT");
2412 add_header(&resp, "X", p->rqnt_ident);
2413 switch (p->hookstate) {
2415 add_header(&resp, "R", "L/hd(N)");
2418 add_header_offhook(sub, &resp, tone);
2421 if (!ast_strlen_zero(tone)) {
2422 add_header(&resp, "S", tone);
2424 /* fill in new fields */
2425 resp.cmd = MGCP_CMD_RQNT;
2427 return send_request(p, NULL, &resp, oseq);
2430 static int transmit_notify_request_with_callerid(struct mgcp_subchannel *sub, char *tone, char *callernum, char *callername)
2432 struct mgcp_request resp;
2435 struct timeval t = ast_tvnow();
2437 struct mgcp_endpoint *p = sub->parent;
2439 ast_localtime(&t, &tm, NULL);
2447 /* Keep track of last callerid for blacklist and callreturn */
2448 ast_copy_string(p->lastcallerid, l, sizeof(p->lastcallerid));
2450 snprintf(tone2, sizeof(tone2), "%s,L/ci(%02d/%02d/%02d/%02d,%s,%s)", tone,
2451 tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, l, n);
2452 ast_copy_string(p->curtone, tone, sizeof(p->curtone));
2453 reqprep(&resp, p, "RQNT");
2454 add_header(&resp, "X", p->rqnt_ident);
2455 switch (p->hookstate) {
2457 add_header(&resp, "R", "L/hd(N)");
2460 add_header_offhook(sub, &resp, tone);
2463 if (!ast_strlen_zero(tone2)) {
2464 add_header(&resp, "S", tone2);
2466 ast_debug(3, "MGCP Asked to indicate tone: %s on %s@%s-%d in cxmode: %s\n",
2467 tone2, p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode]);
2468 /* fill in new fields */
2469 resp.cmd = MGCP_CMD_RQNT;
2471 return send_request(p, NULL, &resp, oseq);
2474 static int transmit_modify_request(struct mgcp_subchannel *sub)
2476 struct mgcp_request resp;
2477 struct mgcp_endpoint *p = sub->parent;
2483 if (ast_strlen_zero(sub->cxident)) {
2484 /* We don't have a CXident yet, store the destination and
2488 ast_debug(3, "Modified %s@%s-%d with new mode: %s on callid: %s\n",
2489 p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode], sub->callid);
2491 ast_copy_string(local, "", sizeof(local));
2492 for (x = 1; x <= AST_FORMAT_AUDIO_MASK; x <<= 1) {
2493 if (p->capability & x) {
2494 if (p->ncs && !fc) {
2495 p->capability = x; /* sb5120e bug */
2499 snprintf(tmp, sizeof(tmp), ", a:%s", ast_rtp_lookup_mime_subtype2(1, x, 0));
2501 strncat(local, tmp, sizeof(local) - strlen(local) - 1);
2505 if (!sub->sdpsent) {
2507 if (sub->gate->state == GATE_ALLOCATED || sub->gate->state == GATE_OPEN) {
2508 snprintf(tmp, sizeof(tmp), ", dq-gi:%x", sub->gate->gateid);
2509 strncat(local, tmp, sizeof(local) - strlen(local) - 1);
2511 /* we still dont have gateid wait */
2517 reqprep(&resp, p, "MDCX");
2518 add_header(&resp, "C", sub->callid);
2519 if (!sub->sdpsent) {
2520 add_header(&resp, "L", local);
2522 add_header(&resp, "M", mgcp_cxmodes[sub->cxmode]);
2523 /* X header should not be sent. kept for compatibility */
2524 add_header(&resp, "X", sub->txident);
2525 add_header(&resp, "I", sub->cxident);
2526 switch (sub->parent->hookstate) {
2528 add_header(&resp, "R", "L/hd(N)");
2531 add_header_offhook(sub, &resp, "");
2534 if (!sub->sdpsent) {
2535 add_sdp(&resp, sub, NULL);
2538 /* fill in new fields */
2539 resp.cmd = MGCP_CMD_MDCX;
2541 return send_request(p, sub, &resp, oseq);
2545 static void add_header_offhook(struct mgcp_subchannel *sub, struct mgcp_request *resp, char *tone)
2547 struct mgcp_endpoint *p = sub->parent;
2548 char tone_indicate_end = 0;
2550 /* We also should check the tone to indicate, because it have no sense
2551 to request notify D/[0-9#*] (dtmf keys) if we are sending congestion
2552 tone for example G/cg */
2553 if (p && (!strcasecmp(tone, (p->ncs ? "L/ro" : "G/cg")))) {
2554 tone_indicate_end = 1;
2557 if (p && p->sub && p->sub->owner &&
2558 p->sub->owner->_state >= AST_STATE_RINGING &&
2559 (p->dtmfmode & (MGCP_DTMF_INBAND | MGCP_DTMF_HYBRID))) {
2560 add_header(resp, "R", "L/hu(N),L/hf(N)");
2562 } else if (!tone_indicate_end){
2563 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)"));
2565 ast_debug(1, "We don't want more digits if we will end the call\n");
2566 add_header(resp, "R", "L/hu(N),L/hf(N)");
2573 static int transmit_audit_endpoint(struct mgcp_endpoint *p)
2575 struct mgcp_request resp;
2576 reqprep(&resp, p, "AUEP");
2577 /* removed unknown param VS */
2578 /*add_header(&resp, "F", "A,R,D,S,X,N,I,T,O,ES,E,MD,M");*/
2579 add_header(&resp, "F", "A");
2580 /* fill in new fields */
2581 resp.cmd = MGCP_CMD_AUEP;
2583 return send_request(p, NULL, &resp, oseq);
2586 static int transmit_connection_del(struct mgcp_subchannel *sub)
2588 struct mgcp_endpoint *p = sub->parent;
2589 struct mgcp_request resp;
2591 ast_debug(3, "Delete connection %s %s@%s-%d with new mode: %s on callid: %s\n",
2592 sub->cxident, p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode], sub->callid);
2593 reqprep(&resp, p, "DLCX");
2594 /* check if call id is avail */
2596 add_header(&resp, "C", sub->callid);
2597 /* X header should not be sent. kept for compatibility */
2598 add_header(&resp, "X", sub->txident);
2599 /* check if cxident is avail */
2600 if (sub->cxident[0])
2601 add_header(&resp, "I", sub->cxident);
2602 /* fill in new fields */
2603 resp.cmd = MGCP_CMD_DLCX;
2605 return send_request(p, sub, &resp, oseq);
2608 static int transmit_connection_del_w_params(struct mgcp_endpoint *p, char *callid, char *cxident)
2610 struct mgcp_request resp;
2612 ast_debug(3, "Delete connection %s %s@%s on callid: %s\n",
2613 cxident ? cxident : "", p->name, p->parent->name, callid ? callid : "");
2614 reqprep(&resp, p, "DLCX");
2615 /* check if call id is avail */
2616 if (callid && *callid)
2617 add_header(&resp, "C", callid);
2618 /* check if cxident is avail */
2619 if (cxident && *cxident)
2620 add_header(&resp, "I", cxident);
2621 /* fill in new fields */
2622 resp.cmd = MGCP_CMD_DLCX;
2624 return send_request(p, p->sub, &resp, oseq);
2627 /*! \brief dump_cmd_queues: (SC:) cleanup pending commands */
2628 static void dump_cmd_queues(struct mgcp_endpoint *p, struct mgcp_subchannel *sub)
2630 struct mgcp_request *t, *q;
2633 ast_mutex_lock(&p->rqnt_queue_lock);
2634 for (q = p->rqnt_queue; q; t = q->next, ast_free(q), q=t);
2635 p->rqnt_queue = NULL;
2636 ast_mutex_unlock(&p->rqnt_queue_lock);
2638 ast_mutex_lock(&p->cmd_queue_lock);
2639 for (q = p->cmd_queue; q; t = q->next, ast_free(q), q=t);
2640 p->cmd_queue = NULL;
2641 ast_mutex_unlock(&p->cmd_queue_lock);
2643 ast_mutex_lock(&p->sub->cx_queue_lock);
2644 for (q = p->sub->cx_queue; q; t = q->next, ast_free(q), q=t);
2645 p->sub->cx_queue = NULL;
2646 ast_mutex_unlock(&p->sub->cx_queue_lock);
2648 ast_mutex_lock(&p->sub->next->cx_queue_lock);
2649 for (q = p->sub->next->cx_queue; q; t = q->next, ast_free(q), q=t);
2650 p->sub->next->cx_queue = NULL;
2651 ast_mutex_unlock(&p->sub->next->cx_queue_lock);
2653 ast_mutex_lock(&sub->cx_queue_lock);
2654 for (q = sub->cx_queue; q; t = q->next, ast_free(q), q=t);
2655 sub->cx_queue = NULL;
2656 ast_mutex_unlock(&sub->cx_queue_lock);
2661 /*! \brief find_command: (SC:) remove command transaction from queue */
2662 static struct mgcp_request *find_command(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,
2663 struct mgcp_request **queue, ast_mutex_t *l, int ident)
2665 struct mgcp_request *prev, *req;
2668 for (prev = NULL, req = *queue; req; prev = req, req = req->next) {
2669 if (req->trid == ident) {
2670 /* remove from queue */
2674 prev->next = req->next;
2676 /* send next pending command */
2678 ast_debug(1, "Posting Queued Request:\n%s to %s:%d\n", (*queue)->data,
2679 ast_inet_ntoa(p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
2681 mgcp_postrequest(p, sub, (*queue)->data, (*queue)->len, (*queue)->trid);
2686 ast_mutex_unlock(l);
2690 /* modified for new transport mechanism */
2691 static void handle_response(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,
2692 int result, unsigned int ident, struct mgcp_request *resp)
2695 struct mgcp_request *req;
2696 struct mgcp_gateway *gw = p->parent;
2699 /* provisional response */
2703 if (p->slowsequence)
2704 req = find_command(p, sub, &p->cmd_queue, &p->cmd_queue_lock, ident);
2706 req = find_command(p, sub, &sub->cx_queue, &sub->cx_queue_lock, ident);
2707 else if (!(req = find_command(p, sub, &p->rqnt_queue, &p->rqnt_queue_lock, ident)))
2708 req = find_command(p, sub, &p->cmd_queue, &p->cmd_queue_lock, ident);
2711 ast_verb(3, "No command found on [%s] for transaction %d. Ignoring...\n",
2716 if (p && (result >= 400) && (result <= 599)) {
2719 p->hookstate = MGCP_OFFHOOK;
2722 p->hookstate = MGCP_ONHOOK;
2725 ast_log(LOG_NOTICE, "Transaction %d timed out\n", ident);
2728 ast_log(LOG_NOTICE, "Transaction %d aborted\n", ident);
2732 if (!sub->cxident[0] && (req->cmd == MGCP_CMD_CRCX)) {
2733 ast_log(LOG_NOTICE, "DLCX for all connections on %s due to error %d\n", gw->name, result);
2734 transmit_connection_del(sub);
2737 ast_log(LOG_NOTICE, "Terminating on result %d from %s@%s-%d\n",
2738 result, p->name, p->parent->name, sub ? sub->id:-1);
2739 mgcp_queue_hangup(sub);
2742 if (p->sub->next->owner) {
2743 ast_log(LOG_NOTICE, "Terminating on result %d from %s@%s-%d\n",
2744 result, p->name, p->parent->name, sub ? sub->id:-1);
2745 mgcp_queue_hangup(p->sub);
2748 if (p->sub->owner) {
2749 ast_log(LOG_NOTICE, "Terminating on result %d from %s@%s-%d\n",
2750 result, p->name, p->parent->name, sub ? sub->id:-1);
2751 mgcp_queue_hangup(p->sub);
2754 dump_cmd_queues(p, NULL);
2760 if (result == 200 && (req->cmd == MGCP_CMD_CRCX || req->cmd == MGCP_CMD_MDCX)) {
2762 transmit_response(sub, "000", resp, "OK");
2763 if (sub->owner && sub->owner->_state == AST_STATE_RINGING) {
2764 ast_queue_control(sub->owner, AST_CONTROL_RINGING);
2768 if (req->cmd == MGCP_CMD_CRCX) {
2769 if ((c = get_header(resp, "I"))) {
2770 if (!ast_strlen_zero(c) && sub) {
2771 /* if we are hanging up do not process this conn. */
2773 if (!ast_strlen_zero(sub->cxident)) {
2774 if (strcasecmp(c, sub->cxident)) {
2775 ast_log(LOG_WARNING, "Subchannel already has a cxident. sub->cxident: %s requested %s\n", sub->cxident, c);
2778 ast_copy_string(sub->cxident, c, sizeof(sub->cxident));
2779 if (sub->tmpdest.sin_addr.s_addr) {
2780 transmit_modify_with_sdp(sub, NULL, 0);
2783 /* XXX delete this one
2784 callid and conn id may already be lost.
2785 so the following del conn may have a side effect of
2786 cleaning up the next subchannel */
2787 transmit_connection_del(sub);
2793 if (req->cmd == MGCP_CMD_AUEP) {
2794 /* check stale connection ids */
2795 if ((c = get_header(resp, "I"))) {
2798 while ((v = get_csv(c, &len, &n))) {
2800 if (strncasecmp(v, p->sub->cxident, len) &&
2801 strncasecmp(v, p->sub->next->cxident, len)) {
2802 /* connection id not found. delete it */
2803 char cxident[80] = "";
2805 if (len > (sizeof(cxident) - 1))
2806 len = sizeof(cxident) - 1;
2807 ast_copy_string(cxident, v, len);
2808 ast_verb(3, "Non existing connection id %s on %s@%s \n",
2809 cxident, p->name, gw->name);
2810 transmit_connection_del_w_params(p, NULL, cxident);
2817 /* Try to determine the hookstate returned from an audit endpoint command */
2818 if ((c = get_header(resp, "ES"))) {
2819 if (!ast_strlen_zero(c)) {
2820 if (strstr(c, "hu")) {
2821 if (p->hookstate != MGCP_ONHOOK) {
2822 /* XXX cleanup if we think we are offhook XXX */
2823 if ((p->sub->owner || p->sub->next->owner ) &&
2824 p->hookstate == MGCP_OFFHOOK)
2825 mgcp_queue_hangup(sub);
2826 p->hookstate = MGCP_ONHOOK;
2828 /* update the requested events according to the new hookstate */
2829 transmit_notify_request(p->sub, "");
2831 ast_verb(3, "Setting hookstate of %s@%s to ONHOOK\n", p->name, gw->name);
2833 } else if (strstr(c, "hd")) {
2834 if (p->hookstate != MGCP_OFFHOOK) {
2835 p->hookstate = MGCP_OFFHOOK;
2837 /* update the requested events according to the new hookstate */
2838 transmit_notify_request(p->sub, "");
2840 ast_verb(3, "Setting hookstate of %s@%s to OFFHOOK\n", p->name, gw->name);
2847 if (resp && resp->lines) {
2848 /* do not process sdp if we are hanging up. this may be a late response */
2849 if (sub && sub->owner) {
2853 process_sdp(sub, resp);
2861 static void start_rtp(struct mgcp_subchannel *sub)
2863 ast_mutex_lock(&sub->lock);
2864 /* check again to be on the safe side */
2866 ast_rtp_instance_destroy(sub->rtp);
2869 /* Allocate the RTP now */
2870 sub->rtp = ast_rtp_instance_new("asterisk", sched, &bindaddr, NULL);
2871 if (sub->rtp && sub->owner)
2872 ast_channel_set_fd(sub->owner, 0, ast_rtp_instance_fd(sub->rtp, 0));
2874 ast_rtp_instance_set_qos(sub->rtp, qos.tos_audio, qos.cos_audio, "MGCP RTP");
2875 ast_rtp_instance_set_prop(sub->rtp, AST_RTP_PROPERTY_NAT, sub->nat);
2877 /* Make a call*ID */
2878 snprintf(sub->callid, sizeof(sub->callid), "%08lx%s", ast_random(), sub->txident);
2879 /* Transmit the connection create */
2880 if(!sub->parent->pktcgatealloc) {
2881 transmit_connect_with_sdp(sub, NULL);
2883 transmit_connect(sub);
2885 if(!mgcp_alloc_pktcgate(sub))
2886 mgcp_queue_hangup(sub);
2888 ast_mutex_unlock(&sub->lock);
2891 static void *mgcp_ss(void *data)
2893 struct ast_channel *chan = data;
2894 struct mgcp_subchannel *sub = chan->tech_pvt;
2895 struct mgcp_endpoint *p = sub->parent;
2896 /* char exten[AST_MAX_EXTENSION] = ""; */
2898 int timeout = firstdigittimeout;
2901 int loop_pause = 100;
2903 len = strlen(p->dtmf_buf);
2905 while (len < AST_MAX_EXTENSION - 1) {
2906 ast_debug(1, "Dtmf buffer '%s' for '%s@%s'\n", p->dtmf_buf, p->name, p->parent->name);
2907 res = 1; /* Assume that we will get a digit */
2908 while (strlen(p->dtmf_buf) == len) {
2909 ast_safe_sleep(chan, loop_pause);
2910 timeout -= loop_pause;
2919 len = strlen(p->dtmf_buf);
2921 if (!ast_ignore_pattern(chan->context, p->dtmf_buf)) {
2922 /*res = tone_zone_play_tone(p->subs[index].zfd, -1);*/
2923 ast_indicate(chan, -1);
2925 /* XXX Redundant? We should already be playing dialtone */
2926 /*tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALTONE);*/
2927 transmit_notify_request(sub, "L/dl");
2929 if (ast_exists_extension(chan, chan->context, p->dtmf_buf, 1, p->cid_num)) {
2930 if (!res || !ast_matchmore_extension(chan, chan->context, p->dtmf_buf, 1, p->cid_num)) {
2932 /* Record this as the forwarding extension */
2933 ast_copy_string(p->call_forward, p->dtmf_buf, sizeof(p->call_forward));
2934 ast_verb(3, "Setting call forward to '%s' on channel %s\n",
2935 p->call_forward, chan->name);
2936 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
2937 transmit_notify_request(sub, "L/sl");
2941 /*res = tone_zone_play_tone(p->subs[index].zfd, -1);*/
2942 ast_indicate(chan, -1);
2944 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2945 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALTONE);*/
2946 transmit_notify_request(sub, "L/dl");
2950 /*res = tone_zone_play_tone(p->subs[index].zfd, -1);*/
2951 ast_indicate(chan, -1);
2952 ast_copy_string(chan->exten, p->dtmf_buf, sizeof(chan->exten));
2953 chan->cid.cid_dnid = ast_strdup(p->dtmf_buf);
2954 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2955 ast_set_callerid(chan,
2956 p->hidecallerid ? "" : p->cid_num,
2957 p->hidecallerid ? "" : p->cid_name,
2958 chan->cid.cid_ani ? NULL : p->cid_num);
2959 ast_setstate(chan, AST_STATE_RING);
2960 /*dahdi_enable_ec(p);*/
2961 if (p->dtmfmode & MGCP_DTMF_HYBRID) {
2962 p->dtmfmode |= MGCP_DTMF_INBAND;
2963 ast_indicate(chan, -1);
2965 res = ast_pbx_run(chan);
2967 ast_log(LOG_WARNING, "PBX exited non-zero\n");
2968 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_CONGESTION);*/
2969 /*transmit_notify_request(p, "nbz", 1);*/
2970 transmit_notify_request(sub, p->ncs ? "L/cg" : "G/cg");
2975 /* It's a match, but they just typed a digit, and there is an ambiguous match,
2976 so just set the timeout to matchdigittimeout and wait some more */
2977 timeout = matchdigittimeout;
2979 } else if (res == 0) {
2980 ast_debug(1, "not enough digits (and no ambiguous match)...\n");
2981 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_CONGESTION);*/
2982 transmit_notify_request(sub, p->ncs ? "L/cg" : "G/cg");
2983 /*dahdi_wait_event(p->subs[index].zfd);*/
2985 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2987 } else if (p->hascallwaiting && p->callwaiting && !strcmp(p->dtmf_buf, "*70")) {
2988 ast_verb(3, "Disabling call waiting on %s\n", chan->name);
2989 /* Disable call waiting if enabled */
2991 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
2992 transmit_notify_request(sub, "L/sl");
2994 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2995 timeout = firstdigittimeout;
2996 } else if (!strcmp(p->dtmf_buf,ast_pickup_ext())) {
2997 /* Scan all channels and see if any there
2998 * ringing channqels with that have call groups
2999 * that equal this channels pickup group
3001 if (ast_pickup_call(chan)) {
3002 ast_log(LOG_WARNING, "No call pickup possible...\n");
3003 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_CONGESTION);*/
3004 transmit_notify_request(sub, p->ncs ? "L/cg" : "G/cg");
3006 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
3009 } else if (!p->hidecallerid && !strcmp(p->dtmf_buf, "*67")) {
3010 ast_verb(3, "Disabling Caller*ID on %s\n", chan->name);
3011 /* Disable Caller*ID if enabled */
3012 p->hidecallerid = 1;
3013 ast_set_callerid(chan, "", "", NULL);
3014 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
3015 transmit_notify_request(sub, "L/sl");
3017 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
3018 timeout = firstdigittimeout;
3019 } else if (p->callreturn && !strcmp(p->dtmf_buf, "*69")) {
3021 if (!ast_strlen_zero(p->lastcallerid)) {
3022 res = ast_say_digit_str(chan, p->lastcallerid, "", chan->language);
3025 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
3026 transmit_notify_request(sub, "L/sl");
3028 } else if (!strcmp(p->dtmf_buf, "*78")) {
3029 /* Do not disturb */
3030 ast_verb(3, "Enabled DND on channel %s\n", chan->name);
3031 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
3032 transmit_notify_request(sub, "L/sl");
3035 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
3037 } else if (!strcmp(p->dtmf_buf, "*79")) {
3038 /* Do not disturb */
3039 ast_verb(3, "Disabled DND on channel %s\n", chan->name);
3040 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
3041 transmit_notify_request(sub, "L/sl");
3044 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
3046 } else if (p->cancallforward && !strcmp(p->dtmf_buf, "*72")) {
3047 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
3048 transmit_notify_request(sub, "L/sl");
3050 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
3052 } else if (p->cancallforward && !strcmp(p->dtmf_buf, "*73")) {
3053 ast_verb(3, "Cancelling call forwarding on channel %s\n", chan->name);
3054 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
3055 transmit_notify_request(sub, "L/sl");
3056 memset(p->call_forward, 0, sizeof(p->call_forward));
3058 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
3060 } else if (!strcmp(p->dtmf_buf, ast_parking_ext()) &&
3061 sub->next->owner && ast_bridged_channel(sub->next->owner)) {
3062 /* This is a three way call, the main call being a real channel,
3063 and we're parking the first call. */
3064 ast_masq_park_call(ast_bridged_channel(sub->next->owner), chan, 0, NULL);
3065 ast_verb(3, "Parking call to '%s'\n", chan->name);
3067 } else if (!ast_strlen_zero(p->lastcallerid) && !strcmp(p->dtmf_buf, "*60")) {
3068 ast_verb(3, "Blacklisting number %s\n", p->lastcallerid);
3069 res = ast_db_put("blacklist", p->lastcallerid, "1");
3071 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
3072 transmit_notify_request(sub, "L/sl");
3073 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
3076 } else if (p->hidecallerid && !strcmp(p->dtmf_buf, "*82")) {
3077 ast_verb(3, "Enabling Caller*ID on %s\n", chan->name);
3078 /* Enable Caller*ID if enabled */
3079 p->hidecallerid = 0;
3080 ast_set_callerid(chan, p->cid_num, p->cid_name, NULL);
3081 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
3082 transmit_notify_request(sub, "L/sl");
3084 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
3085 timeout = firstdigittimeout;
3086 } else if (!ast_canmatch_extension(chan, chan->context, p->dtmf_buf, 1, chan->cid.cid_num) &&
3087 ((p->dtmf_buf[0] != '*') || (strlen(p->dtmf_buf) > 2))) {
3088 ast_debug(1, "Can't match %s from '%s' in context %s\n", p->dtmf_buf, chan->cid.cid_num ? chan->cid.cid_num : "<Unknown Caller>", chan->context);
3092 timeout = gendigittimeout;
3093 if (len && !ast_ignore_pattern(chan->context, p->dtmf_buf))
3094 /*tone_zone_play_tone(p->subs[index].zfd, -1);*/
3095 ast_indicate(chan, -1);
3099 res = ast_waitfordigit(chan, to);
3101 ast_debug(1, "Timeout...\n");
3105 ast_debug(1, "Got hangup...\n");
3110 if (!ast_ignore_pattern(chan->context, exten))
3111 ast_indicate(chan, -1);
3112 if (ast_matchmore_extension(chan, chan->context, exten, 1, chan->callerid)) {
3113 if (ast_exists_extension(chan, chan->context, exten, 1, chan->callerid))
3120 if (ast_exists_extension(chan, chan->context, exten, 1, chan->callerid)) {
3121 ast_copy_string(chan->exten, exten, sizeof(chan->exten)1);
3125 ast_setstate(chan, AST_STATE_RING);
3127 if (ast_pbx_run(chan)) {
3128 ast_log(LOG_WARNING, "Unable to launch PBX on %s\n", chan->name);
3130 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
3136 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
3140 static int attempt_transfer(struct mgcp_endpoint *p)
3142 /* *************************
3143 * I hope this works.
3144 * Copied out of chan_zap
3145 * Cross your fingers
3146 * *************************/
3148 /* In order to transfer, we need at least one of the channels to
3149 actually be in a call bridge. We can't conference two applications
3150 together (but then, why would we want to?) */
3151 if (ast_bridged_channel(p->sub->owner)) {
3152 /* The three-way person we're about to transfer to could still be in MOH, so
3153 stop if now if appropriate */
3154 if (ast_bridged_channel(p->sub->next->owner))
3155 ast_queue_control(p->sub->next->owner, AST_CONTROL_UNHOLD);
3156 if (p->sub->owner->_state == AST_STATE_RINGING) {
3157 ast_indicate(ast_bridged_channel(p->sub->next->owner), AST_CONTROL_RINGING);
3159 if (ast_channel_masquerade(p->sub->next->owner, ast_bridged_channel(p->sub->owner))) {
3160 ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
3161 ast_bridged_channel(p->sub->owner)->name, p->sub->next->owner->name);
3164 /* Orphan the channel */
3165 unalloc_sub(p->sub->next);
3166 } else if (ast_bridged_channel(p->sub->next->owner)) {
3167 if (p->sub->owner->_state == AST_STATE_RINGING) {
3168 ast_indicate(ast_bridged_channel(p->sub->next->owner), AST_CONTROL_RINGING);
3170 ast_queue_control(p->sub->next->owner, AST_CONTROL_UNHOLD);
3171 if (ast_channel_masquerade(p->sub->owner, ast_bridged_channel(p->sub->next->owner))) {
3172 ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
3173 ast_bridged_channel(p->sub->next->owner)->name, p->sub->owner->name);
3176 /*swap_subs(p, SUB_THREEWAY, SUB_REAL);*/
3177 ast_verb(3, "Swapping %d for %d on %s@%s\n", p->sub->id, p->sub->next->id, p->name, p->parent->name);
3178 p->sub = p->sub->next;
3179 unalloc_sub(p->sub->next);
3180 /* Tell the caller not to hangup */
3183 ast_debug(1, "Neither %s nor %s are in a bridge, nothing to transfer\n",
3184 p->sub->owner->name, p->sub->next->owner->name);
3185 p->sub->next->owner->_softhangup |= AST_SOFTHANGUP_DEV;
3186 if (p->sub->next->owner) {
3187 p->sub->next->alreadygone = 1;
3188 mgcp_queue_hangup(p->sub->next);
3194 static void handle_hd_hf(struct mgcp_subchannel *sub, char *ev)
3196 struct mgcp_endpoint *p = sub->parent;
3197 struct ast_channel *c;
3200 /* Off hook / answer */
3201 if (sub->outgoing) {
3204 if (ast_bridged_channel(sub->owner))
3205 ast_queue_control(sub->owner, AST_CONTROL_UNHOLD);
3206 sub->cxmode = MGCP_CX_SENDRECV;
3210 transmit_modify_request(sub);
3212 /*transmit_notify_request(sub, "aw");*/
3213 transmit_notify_request(sub, "");
3214 mgcp_queue_control(sub, AST_CONTROL_ANSWER);
3218 /*sub->cxmode = MGCP_CX_SENDRECV;*/
3223 transmit_modify_request(sub);
3226 /* The channel is immediately up. Start right away */
3227 #ifdef DLINK_BUGGY_FIRMWARE
3228 transmit_notify_request(sub, "rt");
3230 transmit_notify_request(sub, p->ncs ? "L/rt" : "G/rt");
3232 c = mgcp_new(sub, AST_STATE_RING, NULL);
3234 ast_log(LOG_WARNING, "Unable to start PBX on channel %s@%s\n", p->name, p->parent->name);
3235 transmit_notify_request(sub, p->ncs ? "L/cg" : "G/cg");
3239 if (has_voicemail(p)) {
3240 transmit_notify_request(sub, "L/sl");
3242 transmit_notify_request(sub, "L/dl");
3244 c = mgcp_new(sub, AST_STATE_DOWN, NULL);
3246 if (ast_pthread_create_detached(&t, NULL, mgcp_ss, c)) {
3247 ast_log(LOG_WARNING, "Unable to create switch thread: %s\n", strerror(errno));
3251 ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", p->name, p->parent->name);
3255 if (p->hookstate == MGCP_OFFHOOK) {
3256 ast_log(LOG_WARNING, "Off hook, but already have owner on %s@%s\n", p->name, p->parent->name);
3258 ast_log(LOG_WARNING, "On hook, but already have owner on %s@%s\n", p->name, p->parent->name);
3259 ast_log(LOG_WARNING, "If we're onhook why are we here trying to handle a hd or hf?\n");
3261 if (ast_bridged_channel(sub->owner))
3262 ast_queue_control(sub->owner, AST_CONTROL_UNHOLD);
3263 sub->cxmode = MGCP_CX_SENDRECV;
3267 transmit_modify_request(sub);
3269 /*transmit_notify_request(sub, "aw");*/
3270 transmit_notify_request(sub, "");
3271 /*ast_queue_control(sub->owner, AST_CONTROL_ANSWER);*/
3276 static int handle_request(struct mgcp_subchannel *sub, struct mgcp_request *req, struct sockaddr_in *sin)
3279 struct ast_frame f = { 0, };
3280 struct mgcp_endpoint *p = sub->parent;
3281 struct mgcp_gateway *g = NULL;
3284 ast_debug(1, "Handling request '%s' on %s@%s\n", req->verb, p->name, p->parent->name);
3285 /* Clear out potential response */
3286 if (!strcasecmp(req->verb, "RSIP")) {
3287 /* Test if this RSIP request is just a keepalive */
3288 if (!strcasecmp( get_header(req, "RM"), "X-keepalive")) {
3289 ast_verb(3, "Received keepalive request from %s@%s\n", p->name, p->parent->name);
3290 transmit_response(sub, "200", req, "OK");
3292 dump_queue(p->parent, p);
3293 dump_cmd_queues(p, NULL);
3295 if ((strcmp(p->name, p->parent->wcardep) != 0)) {
3296 ast_verb(3, "Resetting interface %s@%s\n", p->name, p->parent->name);
3298 /* For RSIP on wildcard we reset all endpoints */
3299 if (!strcmp(p->name, p->parent->wcardep)) {
3300 /* Reset all endpoints */
3301 struct mgcp_endpoint *tmp_ep;
3304 for (tmp_ep = g->endpoints; tmp_ep; tmp_ep = tmp_ep->next) {
3305 /*if ((strcmp(tmp_ep->name, "*") != 0) && (strcmp(tmp_ep->name, "aaln/" "*") != 0)) {*/
3306 if (strcmp(tmp_ep->name, g->wcardep) != 0) {
3307 struct mgcp_subchannel *tmp_sub, *first_sub;
3308 ast_verb(3, "Resetting interface %s@%s\n", tmp_ep->name, p->parent->name);
3310 first_sub = tmp_ep->sub;
3311 tmp_sub = tmp_ep->sub;
3313 mgcp_queue_hangup(tmp_sub);
3314 tmp_sub = tmp_sub->next;
3315 if (tmp_sub == first_sub)
3320 } else if (sub->owner) {
3321 mgcp_queue_hangup(sub);
3323 transmit_response(sub, "200", req, "OK");
3324 /* We dont send NTFY or AUEP to wildcard ep */
3325 if (strcmp(p->name, p->parent->wcardep) != 0) {
3326 transmit_notify_request(sub, "");
3328 Idea is to prevent lost lines due to race conditions
3330 transmit_audit_endpoint(p);
3333 } else if (!strcasecmp(req->verb, "NTFY")) {
3334 /* Acknowledge and be sure we keep looking for the same things */
3335 transmit_response(sub, "200", req, "OK");
3336 /* Notified of an event */
3337 ev = get_header(req, "O");
3338 s = strchr(ev, '/');
3340 ast_debug(1, "Endpoint '%s@%s-%d' observed '%s'\n", p->name, p->parent->name, sub->id, ev);
3341 /* Keep looking for events unless this was a hangup */
3342 if (strcasecmp(ev, "hu") && strcasecmp(ev, "hd") && strcasecmp(ev, "ping")) {
3343 transmit_notify_request(sub, p->curtone);
3345 if (!strcasecmp(ev, "hd")) {
3346 p->hookstate = MGCP_OFFHOOK;
3347 sub->cxmode = MGCP_CX_SENDRECV;
3350 /* When the endpoint have a Off hook transition we allways
3351 starts without any previous dtmfs */
3352 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
3355 handle_hd_hf(sub, ev);
3356 } else if (!strcasecmp(ev, "hf")) {
3357 /* We can assume we are offhook if we received a hookflash */
3358 /* First let's just do call wait and ignore threeway */
3359 /* We're currently in charge */
3360 if (p->hookstate != MGCP_OFFHOOK) {
3361 /* Cisco c7940 sends hf even if the phone is onhook */
3362 /* Thanks to point on IRC for pointing this out */
3365 /* do not let * conference two down channels */
3366 if (sub->owner && sub->owner->_state == AST_STATE_DOWN && !sub->next->owner)
3369 if (p->callwaiting || p->transfer || p->threewaycalling) {
3370 ast_verb(3, "Swapping %d for %d on %s@%s\n", p->sub->id, p->sub->next->id, p->name, p->parent->name);
3371 p->sub = p->sub->next;
3373 /* transfer control to our next subchannel */
3374 if (!sub->next->owner) {
3375 /* plave the first call on hold and start up a new call */
3376 sub->cxmode = MGCP_CX_MUTE;
3377 ast_verb(3, "MGCP Muting %d on %s@%s\n", sub->id, p->name, p->parent->name);
3378 transmit_modify_request(sub);
3379 if (sub->owner && ast_bridged_channel(sub->owner))
3380 ast_queue_control(sub->owner, AST_CONTROL_HOLD);
3381 sub->next->cxmode = MGCP_CX_RECVONLY;
3382 handle_hd_hf(sub->next, ev);
3383 } else if (sub->owner && sub->next->owner) {
3384 /* We've got two active calls lets decide whether or not to conference or just flip flop */
3385 if ((!sub->outgoing) && (!sub->next->outgoing)) {
3386 /* We made both calls lets conferenct */
3387 ast_verb(3, "MGCP Conferencing %d and %d on %s@%s\n",
3388 sub->id, sub->next->id, p->name, p->parent->name);
3389 sub->cxmode = MGCP_CX_CONF;
3390 sub->next->cxmode = MGCP_CX_CONF;
3391 if (ast_bridged_channel(sub->next->owner))
3392 ast_queue_control(sub->next->owner, AST_CONTROL_UNHOLD);
3393 transmit_modify_request(sub);
3394 transmit_modify_request(sub->next);
3396 /* Let's flipflop between calls */
3397 /* XXX Need to check for state up ??? */
3398 /* XXX Need a way to indicate the current call, or maybe the call that's waiting */
3399 ast_verb(3, "We didn't make one of the calls FLIPFLOP %d and %d on %s@%s\n",
3400 sub->id, sub->next->id, p->name, p->parent->name);
3401 sub->cxmode = MGCP_CX_MUTE;
3402 ast_verb(3, "MGCP Muting %d on %s@%s\n", sub->id, p->name, p->parent->name);
3403 transmit_modify_request(sub);
3404 if (ast_bridged_channel(sub->owner))
3405 ast_queue_control(sub->owner, AST_CONTROL_HOLD);
3407 if (ast_bridged_channel(sub->next->owner))
3408 ast_queue_control(sub->next->owner, AST_CONTROL_HOLD);
3410 handle_hd_hf(sub->next, ev);
3413 /* We've most likely lost one of our calls find an active call and bring&nbs