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"
75 * Define to work around buggy dlink MGCP phone firmware which
76 * appears not to know that "rt" is part of the "G" package.
78 /* #define DLINK_BUGGY_FIRMWARE */
81 #define DEFAULT_EXPIRY 120
82 #define MAX_EXPIRY 3600
86 #define INADDR_NONE (in_addr_t)(-1)
89 /*! Global jitterbuffer configuration - by default, jb is disabled */
90 static struct ast_jb_conf default_jbconf =
94 .resync_threshold = -1,
97 static struct ast_jb_conf global_jbconf;
99 static const char tdesc[] = "Media Gateway Control Protocol (MGCP)";
100 static const char config[] = "mgcp.conf";
102 #define MGCP_DTMF_RFC2833 (1 << 0)
103 #define MGCP_DTMF_INBAND (1 << 1)
104 #define MGCP_DTMF_HYBRID (1 << 2)
106 #define DEFAULT_MGCP_GW_PORT 2427 /*!< From RFC 2705 */
107 #define DEFAULT_MGCP_CA_PORT 2727 /*!< From RFC 2705 */
108 #define MGCP_MAX_PACKET 1500 /*!< Also from RFC 2543, should sub headers tho */
109 #define DEFAULT_RETRANS 1000 /*!< How frequently to retransmit */
110 #define MAX_RETRANS 5 /*!< Try only 5 times for retransmissions */
112 /*! MGCP rtp stream modes { */
113 #define MGCP_CX_SENDONLY 0
114 #define MGCP_CX_RECVONLY 1
115 #define MGCP_CX_SENDRECV 2
116 #define MGCP_CX_CONF 3
117 #define MGCP_CX_CONFERENCE 3
118 #define MGCP_CX_MUTE 4
119 #define MGCP_CX_INACTIVE 4
122 static const char * const mgcp_cxmodes[] = {
142 static char context[AST_MAX_EXTENSION] = "default";
144 static char language[MAX_LANGUAGE] = "";
145 static char musicclass[MAX_MUSICCLASS] = "";
146 static char parkinglot[AST_MAX_CONTEXT];
147 static char cid_num[AST_MAX_EXTENSION] = "";
148 static char cid_name[AST_MAX_EXTENSION] = "";
150 static int dtmfmode = 0;
153 static ast_group_t cur_callergroup = 0;
154 static ast_group_t cur_pickupgroup = 0;
158 unsigned int tos_audio;
160 unsigned int cos_audio;
161 } qos = { 0, 0, 0, 0 };
163 static int immediate = 0;
165 static int callwaiting = 0;
167 static int callreturn = 0;
169 static int slowsequence = 0;
171 static int threewaycalling = 0;
173 /*! This is for flashhook transfers */
174 static int transfer = 0;
176 static int cancallforward = 0;
178 static int singlepath = 0;
180 static int directmedia = DIRECTMEDIA;
182 static char accountcode[AST_MAX_ACCOUNT_CODE] = "";
184 static char mailbox[AST_MAX_EXTENSION];
186 static int amaflags = 0;
190 static unsigned int oseq;
192 /*! Wait up to 16 seconds for first digit (FXO logic) */
193 static int firstdigittimeout = 16000;
195 /*! How long to wait for following digits (FXO logic) */
196 static int gendigittimeout = 8000;
198 /*! How long to wait for an extra digit, if there is an ambiguous match */
199 static int matchdigittimeout = 3000;
201 /*! Protect the monitoring thread, so only one process can kill or start it, and not
202 when it's doing something critical. */
203 AST_MUTEX_DEFINE_STATIC(netlock);
205 AST_MUTEX_DEFINE_STATIC(monlock);
207 /*! This is the thread for the monitor which checks for input on the channels
208 which are not currently in use. */
209 static pthread_t monitor_thread = AST_PTHREADT_NULL;
211 static int restart_monitor(void);
213 static int capability = AST_FORMAT_ULAW;
214 static int nonCodecCapability = AST_RTP_DTMF;
216 static char ourhost[MAXHOSTNAMELEN];
217 static struct in_addr __ourip;
220 static int mgcpdebug = 0;
222 static struct sched_context *sched;
223 static struct io_context *io;
224 /*! The private structures of the mgcp channels are linked for
225 ! selecting outgoing channels */
227 #define MGCP_MAX_HEADERS 64
228 #define MGCP_MAX_LINES 64
230 struct mgcp_request {
236 int headers; /*!< MGCP Headers */
237 char *header[MGCP_MAX_HEADERS];
238 int lines; /*!< SDP Content */
239 char *line[MGCP_MAX_LINES];
240 char data[MGCP_MAX_PACKET];
241 int cmd; /*!< int version of verb = command */
242 unsigned int trid; /*!< int version of identifier = transaction id */
243 struct mgcp_request *next; /*!< next in the queue */
246 /*! \brief mgcp_message: MGCP message for queuing up */
247 struct mgcp_message {
248 struct mgcp_endpoint *owner_ep;
249 struct mgcp_subchannel *owner_sub;
251 unsigned long expire;
254 struct mgcp_message *next;
258 #define RESPONSE_TIMEOUT 30 /*!< in seconds */
260 struct mgcp_response {
264 struct mgcp_response *next;
273 struct mgcp_subchannel {
274 /*! subchannel magic string.
275 Needed to prove that any subchannel pointer passed by asterisk
276 really points to a valid subchannel memory area.
277 Ugly.. But serves the purpose for the time being.
279 #define MGCP_SUBCHANNEL_MAGIC "!978!"
283 struct ast_channel *owner;
284 struct mgcp_endpoint *parent;
285 struct ast_rtp_instance *rtp;
286 struct sockaddr_in tmpdest;
287 char txident[80]; /*! \todo FIXME txident is replaced by rqnt_ident in endpoint.
288 This should be obsoleted */
292 struct mgcp_request *cx_queue; /*!< pending CX commands */
293 ast_mutex_t cx_queue_lock; /*!< CX queue lock */
295 int iseq; /*!< Not used? RTP? */
298 struct mgcp_subchannel *next; /*!< for out circular linked list */
301 #define MGCP_ONHOOK 1
302 #define MGCP_OFFHOOK 2
307 struct mgcp_endpoint {
310 struct mgcp_subchannel *sub; /*!< Pointer to our current connection, channel and stuff */
311 char accountcode[AST_MAX_ACCOUNT_CODE];
312 char exten[AST_MAX_EXTENSION]; /*!< Extention where to start */
313 char context[AST_MAX_EXTENSION];
314 char language[MAX_LANGUAGE];
315 char cid_num[AST_MAX_EXTENSION]; /*!< Caller*ID number */
316 char cid_name[AST_MAX_EXTENSION]; /*!< Caller*ID name */
317 char lastcallerid[AST_MAX_EXTENSION]; /*!< Last Caller*ID */
318 char dtmf_buf[AST_MAX_EXTENSION]; /*!< place to collect digits be */
319 char call_forward[AST_MAX_EXTENSION]; /*!< Last Caller*ID */
320 char musicclass[MAX_MUSICCLASS];
321 char curtone[80]; /*!< Current tone */
322 char mailbox[AST_MAX_EXTENSION];
323 char parkinglot[AST_MAX_CONTEXT]; /*!< Parkinglot */
324 struct ast_event_sub *mwi_event_sub;
325 ast_group_t callgroup;
326 ast_group_t pickupgroup;
335 int dnd; /* How does this affect callwait? Do we just deny a mgcp_request if we're dnd? */
341 int slowsequence; /*!< MS: Sequence the endpoint as a whole */
343 int iseq; /*!< Not used? */
344 int lastout; /*!< tracking this on the subchannels. Is it needed here? */
345 int needdestroy; /*!< Not used? */
347 int nonCodecCapability;
349 int msgstate; /*!< voicemail message state */
353 char rqnt_ident[80]; /*!< request identifier */
354 struct mgcp_request *rqnt_queue; /*!< pending RQNT commands */
355 ast_mutex_t rqnt_queue_lock;
356 struct mgcp_request *cmd_queue; /*!< pending commands other than RQNT */
357 ast_mutex_t cmd_queue_lock;
358 int delme; /*!< needed for reload */
359 int needaudit; /*!< needed for reload */
360 struct ast_dsp *dsp; /*!< XXX Should there be a dsp/subchannel? XXX */
361 /* owner is tracked on the subchannels, and the *sub indicates whos in charge */
362 /* struct ast_channel *owner; */
363 /* struct ast_rtp *rtp; */
364 /* struct sockaddr_in tmpdest; */
365 /* message go the the endpoint and not the channel so they stay here */
366 struct mgcp_endpoint *next;
367 struct mgcp_gateway *parent;
370 static struct mgcp_gateway {
371 /* A gateway containing one or more endpoints */
373 int isnamedottedip; /*!< is the name FQDN or dotted ip */
374 struct sockaddr_in addr;
375 struct sockaddr_in defaddr;
376 struct in_addr ourip;
378 int expire; /*!< XXX Should we ever expire dynamic registrations? XXX */
379 struct mgcp_endpoint *endpoints;
386 /* Wildcard endpoint name */
388 struct mgcp_message *msgs; /*!< gw msg queue */
389 ast_mutex_t msgs_lock; /*!< queue lock */
390 int retransid; /*!< retrans timer id */
391 int delme; /*!< needed for reload */
392 struct mgcp_response *responses;
393 struct mgcp_gateway *next;
396 AST_MUTEX_DEFINE_STATIC(mgcp_reload_lock);
397 static int mgcp_reloading = 0;
399 /*! \brief gatelock: mutex for gateway/endpoint lists */
400 AST_MUTEX_DEFINE_STATIC(gatelock);
402 static int mgcpsock = -1;
404 static struct sockaddr_in bindaddr;
406 static struct ast_frame *mgcp_read(struct ast_channel *ast);
407 static int transmit_response(struct mgcp_subchannel *sub, char *msg, struct mgcp_request *req, char *msgrest);
408 static int transmit_notify_request(struct mgcp_subchannel *sub, char *tone);
409 static int transmit_modify_request(struct mgcp_subchannel *sub);
410 static int transmit_notify_request_with_callerid(struct mgcp_subchannel *sub, char *tone, char *callernum, char *callername);
411 static int transmit_modify_with_sdp(struct mgcp_subchannel *sub, struct ast_rtp_instance *rtp, int codecs);
412 static int transmit_connection_del(struct mgcp_subchannel *sub);
413 static int transmit_audit_endpoint(struct mgcp_endpoint *p);
414 static void start_rtp(struct mgcp_subchannel *sub);
415 static void handle_response(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,
416 int result, unsigned int ident, struct mgcp_request *resp);
417 static void dump_cmd_queues(struct mgcp_endpoint *p, struct mgcp_subchannel *sub);
418 static char *mgcp_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
419 static int reload_config(int reload);
421 static struct ast_channel *mgcp_request(const char *type, int format, const struct ast_channel *requestor, void *data, int *cause);
422 static int mgcp_call(struct ast_channel *ast, char *dest, int timeout);
423 static int mgcp_hangup(struct ast_channel *ast);
424 static int mgcp_answer(struct ast_channel *ast);
425 static struct ast_frame *mgcp_read(struct ast_channel *ast);
426 static int mgcp_write(struct ast_channel *ast, struct ast_frame *frame);
427 static int mgcp_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen);
428 static int mgcp_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
429 static int mgcp_senddigit_begin(struct ast_channel *ast, char digit);
430 static int mgcp_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
431 static int mgcp_devicestate(void *data);
432 static void add_header_offhook(struct mgcp_subchannel *sub, struct mgcp_request *resp);
434 static const struct ast_channel_tech mgcp_tech = {
436 .description = tdesc,
437 .capabilities = AST_FORMAT_ULAW,
438 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
439 .requester = mgcp_request,
440 .devicestate = mgcp_devicestate,
442 .hangup = mgcp_hangup,
443 .answer = mgcp_answer,
446 .indicate = mgcp_indicate,
448 .send_digit_begin = mgcp_senddigit_begin,
449 .send_digit_end = mgcp_senddigit_end,
450 .bridge = ast_rtp_instance_bridge,
453 static void mwi_event_cb(const struct ast_event *event, void *userdata)
455 /* This module does not handle MWI in an event-based manner. However, it
456 * subscribes to MWI for each mailbox that is configured so that the core
457 * knows that we care about it. Then, chan_mgcp will get the MWI from the
458 * event cache instead of checking the mailbox directly. */
461 static int has_voicemail(struct mgcp_endpoint *p)
464 struct ast_event *event;
467 cntx = mbox = ast_strdupa(p->mailbox);
469 if (ast_strlen_zero(cntx))
472 event = ast_event_get_cached(AST_EVENT_MWI,
473 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mbox,
474 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, cntx,
478 new_msgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
479 ast_event_destroy(event);
481 new_msgs = ast_app_has_voicemail(p->mailbox, NULL);
486 static int unalloc_sub(struct mgcp_subchannel *sub)
488 struct mgcp_endpoint *p = sub->parent;
490 ast_log(LOG_WARNING, "Trying to unalloc the real channel %s@%s?!?\n", p->name, p->parent->name);
493 ast_debug(1, "Released sub %d of channel %s@%s\n", sub->id, p->name, p->parent->name);
496 if (!ast_strlen_zero(sub->cxident)) {
497 transmit_connection_del(sub);
499 sub->cxident[0] = '\0';
500 sub->callid[0] = '\0';
501 sub->cxmode = MGCP_CX_INACTIVE;
503 sub->alreadygone = 0;
504 memset(&sub->tmpdest, 0, sizeof(sub->tmpdest));
506 ast_rtp_instance_destroy(sub->rtp);
509 dump_cmd_queues(NULL, sub); /* SC */
513 /* modified for new transport mechanism */
514 static int __mgcp_xmit(struct mgcp_gateway *gw, char *data, int len)
517 if (gw->addr.sin_addr.s_addr)
518 res=sendto(mgcpsock, data, len, 0, (struct sockaddr *)&gw->addr, sizeof(struct sockaddr_in));
520 res=sendto(mgcpsock, data, len, 0, (struct sockaddr *)&gw->defaddr, sizeof(struct sockaddr_in));
522 ast_log(LOG_WARNING, "mgcp_xmit returned %d: %s\n", res, strerror(errno));
527 static int resend_response(struct mgcp_subchannel *sub, struct mgcp_response *resp)
529 struct mgcp_endpoint *p = sub->parent;
532 ast_verbose("Retransmitting:\n%s\n to %s:%d\n", resp->buf, ast_inet_ntoa(p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
534 res = __mgcp_xmit(p->parent, resp->buf, resp->len);
540 static int send_response(struct mgcp_subchannel *sub, struct mgcp_request *req)
542 struct mgcp_endpoint *p = sub->parent;
545 ast_verbose("Transmitting:\n%s\n to %s:%d\n", req->data, ast_inet_ntoa(p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
547 res = __mgcp_xmit(p->parent, req->data, req->len);
553 /* modified for new transport framework */
554 static void dump_queue(struct mgcp_gateway *gw, struct mgcp_endpoint *p)
556 struct mgcp_message *cur, *q = NULL, *w, *prev;
558 ast_mutex_lock(&gw->msgs_lock);
559 prev = NULL, cur = gw->msgs;
561 if (!p || cur->owner_ep == p) {
563 prev->next = cur->next;
565 gw->msgs = cur->next;
567 ast_log(LOG_NOTICE, "Removing message from %s transaction %u\n",
568 gw->name, cur->seqno);
579 prev = cur, cur=cur->next;
582 ast_mutex_unlock(&gw->msgs_lock);
591 static void mgcp_queue_frame(struct mgcp_subchannel *sub, struct ast_frame *f)
595 if (!ast_channel_trylock(sub->owner)) {
596 ast_queue_frame(sub->owner, f);
597 ast_channel_unlock(sub->owner);
600 DEADLOCK_AVOIDANCE(&sub->lock);
607 static void mgcp_queue_hangup(struct mgcp_subchannel *sub)
611 if (!ast_channel_trylock(sub->owner)) {
612 ast_queue_hangup(sub->owner);
613 ast_channel_unlock(sub->owner);
616 DEADLOCK_AVOIDANCE(&sub->lock);
623 static void mgcp_queue_control(struct mgcp_subchannel *sub, int control)
625 struct ast_frame f = { AST_FRAME_CONTROL, };
626 f.subclass = control;
627 return mgcp_queue_frame(sub, &f);
630 static int retrans_pkt(const void *data)
632 struct mgcp_gateway *gw = (struct mgcp_gateway *)data;
633 struct mgcp_message *cur, *exq = NULL, *w, *prev;
636 /* find out expired msgs */
637 ast_mutex_lock(&gw->msgs_lock);
639 prev = NULL, cur = gw->msgs;
641 if (cur->retrans < MAX_RETRANS) {
644 ast_verbose("Retransmitting #%d transaction %u on [%s]\n",
645 cur->retrans, cur->seqno, gw->name);
647 __mgcp_xmit(gw, cur->buf, cur->len);
653 prev->next = cur->next;
655 gw->msgs = cur->next;
657 ast_log(LOG_WARNING, "Maximum retries exceeded for transaction %u on [%s]\n",
658 cur->seqno, gw->name);
678 ast_mutex_unlock(&gw->msgs_lock);
682 /* time-out transaction */
683 handle_response(cur->owner_ep, cur->owner_sub, 406, cur->seqno, NULL);
691 /* modified for the new transaction mechanism */
692 static int mgcp_postrequest(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,
693 char *data, int len, unsigned int seqno)
695 struct mgcp_message *msg;
696 struct mgcp_message *cur;
697 struct mgcp_gateway *gw;
700 msg = ast_malloc(sizeof(*msg) + len);
704 gw = ((p && p->parent) ? p->parent : NULL);
711 if (gw->messagepending && (gw->lastouttime + 20 < t)) {
712 ast_log(LOG_NOTICE, "Timeout waiting for response to message:%d, lastouttime: %ld, now: %ld. Dumping pending queue\n",
713 gw->msgs ? gw->msgs->seqno : -1, (long) gw->lastouttime, (long) t);
714 dump_queue(sub->parent);
717 msg->owner_sub = sub;
723 memcpy(msg->buf, data, msg->len);
725 ast_mutex_lock(&gw->msgs_lock);
736 msg->expire = now.tv_sec * 1000 + now.tv_usec / 1000 + DEFAULT_RETRANS;
738 if (gw->retransid == -1)
739 gw->retransid = ast_sched_add(sched, DEFAULT_RETRANS, retrans_pkt, (void *)gw);
740 ast_mutex_unlock(&gw->msgs_lock);
742 if (!gw->messagepending) {
743 gw->messagepending = 1;
747 __mgcp_xmit(gw, msg->buf, msg->len);
748 /* XXX Should schedule retransmission XXX */
751 ast_debug(1, "Deferring transmission of transaction %d\n", seqno);
756 /* modified for new transport */
757 static int send_request(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,
758 struct mgcp_request *req, unsigned int seqno)
761 struct mgcp_request **queue, *q, *r, *t;
764 ast_debug(1, "Slow sequence is %d\n", p->slowsequence);
765 if (p->slowsequence) {
766 queue = &p->cmd_queue;
767 l = &p->cmd_queue_lock;
772 queue = &sub->cx_queue;
773 l = &sub->cx_queue_lock;
776 /* delete pending cx cmds */
787 queue = &sub->cx_queue;
788 l = &sub->cx_queue_lock;
793 queue = &p->rqnt_queue;
794 l = &p->rqnt_queue_lock;
799 queue = &p->cmd_queue;
800 l = &p->cmd_queue_lock;
806 r = ast_malloc(sizeof(*r));
808 ast_log(LOG_WARNING, "Cannot post MGCP request: insufficient memory\n");
812 memcpy(r, req, sizeof(*r));
816 ast_verbose("Posting Request:\n%s to %s:%d\n", req->data,
817 ast_inet_ntoa(p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
820 res = mgcp_postrequest(p, sub, req->data, req->len, seqno);
823 ast_verbose("Queueing Request:\n%s to %s:%d\n", req->data,
824 ast_inet_ntoa(p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
828 /* XXX find tail. We could also keep tail in the data struct for faster access */
829 for (t = *queue; t && t->next; t = t->next);
842 static int mgcp_call(struct ast_channel *ast, char *dest, int timeout)
845 struct mgcp_endpoint *p;
846 struct mgcp_subchannel *sub;
848 const char *distinctive_ring = NULL;
849 struct varshead *headp;
850 struct ast_var_t *current;
853 ast_verb(3, "MGCP mgcp_call(%s)\n", ast->name);
857 headp = &ast->varshead;
858 AST_LIST_TRAVERSE(headp,current,entries) {
859 /* Check whether there is an ALERT_INFO variable */
860 if (strcasecmp(ast_var_name(current),"ALERT_INFO") == 0) {
861 distinctive_ring = ast_var_value(current);
865 ast_mutex_lock(&sub->lock);
866 switch (p->hookstate) {
868 if (!ast_strlen_zero(distinctive_ring)) {
869 snprintf(tone, sizeof(tone), "L/wt%s", distinctive_ring);
871 ast_verb(3, "MGCP distinctive callwait %s\n", tone);
874 ast_copy_string(tone, "L/wt", sizeof(tone));
876 ast_verb(3, "MGCP normal callwait %s\n", tone);
882 if (!ast_strlen_zero(distinctive_ring)) {
883 snprintf(tone, sizeof(tone), "L/r%s", distinctive_ring);
885 ast_verb(3, "MGCP distinctive ring %s\n", tone);
888 ast_copy_string(tone, "L/rg", sizeof(tone));
890 ast_verb(3, "MGCP default ring\n");
896 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
897 ast_log(LOG_WARNING, "mgcp_call called on %s, neither down nor reserved\n", ast->name);
898 ast_mutex_unlock(&sub->lock);
904 sub->cxmode = MGCP_CX_RECVONLY;
905 if (p->type == TYPE_LINE) {
909 transmit_modify_request(sub);
912 if (sub->next->owner && !ast_strlen_zero(sub->next->cxident) && !ast_strlen_zero(sub->next->callid)) {
913 /* try to prevent a callwait from disturbing the other connection */
914 sub->next->cxmode = MGCP_CX_RECVONLY;
915 transmit_modify_request(sub->next);
918 transmit_notify_request_with_callerid(sub, tone, ast->connected.id.number, ast->connected.id.name);
919 ast_setstate(ast, AST_STATE_RINGING);
921 if (sub->next->owner && !ast_strlen_zero(sub->next->cxident) && !ast_strlen_zero(sub->next->callid)) {
922 /* Put the connection back in sendrecv */
923 sub->next->cxmode = MGCP_CX_SENDRECV;
924 transmit_modify_request(sub->next);
927 ast_log(LOG_NOTICE, "Don't know how to dial on trunks yet\n");
930 ast_mutex_unlock(&sub->lock);
931 ast_queue_control(ast, AST_CONTROL_RINGING);
935 static int mgcp_hangup(struct ast_channel *ast)
937 struct mgcp_subchannel *sub = ast->tech_pvt;
938 struct mgcp_endpoint *p = sub->parent;
940 ast_debug(1, "mgcp_hangup(%s)\n", ast->name);
941 if (!ast->tech_pvt) {
942 ast_debug(1, "Asked to hangup channel not connected\n");
945 if (strcmp(sub->magic, MGCP_SUBCHANNEL_MAGIC)) {
946 ast_debug(1, "Invalid magic. MGCP subchannel freed up already.\n");
949 ast_mutex_lock(&sub->lock);
951 ast_verb(3, "MGCP mgcp_hangup(%s) on %s@%s\n", ast->name, p->name, p->parent->name);
954 if ((p->dtmfmode & MGCP_DTMF_INBAND) && p->dsp) {
955 /* check whether other channel is active. */
956 if (!sub->next->owner) {
957 if (p->dtmfmode & MGCP_DTMF_HYBRID)
958 p->dtmfmode &= ~MGCP_DTMF_INBAND;
960 ast_verb(2, "MGCP free dsp on %s@%s\n", p->name, p->parent->name);
962 ast_dsp_free(p->dsp);
968 if (!ast_strlen_zero(sub->cxident)) {
969 transmit_connection_del(sub);
971 sub->cxident[0] = '\0';
972 if ((sub == p->sub) && sub->next->owner) {
973 if (p->hookstate == MGCP_OFFHOOK) {
974 if (sub->next->owner && ast_bridged_channel(sub->next->owner)) {
975 transmit_notify_request_with_callerid(p->sub, "L/wt", ast_bridged_channel(sub->next->owner)->cid.cid_num, ast_bridged_channel(sub->next->owner)->cid.cid_name);
978 /* set our other connection as the primary and swith over to it */
980 p->sub->cxmode = MGCP_CX_RECVONLY;
981 transmit_modify_request(p->sub);
982 if (sub->next->owner && ast_bridged_channel(sub->next->owner)) {
983 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);
987 } else if ((sub == p->sub->next) && p->hookstate == MGCP_OFFHOOK) {
988 transmit_notify_request(sub, "L/v");
989 } else if (p->hookstate == MGCP_OFFHOOK) {
990 transmit_notify_request(sub, "L/ro");
992 transmit_notify_request(sub, "");
995 ast->tech_pvt = NULL;
996 sub->alreadygone = 0;
998 sub->cxmode = MGCP_CX_INACTIVE;
999 sub->callid[0] = '\0';
1001 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
1003 /* Reset temporary destination */
1004 memset(&sub->tmpdest, 0, sizeof(sub->tmpdest));
1006 ast_rtp_instance_destroy(sub->rtp);
1010 ast_module_unref(ast_module_info->self);
1012 if ((p->hookstate == MGCP_ONHOOK) && (!sub->next->rtp)) {
1013 p->hidecallerid = 0;
1014 if (p->hascallwaiting && !p->callwaiting) {
1015 ast_verb(3, "Enabling call waiting on %s\n", ast->name);
1016 p->callwaiting = -1;
1018 if (has_voicemail(p)) {
1020 ast_verb(3, "MGCP mgcp_hangup(%s) on %s@%s set vmwi(+)\n",
1021 ast->name, p->name, p->parent->name);
1023 transmit_notify_request(sub, "L/vmwi(+)");
1026 ast_verb(3, "MGCP mgcp_hangup(%s) on %s@%s set vmwi(-)\n",
1027 ast->name, p->name, p->parent->name);
1029 transmit_notify_request(sub, "L/vmwi(-)");
1032 ast_mutex_unlock(&sub->lock);
1036 static char *handle_mgcp_show_endpoints(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1038 struct mgcp_gateway *mg;
1039 struct mgcp_endpoint *me;
1040 int hasendpoints = 0;
1044 e->command = "mgcp show endpoints";
1046 "Usage: mgcp show endpoints\n"
1047 " Lists all endpoints known to the MGCP (Media Gateway Control Protocol) subsystem.\n";
1054 return CLI_SHOWUSAGE;
1055 ast_mutex_lock(&gatelock);
1059 ast_cli(a->fd, "Gateway '%s' at %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->dynamic ? "Dynamic" : "Static");
1061 /* Don't show wilcard endpoint */
1062 if (strcmp(me->name, mg->wcardep) != 0)
1063 ast_cli(a->fd, " -- '%s@%s in '%s' is %s\n", me->name, mg->name, me->context, me->sub->owner ? "active" : "idle");
1067 if (!hasendpoints) {
1068 ast_cli(a->fd, " << No Endpoints Defined >> ");
1072 ast_mutex_unlock(&gatelock);
1076 static char *handle_mgcp_audit_endpoint(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1078 struct mgcp_gateway *mg;
1079 struct mgcp_endpoint *me;
1081 char *ename,*gname, *c;
1085 e->command = "mgcp audit endpoint";
1087 "Usage: mgcp audit endpoint <endpointid>\n"
1088 " Lists the capabilities of an endpoint in the MGCP (Media Gateway Control Protocol) subsystem.\n"
1089 " mgcp debug MUST be on to see the results of this command.\n";
1096 return CLI_SHOWUSAGE;
1099 return CLI_SHOWUSAGE;
1100 /* split the name into parts by null */
1101 ename = ast_strdupa(a->argv[3]);
1104 if (*gname == '@') {
1111 if (gname[0] == '[')
1113 if ((c = strrchr(gname, ']')))
1115 ast_mutex_lock(&gatelock);
1118 if (!strcasecmp(mg->name, gname)) {
1121 if (!strcasecmp(me->name, ename)) {
1123 transmit_audit_endpoint(me);
1135 ast_cli(a->fd, " << Could not find endpoint >> ");
1137 ast_mutex_unlock(&gatelock);
1141 static char *handle_mgcp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1145 e->command = "mgcp set debug {on|off}";
1147 "Usage: mgcp set debug {on|off}\n"
1148 " Enables/Disables dumping of MGCP packets for debugging purposes\n";
1154 if (a->argc != e->args)
1155 return CLI_SHOWUSAGE;
1157 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
1159 ast_cli(a->fd, "MGCP Debugging Enabled\n");
1160 } else if (!strncasecmp(a->argv[3], "off", 3)) {
1162 ast_cli(a->fd, "MGCP Debugging Disabled\n");
1164 return CLI_SHOWUSAGE;
1169 static struct ast_cli_entry cli_mgcp[] = {
1170 AST_CLI_DEFINE(handle_mgcp_audit_endpoint, "Audit specified MGCP endpoint"),
1171 AST_CLI_DEFINE(handle_mgcp_show_endpoints, "List defined MGCP endpoints"),
1172 AST_CLI_DEFINE(handle_mgcp_set_debug, "Enable/Disable MGCP debugging"),
1173 AST_CLI_DEFINE(mgcp_reload, "Reload MGCP configuration"),
1176 static int mgcp_answer(struct ast_channel *ast)
1179 struct mgcp_subchannel *sub = ast->tech_pvt;
1180 struct mgcp_endpoint *p = sub->parent;
1182 ast_mutex_lock(&sub->lock);
1183 sub->cxmode = MGCP_CX_SENDRECV;
1187 transmit_modify_request(sub);
1189 ast_verb(3, "MGCP mgcp_answer(%s) on %s@%s-%d\n",
1190 ast->name, p->name, p->parent->name, sub->id);
1191 if (ast->_state != AST_STATE_UP) {
1192 ast_setstate(ast, AST_STATE_UP);
1193 ast_debug(1, "mgcp_answer(%s)\n", ast->name);
1194 transmit_notify_request(sub, "");
1195 transmit_modify_request(sub);
1197 ast_mutex_unlock(&sub->lock);
1201 static struct ast_frame *mgcp_rtp_read(struct mgcp_subchannel *sub)
1203 /* Retrieve audio/etc from channel. Assumes sub->lock is already held. */
1204 struct ast_frame *f;
1206 f = ast_rtp_instance_read(sub->rtp, 0);
1207 /* Don't send RFC2833 if we're not supposed to */
1208 if (f && (f->frametype == AST_FRAME_DTMF) && !(sub->parent->dtmfmode & MGCP_DTMF_RFC2833))
1209 return &ast_null_frame;
1211 /* We already hold the channel lock */
1212 if (f->frametype == AST_FRAME_VOICE) {
1213 if (f->subclass != sub->owner->nativeformats) {
1214 ast_debug(1, "Oooh, format changed to %d\n", f->subclass);
1215 sub->owner->nativeformats = f->subclass;
1216 ast_set_read_format(sub->owner, sub->owner->readformat);
1217 ast_set_write_format(sub->owner, sub->owner->writeformat);
1219 /* Courtesy fearnor aka alex@pilosoft.com */
1220 if ((sub->parent->dtmfmode & MGCP_DTMF_INBAND) && (sub->parent->dsp)) {
1222 ast_log(LOG_NOTICE, "MGCP ast_dsp_process\n");
1224 f = ast_dsp_process(sub->owner, sub->parent->dsp, f);
1232 static struct ast_frame *mgcp_read(struct ast_channel *ast)
1234 struct ast_frame *f;
1235 struct mgcp_subchannel *sub = ast->tech_pvt;
1236 ast_mutex_lock(&sub->lock);
1237 f = mgcp_rtp_read(sub);
1238 ast_mutex_unlock(&sub->lock);
1242 static int mgcp_write(struct ast_channel *ast, struct ast_frame *frame)
1244 struct mgcp_subchannel *sub = ast->tech_pvt;
1246 if (frame->frametype != AST_FRAME_VOICE) {
1247 if (frame->frametype == AST_FRAME_IMAGE)
1250 ast_log(LOG_WARNING, "Can't send %d type frames with MGCP write\n", frame->frametype);
1254 if (!(frame->subclass & ast->nativeformats)) {
1255 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1256 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
1261 ast_mutex_lock(&sub->lock);
1262 if ((sub->parent->sub == sub) || !sub->parent->singlepath) {
1264 res = ast_rtp_instance_write(sub->rtp, frame);
1267 ast_mutex_unlock(&sub->lock);
1272 static int mgcp_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1274 struct mgcp_subchannel *sub = newchan->tech_pvt;
1276 ast_mutex_lock(&sub->lock);
1277 ast_log(LOG_NOTICE, "mgcp_fixup(%s, %s)\n", oldchan->name, newchan->name);
1278 if (sub->owner != oldchan) {
1279 ast_mutex_unlock(&sub->lock);
1280 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, sub->owner);
1283 sub->owner = newchan;
1284 ast_mutex_unlock(&sub->lock);
1288 static int mgcp_senddigit_begin(struct ast_channel *ast, char digit)
1290 struct mgcp_subchannel *sub = ast->tech_pvt;
1291 struct mgcp_endpoint *p = sub->parent;
1294 ast_mutex_lock(&sub->lock);
1295 if (p->dtmfmode & MGCP_DTMF_INBAND || p->dtmfmode & MGCP_DTMF_HYBRID) {
1296 ast_log(LOG_DEBUG, "Sending DTMF using inband/hybrid\n");
1297 res = -1; /* Let asterisk play inband indications */
1298 } else if (p->dtmfmode & MGCP_DTMF_RFC2833) {
1299 ast_log(LOG_DEBUG, "Sending DTMF using RFC2833");
1300 ast_rtp_instance_dtmf_begin(sub->rtp, digit);
1302 ast_log(LOG_ERROR, "Don't know about DTMF_MODE %d\n", p->dtmfmode);
1304 ast_mutex_unlock(&sub->lock);
1309 static int mgcp_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
1311 struct mgcp_subchannel *sub = ast->tech_pvt;
1312 struct mgcp_endpoint *p = sub->parent;
1316 ast_mutex_lock(&sub->lock);
1317 if (p->dtmfmode & MGCP_DTMF_INBAND || p->dtmfmode & MGCP_DTMF_HYBRID) {
1318 ast_log(LOG_DEBUG, "Stopping DTMF using inband/hybrid\n");
1319 res = -1; /* Tell Asterisk to stop inband indications */
1320 } else if (p->dtmfmode & MGCP_DTMF_RFC2833) {
1321 ast_log(LOG_DEBUG, "Stopping DTMF using RFC2833\n");
1326 transmit_notify_request(sub, tmp);
1327 ast_rtp_instance_dtmf_end(sub->rtp, digit);
1329 ast_log(LOG_ERROR, "Don't know about DTMF_MODE %d\n", p->dtmfmode);
1331 ast_mutex_unlock(&sub->lock);
1337 * \brief mgcp_devicestate: channel callback for device status monitoring
1338 * \param data tech/resource name of MGCP device to query
1340 * Callback for device state management in channel subsystem
1341 * to obtain device status (up/down) of a specific MGCP endpoint
1343 * \return device status result (from devicestate.h) AST_DEVICE_INVALID (not available) or AST_DEVICE_UNKNOWN (available but unknown state)
1345 static int mgcp_devicestate(void *data)
1347 struct mgcp_gateway *g;
1348 struct mgcp_endpoint *e = NULL;
1349 char *tmp, *endpt, *gw;
1350 int ret = AST_DEVICE_INVALID;
1352 endpt = ast_strdupa(data);
1353 if ((tmp = strchr(endpt, '@'))) {
1359 ast_mutex_lock(&gatelock);
1362 if (strcasecmp(g->name, gw) == 0) {
1373 if (strcasecmp(e->name, endpt) == 0)
1382 * As long as the gateway/endpoint is valid, we'll
1383 * assume that the device is available and its state
1386 ret = AST_DEVICE_UNKNOWN;
1389 ast_mutex_unlock(&gatelock);
1393 static char *control2str(int ind) {
1395 case AST_CONTROL_HANGUP:
1396 return "Other end has hungup";
1397 case AST_CONTROL_RING:
1398 return "Local ring";
1399 case AST_CONTROL_RINGING:
1400 return "Remote end is ringing";
1401 case AST_CONTROL_ANSWER:
1402 return "Remote end has answered";
1403 case AST_CONTROL_BUSY:
1404 return "Remote end is busy";
1405 case AST_CONTROL_TAKEOFFHOOK:
1406 return "Make it go off hook";
1407 case AST_CONTROL_OFFHOOK:
1408 return "Line is off hook";
1409 case AST_CONTROL_CONGESTION:
1410 return "Congestion (circuits busy)";
1411 case AST_CONTROL_FLASH:
1412 return "Flash hook";
1413 case AST_CONTROL_WINK:
1415 case AST_CONTROL_OPTION:
1416 return "Set a low-level option";
1417 case AST_CONTROL_RADIO_KEY:
1419 case AST_CONTROL_RADIO_UNKEY:
1420 return "Un-Key Radio";
1425 static int mgcp_indicate(struct ast_channel *ast, int ind, const void *data, size_t datalen)
1427 struct mgcp_subchannel *sub = ast->tech_pvt;
1431 ast_verb(3, "MGCP asked to indicate %d '%s' condition on channel %s\n",
1432 ind, control2str(ind), ast->name);
1434 ast_mutex_lock(&sub->lock);
1436 case AST_CONTROL_RINGING:
1437 #ifdef DLINK_BUGGY_FIRMWARE
1438 transmit_notify_request(sub, "rt");
1440 transmit_notify_request(sub, "G/rt");
1443 case AST_CONTROL_BUSY:
1444 transmit_notify_request(sub, "L/bz");
1446 case AST_CONTROL_CONGESTION:
1447 transmit_notify_request(sub, "G/cg");
1449 case AST_CONTROL_HOLD:
1450 ast_moh_start(ast, data, NULL);
1452 case AST_CONTROL_UNHOLD:
1455 case AST_CONTROL_SRCUPDATE:
1456 ast_rtp_instance_new_source(sub->rtp);
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 mgcp_endpoint *i = sub->parent;
1475 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);
1477 tmp->tech = &mgcp_tech;
1478 tmp->nativeformats = i->capability;
1479 if (!tmp->nativeformats)
1480 tmp->nativeformats = capability;
1481 fmt = ast_best_codec(tmp->nativeformats);
1483 ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(sub->rtp, 0));
1484 if (i->dtmfmode & (MGCP_DTMF_INBAND | MGCP_DTMF_HYBRID)) {
1485 i->dsp = ast_dsp_new();
1486 ast_dsp_set_features(i->dsp, DSP_FEATURE_DIGIT_DETECT);
1487 /* this is to prevent clipping of dtmf tones during dsp processing */
1488 ast_dsp_set_digitmode(i->dsp, DSP_DIGITMODE_NOQUELCH);
1492 if (state == AST_STATE_RING)
1494 tmp->writeformat = fmt;
1495 tmp->rawwriteformat = fmt;
1496 tmp->readformat = fmt;
1497 tmp->rawreadformat = fmt;
1498 tmp->tech_pvt = sub;
1499 if (!ast_strlen_zero(i->language))
1500 ast_string_field_set(tmp, language, i->language);
1501 if (!ast_strlen_zero(i->accountcode))
1502 ast_string_field_set(tmp, accountcode, i->accountcode);
1504 tmp->amaflags = i->amaflags;
1506 ast_module_ref(ast_module_info->self);
1507 tmp->callgroup = i->callgroup;
1508 tmp->pickupgroup = i->pickupgroup;
1509 ast_string_field_set(tmp, call_forward, i->call_forward);
1510 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
1511 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
1513 /* Don't use ast_set_callerid() here because it will
1514 * generate a needless NewCallerID event */
1515 tmp->cid.cid_ani = ast_strdup(i->cid_num);
1518 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1521 ast_jb_configure(tmp, &global_jbconf);
1522 if (state != AST_STATE_DOWN) {
1523 if (ast_pbx_start(tmp)) {
1524 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1529 ast_verb(3, "MGCP mgcp_new(%s) created in state: %s\n",
1530 tmp->name, ast_state2str(state));
1532 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1537 static char* get_sdp_by_line(char* line, char *name, int nameLen)
1539 if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1540 char* r = line + nameLen + 1;
1541 while (*r && (*r < 33)) ++r;
1547 static char *get_sdp(struct mgcp_request *req, char *name)
1550 int len = strlen(name);
1553 for (x=0; x<req->lines; x++) {
1554 r = get_sdp_by_line(req->line[x], name, len);
1555 if (r[0] != '\0') return r;
1560 static void sdpLineNum_iterator_init(int* iterator)
1565 static char* get_sdp_iterate(int* iterator, struct mgcp_request *req, char *name)
1567 int len = strlen(name);
1569 while (*iterator < req->lines) {
1570 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1571 if (r[0] != '\0') return r;
1576 static char *__get_header(struct mgcp_request *req, char *name, int *start)
1579 int len = strlen(name);
1581 for (x=*start;x<req->headers;x++) {
1582 if (!strncasecmp(req->header[x], name, len) &&
1583 (req->header[x][len] == ':')) {
1584 r = req->header[x] + len + 1;
1585 while(*r && (*r < 33))
1591 /* Don't return NULL, so get_header is always a valid pointer */
1595 static char *get_header(struct mgcp_request *req, char *name)
1598 return __get_header(req, name, &start);
1601 /*! \brief get_csv: (SC:) get comma separated value */
1602 static char *get_csv(char *c, int *len, char **next)
1606 *next = NULL, *len = 0;
1607 if (!c) return NULL;
1609 while (*c && (*c < 33 || *c == ','))
1613 while (*c && (*c >= 33 && *c != ','))
1618 s = NULL, *next = NULL;
1623 static struct mgcp_subchannel *find_subchannel_and_lock(char *name, int msgid, struct sockaddr_in *sin)
1625 struct mgcp_endpoint *p = NULL;
1626 struct mgcp_subchannel *sub = NULL;
1627 struct mgcp_gateway *g;
1629 char *at = NULL, *c;
1632 ast_copy_string(tmp, name, sizeof(tmp));
1633 at = strchr(tmp, '@');
1635 ast_log(LOG_NOTICE, "Endpoint '%s' has no at sign!\n", name);
1640 ast_mutex_lock(&gatelock);
1641 if (at && (at[0] == '[')) {
1643 c = strrchr(at, ']');
1649 if ((!name || !strcasecmp(g->name, at)) &&
1650 (sin || g->addr.sin_addr.s_addr || g->defaddr.sin_addr.s_addr)) {
1651 /* Found the gateway. If it's dynamic, save it's address -- now for the endpoint */
1652 if (sin && g->dynamic && name) {
1653 if ((g->addr.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1654 (g->addr.sin_port != sin->sin_port)) {
1655 memcpy(&g->addr, sin, sizeof(g->addr));
1656 if (ast_ouraddrfor(&g->addr.sin_addr, &g->ourip))
1657 memcpy(&g->ourip, &__ourip, sizeof(g->ourip));
1658 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));
1661 /* not dynamic, check if the name matches */
1663 if (strcasecmp(g->name, at)) {
1668 /* not dynamic, no name, check if the addr matches */
1669 else if (!name && sin) {
1670 if ((g->addr.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1671 (g->addr.sin_port != sin->sin_port)) {
1682 ast_debug(1, "Searching on %s@%s for subchannel\n",
1685 #if 0 /* new transport mech */
1688 ast_debug(1, "Searching on %s@%s-%d for subchannel with lastout: %d\n",
1689 p->name, g->name, sub->id, msgid);
1690 if (sub->lastout == msgid) {
1691 ast_debug(1, "Found subchannel sub%d to handle request %d sub->lastout: %d\n",
1692 sub->id, msgid, sub->lastout);
1697 } while (sub != p->sub);
1707 } else if (name && !strcasecmp(p->name, tmp)) {
1708 ast_debug(1, "Coundn't determine subchannel, assuming current master %s@%s-%d\n",
1709 p->name, g->name, p->sub->id);
1717 ast_mutex_lock(&sub->lock);
1723 ast_mutex_unlock(&gatelock);
1727 ast_log(LOG_NOTICE, "Endpoint '%s' not found on gateway '%s'\n", tmp, at);
1729 ast_log(LOG_NOTICE, "Gateway '%s' (and thus its endpoint '%s') does not exist\n", at, tmp);
1735 static void parse(struct mgcp_request *req)
1737 /* Divide fields by NULL's */
1742 /* First header starts immediately */
1746 /* We've got a new header */
1749 printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1751 if (ast_strlen_zero(req->header[f])) {
1752 /* Line by itself means we're now in content */
1756 if (f >= MGCP_MAX_HEADERS - 1) {
1757 ast_log(LOG_WARNING, "Too many MGCP headers...\n");
1760 req->header[f] = c + 1;
1761 } else if (*c == '\r') {
1762 /* Ignore but eliminate \r's */
1767 /* Check for last header */
1768 if (!ast_strlen_zero(req->header[f]))
1771 /* Now we process any mime content */
1776 /* We've got a new line */
1779 printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1781 if (f >= MGCP_MAX_LINES - 1) {
1782 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1785 req->line[f] = c + 1;
1786 } else if (*c == '\r') {
1787 /* Ignore and eliminate \r's */
1792 /* Check for last line */
1793 if (!ast_strlen_zero(req->line[f]))
1796 /* Parse up the initial header */
1798 while(*c && *c < 33) c++;
1799 /* First the verb */
1801 while(*c && (*c > 32)) c++;
1805 while(*c && (*c < 33)) c++;
1806 req->identifier = c;
1807 while(*c && (*c > 32)) c++;
1811 while(*c && (*c < 33)) c++;
1813 while(*c && (*c > 32)) c++;
1817 while(*c && (*c < 33)) c++;
1819 while(*c && (*c > 32)) c++;
1820 while(*c && (*c < 33)) c++;
1821 while(*c && (*c > 32)) c++;
1828 ast_verbose("Verb: '%s', Identifier: '%s', Endpoint: '%s', Version: '%s'\n",
1829 req->verb, req->identifier, req->endpoint, req->version);
1830 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1833 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1836 static int process_sdp(struct mgcp_subchannel *sub, struct mgcp_request *req)
1844 int peercapability, peerNonCodecCapability;
1845 struct sockaddr_in sin;
1847 struct ast_hostent ahp; struct hostent *hp;
1848 int codec, codec_count=0;
1850 struct mgcp_endpoint *p = sub->parent;
1852 /* Get codec and RTP info from SDP */
1853 m = get_sdp(req, "m");
1854 c = get_sdp(req, "c");
1855 if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
1856 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1859 if (sscanf(c, "IN IP4 %256s", host) != 1) {
1860 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1863 /* XXX This could block for a long time, and block the main thread! XXX */
1864 hp = ast_gethostbyname(host, &ahp);
1866 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1869 if (sscanf(m, "audio %30d RTP/AVP %n", &portno, &len) != 1) {
1870 ast_log(LOG_WARNING, "Unable to determine port number for RTP in '%s'\n", m);
1873 sin.sin_family = AF_INET;
1874 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1875 sin.sin_port = htons(portno);
1876 ast_rtp_instance_set_remote_address(sub->rtp, &sin);
1878 printf("Peer RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1880 /* Scan through the RTP payload types specified in a "m=" line: */
1881 ast_rtp_codecs_payloads_clear(ast_rtp_instance_get_codecs(sub->rtp), sub->rtp);
1882 codecs = ast_strdupa(m + len);
1883 while (!ast_strlen_zero(codecs)) {
1884 if (sscanf(codecs, "%30d%n", &codec, &len) != 1) {
1887 ast_log(LOG_WARNING, "Error in codec string '%s' at '%s'\n", m, codecs);
1890 ast_rtp_codecs_payloads_set_m_type(ast_rtp_instance_get_codecs(sub->rtp), sub->rtp, codec);
1895 /* Next, scan through each "a=rtpmap:" line, noting each */
1896 /* specified RTP payload type (with corresponding MIME subtype): */
1897 sdpLineNum_iterator_init(&iterator);
1898 while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
1899 char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
1900 if (sscanf(a, "rtpmap: %30u %127[^/]/", &codec, mimeSubtype) != 2)
1902 /* Note: should really look at the 'freq' and '#chans' params too */
1903 ast_rtp_codecs_payloads_set_rtpmap_type(ast_rtp_instance_get_codecs(sub->rtp), sub->rtp, codec, "audio", mimeSubtype, 0);
1906 /* Now gather all of the codecs that were asked for: */
1907 ast_rtp_codecs_payload_formats(ast_rtp_instance_get_codecs(sub->rtp), &peercapability, &peerNonCodecCapability);
1908 p->capability = capability & peercapability;
1910 ast_verbose("Capabilities: us - %d, them - %d, combined - %d\n",
1911 capability, peercapability, p->capability);
1912 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
1913 nonCodecCapability, peerNonCodecCapability, p->nonCodecCapability);
1915 if (!p->capability) {
1916 ast_log(LOG_WARNING, "No compatible codecs!\n");
1922 static int add_header(struct mgcp_request *req, const char *var, const char *value)
1924 if (req->len >= sizeof(req->data) - 4) {
1925 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1929 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1932 req->header[req->headers] = req->data + req->len;
1933 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s: %s\r\n", var, value);
1934 req->len += strlen(req->header[req->headers]);
1935 if (req->headers < MGCP_MAX_HEADERS)
1938 ast_log(LOG_WARNING, "Out of header space\n");
1944 static int add_line(struct mgcp_request *req, char *line)
1946 if (req->len >= sizeof(req->data) - 4) {
1947 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1951 /* Add extra empty return */
1952 ast_copy_string(req->data + req->len, "\r\n", sizeof(req->data) - req->len);
1953 req->len += strlen(req->data + req->len);
1955 req->line[req->lines] = req->data + req->len;
1956 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1957 req->len += strlen(req->line[req->lines]);
1958 if (req->lines < MGCP_MAX_LINES)
1961 ast_log(LOG_WARNING, "Out of line space\n");
1967 static int init_resp(struct mgcp_request *req, char *resp, struct mgcp_request *orig, char *resprest)
1969 /* Initialize a response */
1970 if (req->headers || req->len) {
1971 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1974 req->header[req->headers] = req->data + req->len;
1975 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s %s\r\n", resp, orig->identifier, resprest);
1976 req->len += strlen(req->header[req->headers]);
1977 if (req->headers < MGCP_MAX_HEADERS)
1980 ast_log(LOG_WARNING, "Out of header space\n");
1984 static int init_req(struct mgcp_endpoint *p, struct mgcp_request *req, char *verb)
1986 /* Initialize a response */
1987 if (req->headers || req->len) {
1988 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1991 req->header[req->headers] = req->data + req->len;
1992 /* check if we need brackets around the gw name */
1993 if (p->parent->isnamedottedip)
1994 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %d %s@[%s] MGCP 1.0\r\n", verb, oseq, p->name, p->parent->name);
1996 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %d %s@%s MGCP 1.0\r\n", verb, oseq, p->name, p->parent->name);
1997 req->len += strlen(req->header[req->headers]);
1998 if (req->headers < MGCP_MAX_HEADERS)
2001 ast_log(LOG_WARNING, "Out of header space\n");
2006 static int respprep(struct mgcp_request *resp, struct mgcp_endpoint *p, char *msg, struct mgcp_request *req, char *msgrest)
2008 memset(resp, 0, sizeof(*resp));
2009 init_resp(resp, msg, req, msgrest);
2013 static int reqprep(struct mgcp_request *req, struct mgcp_endpoint *p, char *verb)
2015 memset(req, 0, sizeof(struct mgcp_request));
2017 if (oseq > 999999999)
2019 init_req(p, req, verb);
2023 static int transmit_response(struct mgcp_subchannel *sub, char *msg, struct mgcp_request *req, char *msgrest)
2025 struct mgcp_request resp;
2026 struct mgcp_endpoint *p = sub->parent;
2027 struct mgcp_response *mgr;
2029 respprep(&resp, p, msg, req, msgrest);
2030 mgr = ast_calloc(1, sizeof(*mgr) + resp.len + 1);
2032 /* Store MGCP response in case we have to retransmit */
2033 sscanf(req->identifier, "%30d", &mgr->seqno);
2034 time(&mgr->whensent);
2035 mgr->len = resp.len;
2036 memcpy(mgr->buf, resp.data, resp.len);
2037 mgr->buf[resp.len] = '\0';
2038 mgr->next = p->parent->responses;
2039 p->parent->responses = mgr;
2041 return send_response(sub, &resp);
2045 static int add_sdp(struct mgcp_request *resp, struct mgcp_subchannel *sub, struct ast_rtp_instance *rtp)
2050 struct sockaddr_in sin;
2059 struct sockaddr_in dest = { 0, };
2060 struct mgcp_endpoint *p = sub->parent;
2061 /* XXX We break with the "recommendation" and send our IP, in order that our
2062 peer doesn't have to ast_gethostbyname() us XXX */
2065 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2068 ast_rtp_instance_get_local_address(sub->rtp, &sin);
2070 ast_rtp_instance_get_remote_address(sub->rtp, &dest);
2072 if (sub->tmpdest.sin_addr.s_addr) {
2073 dest.sin_addr = sub->tmpdest.sin_addr;
2074 dest.sin_port = sub->tmpdest.sin_port;
2075 /* Reset temporary destination */
2076 memset(&sub->tmpdest, 0, sizeof(sub->tmpdest));
2078 dest.sin_addr = p->parent->ourip;
2079 dest.sin_port = sin.sin_port;
2083 ast_verbose("We're at %s port %d\n", ast_inet_ntoa(p->parent->ourip), ntohs(sin.sin_port));
2085 ast_copy_string(v, "v=0\r\n", sizeof(v));
2086 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", (int)getpid(), (int)getpid(), ast_inet_ntoa(dest.sin_addr));
2087 ast_copy_string(s, "s=session\r\n", sizeof(s));
2088 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
2089 ast_copy_string(t, "t=0 0\r\n", sizeof(t));
2090 snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2091 for (x = 1; x <= AST_FORMAT_AUDIO_MASK; x <<= 1) {
2092 if (p->capability & x) {
2094 ast_verbose("Answering with capability %d\n", x);
2096 codec = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(sub->rtp), 1, x);
2098 snprintf(costr, sizeof(costr), " %d", codec);
2099 strncat(m, costr, sizeof(m) - strlen(m) - 1);
2100 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype2(1, x, 0));
2101 strncat(a, costr, sizeof(a) - strlen(a) - 1);
2105 for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
2106 if (p->nonCodecCapability & x) {
2108 ast_verbose("Answering with non-codec capability %d\n", x);
2110 codec = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(sub->rtp), 0, x);
2112 snprintf(costr, sizeof(costr), " %d", codec);
2113 strncat(m, costr, sizeof(m) - strlen(m) - 1);
2114 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype2(0, x, 0));
2115 strncat(a, costr, sizeof(a) - strlen(a) - 1);
2116 if (x == AST_RTP_DTMF) {
2117 /* Indicate we support DTMF... Not sure about 16,
2118 but MSN supports it so dang it, we will too... */
2119 snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n", codec);
2120 strncat(a, costr, sizeof(a) - strlen(a) - 1);
2125 strncat(m, "\r\n", sizeof(m) - strlen(m) - 1);
2126 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2127 snprintf(costr, sizeof(costr), "%d", len);
2138 static int transmit_modify_with_sdp(struct mgcp_subchannel *sub, struct ast_rtp_instance *rtp, int codecs)
2140 struct mgcp_request resp;
2144 struct mgcp_endpoint *p = sub->parent;
2146 if (ast_strlen_zero(sub->cxident) && rtp) {
2147 /* We don't have a CXident yet, store the destination and
2149 ast_rtp_instance_get_remote_address(rtp, &sub->tmpdest);
2152 ast_copy_string(local, "p:20", sizeof(local));
2153 for (x = 1; x <= AST_FORMAT_AUDIO_MASK; x <<= 1) {
2154 if (p->capability & x) {
2155 snprintf(tmp, sizeof(tmp), ", a:%s", ast_rtp_lookup_mime_subtype2(1, x, 0));
2156 strncat(local, tmp, sizeof(local) - strlen(local) - 1);
2159 reqprep(&resp, p, "MDCX");
2160 add_header(&resp, "C", sub->callid);
2161 add_header(&resp, "L", local);
2162 add_header(&resp, "M", mgcp_cxmodes[sub->cxmode]);
2163 /* X header should not be sent. kept for compatibility */
2164 add_header(&resp, "X", sub->txident);
2165 add_header(&resp, "I", sub->cxident);
2166 /*add_header(&resp, "S", "");*/
2167 add_sdp(&resp, sub, rtp);
2168 /* fill in new fields */
2169 resp.cmd = MGCP_CMD_MDCX;
2171 return send_request(p, sub, &resp, oseq); /* SC */
2174 static int transmit_connect_with_sdp(struct mgcp_subchannel *sub, struct ast_rtp_instance *rtp)
2176 struct mgcp_request resp;
2180 struct mgcp_endpoint *p = sub->parent;
2182 ast_copy_string(local, "p:20", sizeof(local));
2183 for (x = 1; x <= AST_FORMAT_AUDIO_MASK; x <<= 1) {
2184 if (p->capability & x) {
2185 snprintf(tmp, sizeof(tmp), ", a:%s", ast_rtp_lookup_mime_subtype2(1, x, 0));
2186 strncat(local, tmp, sizeof(local) - strlen(local) - 1);
2190 ast_verb(3, "Creating connection for %s@%s-%d in cxmode: %s callid: %s\n",
2191 p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode], sub->callid);
2193 reqprep(&resp, p, "CRCX");
2194 add_header(&resp, "C", sub->callid);
2195 add_header(&resp, "L", local);
2196 add_header(&resp, "M", mgcp_cxmodes[sub->cxmode]);
2197 /* X header should not be sent. kept for compatibility */
2198 add_header(&resp, "X", sub->txident);
2199 /*add_header(&resp, "S", "");*/
2200 add_sdp(&resp, sub, rtp);
2201 /* fill in new fields */
2202 resp.cmd = MGCP_CMD_CRCX;
2204 return send_request(p, sub, &resp, oseq); /* SC */
2207 static int transmit_notify_request(struct mgcp_subchannel *sub, char *tone)
2209 struct mgcp_request resp;
2210 struct mgcp_endpoint *p = sub->parent;
2213 ast_verb(3, "MGCP Asked to indicate tone: %s on %s@%s-%d in cxmode: %s\n",
2214 tone, p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode]);
2216 ast_copy_string(p->curtone, tone, sizeof(p->curtone));
2217 reqprep(&resp, p, "RQNT");
2218 add_header(&resp, "X", p->rqnt_ident); /* SC */
2219 switch (p->hookstate) {
2221 add_header(&resp, "R", "L/hd(N)");
2224 add_header_offhook(sub, &resp);
2227 if (!ast_strlen_zero(tone)) {
2228 add_header(&resp, "S", tone);
2230 /* fill in new fields */
2231 resp.cmd = MGCP_CMD_RQNT;
2233 return send_request(p, NULL, &resp, oseq); /* SC */
2236 static int transmit_notify_request_with_callerid(struct mgcp_subchannel *sub, char *tone, char *callernum, char *callername)
2238 struct mgcp_request resp;
2241 struct timeval t = ast_tvnow();
2243 struct mgcp_endpoint *p = sub->parent;
2245 ast_localtime(&t, &tm, NULL);
2253 /* Keep track of last callerid for blacklist and callreturn */
2254 ast_copy_string(p->lastcallerid, l, sizeof(p->lastcallerid));
2256 snprintf(tone2, sizeof(tone2), "%s,L/ci(%02d/%02d/%02d/%02d,%s,%s)", tone,
2257 tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, l, n);
2258 ast_copy_string(p->curtone, tone, sizeof(p->curtone));
2259 reqprep(&resp, p, "RQNT");
2260 add_header(&resp, "X", p->rqnt_ident); /* SC */
2261 switch (p->hookstate) {
2263 add_header(&resp, "R", "L/hd(N)");
2266 add_header_offhook(sub, &resp);
2269 if (!ast_strlen_zero(tone2)) {
2270 add_header(&resp, "S", tone2);
2273 ast_verb(3, "MGCP Asked to indicate tone: %s on %s@%s-%d in cxmode: %s\n",
2274 tone2, p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode]);
2276 /* fill in new fields */
2277 resp.cmd = MGCP_CMD_RQNT;
2279 return send_request(p, NULL, &resp, oseq); /* SC */
2282 static int transmit_modify_request(struct mgcp_subchannel *sub)
2284 struct mgcp_request resp;
2285 struct mgcp_endpoint *p = sub->parent;
2287 if (ast_strlen_zero(sub->cxident)) {
2288 /* We don't have a CXident yet, store the destination and
2293 ast_verb(3, "Modified %s@%s-%d with new mode: %s on callid: %s\n",
2294 p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode], sub->callid);
2296 reqprep(&resp, p, "MDCX");
2297 add_header(&resp, "C", sub->callid);
2298 add_header(&resp, "M", mgcp_cxmodes[sub->cxmode]);
2299 /* X header should not be sent. kept for compatibility */
2300 add_header(&resp, "X", sub->txident);
2301 add_header(&resp, "I", sub->cxident);
2302 switch (sub->parent->hookstate) {
2304 add_header(&resp, "R", "L/hd(N)");
2307 add_header_offhook(sub, &resp);
2310 /* fill in new fields */
2311 resp.cmd = MGCP_CMD_MDCX;
2313 return send_request(p, sub, &resp, oseq); /* SC */
2317 static void add_header_offhook(struct mgcp_subchannel *sub, struct mgcp_request *resp)
2319 struct mgcp_endpoint *p = sub->parent;
2321 if (p && p->sub && p->sub->owner && p->sub->owner->_state >= AST_STATE_RINGING && (p->dtmfmode & (MGCP_DTMF_INBAND | MGCP_DTMF_HYBRID)))
2322 add_header(resp, "R", "L/hu(N),L/hf(N)");
2324 add_header(resp, "R", "L/hu(N),L/hf(N),D/[0-9#*](N)");
2327 static int transmit_audit_endpoint(struct mgcp_endpoint *p)
2329 struct mgcp_request resp;
2330 reqprep(&resp, p, "AUEP");
2331 /* removed unknown param VS */
2332 /*add_header(&resp, "F", "A,R,D,S,X,N,I,T,O,ES,E,MD,M");*/
2333 add_header(&resp, "F", "A");
2334 /* fill in new fields */
2335 resp.cmd = MGCP_CMD_AUEP;
2337 return send_request(p, NULL, &resp, oseq); /* SC */
2340 static int transmit_connection_del(struct mgcp_subchannel *sub)
2342 struct mgcp_endpoint *p = sub->parent;
2343 struct mgcp_request resp;
2346 ast_verb(3, "Delete connection %s %s@%s-%d with new mode: %s on callid: %s\n",
2347 sub->cxident, p->name, p->parent->name, sub->id, mgcp_cxmodes[sub->cxmode], sub->callid);
2349 reqprep(&resp, p, "DLCX");
2350 /* check if call id is avail */
2352 add_header(&resp, "C", sub->callid);
2353 /* X header should not be sent. kept for compatibility */
2354 add_header(&resp, "X", sub->txident);
2355 /* check if cxident is avail */
2356 if (sub->cxident[0])
2357 add_header(&resp, "I", sub->cxident);
2358 /* fill in new fields */
2359 resp.cmd = MGCP_CMD_DLCX;
2361 return send_request(p, sub, &resp, oseq); /* SC */
2364 static int transmit_connection_del_w_params(struct mgcp_endpoint *p, char *callid, char *cxident)
2366 struct mgcp_request resp;
2369 ast_verb(3, "Delete connection %s %s@%s on callid: %s\n",
2370 cxident ? cxident : "", p->name, p->parent->name, callid ? callid : "");
2372 reqprep(&resp, p, "DLCX");
2373 /* check if call id is avail */
2374 if (callid && *callid)
2375 add_header(&resp, "C", callid);
2376 /* check if cxident is avail */
2377 if (cxident && *cxident)
2378 add_header(&resp, "I", cxident);
2379 /* fill in new fields */
2380 resp.cmd = MGCP_CMD_DLCX;
2382 return send_request(p, p->sub, &resp, oseq);
2385 /*! \brief dump_cmd_queues: (SC:) cleanup pending commands */
2386 static void dump_cmd_queues(struct mgcp_endpoint *p, struct mgcp_subchannel *sub)
2388 struct mgcp_request *t, *q;
2391 ast_mutex_lock(&p->rqnt_queue_lock);
2392 for (q = p->rqnt_queue; q; t = q->next, ast_free(q), q=t);
2393 p->rqnt_queue = NULL;
2394 ast_mutex_unlock(&p->rqnt_queue_lock);
2396 ast_mutex_lock(&p->cmd_queue_lock);
2397 for (q = p->cmd_queue; q; t = q->next, ast_free(q), q=t);
2398 p->cmd_queue = NULL;
2399 ast_mutex_unlock(&p->cmd_queue_lock);
2401 ast_mutex_lock(&p->sub->cx_queue_lock);
2402 for (q = p->sub->cx_queue; q; t = q->next, ast_free(q), q=t);
2403 p->sub->cx_queue = NULL;
2404 ast_mutex_unlock(&p->sub->cx_queue_lock);
2406 ast_mutex_lock(&p->sub->next->cx_queue_lock);
2407 for (q = p->sub->next->cx_queue; q; t = q->next, ast_free(q), q=t);
2408 p->sub->next->cx_queue = NULL;
2409 ast_mutex_unlock(&p->sub->next->cx_queue_lock);
2411 ast_mutex_lock(&sub->cx_queue_lock);
2412 for (q = sub->cx_queue; q; t = q->next, ast_free(q), q=t);
2413 sub->cx_queue = NULL;
2414 ast_mutex_unlock(&sub->cx_queue_lock);
2419 /*! \brief find_command: (SC:) remove command transaction from queue */
2420 static struct mgcp_request *find_command(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,
2421 struct mgcp_request **queue, ast_mutex_t *l, int ident)
2423 struct mgcp_request *prev, *req;
2426 for (prev = NULL, req = *queue; req; prev = req, req = req->next) {
2427 if (req->trid == ident) {
2428 /* remove from queue */
2432 prev->next = req->next;
2434 /* send next pending command */
2437 ast_verbose("Posting Queued Request:\n%s to %s:%d\n", (*queue)->data,
2438 ast_inet_ntoa(p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
2441 mgcp_postrequest(p, sub, (*queue)->data, (*queue)->len, (*queue)->trid);
2446 ast_mutex_unlock(l);
2450 /* modified for new transport mechanism */
2451 static void handle_response(struct mgcp_endpoint *p, struct mgcp_subchannel *sub,
2452 int result, unsigned int ident, struct mgcp_request *resp)
2455 struct mgcp_request *req;
2456 struct mgcp_gateway *gw = p->parent;
2459 /* provisional response */
2463 if (p->slowsequence)
2464 req = find_command(p, sub, &p->cmd_queue, &p->cmd_queue_lock, ident);
2466 req = find_command(p, sub, &sub->cx_queue, &sub->cx_queue_lock, ident);
2467 else if (!(req = find_command(p, sub, &p->rqnt_queue, &p->rqnt_queue_lock, ident)))
2468 req = find_command(p, sub, &p->cmd_queue, &p->cmd_queue_lock, ident);
2471 ast_verb(3, "No command found on [%s] for transaction %d. Ignoring...\n",
2476 if (p && (result >= 400) && (result <= 599)) {
2479 p->hookstate = MGCP_OFFHOOK;
2482 p->hookstate = MGCP_ONHOOK;
2485 ast_log(LOG_NOTICE, "Transaction %d timed out\n", ident);
2488 ast_log(LOG_NOTICE, "Transaction %d aborted\n", ident);
2493 ast_log(LOG_NOTICE, "Terminating on result %d from %s@%s-%d\n",
2494 result, p->name, p->parent->name, sub ? sub->id:-1);
2495 mgcp_queue_hangup(sub);
2498 if (p->sub->next->owner) {
2499 ast_log(LOG_NOTICE, "Terminating on result %d from %s@%s-%d\n",
2500 result, p->name, p->parent->name, sub ? sub->id:-1);
2501 mgcp_queue_hangup(p->sub);
2504 if (p->sub->owner) {
2505 ast_log(LOG_NOTICE, "Terminating on result %d from %s@%s-%d\n",
2506 result, p->name, p->parent->name, sub ? sub->id:-1);
2507 mgcp_queue_hangup(p->sub);
2510 dump_cmd_queues(p, NULL);
2515 if (req->cmd == MGCP_CMD_CRCX) {
2516 if ((c = get_header(resp, "I"))) {
2517 if (!ast_strlen_zero(c) && sub) {
2518 /* if we are hanging up do not process this conn. */
2520 if (!ast_strlen_zero(sub->cxident)) {
2521 if (strcasecmp(c, sub->cxident)) {
2522 ast_log(LOG_WARNING, "Subchannel already has a cxident. sub->cxident: %s requested %s\n", sub->cxident, c);
2525 ast_copy_string(sub->cxident, c, sizeof(sub->cxident));
2526 if (sub->tmpdest.sin_addr.s_addr) {
2527 transmit_modify_with_sdp(sub, NULL, 0);
2530 /* XXX delete this one
2531 callid and conn id may already be lost.
2532 so the following del conn may have a side effect of
2533 cleaning up the next subchannel */
2534 transmit_connection_del(sub);
2540 if (req->cmd == MGCP_CMD_AUEP) {
2541 /* check stale connection ids */
2542 if ((c = get_header(resp, "I"))) {
2545 while ((v = get_csv(c, &len, &n))) {
2547 if (strncasecmp(v, p->sub->cxident, len) &&
2548 strncasecmp(v, p->sub->next->cxident, len)) {
2549 /* connection id not found. delete it */
2550 char cxident[80] = "";
2552 if (len > (sizeof(cxident) - 1))
2553 len = sizeof(cxident) - 1;
2554 ast_copy_string(cxident, v, len);
2555 ast_verb(3, "Non existing connection id %s on %s@%s \n",
2556 cxident, p->name, gw->name);
2557 transmit_connection_del_w_params(p, NULL, cxident);
2564 /* Try to determine the hookstate returned from an audit endpoint command */
2565 if ((c = get_header(resp, "ES"))) {
2566 if (!ast_strlen_zero(c)) {
2567 if (strstr(c, "hu")) {
2568 if (p->hookstate != MGCP_ONHOOK) {
2569 /* XXX cleanup if we think we are offhook XXX */
2570 if ((p->sub->owner || p->sub->next->owner ) &&
2571 p->hookstate == MGCP_OFFHOOK)
2572 mgcp_queue_hangup(sub);
2573 p->hookstate = MGCP_ONHOOK;
2575 /* update the requested events according to the new hookstate */
2576 transmit_notify_request(p->sub, "");
2578 ast_verb(3, "Setting hookstate of %s@%s to ONHOOK\n", p->name, gw->name);
2580 } else if (strstr(c, "hd")) {
2581 if (p->hookstate != MGCP_OFFHOOK) {
2582 p->hookstate = MGCP_OFFHOOK;
2584 /* update the requested events according to the new hookstate */
2585 transmit_notify_request(p->sub, "");
2587 ast_verb(3, "Setting hookstate of %s@%s to OFFHOOK\n", p->name, gw->name);
2594 if (resp && resp->lines) {
2595 /* do not process sdp if we are hanging up. this may be a late response */
2596 if (sub && sub->owner) {
2600 process_sdp(sub, resp);
2608 static void start_rtp(struct mgcp_subchannel *sub)
2610 ast_mutex_lock(&sub->lock);
2611 /* check again to be on the safe side */
2613 ast_rtp_instance_destroy(sub->rtp);
2616 /* Allocate the RTP now */
2617 sub->rtp = ast_rtp_instance_new("asterisk", sched, &bindaddr, NULL);
2618 if (sub->rtp && sub->owner)
2619 ast_channel_set_fd(sub->owner, 0, ast_rtp_instance_fd(sub->rtp, 0));
2621 ast_rtp_instance_set_qos(sub->rtp, qos.tos_audio, qos.cos_audio, "MGCP RTP");
2622 ast_rtp_instance_set_prop(sub->rtp, AST_RTP_PROPERTY_NAT, sub->nat);
2624 /* Make a call*ID */
2625 snprintf(sub->callid, sizeof(sub->callid), "%08lx%s", ast_random(), sub->txident);
2626 /* Transmit the connection create */
2627 transmit_connect_with_sdp(sub, NULL);
2628 ast_mutex_unlock(&sub->lock);
2631 static void *mgcp_ss(void *data)
2633 struct ast_channel *chan = data;
2634 struct mgcp_subchannel *sub = chan->tech_pvt;
2635 struct mgcp_endpoint *p = sub->parent;
2636 /* char exten[AST_MAX_EXTENSION] = ""; */
2638 int timeout = firstdigittimeout;
2641 int loop_pause = 100;
2643 len = strlen(p->dtmf_buf);
2645 while(len < AST_MAX_EXTENSION-1) {
2646 res = 1; /* Assume that we will get a digit */
2647 while (strlen(p->dtmf_buf) == len){
2648 ast_safe_sleep(chan, loop_pause);
2649 timeout -= loop_pause;
2658 len = strlen(p->dtmf_buf);
2660 if (!ast_ignore_pattern(chan->context, p->dtmf_buf)) {
2661 /*res = tone_zone_play_tone(p->subs[index].zfd, -1);*/
2662 ast_indicate(chan, -1);
2664 /* XXX Redundant? We should already be playing dialtone */
2665 /*tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALTONE);*/
2666 transmit_notify_request(sub, "L/dl");
2668 if (ast_exists_extension(chan, chan->context, p->dtmf_buf, 1, p->cid_num)) {
2669 if (!res || !ast_matchmore_extension(chan, chan->context, p->dtmf_buf, 1, p->cid_num)) {
2671 /* Record this as the forwarding extension */
2672 ast_copy_string(p->call_forward, p->dtmf_buf, sizeof(p->call_forward));
2673 ast_verb(3, "Setting call forward to '%s' on channel %s\n",
2674 p->call_forward, chan->name);
2675 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
2676 transmit_notify_request(sub, "L/sl");
2680 /*res = tone_zone_play_tone(p->subs[index].zfd, -1);*/
2681 ast_indicate(chan, -1);
2683 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2684 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALTONE);*/
2685 transmit_notify_request(sub, "L/dl");
2689 /*res = tone_zone_play_tone(p->subs[index].zfd, -1);*/
2690 ast_indicate(chan, -1);
2691 ast_copy_string(chan->exten, p->dtmf_buf, sizeof(chan->exten));
2692 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2693 ast_set_callerid(chan,
2694 p->hidecallerid ? "" : p->cid_num,
2695 p->hidecallerid ? "" : p->cid_name,
2696 chan->cid.cid_ani ? NULL : p->cid_num);
2697 ast_setstate(chan, AST_STATE_RING);
2698 /*dahdi_enable_ec(p);*/
2699 if (p->dtmfmode & MGCP_DTMF_HYBRID) {
2700 p->dtmfmode |= MGCP_DTMF_INBAND;
2701 ast_indicate(chan, -1);
2703 res = ast_pbx_run(chan);
2705 ast_log(LOG_WARNING, "PBX exited non-zero\n");
2706 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_CONGESTION);*/
2707 /*transmit_notify_request(p, "nbz", 1);*/
2708 transmit_notify_request(sub, "G/cg");
2713 /* It's a match, but they just typed a digit, and there is an ambiguous match,
2714 so just set the timeout to matchdigittimeout and wait some more */
2715 timeout = matchdigittimeout;
2717 } else if (res == 0) {
2718 ast_debug(1, "not enough digits (and no ambiguous match)...\n");
2719 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_CONGESTION);*/
2720 transmit_notify_request(sub, "G/cg");
2721 /*dahdi_wait_event(p->subs[index].zfd);*/
2723 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2725 } else if (p->hascallwaiting && p->callwaiting && !strcmp(p->dtmf_buf, "*70")) {
2726 ast_verb(3, "Disabling call waiting on %s\n", chan->name);
2727 /* Disable call waiting if enabled */
2729 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
2730 transmit_notify_request(sub, "L/sl");
2732 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2733 timeout = firstdigittimeout;
2734 } else if (!strcmp(p->dtmf_buf,ast_pickup_ext())) {
2735 /* Scan all channels and see if any there
2736 * ringing channqels with that have call groups
2737 * that equal this channels pickup group
2739 if (ast_pickup_call(chan)) {
2740 ast_log(LOG_WARNING, "No call pickup possible...\n");
2741 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_CONGESTION);*/
2742 transmit_notify_request(sub, "G/cg");
2744 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2747 } else if (!p->hidecallerid && !strcmp(p->dtmf_buf, "*67")) {
2748 ast_verb(3, "Disabling Caller*ID on %s\n", chan->name);
2749 /* Disable Caller*ID if enabled */
2750 p->hidecallerid = 1;
2751 ast_set_callerid(chan, "", "", NULL);
2752 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
2753 transmit_notify_request(sub, "L/sl");
2755 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2756 timeout = firstdigittimeout;
2757 } else if (p->callreturn && !strcmp(p->dtmf_buf, "*69")) {
2759 if (!ast_strlen_zero(p->lastcallerid)) {
2760 res = ast_say_digit_str(chan, p->lastcallerid, "", chan->language);
2763 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
2764 transmit_notify_request(sub, "L/sl");
2766 } else if (!strcmp(p->dtmf_buf, "*78")) {
2767 /* Do not disturb */
2768 ast_verb(3, "Enabled DND on channel %s\n", chan->name);
2769 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
2770 transmit_notify_request(sub, "L/sl");
2773 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2775 } else if (!strcmp(p->dtmf_buf, "*79")) {
2776 /* Do not disturb */
2777 ast_verb(3, "Disabled DND on channel %s\n", chan->name);
2778 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
2779 transmit_notify_request(sub, "L/sl");
2782 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2784 } else if (p->cancallforward && !strcmp(p->dtmf_buf, "*72")) {
2785 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
2786 transmit_notify_request(sub, "L/sl");
2788 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2790 } else if (p->cancallforward && !strcmp(p->dtmf_buf, "*73")) {
2791 ast_verb(3, "Cancelling call forwarding on channel %s\n", chan->name);
2792 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
2793 transmit_notify_request(sub, "L/sl");
2794 memset(p->call_forward, 0, sizeof(p->call_forward));
2796 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2798 } else if (!strcmp(p->dtmf_buf, ast_parking_ext()) &&
2799 sub->next->owner && ast_bridged_channel(sub->next->owner)) {
2800 /* This is a three way call, the main call being a real channel,
2801 and we're parking the first call. */
2802 ast_masq_park_call(ast_bridged_channel(sub->next->owner), chan, 0, NULL);
2803 ast_verb(3, "Parking call to '%s'\n", chan->name);
2805 } else if (!ast_strlen_zero(p->lastcallerid) && !strcmp(p->dtmf_buf, "*60")) {
2806 ast_verb(3, "Blacklisting number %s\n", p->lastcallerid);
2807 res = ast_db_put("blacklist", p->lastcallerid, "1");
2809 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
2810 transmit_notify_request(sub, "L/sl");
2811 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2814 } else if (p->hidecallerid && !strcmp(p->dtmf_buf, "*82")) {
2815 ast_verb(3, "Enabling Caller*ID on %s\n", chan->name);
2816 /* Enable Caller*ID if enabled */
2817 p->hidecallerid = 0;
2818 ast_set_callerid(chan, p->cid_num, p->cid_name, NULL);
2819 /*res = tone_zone_play_tone(p->subs[index].zfd, DAHDI_TONE_DIALRECALL);*/
2820 transmit_notify_request(sub, "L/sl");
2822 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2823 timeout = firstdigittimeout;
2824 } else if (!ast_canmatch_extension(chan, chan->context, p->dtmf_buf, 1, chan->cid.cid_num) &&
2825 ((p->dtmf_buf[0] != '*') || (strlen(p->dtmf_buf) > 2))) {
2826 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);
2830 timeout = gendigittimeout;
2831 if (len && !ast_ignore_pattern(chan->context, p->dtmf_buf))
2832 /*tone_zone_play_tone(p->subs[index].zfd, -1);*/
2833 ast_indicate(chan, -1);
2837 res = ast_waitfordigit(chan, to);
2839 ast_debug(1, "Timeout...\n");
2843 ast_debug(1, "Got hangup...\n");
2848 if (!ast_ignore_pattern(chan->context, exten))
2849 ast_indicate(chan, -1);
2850 if (ast_matchmore_extension(chan, chan->context, exten, 1, chan->callerid)) {
2851 if (ast_exists_extension(chan, chan->context, exten, 1, chan->callerid))
2858 if (ast_exists_extension(chan, chan->context, exten, 1, chan->callerid)) {
2859 ast_copy_string(chan->exten, exten, sizeof(chan->exten)1);
2863 ast_setstate(chan, AST_STATE_RING);
2865 if (ast_pbx_run(chan)) {
2866 ast_log(LOG_WARNING, "Unable to launch PBX on %s\n", chan->name);
2868 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2874 memset(p->dtmf_buf, 0, sizeof(p->dtmf_buf));
2878 static int attempt_transfer(struct mgcp_endpoint *p)
2880 /* *************************
2881 * I hope this works.
2882 * Copied out of chan_zap
2883 * Cross your fingers
2884 * *************************/
2886 /* In order to transfer, we need at least one of the channels to
2887 actually be in a call bridge. We can't conference two applications
2888 together (but then, why would we want to?) */
2889 if (ast_bridged_channel(p->sub->owner)) {
2890 /* The three-way person we're about to transfer to could still be in MOH, so
2891 stop if now if appropriate */
2892 if (ast_bridged_channel(p->sub->next->owner))
2893 ast_queue_control(p->sub->next->owner, AST_CONTROL_UNHOLD);
2894 if (p->sub->owner->_state == AST_STATE_RINGING) {
2895 ast_indicate(ast_bridged_channel(p->sub->next->owner), AST_CONTROL_RINGING);
2897 if (ast_channel_masquerade(p->sub->next->owner, ast_bridged_channel(p->sub->owner))) {
2898 ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
2899 ast_bridged_channel(p->sub->owner)->name, p->sub->next->owner->name);
2902 /* Orphan the channel */
2903 unalloc_sub(p->sub->next);
2904 } else if (ast_bridged_channel(p->sub->next->owner)) {
2905 if (p->sub->owner->_state == AST_STATE_RINGING) {
2906 ast_indicate(ast_bridged_channel(p->sub->next->owner), AST_CONTROL_RINGING);
2908 ast_queue_control(p->sub->next->owner, AST_CONTROL_UNHOLD);
2909 if (ast_channel_masquerade(p->sub->owner, ast_bridged_channel(p->sub->next->owner))) {
2910 ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
2911 ast_bridged_channel(p->sub->next->owner)->name, p->sub->owner->name);
2914 /*swap_subs(p, SUB_THREEWAY, SUB_REAL);*/
2915 ast_verb(3, "Swapping %d for %d on %s@%s\n", p->sub->id, p->sub->next->id, p->name, p->parent->name);
2916 p->sub = p->sub->next;
2917 unalloc_sub(p->sub->next);
2918 /* Tell the caller not to hangup */
2921 ast_debug(1, "Neither %s nor %s are in a bridge, nothing to transfer\n",
2922 p->sub->owner->name, p->sub->next->owner->name);
2923 p->sub->next->owner->_softhangup |= AST_SOFTHANGUP_DEV;
2924 if (p->sub->next->owner) {
2925 p->sub->next->alreadygone = 1;
2926 mgcp_queue_hangup(p->sub->next);
2932 static void handle_hd_hf(struct mgcp_subchannel *sub, char *ev)
2934 struct mgcp_endpoint *p = sub->parent;
2935 struct ast_channel *c;
2938 /* Off hook / answer */
2939 if (sub->outgoing) {
2942 if (ast_bridged_channel(sub->owner))
2943 ast_queue_control(sub->owner, AST_CONTROL_UNHOLD);
2944 sub->cxmode = MGCP_CX_SENDRECV;
2948 transmit_modify_request(sub);
2950 /*transmit_notify_request(sub, "aw");*/
2951 transmit_notify_request(sub, "");
2952 mgcp_queue_control(sub, AST_CONTROL_ANSWER);
2956 /*sub->cxmode = MGCP_CX_SENDRECV;*/
2961 transmit_modify_request(sub);
2964 /* The channel is immediately up. Start right away */
2965 #ifdef DLINK_BUGGY_FIRMWARE
2966 transmit_notify_request(sub, "rt");
2968 transmit_notify_request(sub, "G/rt");
2970 c = mgcp_new(sub, AST_STATE_RING, NULL);
2972 ast_log(LOG_WARNING, "Unable to start PBX on channel %s@%s\n", p->name, p->parent->name);
2973 transmit_notify_request(sub, "G/cg");
2977 if (has_voicemail(p)) {
2978 transmit_notify_request(sub, "L/sl");
2980 transmit_notify_request(sub, "L/dl");
2982 c = mgcp_new(sub, AST_STATE_DOWN, NULL);
2984 if (ast_pthread_create_detached(&t, NULL, mgcp_ss, c)) {
2985 ast_log(LOG_WARNING, "Unable to create switch thread: %s\n", strerror(errno));
2989 ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", p->name, p->parent->name);
2993 if (p->hookstate == MGCP_OFFHOOK) {
2994 ast_log(LOG_WARNING, "Off hook, but already have owner on %s@%s\n", p->name, p->parent->name);
2996 ast_log(LOG_WARNING, "On hook, but already have owner on %s@%s\n", p->name, p->parent->name);
2997 ast_log(LOG_WARNING, "If we're onhook why are we here trying to handle a hd or hf?\n");
2999 if (ast_bridged_channel(sub->owner))
3000 ast_queue_control(sub->owner, AST_CONTROL_UNHOLD);
3001 sub->cxmode = MGCP_CX_SENDRECV;
3005 transmit_modify_request(sub);
3007 /*transmit_notify_request(sub, "aw");*/
3008 transmit_notify_request(sub, "");
3009 /*ast_queue_control(sub->owner, AST_CONTROL_ANSWER);*/
3014 static int handle_request(struct mgcp_subchannel *sub, struct mgcp_request *req, struct sockaddr_in *sin)
3017 struct ast_frame f = { 0, };
3018 struct mgcp_endpoint *p = sub->parent;
3019 struct mgcp_gateway *g = NULL;
3023 ast_verbose("Handling request '%s' on %s@%s\n", req->verb, p->name, p->parent->name);
3025 /* Clear out potential response */
3026 if (!strcasecmp(req->verb, "RSIP")) {
3027 /* Test if this RSIP request is just a keepalive */
3028 if(!strcasecmp( get_header(req, "RM"), "X-keepalive")) {
3029 ast_verb(3, "Received keepalive request from %s@%s\n", p->name, p->parent->name);
3030 transmit_response(sub, "200", req, "OK");
3032 dump_queue(p->parent, p);
3033 dump_cmd_queues(p, NULL);
3035 if ((strcmp(p->name, p->parent->wcardep) != 0)) {
3036 ast_verb(3, "Resetting interface %s@%s\n", p->name, p->parent->name);
3038 /* For RSIP on wildcard we reset all endpoints */
3039 if (!strcmp(p->name, p->parent->wcardep)) {
3040 /* Reset all endpoints */
3041 struct mgcp_endpoint *tmp_ep;
3044 tmp_ep = g->endpoints;
3046 /*if ((strcmp(tmp_ep->name, "*") != 0) && (strcmp(tmp_ep->name, "aaln/" "*") != 0)) {*/
3047 if (strcmp(tmp_ep->name, g->wcardep) != 0) {
3048 struct mgcp_subchannel *tmp_sub, *first_sub;
3049 ast_verb(3, "Resetting interface %s@%s\n", tmp_ep->name, p->parent->name);
3051 first_sub = tmp_ep->sub;
3052 tmp_sub = tmp_ep->sub;
3054 mgcp_queue_hangup(tmp_sub);
3055 tmp_sub = tmp_sub->next;
3056 if (tmp_sub == first_sub)
3060 tmp_ep = tmp_ep->next;
3062 } else if (sub->owner) {
3063 mgcp_queue_hangup(sub);
3065 transmit_response(sub, "200", req, "OK");
3066 /* We dont send NTFY or AUEP to wildcard ep */
3067 if (strcmp(p->name, p->parent->wcardep) != 0) {
3068 transmit_notify_request(sub, "");
3070 Idea is to prevent lost lines due to race conditions
3072 transmit_audit_endpoint(p);
3075 } else if (!strcasecmp(req->verb, "NTFY")) {
3076 /* Acknowledge and be sure we keep looking for the same things */
3077 transmit_response(sub, "200", req, "OK");
3078 /* Notified of an event */
3079 ev = get_header(req, "O");
3080 s = strchr(ev, '/');
3082 ast_debug(1, "Endpoint '%s@%s-%d' observed '%s'\n", p->name, p->parent->name, sub->id, ev);
3083 /* Keep looking for events unless this was a hangup */
3084 if (strcasecmp(ev, "hu") && strcasecmp(ev, "hd") && strcasecmp(ev, "ping")) {
3085 transmit_notify_request(sub, p->curtone);
3087 if (!strcasecmp(ev, "hd")) {
3088 p->hookstate = MGCP_OFFHOOK;
3089 sub->cxmode = MGCP_CX_SENDRECV;
3090 handle_hd_hf(sub, ev);
3091 } else if (!strcasecmp(ev, "hf")) {
3092 /* We can assume we are offhook if we received a hookflash */
3093 /* First let's just do call wait and ignore threeway */
3094 /* We're currently in charge */
3095 if (p->hookstate != MGCP_OFFHOOK) {
3096 /* Cisco c7940 sends hf even if the phone is onhook */
3097 /* Thanks to point on IRC for pointing this out */
3100 /* do not let * conference two down channels */
3101 if (sub->owner && sub->owner->_state == AST_STATE_DOWN && !sub->next->owner)
3104 if (p->callwaiting || p->transfer || p->threewaycalling) {
3105 ast_verb(3, "Swapping %d for %d on %s@%s\n", p->sub->id, p->sub->next->id, p->name, p->parent->name);
3106 p->sub = p->sub->next;
3108 /* transfer control to our next subchannel */
3109 if (!sub->next->owner) {
3110 /* plave the first call on hold and start up a new call */
3111 sub->cxmode = MGCP_CX_MUTE;
3112 ast_verb(3, "MGCP Muting %d on %s@%s\n", sub->id, p->name, p->parent->name);
3113 transmit_modify_request(sub);
3114 if (sub->owner && ast_bridged_channel(sub->owner))
3115 ast_queue_control(sub->owner, AST_CONTROL_HOLD);
3116 sub->next->cxmode = MGCP_CX_RECVONLY;
3117 handle_hd_hf(sub->next, ev);
3118 } else if (sub->owner && sub->next->owner) {
3119 /* We've got two active calls lets decide whether or not to conference or just flip flop */
3120 if ((!sub->outgoing) && (!sub->next->outgoing)) {
3121 /* We made both calls lets conferenct */
3122 ast_verb(3, "MGCP Conferencing %d and %d on %s@%s\n",
3123 sub->id, sub->next->id, p->name, p->parent->name);
3124 sub->cxmode = MGCP_CX_CONF;
3125 sub->next->cxmode = MGCP_CX_CONF;
3126 if (ast_bridged_channel(sub->next->owner))
3127 ast_queue_control(sub->next->owner, AST_CONTROL_UNHOLD);
3128 transmit_modify_request(sub);
3129 transmit_modify_request(sub->next);
3131 /* Let's flipflop between calls */
3132 /* XXX Need to check for state up ??? */
3133 /* XXX Need a way to indicate the current call, or maybe the call that's waiting */
3134 ast_verb(3, "We didn't make one of the calls FLIPFLOP %d and %d on %s@%s\n",
3135 sub->id, sub->next->id, p->name, p->parent->name);
3136 sub->cxmode = MGCP_CX_MUTE;
3137 ast_verb(3, "MGCP Muting %d on %s@%s\n", sub->id, p->name, p->parent->name);
3138 transmit_modify_request(sub);
3139 if (ast_bridged_channel(sub->owner))
3140 ast_queue_control(sub->owner, AST_CONTROL_HOLD);
3142 if (ast_bridged_channel(sub->next->owner))
3143 ast_queue_control(sub->next->owner, AST_CONTROL_HOLD);
3145 handle_hd_hf(sub->next, ev);
3148 /* We've most likely lost one of our calls find an active call and bring it up */
3151 } else if (sub->next->owner) {
3154 /* We seem to have lost both our calls */
3155 /* XXX - What do we do now? */
3158 if (ast_bridged_channel(p->sub->owner))
3159 ast_queue_control(p->sub->owner, AST_CONTROL_UNHOLD);
3160 p->sub->cxmode = MGCP_CX_SENDRECV;
3161 transmit_modify_request(p->sub);
3164 ast_log(LOG_WARNING, "Callwaiting, call transfer or threeway calling not enabled on endpoint %s@%s\n",
3165 p->name, p->parent->name);
3167 } else if (!strcasecmp(ev, "hu")) {
3168 p->hookstate = MGCP_ONHOOK;
3169 sub->cxmode = MGCP_CX_RECVONLY;
3170 ast_debug(1, "MGCP %s@%s Went on hook\n", p->name, p->parent->name);
3171 /* Do we need to send MDCX before a DLCX ?
3173 transmit_modify_request(sub);
3176 if (p->transfer && (sub->owner && sub->next->owner) && ((!sub->outgoing) || (!sub->next->outgoing))) {
3177 /* We're allowed to transfer, we have two avtive calls and */
3178 /* we made at least one of the calls. Let's try and transfer */
3179 ast_mutex_lock(&p->sub->next->lock);
3180 res = attempt_transfer(p);
3182 if (p->sub->next->owner) {
3183 sub->next->alreadygone = 1;
3184 mgcp_queue_hangup(sub->next);
3187 ast_log(LOG_WARNING, "Transfer attempt failed\n");
3188 ast_mutex_unlock(&p->sub->next->lock);
3191 ast_mutex_unlock(&p->sub->next->lock);
3193 /* Hangup the current call */
3194 /* If there is another active call, mgcp_hangup will ring the phone with the other call */
3196 sub->alreadygone = 1;
3197 mgcp_queue_hangup(sub);
3199 ast_verb(3, "MGCP handle_request(%s@%s-%d) ast_channel already destroyed, resending DLCX.\n",
3200 p->name, p->parent->name, sub->id);
3201 /* Instruct the other side to remove the connection since it apparently *
3202 * still thinks the channel is active. *
3203 * For Cisco IAD2421 /BAK/ */
3204 transmit_connection_del(sub);
3207 if ((p->hookstate == MGCP_ONHOOK) && (!sub->rtp) && (!sub->next->rtp)) {
3208 p->hidecallerid = 0;
3209 if (p->hascallwaiting && !p->callwaiting) {
3210 ast_verb(3, "Enabling call waiting on MGCP/%s@%s-%d\n", p->name, p->parent->name, sub->id);
3211 p->callwaiting = -1;
3213 if (has_voicemail(p)) {
3214 ast_verb(3, "MGCP handle_request(%s@%s) set vmwi(+)\n", p->name, p->parent->name);
3215 transmit_notify_request(sub, "L/vmwi(+)");
3217 ast_verb(3, "MGCP handle_request(%s@%s) set vmwi(-)\n", p->name, p->parent->name);
3218 transmit_notify_request(sub, "L/vmwi(-)");
3221 } else if ((strlen(ev) == 1) &&
3222 (((ev[0] >= '0') && (ev[0] <= '9')) ||
3223 ((ev[0] >= 'A') && (ev[0] <= 'D')) ||
3224 (ev[0] == '*') || (ev[0] == '#'))) {
3225 if (sub && sub->owner && (sub->owner->_state >= AST_STATE_UP)) {
3226 f.frametype = AST_FRAME_DTMF;
3229 /* XXX MUST queue this frame to all subs in threeway call if threeway call is active */
3230 mgcp_queue_frame(sub, &f);
3231 ast_mutex_lock(&sub->next->lock);
3232 if (sub->next->owner)
3233 mgcp_queue_frame(sub->next, &f);
3234 ast_mutex_unlock(&sub->next->lock);
3235 if (strstr(p->curtone, "wt") && (ev[0] == 'A')) {
3236 memset(p->curtone, 0, sizeof(p->curtone));
3239 p->dtmf_buf[strlen(p->dtmf_buf)] = ev[0];
3240 p->dtmf_buf[strlen(p->dtmf_buf)] = '\0';
3242 } else if (!strcasecmp(ev, "T")) {
3243 /* Digit timeout -- unimportant */
3244 } else if (!strcasecmp(ev, "ping")) {
3245 /* ping -- unimportant */
3247 ast_log(LOG_NOTICE, "Received unknown event '%s' from %s@%s\n", ev, p->name, p->parent->name);
3250 ast_log(LOG_WARNING, "Unknown verb '%s' received from %s\n", req->verb, ast_inet_ntoa(sin->sin_addr));
3251 transmit_response(sub, "510", req, "Unknown verb");
3256 static int find_and_retrans(struct mgcp_subchannel *sub, struct mgcp_request *req)
3260 struct mgcp_response *prev = NULL, *cur, *next, *answer=NULL;
3262 if (sscanf(req->identifier, "%30d", &seqno) != 1)
3264 cur = sub->parent->parent->responses;
3267 if (now - cur->whensent > RESPONSE_TIMEOUT) {
3268 /* Delete this entry */
3272 sub->parent->parent->responses = next;
3275 if (seqno == cur->seqno)
3282 resend_response(sub, answer);
3288 static int mgcpsock_read(int *id, int fd, short events, void *ignore)
3290 struct mgcp_request req;
3291 struct sockaddr_in sin;
3292 struct mgcp_subchannel *sub;
3298 memset(&req, 0, sizeof(req));
3299 res = recvfrom(mgcpsock, req.data, sizeof(req.data) - 1, 0, (struct sockaddr *)&sin, &len);
3301 if (errno != ECONNREFUSED)
3302 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
3305 req.data[res] = '\0';
3308 ast_verbose("MGCP read: \n%s\nfrom %s:%d\n", req.data, ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
3311 if (req.headers < 1) {
3312 /* Must have at least one header */
3315 if (ast_strlen_zero(req.identifier)) {
3316 ast_log(LOG_NOTICE, "Message from %s missing identifier\n", ast_inet_ntoa(sin.sin_addr));
3320 if (sscanf(req.verb, "%30d", &result) && sscanf(req.identifier, "%30d", &ident)) {
3321 /* Try to find who this message is for, if it's important */
3322 sub = find_subchannel_and_lock(NULL, ident, &sin);
3324 struct mgcp_gateway *gw = sub->parent->parent;
3325 struct mgcp_message *cur, *prev;
3327 ast_mutex_unlock(&sub->lock);
3328 ast_mutex_lock(&gw->msgs_lock);
3329 for (prev = NULL, cur = gw->msgs; cur; prev = cur, cur = cur->next) {
3330 if (cur->seqno == ident) {
3331 ast_debug(1, "Got response back on transaction %d\n", ident);
3333 prev->next = cur->next;
3335 gw->msgs = cur->next;
3340 /* stop retrans timer if the queue is empty */
3342 AST_SCHED_DEL(sched, gw->retransid);
3345 ast_mutex_unlock(&gw->msgs_lock);
3347 handle_response(cur->owner_ep, cur->owner_sub, result, ident, &req);
3352 ast_log(LOG_NOTICE, "Got response back on [%s] for transaction %d we aren't sending?\n",
3356 if (ast_strlen_zero(req.endpoint) ||
3357 ast_strlen_zero(req.version) ||
3358 ast_strlen_zero(req.verb)) {