2 * Asterisk -- A telephony toolkit for Linux.
4 * Implementation of Media Gateway Control Protocol
6 * Copyright (C) 1999, Mark Spencer
8 * Mark Spencer <markster@linux-support.net>
10 * This program is free software, distributed under the terms of
11 * the GNU General Public License
17 #include <asterisk/lock.h>
18 #include <asterisk/channel.h>
19 #include <asterisk/channel_pvt.h>
20 #include <asterisk/config.h>
21 #include <asterisk/logger.h>
22 #include <asterisk/module.h>
23 #include <asterisk/pbx.h>
24 #include <asterisk/options.h>
25 #include <asterisk/lock.h>
26 #include <asterisk/sched.h>
27 #include <asterisk/io.h>
28 #include <asterisk/rtp.h>
29 #include <asterisk/acl.h>
30 #include <asterisk/callerid.h>
31 #include <asterisk/cli.h>
32 #include <sys/socket.h>
33 #include <sys/ioctl.h>
40 #include <arpa/inet.h>
41 #include <sys/signal.h>
44 #define DEFAULT_EXPIREY 120
45 #define MAX_EXPIREY 3600
47 static char *desc = "Media Gateway Control Protocol (MGCP)";
48 static char *type = "MGCP";
49 static char *tdesc = "Media Gateway Control Protocol (MGCP)";
50 static char *config = "mgcp.conf";
52 #define DEFAULT_MGCP_PORT 2427/* From RFC 2705 */
53 #define MGCP_MAX_PACKET 1500 /* Also from RFC 2543, should sub headers tho */
56 static pthread_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
59 /* Protect the monitoring thread, so only one process can kill or start it, and not
60 when it's doing something critical. */
61 static pthread_mutex_t netlock = AST_MUTEX_INITIALIZER;
63 static pthread_mutex_t monlock = AST_MUTEX_INITIALIZER;
65 /* This is the thread for the monitor which checks for input on the channels
66 which are not currently in use. */
67 static pthread_t monitor_thread = 0;
69 static int restart_monitor(void);
71 /* Just about everybody seems to support ulaw, so make it a nice default */
72 static int capability = AST_FORMAT_ULAW;
74 static char ourhost[256];
75 static struct in_addr __ourip;
78 static int mgcpdebug = 0;
80 static struct sched_context *sched;
81 static struct io_context *io;
82 /* The private structures of the mgcp channels are linked for
83 selecting outgoing channels */
85 #define MGCP_MAX_HEADERS 64
86 #define MGCP_MAX_LINES 64
94 int headers; /* MGCP Headers */
95 char *header[MGCP_MAX_HEADERS];
96 int lines; /* SDP Content */
97 char *line[MGCP_MAX_LINES];
98 char data[MGCP_MAX_PACKET];
101 static struct mgcp_pkt {
103 struct mgcp_endpoint *owner;
105 char data[MGCP_MAX_PACKET];
106 struct mgcp_pkt *next;
112 struct mgcp_endpoint {
113 pthread_mutex_t lock;
115 char accountcode[80];
116 char exten[AST_MAX_EXTENSION]; /* Extention where to start */
117 char context[AST_MAX_EXTENSION];
118 char language[MAX_LANGUAGE];
119 char callerid[256]; /* Caller*ID */
120 char curtone[80]; /* Current tone */
135 struct ast_channel *owner;
137 struct sockaddr_in tmpdest;
138 struct mgcp_endpoint *next;
139 struct mgcp_gateway *parent;
142 struct mgcp_gateway {
143 /* A gateway containing one or more endpoints */
145 struct sockaddr_in addr;
146 struct sockaddr_in defaddr;
147 struct in_addr ourip;
149 int expire; /* XXX Should we ever expire dynamic registrations? XXX */
150 struct mgcp_endpoint *endpoints;
152 struct mgcp_gateway *next;
155 static pthread_mutex_t gatelock = AST_MUTEX_INITIALIZER;
157 static int mgcpsock = -1;
159 static struct sockaddr_in bindaddr;
161 static struct ast_frame *mgcp_read(struct ast_channel *ast);
162 static int transmit_response(struct mgcp_endpoint *p, char *msg, struct mgcp_request *req, char *msgrest);
163 static int transmit_notify_request(struct mgcp_endpoint *p, char *tone, int offhook);
164 static int transmit_connection_del(struct mgcp_endpoint *p);
165 static int transmit_notify_request_with_callerid(struct mgcp_endpoint *p, char *tone, int offhook, char *callerid);
167 static int __mgcp_xmit(struct mgcp_endpoint *p, char *data, int len)
170 if (p->parent->addr.sin_addr.s_addr)
171 res=sendto(mgcpsock, data, len, 0, (struct sockaddr *)&p->parent->addr, sizeof(struct sockaddr_in));
173 res=sendto(mgcpsock, data, len, 0, (struct sockaddr *)&p->parent->defaddr, sizeof(struct sockaddr_in));
175 ast_log(LOG_WARNING, "mgcp_xmit returned %d: %s\n", res, strerror(errno));
180 static int send_response(struct mgcp_endpoint *p, struct mgcp_request *req)
184 ast_verbose("Transmitting:\n%s\n to %s:%d\n", req->data, inet_ntoa(p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
185 res = __mgcp_xmit(p, req->data, req->len);
191 static int send_request(struct mgcp_endpoint *p, struct mgcp_request *req)
195 ast_verbose("XXX Need to handle Retransmitting XXX:\n%s to %s:%d\n", req->data, inet_ntoa(p->parent->addr.sin_addr), ntohs(p->parent->addr.sin_port));
196 res = __mgcp_xmit(p, req->data, req->len);
200 static int mgcp_call(struct ast_channel *ast, char *dest, int timeout)
203 struct mgcp_endpoint *p;
206 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
207 ast_log(LOG_WARNING, "mgcp_call called on %s, neither down nor reserved\n", ast->name);
213 if (p->type == TYPE_LINE) {
214 transmit_notify_request_with_callerid(p, "rg", 0, ast->callerid);
215 ast_setstate(ast, AST_STATE_RINGING);
216 ast_queue_control(ast, AST_CONTROL_RINGING, 0);
218 ast_log(LOG_NOTICE, "Don't know how to dial on trunks yet\n");
224 /* Interface lookup code courtesy Tilghman of DrunkCoder.com. Thanks! */
229 char ifrn_name[IFNAMSIZ]; /* Interface name, e.g. "en0". */
234 struct sockaddr_in ifru_addr;
239 struct in_addr *lookup_iface(char *iface) {
242 static struct my_ifreq ifreq;
243 strncpy(ifreq.ifr_ifrn.ifrn_name,iface,sizeof(ifreq.ifr_ifrn.ifrn_name));
245 mysock = socket(PF_INET,SOCK_DGRAM,IPPROTO_IP);
246 res = ioctl(mysock,SIOCGIFADDR,&ifreq);
250 ast_log(LOG_WARNING, "Unable to get IP of %s: %s\n", iface, strerror(errno));
253 return( (struct in_addr *) &ifreq.ifr_ifru.ifru_addr.sin_addr );
256 static struct in_addr *myaddrfor(struct in_addr *them)
259 struct in_addr *temp = NULL;
260 unsigned int remote_ip;
262 remote_ip = them->s_addr;
264 PROC = fopen("/proc/net/route","r");
266 /* If /proc/net/route doesn't exist, fall back to the old method */
269 /* First line contains headers */
270 fgets(line,sizeof(line),PROC);
272 while (!feof(PROC)) {
274 unsigned int dest, gateway, mask;
278 fgets(line,sizeof(line),PROC);
281 for (i=0;i<sizeof(line);i++) {
284 fields[aoffset++] = line + i;
285 boffset = strchr(line + i,'\t');
286 if (boffset == NULL) {
295 sscanf(fields[0],"%s",iface);
296 sscanf(fields[1],"%x",&dest);
297 sscanf(fields[2],"%x",&gateway);
298 sscanf(fields[7],"%x",&mask);
300 printf("Addr: %s %08x Dest: %08x Mask: %08x\n", inet_ntoa(*them), remote_ip, dest, mask);
302 if (((remote_ip & mask) ^ dest) == 0) {
305 ast_verbose("Interface is %s\n",iface);
306 temp = lookup_iface(iface);
308 ast_verbose("IP Address is %s\n",inet_ntoa(*temp));
314 ast_log(LOG_WARNING, "Couldn't figure out how to get to %s. Using default\n", inet_ntoa(*them));
321 static int mgcp_hangup(struct ast_channel *ast)
323 struct mgcp_endpoint *p = ast->pvt->pvt;
325 ast_log(LOG_DEBUG, "mgcp_hangup(%s)\n", ast->name);
326 if (!ast->pvt->pvt) {
327 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
330 ast_pthread_mutex_lock(&p->lock);
332 if (strlen(p->cxident))
333 transmit_connection_del(p);
334 strcpy(p->cxident, "");
335 if (!p->alreadygone && (!p->outgoing || (ast->_state == AST_STATE_UP)))
336 transmit_notify_request(p, "ro", 1);
338 transmit_notify_request(p, "", 0);
339 ast->pvt->pvt = NULL;
342 strcpy(p->callid, "");
343 /* Reset temporary destination */
344 memset(&p->tmpdest, 0, sizeof(p->tmpdest));
346 ast_rtp_destroy(p->rtp);
349 ast_pthread_mutex_unlock(&p->lock);
353 static int mgcp_show_endpoints(int fd, int argc, char *argv[])
355 struct mgcp_gateway *g;
356 struct mgcp_endpoint *e;
357 int hasendpoints = 0;
359 return RESULT_SHOWUSAGE;
360 ast_pthread_mutex_lock(&gatelock);
364 ast_cli(fd, "Gateway '%s' at %s (%s)\n", g->name, g->addr.sin_addr.s_addr ? inet_ntoa(g->addr.sin_addr) : inet_ntoa(g->defaddr.sin_addr), g->dynamic ? "Dynamic" : "Static");
366 ast_cli(fd, " -- '%s@%s in '%s' is %s\n", e->name, g->name, e->context, e->owner ? "active" : "idle");
371 ast_cli(fd, " << No Endpoints Defined >> ");
375 ast_pthread_mutex_unlock(&gatelock);
376 return RESULT_SUCCESS;
379 static char show_endpoints_usage[] =
380 "Usage: mgcp show endpoints\n"
381 " Lists all endpoints known to the MGCP (Media Gateawy Control Protocol) subsystem.\n";
383 static struct ast_cli_entry cli_show_endpoints =
384 { { "mgcp", "show", "endpoints", NULL }, mgcp_show_endpoints, "Show defined MGCP endpoints", show_endpoints_usage };
386 static int mgcp_answer(struct ast_channel *ast)
389 struct mgcp_endpoint *p = ast->pvt->pvt;
390 if (ast->_state != AST_STATE_UP) {
391 ast_setstate(ast, AST_STATE_UP);
393 ast_log(LOG_DEBUG, "mgcp_answer(%s)\n", ast->name);
394 transmit_notify_request(p, "", 1);
399 static struct ast_frame *mgcp_rtp_read(struct mgcp_endpoint *p)
401 /* Retrieve audio/etc from channel. Assumes p->lock is already held. */
403 f = ast_rtp_read(p->rtp);
405 /* We already hold the channel lock */
406 if (f->frametype == AST_FRAME_VOICE) {
407 if (f->subclass != p->owner->nativeformats) {
408 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
409 p->owner->nativeformats = f->subclass;
410 ast_set_read_format(p->owner, p->owner->readformat);
411 ast_set_write_format(p->owner, p->owner->writeformat);
419 static struct ast_frame *mgcp_read(struct ast_channel *ast)
421 struct ast_frame *fr;
422 struct mgcp_endpoint *p = ast->pvt->pvt;
423 ast_pthread_mutex_lock(&p->lock);
424 fr = mgcp_rtp_read(p);
425 ast_pthread_mutex_unlock(&p->lock);
429 static int mgcp_write(struct ast_channel *ast, struct ast_frame *frame)
431 struct mgcp_endpoint *p = ast->pvt->pvt;
433 if (frame->frametype != AST_FRAME_VOICE) {
434 if (frame->frametype == AST_FRAME_IMAGE)
437 ast_log(LOG_WARNING, "Can't send %d type frames with MGCP write\n", frame->frametype);
441 if (!(frame->subclass & ast->nativeformats)) {
442 ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
443 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
448 ast_pthread_mutex_lock(&p->lock);
450 res = ast_rtp_write(p->rtp, frame);
452 ast_pthread_mutex_unlock(&p->lock);
457 static int mgcp_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
459 struct mgcp_endpoint *p = newchan->pvt->pvt;
460 ast_pthread_mutex_lock(&p->lock);
461 if (p->owner != oldchan) {
462 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
466 ast_pthread_mutex_unlock(&p->lock);
470 static int mgcp_senddigit(struct ast_channel *ast, char digit)
472 struct mgcp_endpoint *p = ast->pvt->pvt;
476 transmit_notify_request(p, tmp, 1);
481 static int mgcp_indicate(struct ast_channel *ast, int ind)
483 struct mgcp_endpoint *p = ast->pvt->pvt;
485 case AST_CONTROL_RINGING:
486 transmit_notify_request(p, "rt", 1);
488 case AST_CONTROL_BUSY:
489 transmit_notify_request(p, "bz", 1);
491 case AST_CONTROL_CONGESTION:
492 transmit_notify_request(p, "nbz", 1);
495 transmit_notify_request(p, "", 1);
498 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", ind);
504 static struct ast_channel *mgcp_new(struct mgcp_endpoint *i, int state)
506 struct ast_channel *tmp;
508 tmp = ast_channel_alloc(1);
510 tmp->nativeformats = i->capability;
511 if (!tmp->nativeformats)
512 tmp->nativeformats = capability;
513 fmt = ast_best_codec(tmp->nativeformats);
514 snprintf(tmp->name, sizeof(tmp->name), "MGCP/%s@%s", i->name, i->parent->name);
516 tmp->fds[0] = ast_rtp_fd(i->rtp);
518 ast_setstate(tmp, state);
519 if (state == AST_STATE_RING)
521 tmp->writeformat = fmt;
522 tmp->pvt->rawwriteformat = fmt;
523 tmp->readformat = fmt;
524 tmp->pvt->rawreadformat = fmt;
526 tmp->pvt->call = mgcp_call;
527 tmp->pvt->hangup = mgcp_hangup;
528 tmp->pvt->answer = mgcp_answer;
529 tmp->pvt->read = mgcp_read;
530 tmp->pvt->write = mgcp_write;
531 tmp->pvt->indicate = mgcp_indicate;
532 tmp->pvt->fixup = mgcp_fixup;
533 tmp->pvt->send_digit = mgcp_senddigit;
534 tmp->pvt->bridge = ast_rtp_bridge;
535 if (strlen(i->language))
536 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
538 ast_pthread_mutex_lock(&usecnt_lock);
540 ast_pthread_mutex_unlock(&usecnt_lock);
541 ast_update_use_count();
542 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
543 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
544 if (strlen(i->callerid))
545 tmp->callerid = strdup(i->callerid);
547 if (state != AST_STATE_DOWN) {
548 if (ast_pbx_start(tmp)) {
549 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
555 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
559 static char *get_sdp(struct mgcp_request *req, char *name)
562 int len = strlen(name);
564 for (x=0;x<req->lines;x++) {
565 if (!strncasecmp(req->line[x], name, len) &&
566 (req->line[x][len] == '=')) {
567 r = req->line[x] + len + 1;
568 while(*r && (*r < 33))
576 static char *__get_header(struct mgcp_request *req, char *name, int *start)
579 int len = strlen(name);
581 for (x=*start;x<req->headers;x++) {
582 if (!strncasecmp(req->header[x], name, len) &&
583 (req->header[x][len] == ':')) {
584 r = req->header[x] + len + 1;
585 while(*r && (*r < 33))
591 /* Don't return NULL, so get_header is always a valid pointer */
595 static char *get_header(struct mgcp_request *req, char *name)
598 return __get_header(req, name, &start);
602 static int rtpready(struct ast_rtp *rtp, struct ast_frame *f, void *data)
604 /* Just deliver the audio directly */
605 struct mgcp_endpoint *p = data;
606 ast_pthread_mutex_lock(&p->lock);
608 /* Generally, you lock in the order channel lock, followed by private
609 lock. Since here we are doing the reverse, there is the possibility
610 of deadlock. As a result, in the case of a deadlock, we simply fail out
612 if (!pthread_mutex_trylock(&p->owner->lock)) {
613 if (f->frametype == AST_FRAME_VOICE) {
614 if (f->subclass != p->owner->nativeformats) {
615 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
616 p->owner->nativeformats = f->subclass;
617 ast_set_read_format(p->owner, p->owner->readformat);
618 ast_set_write_format(p->owner, p->owner->writeformat);
621 ast_queue_frame(p->owner, f, 0);
622 pthread_mutex_unlock(&p->owner->lock);
625 ast_pthread_mutex_unlock(&p->lock);
630 static struct mgcp_endpoint *find_endpoint(char *name, int msgid, struct sockaddr_in *sin)
632 struct mgcp_endpoint *p = NULL;
633 struct mgcp_gateway *g;
637 strncpy(tmp, name, sizeof(tmp) - 1);
638 at = strchr(tmp, '@');
640 ast_log(LOG_NOTICE, "Endpoint '%s' has no at sign!\n", name);
646 ast_pthread_mutex_lock(&gatelock);
649 if ((!name || !strcasecmp(g->name, at)) &&
650 (sin || g->addr.sin_addr.s_addr || g->defaddr.sin_addr.s_addr)) {
651 /* Found the gateway. If it's dynamic, save it's address -- now for the endpoint */
652 if (sin && g->dynamic) {
653 if ((g->addr.sin_addr.s_addr != sin->sin_addr.s_addr) ||
654 (g->addr.sin_port != sin->sin_port)) {
655 memcpy(&g->addr, sin, sizeof(g->addr));
656 memcpy(&g->ourip, myaddrfor(&g->addr.sin_addr), sizeof(g->ourip));
657 if (option_verbose > 2)
658 ast_verbose(VERBOSE_PREFIX_3 "Registered MGCP gateway '%s' at %s port %d\n", g->name, inet_ntoa(g->addr.sin_addr), ntohs(g->addr.sin_port));
663 if ((name && !strcasecmp(p->name, tmp)) ||
664 (msgid && (p->lastout == msgid)))
673 ast_pthread_mutex_unlock(&gatelock);
677 ast_log(LOG_NOTICE, "Endpoint '%s' not found on gateway '%s'\n", tmp,at);
679 ast_log(LOG_NOTICE, "Gateway '%s' (and thus its endpoint '%s') does not exist\n", at, tmp);
685 static void parse(struct mgcp_request *req)
687 /* Divide fields by NULL's */
692 /* First header starts immediately */
696 /* We've got a new header */
700 printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
702 if (!strlen(req->header[f])) {
703 /* Line by itself means we're now in content */
707 if (f >= MGCP_MAX_HEADERS - 1) {
708 ast_log(LOG_WARNING, "Too many MGCP headers...\n");
711 req->header[f] = c + 1;
712 } else if (*c == '\r') {
713 /* Ignore but eliminate \r's */
718 /* Check for last header */
719 if (strlen(req->header[f]))
722 /* Now we process any mime content */
727 /* We've got a new line */
730 printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
732 if (f >= MGCP_MAX_LINES - 1) {
733 ast_log(LOG_WARNING, "Too many SDP lines...\n");
736 req->line[f] = c + 1;
737 } else if (*c == '\r') {
738 /* Ignore and eliminate \r's */
743 /* Check for last line */
744 if (strlen(req->line[f]))
747 /* Parse up the initial header */
749 while(*c && *c < 33) c++;
752 while(*c && (*c > 32)) c++;
756 while(*c && (*c < 33)) c++;
758 while(*c && (*c > 32)) c++;
762 while(*c && (*c < 33)) c++;
764 while(*c && (*c > 32)) c++;
768 while(*c && (*c < 33)) c++;
770 while(*c && (*c > 32)) c++;
771 while(*c && (*c < 33)) c++;
772 while(*c && (*c > 32)) c++;
779 ast_verbose("Verb: '%s', Identifier: '%s', Endpoint: '%s', Version: '%s'\n",
780 req->verb, req->identifier, req->endpoint, req->version);
781 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
784 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
787 static int process_sdp(struct mgcp_endpoint *p, struct mgcp_request *req)
795 struct sockaddr_in sin;
799 /* Get codec and RTP info from SDP */
800 m = get_sdp(req, "m");
801 c = get_sdp(req, "c");
802 if (!strlen(m) || !strlen(c)) {
803 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
806 if (sscanf(c, "IN IP4 %256s", host) != 1) {
807 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
810 /* XXX This could block for a long time, and block the main thread! XXX */
811 hp = gethostbyname(host);
813 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
816 if (sscanf(m, "audio %d RTP/AVP %n", &portno, &len) != 1) {
817 ast_log(LOG_WARNING, "Unable to determine port number for RTP in '%s'\n", m);
820 sin.sin_family = AF_INET;
821 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
822 sin.sin_port = htons(portno);
824 ast_rtp_set_peer(p->rtp, &sin);
826 printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
830 while(strlen(codecs)) {
831 if (sscanf(codecs, "%d %n", &codec, &len) != 1) {
832 ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
836 printf("Codec: %d\n", codec);
838 codec = rtp2ast(codec);
840 peercapability |= codec;
843 p->capability = capability & peercapability;
845 ast_verbose("Capabilities: us - %d, them - %d, combined - %d\n",
846 capability, peercapability, p->capability);
847 if (!p->capability) {
848 ast_log(LOG_WARNING, "No compatible codecs!\n");
855 static int add_header(struct mgcp_request *req, char *var, char *value)
857 if (req->len >= sizeof(req->data) - 4) {
858 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
862 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
865 req->header[req->headers] = req->data + req->len;
866 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s: %s\r\n", var, value);
867 req->len += strlen(req->header[req->headers]);
868 if (req->headers < MGCP_MAX_HEADERS)
871 ast_log(LOG_WARNING, "Out of header space\n");
877 static int add_line(struct mgcp_request *req, char *line)
879 if (req->len >= sizeof(req->data) - 4) {
880 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
884 /* Add extra empty return */
885 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
886 req->len += strlen(req->data + req->len);
888 req->line[req->lines] = req->data + req->len;
889 snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
890 req->len += strlen(req->line[req->lines]);
891 if (req->lines < MGCP_MAX_LINES)
894 ast_log(LOG_WARNING, "Out of line space\n");
900 static int init_resp(struct mgcp_request *req, char *resp, struct mgcp_request *orig, char *resprest)
902 /* Initialize a response */
903 if (req->headers || req->len) {
904 ast_log(LOG_WARNING, "Request already initialized?!?\n");
907 req->header[req->headers] = req->data + req->len;
908 snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s %s\r\n", resp, orig->identifier, resprest);
909 req->len += strlen(req->header[req->headers]);
910 if (req->headers < MGCP_MAX_HEADERS)
913 ast_log(LOG_WARNING, "Out of header space\n");
917 static int init_req(struct mgcp_endpoint *p, struct mgcp_request *req, char *verb)
919 /* Initialize a response */
920 if (req->headers || req->len) {
921 ast_log(LOG_WARNING, "Request already initialized?!?\n");
924 req->header[req->headers] = req->data + req->len;
925 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);
926 req->len += strlen(req->header[req->headers]);
927 if (req->headers < MGCP_MAX_HEADERS)
930 ast_log(LOG_WARNING, "Out of header space\n");
935 static int respprep(struct mgcp_request *resp, struct mgcp_endpoint *p, char *msg, struct mgcp_request *req, char *msgrest)
937 memset(resp, 0, sizeof(*resp));
938 init_resp(resp, msg, req, msgrest);
942 static int reqprep(struct mgcp_request *req, struct mgcp_endpoint *p, char *verb)
944 memset(req, 0, sizeof(struct mgcp_request));
946 init_req(p, req, verb);
950 static int transmit_response(struct mgcp_endpoint *p, char *msg, struct mgcp_request *req, char *msgrest)
952 struct mgcp_request resp;
953 respprep(&resp, p, msg, req, msgrest);
954 return send_response(p, &resp);
958 static int add_sdp(struct mgcp_request *resp, struct mgcp_endpoint *p, struct ast_rtp *rtp)
963 struct sockaddr_in sin;
972 struct sockaddr_in dest;
973 /* XXX We break with the "recommendation" and send our IP, in order that our
974 peer doesn't have to gethostbyname() us XXX */
977 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
980 ast_rtp_get_us(p->rtp, &sin);
982 ast_rtp_get_peer(rtp, &dest);
984 if (p->tmpdest.sin_addr.s_addr) {
985 dest.sin_addr = p->tmpdest.sin_addr;
986 dest.sin_port = p->tmpdest.sin_port;
987 /* Reset temporary destination */
988 memset(&p->tmpdest, 0, sizeof(p->tmpdest));
990 dest.sin_addr = p->parent->ourip;
991 dest.sin_port = sin.sin_port;
995 ast_verbose("We're at %s port %d\n", inet_ntoa(p->parent->ourip), ntohs(sin.sin_port));
996 snprintf(v, sizeof(v), "v=0\r\n");
997 snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
998 snprintf(s, sizeof(s), "s=session\r\n");
999 snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
1000 snprintf(t, sizeof(t), "t=0 0\r\n");
1001 snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
1002 for (x=1;x<= AST_FORMAT_MAX_AUDIO; x <<= 1) {
1003 if (p->capability & x) {
1005 ast_verbose("Answering with capability %d\n", x);
1006 if ((codec = ast2rtp(x)) > -1) {
1007 snprintf(costr, sizeof(costr), " %d", codec);
1009 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast2rtpn(x));
1015 len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
1016 snprintf(costr, sizeof(costr), "%d", len);
1027 static int transmit_modify_with_sdp(struct mgcp_endpoint *p, struct ast_rtp *rtp)
1029 struct mgcp_request resp;
1033 if (!strlen(p->cxident) && rtp) {
1034 /* We don't have a CXident yet, store the destination and
1036 ast_rtp_get_peer(rtp, &p->tmpdest);
1039 snprintf(local, sizeof(local), "p:20");
1040 for (x=1;x<= AST_FORMAT_MAX_AUDIO; x <<= 1) {
1041 if (p->capability & x) {
1042 snprintf(tmp, sizeof(tmp), ", a:%s", ast2rtpn(x));
1046 reqprep(&resp, p, "MDCX");
1047 add_header(&resp, "C", p->callid);
1048 add_header(&resp, "L", local);
1049 add_header(&resp, "M", "sendrecv");
1050 add_header(&resp, "X", p->txident);
1051 add_header(&resp, "I", p->cxident);
1052 add_header(&resp, "S", "");
1053 add_sdp(&resp, p, rtp);
1055 return send_request(p, &resp);
1058 static int transmit_connect_with_sdp(struct mgcp_endpoint *p, struct ast_rtp *rtp)
1060 struct mgcp_request resp;
1064 snprintf(local, sizeof(local), "p:20");
1065 for (x=1;x<= AST_FORMAT_MAX_AUDIO; x <<= 1) {
1066 if (p->capability & x) {
1067 snprintf(tmp, sizeof(tmp), ", a:%s", ast2rtpn(x));
1071 reqprep(&resp, p, "CRCX");
1072 add_header(&resp, "C", p->callid);
1073 add_header(&resp, "L", local);
1074 add_header(&resp, "M", "sendrecv");
1075 add_header(&resp, "X", p->txident);
1076 add_header(&resp, "S", "");
1077 add_sdp(&resp, p, rtp);
1079 return send_request(p, &resp);
1082 static int transmit_notify_request(struct mgcp_endpoint *p, char *tone, int offhook)
1084 struct mgcp_request resp;
1085 strncpy(p->curtone, tone, sizeof(p->curtone) - 1);
1086 reqprep(&resp, p, "RQNT");
1087 add_header(&resp, "X", p->txident);
1089 add_header(&resp, "R", "hu(N), hf(N), D/[0-9#*](N)");
1091 add_header(&resp, "R", "hd(N)");
1092 add_header(&resp, "S", tone);
1093 return send_request(p, &resp);
1096 static int transmit_notify_request_with_callerid(struct mgcp_endpoint *p, char *tone, int offhook, char *callerid)
1098 struct mgcp_request resp;
1108 strncpy(cid, callerid, sizeof(cid) - 1);
1111 ast_callerid_parse(cid, &n, &l);
1113 ast_shrink_phone_number(l);
1114 if (!ast_isphonenumber(l)) {
1123 snprintf(tone2, sizeof(tone2), "%s, ci(%02d/%02d/%02d/%02d,%s,%s)", tone,
1124 tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, l, n);
1125 strncpy(p->curtone, tone, sizeof(p->curtone) - 1);
1126 reqprep(&resp, p, "RQNT");
1127 add_header(&resp, "X", p->txident);
1129 add_header(&resp, "R", "hu(N), hf(N), D/[0-9#*](N)");
1131 add_header(&resp, "R", "hd(N)");
1132 add_header(&resp, "S", tone2);
1133 return send_request(p, &resp);
1135 static int transmit_connection_del(struct mgcp_endpoint *p)
1137 struct mgcp_request resp;
1138 reqprep(&resp, p, "DLCX");
1139 add_header(&resp, "C", p->callid);
1140 add_header(&resp, "I", p->cxident);
1141 return send_request(p, &resp);
1144 static void handle_response(struct mgcp_endpoint *p, int result, int ident)
1146 if ((result >= 400) && (result <= 499)) {
1147 ast_log(LOG_NOTICE, "Terminating on result %d from %s@%s\n", result, p->name, p->parent->name);
1149 ast_softhangup(p->owner, AST_SOFTHANGUP_DEV);
1153 static void start_rtp(struct mgcp_endpoint *p)
1155 ast_pthread_mutex_lock(&p->lock);
1156 /* Allocate the RTP now */
1157 p->rtp = ast_rtp_new(NULL, NULL);
1158 if (p->rtp && p->owner)
1159 p->owner->fds[0] = ast_rtp_fd(p->rtp);
1161 ast_rtp_setnat(p->rtp, p->nat);
1163 ast_rtp_set_callback(p->rtp, rtpready);
1164 ast_rtp_set_data(p->rtp, p);
1166 /* Make a call*ID */
1167 snprintf(p->callid, sizeof(p->callid), "%08x%s", rand(), p->txident);
1168 /* Transmit the connection create */
1169 transmit_connect_with_sdp(p, NULL);
1170 ast_pthread_mutex_unlock(&p->lock);
1173 static void *mgcp_ss(void *data)
1175 struct ast_channel *chan = data;
1176 struct mgcp_endpoint *p = chan->pvt->pvt;
1177 char exten[AST_MAX_EXTENSION] = "";
1182 res = ast_waitfordigit(chan, to);
1184 ast_log(LOG_DEBUG, "Timeout...\n");
1188 ast_log(LOG_DEBUG, "Got hangup...\n");
1192 if (!ast_ignore_pattern(chan->context, exten))
1193 ast_indicate(chan, -1);
1194 if (ast_matchmore_extension(chan, chan->context, exten, 1, chan->callerid)) {
1195 if (ast_exists_extension(chan, chan->context, exten, 1, chan->callerid))
1202 if (ast_exists_extension(chan, chan->context, exten, 1, chan->callerid)) {
1203 strncpy(chan->exten, exten, sizeof(chan->exten) - 1);
1205 ast_setstate(chan, AST_STATE_RING);
1207 if (ast_pbx_run(chan)) {
1208 ast_log(LOG_WARNING, "Unable to launch PBX on %s\n", chan->name);
1216 static int handle_request(struct mgcp_endpoint *p, struct mgcp_request *req, struct sockaddr_in *sin)
1219 struct ast_channel *c;
1221 struct ast_frame f = { 0, };
1223 ast_verbose("Handling request '%s' on %s@%s\n", req->verb, p->name, p->parent->name);
1224 /* Clear out potential response */
1225 if (!strcasecmp(req->verb, "RSIP")) {
1226 if (option_verbose > 2)
1227 ast_verbose(VERBOSE_PREFIX_3 "Resetting interface %s@%s\n", p->name, p->parent->name);
1229 ast_softhangup(p->owner, AST_SOFTHANGUP_DEV);
1230 transmit_response(p, "200", req, "OK");
1231 } else if (!strcasecmp(req->verb, "NTFY")) {
1232 /* Acknowledge and be sure we keep looking for the same things */
1233 transmit_response(p, "200", req, "OK");
1234 /* Notified of an event */
1235 ev = get_header(req, "O");
1236 s = strchr(ev, '/');
1238 ast_log(LOG_DEBUG, "Endpoint '%s@%s' observed '%s'\n", p->name, p->parent->name, ev);
1239 /* Keep looking for events unless this was a hangup */
1240 if (strcasecmp(ev, "hu") && strcasecmp(ev, "hd"))
1241 transmit_notify_request(p, p->curtone, 1);
1242 if (!strcasecmp(ev, "hd")) {
1243 /* Off hook / answer */
1248 ast_queue_control(p->owner, AST_CONTROL_ANSWER, 1);
1253 transmit_notify_request(p, "dl", 1);
1254 c = mgcp_new(p, AST_STATE_DOWN);
1256 if (pthread_create(&t, NULL, mgcp_ss, c)) {
1257 ast_log(LOG_WARNING, "Unable to create switch thread: %s\n", strerror(errno));
1261 ast_log(LOG_WARNING, "Unable to create channel for %s@%s\n", p->name, p->parent->name);
1263 ast_log(LOG_WARNING, "Off hook, but alreaedy have owner on %s@%s\n", p->name, p->parent->name);
1266 } else if (!strcasecmp(ev, "hu")) {
1267 ast_log(LOG_DEBUG, "Went on hook\n");
1270 ast_queue_hangup(p->owner, 1);
1272 } else if ((strlen(ev) == 1) &&
1273 (((ev[0] >= '0') && (ev[0] <= '9')) ||
1274 ((ev[0] >= 'A') && (ev[0] <= 'D')) ||
1275 (ev[0] == '*') || (ev[0] == '#'))) {
1276 f.frametype = AST_FRAME_DTMF;
1280 ast_queue_frame(p->owner, &f, 1);
1281 } else if (!strcasecmp(ev, "T")) {
1282 /* Digit timeout -- unimportant */
1284 ast_log(LOG_NOTICE, "Received unknown event '%s' from %s@%s\n", ev, p->name, p->parent->name);
1287 ast_log(LOG_WARNING, "Unknown verb '%s' received from %s\n", req->verb, inet_ntoa(sin->sin_addr));
1288 transmit_response(p, "510", req, "Unknown verb");
1293 static int mgcpsock_read(int *id, int fd, short events, void *ignore)
1295 struct mgcp_request req;
1296 struct sockaddr_in sin;
1297 struct mgcp_endpoint *p;
1304 memset(&req, 0, sizeof(req));
1305 res = recvfrom(mgcpsock, req.data, sizeof(req.data) - 1, 0, (struct sockaddr *)&sin, &len);
1307 if (errno != ECONNREFUSED)
1308 ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
1311 req.data[res] = '\0';
1314 ast_verbose("MGCP read: \n%s\nfrom %s:%d", req.data, inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1316 if (req.headers < 1) {
1317 /* Must have at least one header */
1320 if (!req.identifier || !strlen(req.identifier)) {
1321 ast_log(LOG_NOTICE, "Message from %s missing identifier\n", inet_ntoa(sin.sin_addr));
1325 if (sscanf(req.verb, "%d", &result) &&
1326 sscanf(req.identifier, "%d", &ident)) {
1327 /* Try to find who this message is for, if it's important */
1328 p = find_endpoint(NULL, ident, &sin);
1330 handle_response(p, result, ident);
1331 if ((c = get_header(&req, "I"))) {
1333 strncpy(p->cxident, c, sizeof(p->cxident) - 1);
1334 if (p->tmpdest.sin_addr.s_addr) {
1335 transmit_modify_with_sdp(p, NULL);
1340 process_sdp(p, &req);
1343 if (!req.endpoint || !strlen(req.endpoint) ||
1344 !req.version || !strlen(req.version) ||
1345 !req.verb || !strlen(req.verb)) {
1346 ast_log(LOG_NOTICE, "Message must have a verb, an idenitifier, version, and endpoint\n");
1349 /* Process request, with iflock held */
1350 p = find_endpoint(req.endpoint, 0, &sin);
1352 handle_request(p, &req, &sin);
1358 static void *do_monitor(void *data)
1362 sched = sched_context_create();
1364 ast_log(LOG_WARNING, "Unable to create schedule context\n");
1367 io = io_context_create();
1369 ast_log(LOG_WARNING, "Unable to create I/O context\n");
1373 /* Add an I/O event to our UDP socket */
1375 ast_io_add(io, mgcpsock, mgcpsock_read, AST_IO_IN, NULL);
1377 /* This thread monitors all the frame relay interfaces which are not yet in use
1378 (and thus do not have a separate thread) indefinitely */
1379 /* From here on out, we die whenever asked */
1381 /* Check for interfaces needing to be killed */
1382 /* Don't let anybody kill us right away. Nobody should lock the interface list
1383 and wait for the monitor list, but the other way around is okay. */
1384 ast_pthread_mutex_lock(&monlock);
1385 /* Lock the network interface */
1386 ast_pthread_mutex_lock(&netlock);
1389 /* Handle any retransmissions */
1392 /* Okay, now that we know what to do, release the network lock */
1393 ast_pthread_mutex_unlock(&netlock);
1394 /* And from now on, we're okay to be killed, so release the monitor lock as well */
1395 ast_pthread_mutex_unlock(&monlock);
1396 pthread_testcancel();
1397 /* Wait for sched or io */
1398 res = ast_sched_wait(sched);
1399 res = ast_io_wait(io, res);
1400 ast_pthread_mutex_lock(&monlock);
1402 ast_sched_runq(sched);
1403 ast_pthread_mutex_unlock(&monlock);
1410 static int restart_monitor(void)
1412 /* If we're supposed to be stopped -- stay stopped */
1413 if (monitor_thread == -2)
1415 if (ast_pthread_mutex_lock(&monlock)) {
1416 ast_log(LOG_WARNING, "Unable to lock monitor\n");
1419 if (monitor_thread == pthread_self()) {
1420 ast_pthread_mutex_unlock(&monlock);
1421 ast_log(LOG_WARNING, "Cannot kill myself\n");
1424 if (monitor_thread) {
1425 /* Wake up the thread */
1426 pthread_kill(monitor_thread, SIGURG);
1428 /* Start a new monitor */
1429 if (pthread_create(&monitor_thread, NULL, do_monitor, NULL) < 0) {
1430 ast_pthread_mutex_unlock(&monlock);
1431 ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
1435 ast_pthread_mutex_unlock(&monlock);
1439 static struct ast_channel *mgcp_request(char *type, int format, void *data)
1442 struct mgcp_endpoint *p;
1443 struct ast_channel *tmpc = NULL;
1448 format &= capability;
1450 ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format '%d'\n", format);
1453 strncpy(tmp, dest, sizeof(tmp) - 1);
1455 ast_log(LOG_NOTICE, "MGCP Channels require an endpoint\n");
1458 p = find_endpoint(tmp, 0, NULL);
1460 ast_log(LOG_WARNING, "Unable to find MGCP endpoint '%s'\n", tmp);
1467 tmpc = mgcp_new(p, AST_STATE_DOWN);
1469 ast_log(LOG_WARNING, "Unable to make channel for '%s'\n", tmp);
1474 struct mgcp_gateway *build_gateway(char *cat, struct ast_variable *v)
1476 struct mgcp_gateway *gw;
1477 struct mgcp_endpoint *e;
1478 char context[AST_MAX_EXTENSION] = "default";
1479 char language[80] = "";
1480 char callerid[AST_MAX_EXTENSION] = "";
1483 gw = malloc(sizeof(struct mgcp_gateway));
1485 memset(gw, 0, sizeof(struct mgcp_gateway));
1487 strncpy(gw->name, cat, sizeof(gw->name) - 1);
1489 if (!strcasecmp(v->name, "host")) {
1490 if (!strcasecmp(v->value, "dynamic")) {
1491 /* They'll register with us */
1493 memset(&gw->addr.sin_addr, 0, 4);
1494 if (gw->addr.sin_port) {
1495 /* If we've already got a port, make it the default rather than absolute */
1496 gw->defaddr.sin_port = gw->addr.sin_port;
1497 gw->addr.sin_port = 0;
1500 /* Non-dynamic. Make sure we become that way if we're not */
1501 if (gw->expire > -1)
1502 ast_sched_del(sched, gw->expire);
1505 if (ast_get_ip(&gw->addr, v->value)) {
1510 } else if (!strcasecmp(v->name, "defaultip")) {
1511 if (ast_get_ip(&gw->defaddr, v->value)) {
1515 } else if (!strcasecmp(v->name, "permit") ||
1516 !strcasecmp(v->name, "deny")) {
1517 gw->ha = ast_append_ha(v->name, v->value, gw->ha);
1518 } else if (!strcasecmp(v->name, "port")) {
1519 gw->addr.sin_port = htons(atoi(v->value));
1520 } else if (!strcasecmp(v->name, "context")) {
1521 strncpy(context, v->value, sizeof(context) - 1);
1522 } else if (!strcasecmp(v->name, "nat")) {
1523 nat = ast_true(v->value);
1524 } else if (!strcasecmp(v->name, "callerid")) {
1525 if (!strcasecmp(v->value, "asreceived"))
1526 strcpy(callerid, "");
1528 strncpy(callerid, v->value, sizeof(callerid) - 1);
1529 } else if (!strcasecmp(v->name, "language")) {
1530 strncpy(language, v->value, sizeof(language)-1);
1531 } else if (!strcasecmp(v->name, "trunk") ||
1532 !strcasecmp(v->name, "line")) {
1533 e = malloc(sizeof(struct mgcp_endpoint));
1535 memset(e, 0, sizeof(struct mgcp_endpoint));
1536 /* XXX Should we really check for uniqueness?? XXX */
1537 snprintf(e->txident, sizeof(e->txident), "%08x", rand());
1538 strncpy(e->context, context, sizeof(e->context) - 1);
1539 strncpy(e->callerid, callerid, sizeof(e->callerid) - 1);
1540 strncpy(e->language, language, sizeof(e->language) - 1);
1541 e->capability = capability;
1544 strncpy(e->name, v->value, sizeof(e->name) - 1);
1545 if (!strcasecmp(v->name, "trunk"))
1546 e->type = TYPE_TRUNK;
1548 e->type = TYPE_LINE;
1549 e->next = gw->endpoints;
1553 ast_log(LOG_WARNING, "Don't know keyword '%s' at line %d\n", v->name, v->lineno);
1558 if (!ntohl(gw->addr.sin_addr.s_addr) && !gw->dynamic) {
1559 ast_log(LOG_WARNING, "Gateway '%s' lacks IP address and isn't dynamic\n", gw->name);
1563 if (gw->defaddr.sin_addr.s_addr && !ntohs(gw->defaddr.sin_port))
1564 gw->defaddr.sin_port = htons(DEFAULT_MGCP_PORT);
1565 if (gw->addr.sin_addr.s_addr && !ntohs(gw->addr.sin_port))
1566 gw->addr.sin_port = htons(DEFAULT_MGCP_PORT);
1567 if (gw->addr.sin_addr.s_addr)
1568 memcpy(&gw->ourip, myaddrfor(&gw->addr.sin_addr), sizeof(gw->ourip));
1572 static struct ast_rtp *mgcp_get_rtp_peer(struct ast_channel *chan)
1574 struct mgcp_endpoint *p;
1581 static int mgcp_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp)
1583 struct mgcp_endpoint *p;
1586 transmit_modify_with_sdp(p, rtp);
1592 static struct ast_rtp_protocol mgcp_rtp = {
1593 get_rtp_info: mgcp_get_rtp_peer,
1594 set_rtp_peer: mgcp_set_rtp_peer,
1597 static int mgcp_do_debug(int fd, int argc, char *argv[])
1600 return RESULT_SHOWUSAGE;
1602 ast_cli(fd, "MGCP Debugging Enabled\n");
1603 return RESULT_SUCCESS;
1606 static int mgcp_no_debug(int fd, int argc, char *argv[])
1609 return RESULT_SHOWUSAGE;
1611 ast_cli(fd, "MGCP Debugging Disabled\n");
1612 return RESULT_SUCCESS;
1615 static char debug_usage[] =
1616 "Usage: mgcp debug\n"
1617 " Enables dumping of MGCP packets for debugging purposes\n";
1619 static char no_debug_usage[] =
1620 "Usage: mgcp no debug\n"
1621 " Disables dumping of MGCP packets for debugging purposes\n";
1623 static struct ast_cli_entry cli_debug =
1624 { { "mgcp", "debug", NULL }, mgcp_do_debug, "Enable MGCP debugging", debug_usage };
1625 static struct ast_cli_entry cli_no_debug =
1626 { { "mgcp", "no", "debug", NULL }, mgcp_no_debug, "Disable MGCP debugging", no_debug_usage };
1631 struct ast_config *cfg;
1632 struct ast_variable *v;
1633 struct mgcp_gateway *g;
1638 if (gethostname(ourhost, sizeof(ourhost))) {
1639 ast_log(LOG_WARNING, "Unable to get hostname, MGCP disabled\n");
1642 cfg = ast_load(config);
1644 /* We *must* have a config file otherwise stop immediately */
1646 ast_log(LOG_NOTICE, "Unable to load config %s, MGCP disabled\n", config);
1649 memset(&bindaddr, 0, sizeof(bindaddr));
1650 v = ast_variable_browse(cfg, "general");
1652 /* Create the interface list */
1653 if (!strcasecmp(v->name, "bindaddr")) {
1654 if (!(hp = gethostbyname(v->value))) {
1655 ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
1657 memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
1659 } else if (!strcasecmp(v->name, "allow")) {
1660 format = ast_getformatbyname(v->value);
1662 ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
1664 capability |= format;
1665 } else if (!strcasecmp(v->name, "disallow")) {
1666 format = ast_getformatbyname(v->value);
1668 ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
1670 capability &= ~format;
1671 } else if (!strcasecmp(v->name, "port")) {
1672 if (sscanf(v->value, "%i", &ourport) == 1) {
1673 bindaddr.sin_port = htons(ourport);
1675 ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
1681 cat = ast_category_browse(cfg, NULL);
1683 if (strcasecmp(cat, "general")) {
1684 g = build_gateway(cat, ast_variable_browse(cfg, cat));
1686 if (option_verbose > 2)
1687 ast_verbose(VERBOSE_PREFIX_3 "Added gateway '%s'\n", g->name);
1688 ast_pthread_mutex_lock(&gatelock);
1691 ast_pthread_mutex_unlock(&gatelock);
1694 cat = ast_category_browse(cfg, cat);
1697 if (ntohl(bindaddr.sin_addr.s_addr)) {
1698 memcpy(&__ourip, &bindaddr, sizeof(__ourip));
1700 hp = gethostbyname(ourhost);
1702 ast_log(LOG_WARNING, "Unable to get our IP address, MGCP disabled\n");
1705 memcpy(&__ourip, hp->h_addr, sizeof(__ourip));
1707 if (!ntohs(bindaddr.sin_port))
1708 bindaddr.sin_port = ntohs(DEFAULT_MGCP_PORT);
1709 bindaddr.sin_family = AF_INET;
1710 pthread_mutex_lock(&netlock);
1713 mgcpsock = socket(AF_INET, SOCK_DGRAM, 0);
1715 ast_log(LOG_WARNING, "Unable to create MGCP socket: %s\n", strerror(errno));
1717 if (bind(mgcpsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
1718 ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
1719 inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
1723 } else if (option_verbose > 1)
1724 ast_verbose(VERBOSE_PREFIX_2 "MGCP Listening on %s:%d\n",
1725 inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
1727 pthread_mutex_unlock(&netlock);
1730 /* Make sure we can register our mgcp channel type */
1731 if (ast_channel_register(type, tdesc, capability, mgcp_request)) {
1732 ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
1736 mgcp_rtp.type = type;
1737 ast_rtp_proto_register(&mgcp_rtp);
1738 ast_cli_register(&cli_show_endpoints);
1739 ast_cli_register(&cli_debug);
1740 ast_cli_register(&cli_no_debug);
1741 /* And start the monitor for the first time */
1748 struct mgcp_endpoint *p, *pl;
1750 /* First, take us out of the channel loop */
1751 ast_channel_unregister(type);
1752 if (!ast_pthread_mutex_lock(&gatelock)) {
1753 /* Hangup all interfaces if they have an owner */
1757 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
1761 ast_pthread_mutex_unlock(&iflock);
1763 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1766 if (!ast_pthread_mutex_lock(&monlock)) {
1767 if (monitor_thread) {
1768 pthread_cancel(monitor_thread);
1769 pthread_kill(monitor_thread, SIGURG);
1770 pthread_join(monitor_thread, NULL);
1772 monitor_thread = -2;
1773 ast_pthread_mutex_unlock(&monlock);
1775 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1779 if (!ast_pthread_mutex_lock(&iflock)) {
1780 /* Destroy all the interfaces and free their memory */
1785 /* Free associated memory */
1789 ast_pthread_mutex_unlock(&iflock);
1791 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1801 ast_pthread_mutex_lock(&usecnt_lock);
1803 ast_pthread_mutex_unlock(&usecnt_lock);
1809 return ASTERISK_GPL_KEY;