receive.c
888ca09d
 /* 
  *$Id$
  */
 
 #include <string.h>
3e429f5c
 #include <stdlib.h>
888ca09d
 
 #include "receive.h"
 #include "dprint.h"
 #include "route.h"
 #include "msg_parser.h"
 #include "forward.h"
3e429f5c
 #include "action.h"
888ca09d
 
03150098
 #ifdef DEBUG_DMALLOC
 #include <dmalloc.h>
 #endif
888ca09d
 
1b1b19d8
 int receive_msg(char* buf, unsigned int len, unsigned long src_ip)
888ca09d
 {
 	struct sip_msg msg;
 	struct route_elem *re;
 
7268726e
 	memset(&msg,0, sizeof(struct sip_msg)); /* init everything to 0 */
4ac74c03
 	/* fill in msg */
 	msg.buf=buf;
 	msg.len=len;
 	msg.src_ip=src_ip;
888ca09d
 	/* make a copy of the message */
4ac74c03
 	msg.orig=(char*) malloc(len);
 	if (msg.orig==0){
efeaaf53
 		LOG(L_ERR, "ERROR:receive_msg: memory allocation failure\n");
038e5c9e
 		goto error1;
888ca09d
 	}
4ac74c03
 	memcpy(msg.orig, buf, len);
888ca09d
 	
 	if (parse_msg(buf,len, &msg)!=0){
 		goto error;
 	}
 	
 	if (msg.first_line.type==SIP_REQUEST){
 		/* sanity checks */
 		if (msg.via1.error!=VIA_PARSE_OK){
 			/* no via, send back error ? */
 			goto skip;
 		}
 		/* check if neccesarry to add receive? */
 		
 		/* find route */
4ac74c03
 		re=route_match( &msg, &rlist[0]);
888ca09d
 		if (re==0){
 			/* no route found, send back error msg? */
efeaaf53
 			LOG(L_WARN, "WARNING: receive_msg: no route found!\n");
888ca09d
 			goto skip;
 		}
 		re->tx++;
 		/* send msg */
4ac74c03
 		DBG(" found route \n");
3e429f5c
 		if (run_actions(re->actions, &msg)<0){
4ac74c03
 			LOG(L_WARN, "WARNING: receive_msg: "
 					"error while trying actions\n");
 			goto error;
 		}
888ca09d
 	}else if (msg.first_line.type==SIP_REPLY){
 		/* sanity checks */
 		if (msg.via1.error!=VIA_PARSE_OK){
 			/* no via, send back error ? */
 			goto skip;
 		}
 		if (msg.via2.error!=VIA_PARSE_OK){
 			/* no second via => error? */
 			goto skip;
 		}
 		/* check if via1 == us */
 		
 		/* send the msg */
4ac74c03
 		if (forward_reply(&msg)==0){
efeaaf53
 			DBG(" reply forwarded to %s:%d\n", 
1b1b19d8
 						msg.via2.host,
 						(unsigned short) msg.via2.port);
 		}
888ca09d
 	}
 skip:
03150098
 	if (msg.new_uri) free(msg.new_uri);
4ac74c03
 	free(msg.orig);
888ca09d
 	return 0;
 error:
03150098
 	if (msg.new_uri) free(msg.new_uri);
4ac74c03
 	free(msg.orig);
038e5c9e
 error1:
888ca09d
 	return -1;
 }