Skip to content
Snippets Groups Projects
chan_mgcp.c 49 KiB
Newer Older
  • Learn to ignore specific revisions
  • Mark Spencer's avatar
    Mark Spencer committed
    /*
     * Asterisk -- A telephony toolkit for Linux.
     *
     * Implementation of Media Gateway Control Protocol
     * 
     * Copyright (C) 1999, Mark Spencer
     *
     * Mark Spencer <markster@linux-support.net>
     *
     * This program is free software, distributed under the terms of
     * the GNU General Public License
     */
    
    #include <stdio.h>
    #include <pthread.h>
    #include <string.h>
    #include <asterisk/lock.h>
    #include <asterisk/channel.h>
    #include <asterisk/channel_pvt.h>
    #include <asterisk/config.h>
    #include <asterisk/logger.h>
    #include <asterisk/module.h>
    #include <asterisk/pbx.h>
    #include <asterisk/options.h>
    #include <asterisk/lock.h>
    #include <asterisk/sched.h>
    #include <asterisk/io.h>
    #include <asterisk/rtp.h>
    #include <asterisk/acl.h>
    #include <asterisk/callerid.h>
    #include <asterisk/cli.h>
    #include <sys/socket.h>
    #include <sys/ioctl.h>
    #include <net/if.h>
    #include <errno.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <fcntl.h>
    #include <netdb.h>
    #include <arpa/inet.h>
    #include <sys/signal.h>
    
    #include <asterisk/dsp.h>
    
    Mark Spencer's avatar
    Mark Spencer committed
    
    #define MGCPDUMPER
    #define DEFAULT_EXPIREY 120
    #define MAX_EXPIREY     3600
    
    static char *desc = "Media Gateway Control Protocol (MGCP)";
    static char *type = "MGCP";
    static char *tdesc = "Media Gateway Control Protocol (MGCP)";
    static char *config = "mgcp.conf";
    
    #define DEFAULT_MGCP_PORT	2427/* From RFC 2705 */
    #define MGCP_MAX_PACKET	1500		/* Also from RFC 2543, should sub headers tho */
    
    static int usecnt =0;
    static pthread_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
    static int oseq;
    
    /* Protect the monitoring thread, so only one process can kill or start it, and not
       when it's doing something critical. */
    static pthread_mutex_t netlock = AST_MUTEX_INITIALIZER;
    
    static pthread_mutex_t monlock = AST_MUTEX_INITIALIZER;
    
    /* This is the thread for the monitor which checks for input on the channels
       which are not currently in use.  */
    static pthread_t monitor_thread = 0;
    
    static int restart_monitor(void);
    
    /* Just about everybody seems to support ulaw, so make it a nice default */
    static int capability = AST_FORMAT_ULAW;
    
    static char ourhost[256];
    static struct in_addr __ourip;
    static int ourport;
    
    
    static int mgcpdebug = 0;
    
    
    Mark Spencer's avatar
    Mark Spencer committed
    static struct sched_context *sched;
    static struct io_context *io;
    /* The private structures of the  mgcp channels are linked for
       selecting outgoing channels */
       
    #define MGCP_MAX_HEADERS		64
    #define MGCP_MAX_LINES 		64
    
    struct mgcp_request {
    	int len;
    	char *verb;
    	char *identifier;
    	char *endpoint;
    	char *version;
    	int headers;					/* MGCP Headers */
    	char *header[MGCP_MAX_HEADERS];
    	int lines;						/* SDP Content */
    	char *line[MGCP_MAX_LINES];
    	char data[MGCP_MAX_PACKET];
    };
    
    static struct mgcp_pkt {
    	int retrans;
    	struct mgcp_endpoint *owner;
    	int packetlen;
    	char data[MGCP_MAX_PACKET];
    	struct mgcp_pkt *next;
    } *packets = NULL;	
    
    #define TYPE_TRUNK		1
    #define TYPE_LINE		2
    
    struct mgcp_endpoint {
    	pthread_mutex_t lock;
    	char name[80];
    	char accountcode[80];
    	char exten[AST_MAX_EXTENSION];		/* Extention where to start */
    	char context[AST_MAX_EXTENSION];
    	char language[MAX_LANGUAGE];
    	char callerid[256];					/* Caller*ID */
    	char curtone[80];					/* Current tone */
    	char txident[80];
    	char cxident[80];
    	char callid[80];
    	int hascallerid;
    
    	int dtmfinband;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	int amaflags;
    	int type;
    	int group;
    	int iseq;
    
    	int nat;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	int lastout;
    	int alreadygone;
    	int needdestroy;
    	int capability;
    	int outgoing;
    
    	struct ast_dsp *vad;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	struct ast_channel *owner;
    	struct ast_rtp *rtp;
    
    	struct sockaddr_in tmpdest;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	struct mgcp_endpoint *next;
    	struct mgcp_gateway *parent;
    };
    
    struct mgcp_gateway {
    	/* A gateway containing one or more endpoints */
    	char name[80];
    	struct sockaddr_in addr;
    
    	struct sockaddr_in defaddr;
    
    Mark Spencer's avatar
    Mark Spencer committed
    	struct in_addr ourip;
    
    	int dynamic;
    	int expire;		/* XXX Should we ever expire dynamic registrations? XXX */
    
    Mark Spencer's avatar
    Mark Spencer committed
    	struct mgcp_endpoint *endpoints;
    	struct ast_ha *ha;
    	struct mgcp_gateway *next;
    } *gateways;
    
    static pthread_mutex_t gatelock  = AST_MUTEX_INITIALIZER;
    
    static int mgcpsock  = -1;
    
    static struct sockaddr_in bindaddr;
    
    static struct ast_frame  *mgcp_read(struct ast_channel *ast);
    static int transmit_response(struct mgcp_endpoint *p, char *msg, struct mgcp_request *req, char *msgrest);
    static int transmit_notify_request(struct mgcp_endpoint *p, char *tone, int offhook);
    static int transmit_connection_del(struct mgcp_endpoint *p);
    static int transmit_notify_request_with_callerid(struct mgcp_endpoint *p, char *tone, int offhook, char *callerid);
    
    static int __mgcp_xmit(struct mgcp_endpoint *p, char *data, int len)
    {
    	int res;
    
    	if (p->parent->addr.sin_addr.s_addr)
    	    res=sendto(mgcpsock, data, len, 0, (struct sockaddr *)&p->parent->addr, sizeof(struct sockaddr_in));
    	else 
    	    res=sendto(mgcpsock, data, len, 0, (struct sockaddr *)&p->parent->defaddr, sizeof(struct sockaddr_in));
    
    Mark Spencer's avatar
    Mark Spencer committed
    	if (res != len) {
    		ast_log(LOG_WARNING, "mgcp_xmit returned %d: %s\n", res, strerror(errno));
    	}
    	return res;
    }
    
    static int send_response(struct mgcp_endpoint *p, struct mgcp_request *req)
    {
    	int res;
    
    	if (mgcpdebug)
    		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));
    
    Mark Spencer's avatar
    Mark Spencer committed
    	res = __mgcp_xmit(p, req->data, req->len);
    	if (res > 0)
    		res = 0;
    	return res;
    }
    
    static int send_request(struct mgcp_endpoint *p, struct mgcp_request *req)
    {
    	int res;
    
    	if (mgcpdebug)
    		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));
    
    Mark Spencer's avatar
    Mark Spencer committed
    	res = __mgcp_xmit(p, req->data, req->len);
    	return res;
    }
    
    static int mgcp_call(struct ast_channel *ast, char *dest, int timeout)
    {
    	int res;
    	struct mgcp_endpoint *p;
    	
    	p = ast->pvt->pvt;
    	if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
    		ast_log(LOG_WARNING, "mgcp_call called on %s, neither down nor reserved\n", ast->name);
    		return -1;
    	}
    
    	res = 0;
    	p->outgoing = 1;
    	if (p->type == TYPE_LINE) {
    		transmit_notify_request_with_callerid(p, "rg", 0, ast->callerid);
    		ast_setstate(ast, AST_STATE_RINGING);
    		ast_queue_control(ast, AST_CONTROL_RINGING, 0);
    	} else {
    		ast_log(LOG_NOTICE, "Don't know how to dial on trunks yet\n");
    		res = -1;
    	}
    	return res;
    }
    
    /* Interface lookup code courtesy Tilghman of DrunkCoder.com.  Thanks! */
    
    struct my_ifreq {
        union
          {
    	char ifrn_name[IFNAMSIZ];	/* Interface name, e.g. "en0".  */
          } ifr_ifrn;
    
        union
          {
    	struct sockaddr_in ifru_addr;
    	char ifru_data[512];
          } ifr_ifru;
    };
    
    struct in_addr *lookup_iface(char *iface) {
    	int mysock;
    	int res;
    	static struct  my_ifreq ifreq;
    	strncpy(ifreq.ifr_ifrn.ifrn_name,iface,sizeof(ifreq.ifr_ifrn.ifrn_name));
    
    	mysock = socket(PF_INET,SOCK_DGRAM,IPPROTO_IP);
    	res = ioctl(mysock,SIOCGIFADDR,&ifreq);
    	
    	close(mysock);
    	if (res < 0) {
    		ast_log(LOG_WARNING, "Unable to get IP of %s: %s\n", iface, strerror(errno));
    		return &__ourip;
    	}
    	return( (struct in_addr *) &ifreq.ifr_ifru.ifru_addr.sin_addr );
    }
    
    static struct in_addr *myaddrfor(struct in_addr *them)
    {
    	FILE *PROC;
    	struct in_addr *temp = NULL;
    	unsigned int remote_ip;
    	char line[256];
    	remote_ip = them->s_addr;
    	
    	PROC = fopen("/proc/net/route","r");
    	if (!PROC) {
    		/* If /proc/net/route doesn't exist, fall back to the old method */
    		return &__ourip;
    	}
    	/* First line contains headers */
    	fgets(line,sizeof(line),PROC);
    
    	while (!feof(PROC)) {
    		char iface[8];
    		unsigned int dest, gateway, mask;
    		int i,aoffset;
    		char *fields[40];
    
    		fgets(line,sizeof(line),PROC);
    
    		aoffset = 0;
    		for (i=0;i<sizeof(line);i++) {
    			char *boffset;
    
    			fields[aoffset++] = line + i;
    			boffset = strchr(line + i,'\t');
    			if (boffset == NULL) {
    				/* Exit loop */
    				break;
    			} else {
    				*boffset = '\0';
    				i = boffset - line;
    			}
    		}
    
    		sscanf(fields[0],"%s",iface);
    		sscanf(fields[1],"%x",&dest);
    		sscanf(fields[2],"%x",&gateway);
    		sscanf(fields[7],"%x",&mask);
    #if 0
    		printf("Addr: %s %08x Dest: %08x Mask: %08x\n", inet_ntoa(*them), remote_ip, dest, mask);
    #endif		
    		if (((remote_ip & mask) ^ dest) == 0) {
    
    
    			if (mgcpdebug)
    					ast_verbose("Interface is %s\n",iface);
    
    Mark Spencer's avatar
    Mark Spencer committed
    			temp = lookup_iface(iface);
    
    			if (mgcpdebug)
    				ast_verbose("IP Address is %s\n",inet_ntoa(*temp));
    
    Mark Spencer's avatar
    Mark Spencer committed
    			break;
    		}
    	}
    	fclose(PROC);
    	if (!temp) {
    		ast_log(LOG_WARNING, "Couldn't figure out how to get to %s.  Using default\n", inet_ntoa(*them));
     		temp = &__ourip;
     	}
    	return temp;
    }
    
    
    static int mgcp_hangup(struct ast_channel *ast)
    {
    	struct mgcp_endpoint *p = ast->pvt->pvt;
    	if (option_debug)
    		ast_log(LOG_DEBUG, "mgcp_hangup(%s)\n", ast->name);
    	if (!ast->pvt->pvt) {
    		ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
    		return 0;
    	}
    
    	if ((p->dtmfinband) && (p->vad != NULL)){
    	    ast_dsp_free(p->vad);
    	}
    
    Mark Spencer's avatar
    Mark Spencer committed
    	ast_pthread_mutex_lock(&p->lock);
    	p->owner = NULL;
    	if (strlen(p->cxident))
    		transmit_connection_del(p);
    
    	strcpy(p->cxident, "");
    
    Mark Spencer's avatar
    Mark Spencer committed
    	if (!p->alreadygone && (!p->outgoing || (ast->_state == AST_STATE_UP)))
    		transmit_notify_request(p, "ro", 1);
    	else
    		transmit_notify_request(p, "", 0);
    	ast->pvt->pvt = NULL;
    	p->alreadygone = 0;
    	p->outgoing = 0;
    	strcpy(p->callid, "");
    
    	/* Reset temporary destination */
    	memset(&p->tmpdest, 0, sizeof(p->tmpdest));
    
    Mark Spencer's avatar
    Mark Spencer committed
    	if (p->rtp) {
    		ast_rtp_destroy(p->rtp);
    		p->rtp = NULL;
    	}
    	ast_pthread_mutex_unlock(&p->lock);
    	return 0;
    }
    
    static int mgcp_show_endpoints(int fd, int argc, char *argv[])
    {
    	struct mgcp_gateway  *g;
    	struct mgcp_endpoint *e;
    	int hasendpoints = 0;
    	if (argc != 3) 
    		return RESULT_SHOWUSAGE;
    	ast_pthread_mutex_lock(&gatelock);
    	g = gateways;
    	while(g) {
    		e = g->endpoints;
    
    		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");
    
    Mark Spencer's avatar
    Mark Spencer committed
    		while(e) {
    			ast_cli(fd, "   -- '%s@%s in '%s' is %s\n", e->name, g->name, e->context, e->owner ? "active" : "idle");
    			hasendpoints = 1;
    			e = e->next;
    		}
    		if (!hasendpoints) {
    			ast_cli(fd, "   << No Endpoints Defined >>     ");
    		}
    		g = g->next;
    	}
    	ast_pthread_mutex_unlock(&gatelock);
    	return RESULT_SUCCESS;
    }
    
    static char show_endpoints_usage[] = 
    "Usage: mgcp show endpoints\n"
    "       Lists all endpoints known to the MGCP (Media Gateawy Control Protocol) subsystem.\n";
    
    static struct ast_cli_entry  cli_show_endpoints = 
    	{ { "mgcp", "show", "endpoints", NULL }, mgcp_show_endpoints, "Show defined MGCP endpoints", show_endpoints_usage };
    
    static int mgcp_answer(struct ast_channel *ast)
    {
    	int res = 0;
    	struct mgcp_endpoint *p = ast->pvt->pvt;
    	if (ast->_state != AST_STATE_UP) {
    		ast_setstate(ast, AST_STATE_UP);
    		if (option_debug)
    			ast_log(LOG_DEBUG, "mgcp_answer(%s)\n", ast->name);
    		transmit_notify_request(p, "", 1);
    	}
    	return res;
    }
    
    
    static struct ast_frame *mgcp_rtp_read(struct mgcp_endpoint *p)
    {
    	/* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
    	struct ast_frame *f;
    	f = ast_rtp_read(p->rtp);
    	if (p->owner) {
    		/* We already hold the channel lock */
    		if (f->frametype == AST_FRAME_VOICE) {
    			if (f->subclass != p->owner->nativeformats) {
    				ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
    				p->owner->nativeformats = f->subclass;
    				ast_set_read_format(p->owner, p->owner->readformat);
    				ast_set_write_format(p->owner, p->owner->writeformat);
    			}
    		}
    	}
    	return f;
    }
    
    
    
    Mark Spencer's avatar
    Mark Spencer committed
    static struct ast_frame  *mgcp_read(struct ast_channel *ast)
    {
    
    	struct ast_frame *fr;
    	struct mgcp_endpoint *p = ast->pvt->pvt;
    	ast_pthread_mutex_lock(&p->lock);
    	fr = mgcp_rtp_read(p);
    	ast_pthread_mutex_unlock(&p->lock);
    	return fr;
    
    Mark Spencer's avatar
    Mark Spencer committed
    }
    
    static int mgcp_write(struct ast_channel *ast, struct ast_frame *frame)
    {
    	struct mgcp_endpoint *p = ast->pvt->pvt;
    	int res = 0;
    	if (frame->frametype != AST_FRAME_VOICE) {
    		if (frame->frametype == AST_FRAME_IMAGE)
    			return 0;
    		else {
    			ast_log(LOG_WARNING, "Can't send %d type frames with MGCP write\n", frame->frametype);
    			return 0;
    		}
    	} else {
    		if (!(frame->subclass & ast->nativeformats)) {
    			ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
    				frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
    			return -1;
    		}
    	}
    	if (p) {
    		ast_pthread_mutex_lock(&p->lock);
    		if (p->rtp) {
    			res =  ast_rtp_write(p->rtp, frame);
    		}
    		ast_pthread_mutex_unlock(&p->lock);
    	}
    	return res;
    }
    
    static int mgcp_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
    {
    	struct mgcp_endpoint *p = newchan->pvt->pvt;
    	ast_pthread_mutex_lock(&p->lock);
    	if (p->owner != oldchan) {
    		ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
    		return -1;
    	}
    	p->owner = newchan;
    	ast_pthread_mutex_unlock(&p->lock);
    	return 0;
    }
    
    static int mgcp_senddigit(struct ast_channel *ast, char digit)
    {
    	struct mgcp_endpoint *p = ast->pvt->pvt;
    	char tmp[2];
    	tmp[0] = digit;
    	tmp[1] = '\0';
    	transmit_notify_request(p, tmp, 1);
    	return -1;
    }
    
    
    static int mgcp_indicate(struct ast_channel *ast, int ind)
    {
    	struct mgcp_endpoint *p = ast->pvt->pvt;
    	switch(ind) {
    	case AST_CONTROL_RINGING:
    		transmit_notify_request(p, "rt", 1);
    		break;
    	case AST_CONTROL_BUSY:
    		transmit_notify_request(p, "bz", 1);
    		break;
    	case AST_CONTROL_CONGESTION:
    		transmit_notify_request(p, "nbz", 1);
    		break;
    	case -1:
    		transmit_notify_request(p, "", 1);
    		break;		
    	default:
    		ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", ind);
    		return -1;
    	}
    	return 0;
    }
    
    static struct ast_channel *mgcp_new(struct mgcp_endpoint *i, int state)
    {
    	struct ast_channel *tmp;
    	int fmt;
    	tmp = ast_channel_alloc(1);
    	if (tmp) {
    		tmp->nativeformats = i->capability;
    		if (!tmp->nativeformats)
    			tmp->nativeformats = capability;
    		fmt = ast_best_codec(tmp->nativeformats);
    		snprintf(tmp->name, sizeof(tmp->name), "MGCP/%s@%s", i->name, i->parent->name);
    
    		if (i->rtp)
    			tmp->fds[0] = ast_rtp_fd(i->rtp);
    
    Mark Spencer's avatar
    Mark Spencer committed
    		tmp->type = type;
    
    		if (i->dtmfinband) {
    		    i->vad = ast_dsp_new();
    		    ast_dsp_set_features(i->vad,DSP_FEATURE_DTMF_DETECT);
    		} else {
    		    i->vad = NULL;
    		}
    
    Mark Spencer's avatar
    Mark Spencer committed
    		ast_setstate(tmp, state);
    		if (state == AST_STATE_RING)
    			tmp->rings = 1;
    		tmp->writeformat = fmt;
    		tmp->pvt->rawwriteformat = fmt;
    		tmp->readformat = fmt;
    		tmp->pvt->rawreadformat = fmt;
    		tmp->pvt->pvt = i;
    		tmp->pvt->call = mgcp_call;
    		tmp->pvt->hangup = mgcp_hangup;
    		tmp->pvt->answer = mgcp_answer;
    		tmp->pvt->read = mgcp_read;
    		tmp->pvt->write = mgcp_write;
    		tmp->pvt->indicate = mgcp_indicate;
    		tmp->pvt->fixup = mgcp_fixup;
    		tmp->pvt->send_digit = mgcp_senddigit;
    
    		tmp->pvt->bridge = ast_rtp_bridge;
    
    Mark Spencer's avatar
    Mark Spencer committed
    		if (strlen(i->language))
    			strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
    		i->owner = tmp;
    		ast_pthread_mutex_lock(&usecnt_lock);
    		usecnt++;
    		ast_pthread_mutex_unlock(&usecnt_lock);
    		ast_update_use_count();
    		strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
    		strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
    		if (strlen(i->callerid))
    			tmp->callerid = strdup(i->callerid);
    		tmp->priority = 1;
    		if (state != AST_STATE_DOWN) {
    			if (ast_pbx_start(tmp)) {
    				ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
    				ast_hangup(tmp);
    				tmp = NULL;
    			}
    		}
    	} else
    		ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
    	return tmp;
    }
    
    static char *get_sdp(struct mgcp_request *req, char *name)
    {
    	int x;
    	int len = strlen(name);
    	char *r;
    	for (x=0;x<req->lines;x++) {
    		if (!strncasecmp(req->line[x], name, len) && 
    				(req->line[x][len] == '=')) {
    					r = req->line[x] + len + 1;
    					while(*r && (*r < 33))
    							r++;
    					return r;
    		}
    	}
    	return "";
    }
    
    static char *__get_header(struct mgcp_request *req, char *name, int *start)
    {
    	int x;
    	int len = strlen(name);
    	char *r;
    	for (x=*start;x<req->headers;x++) {
    		if (!strncasecmp(req->header[x], name, len) && 
    				(req->header[x][len] == ':')) {
    					r = req->header[x] + len + 1;
    					while(*r && (*r < 33))
    							r++;
    					*start = x+1;
    					return r;
    		}
    	}
    	/* Don't return NULL, so get_header is always a valid pointer */
    	return "";
    }
    
    static char *get_header(struct mgcp_request *req, char *name)
    {
    	int start = 0;
    	return __get_header(req, name, &start);
    }
    
    
    Mark Spencer's avatar
    Mark Spencer committed
    static int rtpready(struct ast_rtp *rtp, struct ast_frame *f, void *data)
    {
    	/* Just deliver the audio directly */
    	struct mgcp_endpoint *p = data;
    	ast_pthread_mutex_lock(&p->lock);
    	if (p->owner) {
    		/* Generally, you lock in the order channel lock, followed by private
    		   lock.  Since here we are doing the reverse, there is the possibility
    		   of deadlock.  As a result, in the case of a deadlock, we simply fail out
    		   here. */
    		if (!pthread_mutex_trylock(&p->owner->lock)) {
    			if (f->frametype == AST_FRAME_VOICE) {
    				if (f->subclass != p->owner->nativeformats) {
    					ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
    					p->owner->nativeformats = f->subclass;
    					ast_set_read_format(p->owner, p->owner->readformat);
    					ast_set_write_format(p->owner, p->owner->writeformat);
    				}
    
    				if (p->dtmfinband) {
    				    f = ast_dsp_process(p->owner,p->vad,f,0);
    				}
    
    Mark Spencer's avatar
    Mark Spencer committed
    			}
    			ast_queue_frame(p->owner, f, 0);
    			pthread_mutex_unlock(&p->owner->lock);
    		}
    	}
    	ast_pthread_mutex_unlock(&p->lock);
    	return 0;
    }
    
    Mark Spencer's avatar
    Mark Spencer committed
    
    static struct mgcp_endpoint *find_endpoint(char *name, int msgid, struct sockaddr_in *sin)
    {
    	struct mgcp_endpoint *p = NULL;
    	struct mgcp_gateway *g;
    	char tmp[256] = "";
    	char *at = NULL;
    	if (name) {
    		strncpy(tmp, name, sizeof(tmp) - 1);
    		at = strchr(tmp, '@');
    		if (!at) {
    			ast_log(LOG_NOTICE, "Endpoint '%s' has no at sign!\n", name);
    			return NULL;
    		}
    		*at = '\0';
    		at++;
    	}
    	ast_pthread_mutex_lock(&gatelock);
    	g = gateways;
    	while(g) {
    
    		if ((!name || !strcasecmp(g->name, at)) && 
    		    (sin || g->addr.sin_addr.s_addr || g->defaddr.sin_addr.s_addr)) {
    			/* Found the gateway.  If it's dynamic, save it's address -- now for the endpoint */
    			if (sin && g->dynamic) {
    				if ((g->addr.sin_addr.s_addr != sin->sin_addr.s_addr) ||
    					(g->addr.sin_port != sin->sin_port)) {
    					memcpy(&g->addr, sin, sizeof(g->addr));
    					memcpy(&g->ourip, myaddrfor(&g->addr.sin_addr), sizeof(g->ourip));
    					if (option_verbose > 2)
    						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));
    				}
    			}
    
    Mark Spencer's avatar
    Mark Spencer committed
    			p = g->endpoints;
    			while(p) {
    				if ((name && !strcasecmp(p->name, tmp)) ||
    				    (msgid && (p->lastout == msgid)))
    					break;
    				p = p->next;
    			}
    			if (name || p)
    				break;
    		}
    		g = g->next;
    	}
    	ast_pthread_mutex_unlock(&gatelock);
    	if (!p) {
    		if (name) {
    			if (g)
    				ast_log(LOG_NOTICE, "Endpoint '%s' not found on gateway '%s'\n", tmp,at);
    			else
    				ast_log(LOG_NOTICE, "Gateway '%s' (and thus its endpoint '%s') does not exist\n", at, tmp);
    		} 
    	}
    	return p;
    }
    
    static void parse(struct mgcp_request *req)
    {
    	/* Divide fields by NULL's */
    	char *c;
    	int f = 0;
    	c = req->data;
    
    	/* First header starts immediately */
    	req->header[f] = c;
    	while(*c) {
    		if (*c == '\n') {
    			/* We've got a new header */
    			*c = 0;
    
    #if 0
    			printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
    #endif			
    			if (!strlen(req->header[f])) {
    				/* Line by itself means we're now in content */
    				c++;
    				break;
    			}
    			if (f >= MGCP_MAX_HEADERS - 1) {
    				ast_log(LOG_WARNING, "Too many MGCP headers...\n");
    			} else
    				f++;
    			req->header[f] = c + 1;
    		} else if (*c == '\r') {
    			/* Ignore but eliminate \r's */
    			*c = 0;
    		}
    		c++;
    	}
    	/* Check for last header */
    	if (strlen(req->header[f])) 
    		f++;
    	req->headers = f;
    	/* Now we process any mime content */
    	f = 0;
    	req->line[f] = c;
    	while(*c) {
    		if (*c == '\n') {
    			/* We've got a new line */
    			*c = 0;
    #if 0
    			printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
    #endif			
    			if (f >= MGCP_MAX_LINES - 1) {
    				ast_log(LOG_WARNING, "Too many SDP lines...\n");
    			} else
    				f++;
    			req->line[f] = c + 1;
    		} else if (*c == '\r') {
    			/* Ignore and eliminate \r's */
    			*c = 0;
    		}
    		c++;
    	}
    	/* Check for last line */
    	if (strlen(req->line[f])) 
    		f++;
    	req->lines = f;
    	/* Parse up the initial header */
    	c = req->header[0];
    	while(*c && *c < 33) c++;
    	/* First the verb */
    	req->verb = c;
    	while(*c && (*c > 32)) c++;
    	if (*c) {
    		*c = '\0';
    		c++;
    		while(*c && (*c < 33)) c++;
    		req->identifier = c;
    		while(*c && (*c > 32)) c++;
    		if (*c) {
    			*c = '\0';
    			c++;
    			while(*c && (*c < 33)) c++;
    			req->endpoint = c;
    			while(*c && (*c > 32)) c++;
    			if (*c) {
    				*c = '\0';
    				c++;
    				while(*c && (*c < 33)) c++;
    				req->version = c;
    				while(*c && (*c > 32)) c++;
    				while(*c && (*c < 33)) c++;
    				while(*c && (*c > 32)) c++;
    				*c = '\0';
    			}
    		}
    	}
    		
    
    	if (mgcpdebug) {
    		ast_verbose("Verb: '%s', Identifier: '%s', Endpoint: '%s', Version: '%s'\n",
    
    Mark Spencer's avatar
    Mark Spencer committed
    		req->verb, req->identifier, req->endpoint, req->version);
    
    		ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
    	}
    
    Mark Spencer's avatar
    Mark Spencer committed
    	if (*c) 
    		ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
    }
    
    static int process_sdp(struct mgcp_endpoint *p, struct mgcp_request *req)
    {
    	char *m;
    	char *c;
    	char host[258];
    	int len;
    	int portno;
    	int peercapability;
    	struct sockaddr_in sin;
    	char *codecs;
    	struct hostent *hp;
    	int codec;
    	/* Get codec and RTP info from SDP */
    	m = get_sdp(req, "m");
    	c = get_sdp(req, "c");
    	if (!strlen(m) || !strlen(c)) {
    		ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
    		return -1;
    	}
    	if (sscanf(c, "IN IP4 %256s", host) != 1) {
    		ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
    		return -1;
    	}
    	/* XXX This could block for a long time, and block the main thread! XXX */
    	hp = gethostbyname(host);
    	if (!hp) {
    		ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
    		return -1;
    	}
    	if (sscanf(m, "audio %d RTP/AVP %n", &portno, &len) != 1) {
    		ast_log(LOG_WARNING, "Unable to determine port number for RTP in '%s'\n", m); 
    		return -1;
    	}
    	sin.sin_family = AF_INET;
    	memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
    	sin.sin_port = htons(portno);
    	if (p->rtp)
    		ast_rtp_set_peer(p->rtp, &sin);
    #if 0
    	printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
    #endif	
    	peercapability = 0;
    	codecs = m + len;
    	while(strlen(codecs)) {
    		if (sscanf(codecs, "%d %n", &codec, &len) != 1) {
    			ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
    			return -1;
    		}
    #if 0
    		printf("Codec: %d\n", codec);
    #endif		
    		codec = rtp2ast(codec);
    		if (codec  > -1)
    			peercapability |= codec;
    		codecs += len;
    	}
    	p->capability = capability & peercapability;
    
    	if (mgcpdebug)
    		ast_verbose("Capabilities: us - %d, them - %d, combined - %d\n",
    
    Mark Spencer's avatar
    Mark Spencer committed
    		capability, peercapability, p->capability);
    	if (!p->capability) {
    		ast_log(LOG_WARNING, "No compatible codecs!\n");
    		return -1;
    	}
    	return 0;
    	
    }
    
    static int add_header(struct mgcp_request *req, char *var, char *value)
    {
    	if (req->len >= sizeof(req->data) - 4) {
    		ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
    		return -1;
    	}
    	if (req->lines) {
    		ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
    		return -1;
    	}
    	req->header[req->headers] = req->data + req->len;
    	snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s: %s\r\n", var, value);
    	req->len += strlen(req->header[req->headers]);
    	if (req->headers < MGCP_MAX_HEADERS)
    		req->headers++;
    	else {
    		ast_log(LOG_WARNING, "Out of header space\n");
    		return -1;
    	}
    	return 0;	
    }
    
    static int add_line(struct mgcp_request *req, char *line)
    {
    	if (req->len >= sizeof(req->data) - 4) {
    		ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
    		return -1;
    	}
    	if (!req->lines) {
    		/* Add extra empty return */
    		snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
    		req->len += strlen(req->data + req->len);
    	}
    	req->line[req->lines] = req->data + req->len;
    	snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
    	req->len += strlen(req->line[req->lines]);
    	if (req->lines < MGCP_MAX_LINES)
    		req->lines++;
    	else {
    		ast_log(LOG_WARNING, "Out of line space\n");
    		return -1;
    	}
    	return 0;	
    }
    
    static int init_resp(struct mgcp_request *req, char *resp, struct mgcp_request *orig, char *resprest)
    {
    	/* Initialize a response */
    	if (req->headers || req->len) {
    		ast_log(LOG_WARNING, "Request already initialized?!?\n");
    		return -1;
    	}
    	req->header[req->headers] = req->data + req->len;
    	snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s %s\r\n", resp, orig->identifier, resprest);
    	req->len += strlen(req->header[req->headers]);
    	if (req->headers < MGCP_MAX_HEADERS)
    		req->headers++;
    	else
    		ast_log(LOG_WARNING, "Out of header space\n");
    	return 0;
    }
    
    static int init_req(struct mgcp_endpoint *p, struct mgcp_request *req, char *verb)
    {
    	/* Initialize a response */
    	if (req->headers || req->len) {
    		ast_log(LOG_WARNING, "Request already initialized?!?\n");
    		return -1;
    	}
    	req->header[req->headers] = req->data + req->len;
    	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);
    	req->len += strlen(req->header[req->headers]);
    	if (req->headers < MGCP_MAX_HEADERS)
    		req->headers++;
    	else
    		ast_log(LOG_WARNING, "Out of header space\n");
    	return 0;
    }
    
    
    static int respprep(struct mgcp_request *resp, struct mgcp_endpoint *p, char *msg, struct mgcp_request *req, char *msgrest)
    {
    	memset(resp, 0, sizeof(*resp));
    	init_resp(resp, msg, req, msgrest);
    	return 0;
    }
    
    static int reqprep(struct mgcp_request *req, struct mgcp_endpoint *p, char *verb)
    {
    	memset(req, 0, sizeof(struct mgcp_request));
    	oseq++;
    	init_req(p, req, verb);
    	return 0;
    }
    
    static int transmit_response(struct mgcp_endpoint *p, char *msg, struct mgcp_request *req, char *msgrest)
    {
    	struct mgcp_request resp;
    	respprep(&resp, p, msg, req, msgrest);
    	return send_response(p, &resp);
    }
    
    
    static int add_sdp(struct mgcp_request *resp, struct mgcp_endpoint *p, struct ast_rtp *rtp)
    {
    	int len;
    	int codec;
    	char costr[80];
    	struct sockaddr_in sin;
    	char v[256];
    	char s[256];
    	char o[256];
    	char c[256];
    	char t[256];
    	char m[256];
    	char a[1024] = "";
    	int x;
    	struct sockaddr_in dest;
    	/* XXX We break with the "recommendation" and send our IP, in order that our
    	       peer doesn't have to gethostbyname() us XXX */
    	len = 0;
    	if (!p->rtp) {
    		ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
    		return -1;
    	}
    	ast_rtp_get_us(p->rtp, &sin);
    	if (rtp) {
    		ast_rtp_get_peer(rtp, &dest);
    	} else {
    
    		if (p->tmpdest.sin_addr.s_addr) {
    			dest.sin_addr = p->tmpdest.sin_addr;