#!KAMAILIO
#
# This config file implements the basic P-CSCF functionality
#     - web: http://www.kamailio.org
#     - git: http://sip-router.org
#
# Refer to the Core CookBook at http://www.kamailio.org/dokuwiki/doku.php
# for an explanation of possible statements, functions and parameters.
#
# Direct your questions about this file to: <sr-users@lists.sip-router.org>.
#
# For more information about the various parameters, functions and statements
# try http://sip-router.org/wiki/ .
#

include_file "pcscf.cfg"

####### Defined Values #########
# *** Value defines - IDs used later in config

# - flags
#	FLT_ - per transaction (message) flags
#	FLB_ - per branch flags

#!define FLT_CAPTURE 1
#!define FLT_DIALOG 2
#!define FLT_NAT 3
#!define FLT_IPV4 4

#!define DLG_TIMEOUT_AVP "i:1"
#!define RR_CUSTOM_USER_AVP "i:2"
#!define NATHELPER_RECEIVED_AVP "i:3"

system.shutdownmode = 0 desc "System shutdown mode"

####### Global Parameters #########
#!ifdef WITH_DEBUG
debug=5
log_stderror=no
sip_warning=yes
children=4
#!else
debug=2
log_stderror=no
sip_warning=no
children=64
#!endif

# Locks all ser pages into memory making it unswappable (in general one 
# doesn't want his sip proxy swapped out )
mlock_pages=yes
# Tries to pre-fault all the shared memory, before starting. When "on", start 
# time will increase, but combined with mlock_pages will guarantee ser will get 
# all its memory from the beginning (no more kswapd slow downs)
shm_force_alloc=yes


# Do SRV-Loadbalancing:
dns_srv_lb=yes
# Always: Also try IPv6:
dns_try_ipv6=yes

/* uncomment and configure the following line if you want Kamailio to 
   bind on a specific interface/port/proto (default bind on all available) */
#!ifdef NETWORK_INTERFACE
listen=NETWORK_INTERFACE
#!endif
/* Second interface to use, e.g. for IPv6 */
#!ifdef NETWORK_INTERFACE_2
listen=NETWORK_INTERFACE_2
#!endif


/* port to listen to
 * - can be specified more than once if needed to listen on many ports */
port=PORT
alias=HOSTNAME_IP

user_agent_header="User-Agent: Kamailio P-CSCF"
server_header="Server: Kamailio P-CSCF"

/* comment the next line to enable the auto discovery of local aliases
   based on reverse DNS on IPs (default on) */
auto_aliases=no

#!ifdef WITH_TLS

# Check, if TCP is enabled:
#!ifndef WITH_TCP
#!define WITH_TCP
#!endif
enable_tls=yes
#!endif

#!ifdef WITH_XMLRPC
#!ifndef WITH_TCP
#!define WITH_TCP
#!endif
#!ifndef TCP_PROCESSES
# Number of TCP Processes
#!define TCP_PROCESSES 3
#!endif
#!endif

# Check, if NAT is enabled (in case you want to Force all calls through the RTPProxy)
#!ifdef FORCE_RTPRELAY
#!ifndef WITH_NAT
#!define WITH_NAT
#!endif
#!endif

# Check, if NAT is enabled (in case you want to Force all calls through the RTPProxy)
#!ifdef WITH_RTPIPV4
#!ifndef WITH_NAT
#!define WITH_NAT
#!endif
#!endif

#!ifdef WITH_TCP
# life time of TCP connection when there is no traffic
# - a bit higher than registration expires to cope with UA behind NAT
tcp_connection_lifetime=3615
# If a message received over a tcp connection has "alias" in its via a new tcp
# alias port will be created for the connection the message came from (the
# alias port will be set to the via one).
#
# Note: For NAT traversal of TCP clients it is better to not use 
# tcp_accept_aliases but just use nathelper module and 
# fix_nated_[contact|register] functions. 
tcp_accept_aliases=no
# Enable SIP outbound TCP keep-alive using PING-PONG (CRLFCRLF - CRLF).
tcp_crlf_ping=yes
#!ifdef TCP_PROCESSES
tcp_children=TCP_PROCESSES
#!endif
#!else
disable_tcp=yes
#!endif

check_via=no    # (cmd. line: -v)
dns=no          # (cmd. line: -r)
rev_dns=no      # (cmd. line: -R)

# ------------------ module loading ----------------------------------
mpath="/usr/lib64/kamailio/modules_k/:/usr/lib64/kamailio/modules/:/usr/lib/kamailio/modules_k/:/usr/lib/kamailio/modules/"
# (we try both the lib64 and the lib directory)

loadmodule "tm"
loadmodule "pv"
loadmodule "sl"
loadmodule "rr"
loadmodule "dialog_ng"
loadmodule "ims_usrloc_pcscf" 
loadmodule "textops"
loadmodule "textopsx"
loadmodule "maxfwd"
loadmodule "xlog"
loadmodule "ims_registrar_pcscf"
loadmodule "sanity"
loadmodule "siputils"
loadmodule "kex"

# Control interfaces:
loadmodule "ctl"
loadmodule "cfg_rpc"
loadmodule "mi_rpc"
loadmodule "mi_fifo"
#!ifdef WITH_XMLRPC
loadmodule "xmlrpc"
#!endif

#!ifdef WITH_RX
loadmodule "cdp"
loadmodule "cdp_avp"
loadmodule "ims_qos"
#!endif

#!ifdef CAPTURE_NODE
loadmodule "siptrace"
#!endif

#!ifdef WITH_DEBUG
loadmodule "debugger"
#!endif

#!ifdef WITH_TLS
loadmodule "tls"
#!endif

#!ifdef WITH_ANTIFLOOD
loadmodule "pike"
loadmodule "htable"
loadmodule "dispatcher"
#!endif

#!ifdef WITH_NAT
loadmodule "path"
loadmodule "rtpproxy"
loadmodule "nat_traversal"
loadmodule "nathelper"
#!endif

# ----------------- setting module-specific parameters ---------------
# ----- mi_fifo params -----
modparam("mi_fifo", "fifo_name", "/tmp/kamailio_fifo")
modparam("mi_fifo", "fifo_mode", 0666)
modparam("mi_fifo", "fifo_user", "kamailio")
modparam("mi_fifo", "fifo_group", "kamailio")

# ----- tm params -----
# auto-discard branches from previous serial forking leg
modparam("tm", "failure_reply_mode", 3)
# default retransmission timeout: 10sec
modparam("tm", "fr_timer", 10000)
# default invite retransmission timeout after 1xx: 120sec
modparam("tm", "fr_inv_timer", 120000)
# Don't reply automatically with "100 Trying"
modparam("tm", "auto_inv_100", 1)

# ----- rr params -----
# add value to ;lr param to cope with most of the UAs
modparam("rr", "enable_full_lr", 1)
# append from tag to the RR
modparam("rr", "append_fromtag", 1)
# add a Username to RR-Header
modparam("rr", "add_username", 1)
# Take User from a custom AVP
modparam("rr", "custom_user_avp", "$avp(RR_CUSTOM_USER_AVP)")

#!ifdef WITH_NAT
# ----- path params -----
# Evaluate the received info in the route-header:
modparam("path", "use_received", 1)
#!endif

# -- usrloc params --
#!ifdef WITH_DEBUG
modparam("ims_usrloc_pcscf", "enable_debug_file", 1)
modparam("ims_usrloc_pcscf", "usrloc_debug_file", "/var/log/usrloc_debug")
#!else
modparam("ims_usrloc_pcscf", "enable_debug_file", 0)
#!endif

#!ifdef WITH_RX
# -- CDP params --
modparam("cdp","config_file","/etc/kamailio/pcscf.xml")
# -- diameter_rx params --
modparam("ims_qos", "rx_dest_realm", "NETWORKNAME")
#!endif

# -- dialog_ng params --
modparam("dialog_ng", "dlg_flag", FLT_DIALOG)
modparam("dialog_ng", "timeout_avp", "$avp(DLG_TIMEOUT_AVP)")
modparam("dialog_ng", "detect_spirals", 0)
modparam("dialog_ng", "profiles_no_value", "orig ; term")

#!ifdef WITH_TLS
# ----- tls params -----
modparam("tls", "config", "/etc/kamailio/tls.cfg")
#!endif

#!ifdef WITH_ANTIFLOOD
# ----- pike params -----
modparam("pike", "sampling_time_unit", 2)
modparam("pike", "reqs_density_per_unit", 16)
modparam("pike", "remove_latency", 4)

# ----- htable params -----
# ip ban htable with autoexpire after 5 minutes
modparam("htable", "htable", "ipban=>size=8;autoexpire=300;")

# ----------------- Settings for Dispatcher ---------------
modparam("dispatcher", "list_file", "/etc/kamailio/dispatcher.list")
# Actively query the gateways:
modparam("dispatcher", "ds_probing_mode", 1)
#!endif

#!ifdef WITH_XMLRPC
# ----- xmlrpc params -----
modparam("xmlrpc", "route", "XMLRPC");
modparam("xmlrpc", "url_match", "^/RPC")
#!endif

#!ifdef WITH_DEBUG
# ----- debugger params -----
modparam("debugger", "cfgtrace", 1)
#!endif

#!ifdef CAPTURE_NODE
# Destination, where to send the traffic
modparam("siptrace", "duplicate_uri", CAPTURE_NODE)
# Trace all traffic
modparam("siptrace", "trace_on", 1)
modparam("siptrace", "trace_to_database", 0)
modparam("siptrace", "trace_flag", FLT_CAPTURE)
modparam("siptrace", "hep_mode_on", 1)
#!endif

#!ifdef WITH_NAT
# ----- rtpproxy params -----
modparam("rtpproxy", "rtpproxy_sock", RTPPROXY_ADDRESS)

# ----- nat_traversal params -----
# If another keepalive is wanted, this is the place
modparam("nat_traversal", "keepalive_interval", 10)
# If another method than NOTIFY is wanted:
modparam("nat_traversal", "keepalive_method", "OPTIONS")
# From?
modparam("nat_traversal", "keepalive_from", "sip:keepalive@HOSTNAME")
# Where we store information about keep-alives:
modparam("nat_traversal", "keepalive_state_file", "/var/run/kamailio/keepalive_state")
#!endif

####### Routing Logic ########
# Main SIP request routing logic
# - processing of any incoming SIP request starts with this route

route {
#!ifdef WITH_DEBUG
	xlog("L_ERR", "$rm ($fu ($si:$sp) to $tu, $ci)\n");
#!endif

	# per request initial checks
	route(REQINIT);

	# Check for NAT, if enabled.
	route(NAT);

	# Handle Registrations:
	if (is_method("REGISTER")) {
		route(REGISTER);
		exit;
	}

	#Set DLG flag to track dialogs using dialog2
	if (!is_method("SUBSCRIBE"))
		setflag(FLT_DIALOG);

	# Evaluate Route-Header and set $route_uri
	loose_route();

	if !(($route_uri =~ "sip:term@"+HOSTNAME_ESC+".*")) {
		if ((is_in_profile("orig") || has_totag()) && ($route_uri =~ "sip:mo@"+".*")) {
			if (!is_method("CANCEL")) route(Orig_Subsequent);
			else route(Orig_Standalone);
			break;
		}

		if ((is_in_profile("term") || has_totag()) && ($route_uri =~ "sip:mt@"+".*")) {
			if (!is_method("CANCEL")) route(Term_Subsequent);
			else route(Term_Standalone);
			break;
		}

		# No dialog yet - ACK not relayed as hop-to-hop
		if (is_method("ACK"))
			break;

		if (is_method("INVITE|SUBSCRIBE")) {
			route(Orig_Initial);
			break;
		} else {
			if (is_method("UPDATE")) {
				send_reply("403","Forbidden - Target refresh outside dialog not allowed");
				break;
			}
			if (is_method("BYE|PRACK")) {
				send_reply("403","Forbidden - Originating subsequent requests outside dialog not allowed");
				break;
			}
         
			route(Orig_Standalone);
			break;
		}
	} else {
		# TODO - check if this does come from an UE and that UE is unregistered
		if(is_known_dlg()) {
			xlog("L_DBG", "TERM: Request $rm from $si is in-dialog\n");
		}
		if (!is_in_profile("term") && is_method("INVITE|SUBSCRIBE")){
			route(Term_Initial);
			break;
		} else {
			if (is_in_profile("term")){
				if (!is_method("CANCEL")) route(Term_Subsequent);
				else route(Term_Standalone);
				break;
			} else {
				if (is_method("UPDATE")) {
					send_reply("403","Forbidden - Target refresh outside dialog not allowed");
					break;
				}
				if (is_method("BYE|ACK|PRACK")) {
					send_reply("403","Forbidden - Terminating subsequent requests outside dialog not allowed");
					break;
				}
				route(Term_Standalone);
				break;
			}
		}
		break;
	}
}

######################################################################
# Helper routes (Basic-Checks, NAT-Handling/RTP-Control, XML-RPC)
######################################################################
# Per SIP request initial checks
route[REQINIT] {
#!ifdef WITH_ANTIFLOOD
	# flood dection from same IP and traffic ban for a while
	# be sure you exclude checking trusted peers, such as pstn gateways
	# - local host excluded (e.g., loop to self)
	if (!has_totag() && (src_ip!=myself) && !ds_is_from_list())
	{
		if($sht(ipban=>$si)!=$null)
		{
			# ip is already blocked
			xdbg("request from blocked IP - $rm from $fu (IP:$si:$sp)\n");
			exit;
		}
		if (!pike_check_req())
		{
			xlog("L_ALERT","ALERT: pike blocking $rm from $fu (IP:$si:$sp)\n");
			$sht(ipban=>$si) = 1;
			exit;
		}
	}
#!endif
	# Trace this message
#!ifdef CAPTURE_NODE
	sip_trace();	
	setflag(FLT_CAPTURE);
#!endif

	if (!mf_process_maxfwd_header("10")) {
		sl_send_reply("483","Too Many Hops");
		exit;
	}

	if(!sanity_check("1511", "7")) {
		xlog("Malformed SIP message from $si:$sp\n");
		exit;
	}

	# Check for shutdown mode:
	if (!has_totag() && ($sel(cfg_get.system.shutdownmode) > 0)) {
		send_reply("503", "Server shutting down");
		exit;
	}

	# Reply to OPTIONS:
	if (is_method("OPTIONS") && (uri==myself)) {
		options_reply();
		exit;
	}	
	
	# Ignore Re-Transmits:
	if (t_lookup_request()) {
		exit;
	}
}

######################################################################
# XMLRPC routing
######################################################################
#!ifdef WITH_XMLRPC
route[XMLRPC] {
	if ((method=="POST" || method=="GET")
#!ifdef XMLRPC_WHITELIST_1
&& ((src_ip == XMLRPC_WHITELIST_1)
#!ifdef XMLRPC_WHITELIST_2
 || (src_ip == XMLRPC_WHITELIST_2)
#!endif
#!ifdef XMLRPC_WHITELIST_3
 || (src_ip == XMLRPC_WHITELIST_3)
#!endif
)
#!endif
) {
		# close connection only for xmlrpclib user agents (there is a bug in
		# xmlrpclib: it waits for EOF before interpreting the response).
		if ($hdr(User-Agent) =~ "xmlrpclib")
			set_reply_close();
		set_reply_no_connect();
		dispatch_rpc();
		exit;
	}
	send_reply("403", "Forbidden");
	exit;
}
#!endif

######################################################################
# Caller NAT detection route
######################################################################
route[NAT] {
#!ifdef WITH_NAT
	if (client_nat_test("7")) {
		force_rport();
		if (is_method("REGISTER")) {
			force_rport();
			xlog("L_DBG", "Enabling keep-alive\n");
	        	nat_keepalive();
		} else {
			fix_contact();
		}
		setflag(FLT_NAT);
	}
#!ifdef WITH_RTPIPV4
	if (is_request() && (af==INET)) {
		setflag(FLT_IPV4);
	}
#!endif
#!endif
	return;
}

######################################################################
# Route for RTPProxy control (Originating Requests)
######################################################################
route[RTPPROXY_ORIG] {
#!ifdef WITH_NAT
#!ifndef FORCE_RTPRELAY
	if (is_request() && has_totag()) {
		if(check_route_param("nat=yes")) {
			setflag(FLT_NAT);
#!ifdef WITH_RTPIPV4
		} else {
			if(check_route_param("nat=v4")) {
				setflag(FLT_IPV4);
			}
#!endif
		}
	}

	if !(isflagset(FLT_NAT) || isflagset(FLT_IPV4))
		return;
#!endif

/*	## P-RTP-Stats snippet for Kamailio/RTPProxy
	if (is_method("BYE")) {
		$var(xrtpstat) = $rtpstat;
		xlog("L_ERR", "$$rtpstat = $rtpstat\n");
		# Work the stats
		$var(rtp0) = $(var(xrtpstat){s.select,1, });
		$var(rtp1) = $(var(xrtpstat){s.select,2, });
		$var(rtp2) = $(var(xrtpstat){s.select,3, });
		$var(rtp3) = $(var(xrtpstat){s.select,4, });
		$var(rtp4) = $(var(xrtpstat){s.select,5, });
		if ($var(rtp0) != "" || $var(rtp1) != "") {
			append_hf("P-RTP-Stat:  EX=RTPProxy,PS=$var(rtp0),PR=$var(rtp1),PL=$var(rtp3)\r\n");
		}
	} */

#!ifdef WITH_RTPIPV4
	# I = IPv4
	# E = IPv6
	if(isflagset(FLT_IPV4)) {
		if (is_request()) {
			if (is_direction("downstream"))
				rtpproxy_manage("1FOX");
			else
				rtpproxy_manage("1FOXR");
		} else {
			if (is_direction("downstream"))
				rtpproxy_manage("2FOXR");
			else
				rtpproxy_manage("2FOX");
		}
	} else {
		if (is_request()) {
			if (is_direction("downstream"))
				rtpproxy_manage("1FOEE");
			else
				rtpproxy_manage("1FOEER");
		} else {
			if (is_direction("downstream"))
				rtpproxy_manage("2FOEER");
			else
				rtpproxy_manage("2FOEE");
		}
	}
#!else
	# No Bridging
	if (is_request()) {
		if (is_direction("downstream"))
			rtpproxy_manage("1FOII");
		else
			rtpproxy_manage("1FOIIR");
	} else {
		if (is_direction("downstream"))
			rtpproxy_manage("2FOIIR");
		else
			rtpproxy_manage("2FOII");
	}
#!endif

#!ifndef FORCE_RTPRELAY
	if (is_request()) {
		if (!has_totag()) {
			if(isflagset(FLT_IPV4)) {
				add_rr_param(";nat=v4");
			} else {
				add_rr_param(";nat=yes");
			}
		}
	}
#!endif
#!ifdef WITH_MOH
	if (is_request()) {
		if (is_method("INVITE")) {
			if (search_body("^a=sendonly")) {
				rtpproxy_stream2uas("/etc/kamailio/moh/moh.sln16", "-1");
			} else {
				rtpproxy_stop_stream2uas();
			}
		}
	} else {
		if (status=="200") {
			if (search_body("^a=sendonly")) {
				rtpproxy_stream2uac("/etc/kamailio/moh/moh.sln16", "-1");
			} else {
				rtpproxy_stop_stream2uac();
			}
		}
	}
#!endif
#!endif
	return;
}

######################################################################
# Route for RTPProxy control (Terminating Requests)
######################################################################
route[RTPPROXY_TERM] {
#!ifdef WITH_NAT
#!ifndef FORCE_RTPRELAY
	if (is_request()) {
		if(check_route_param("nat=yes")) {
			setflag(FLT_NAT);
#!ifdef WITH_RTPIPV4
		} else {
			if(check_route_param("nat=v4")) {
				setflag(FLT_IPV4);
			}
#!endif
		}
	}

	if !(isflagset(FLT_NAT) || isflagset(FLT_IPV4))
		return;
#!endif

#!ifdef WITH_RTPIPV4
	# I = IPv4
	# E = IPv6
	if(isflagset(FLT_IPV4)) {
		# xlog("L_ERR", "IPv6-to-4 Bridge\n");
		if (is_request()) {
			if (is_direction("downstream"))
				rtpproxy_manage("1FOXR");
			else
				rtpproxy_manage("1FOX");
		} else {
			if (is_direction("downstream"))
				rtpproxy_manage("2FOX");
			else
				rtpproxy_manage("2FOXR");
		}
	} else {
		if (is_request()) {
			if (is_direction("downstream"))
				rtpproxy_manage("1FOEER");
			else
				rtpproxy_manage("1FOEE");
		} else {
			if (is_direction("downstream"))
				rtpproxy_manage("2FOEE");
			else
				rtpproxy_manage("2FOEER");
		}
	}
#!else
	# No Bridging
	if (is_request()) {
		if (is_direction("downstream"))
			rtpproxy_manage("1FOIIR");
		else
			rtpproxy_manage("1FOII");
	} else {
		if (is_direction("downstream"))
			rtpproxy_manage("2FORII");
		else
			rtpproxy_manage("2FORIIR");
	}
#!endif
 
#!ifndef FORCE_RTPRELAY
	if (is_request()) {
		if (!has_totag()) {
			if(isflagset(FLT_IPV4)) {
				add_rr_param(";nat=v4");
			} else {
				add_rr_param(";nat=yes");
			}
		}
	}
#!endif
#!ifdef WITH_MOH
	if (is_request()) {
		if (is_method("INVITE")) {
			if (search_body("^a=sendonly")) {
				rtpproxy_stream2uas("/etc/kamailio/moh/moh.sln16", "-1");
			} else {
				rtpproxy_stop_stream2uas();
			}
		}
	}
#!endif

	if (is_reply()) {
		fix_contact();
#!ifdef WITH_MOH
		if (status=="200") {
			if (search_body("^a=sendonly")) {
				rtpproxy_stream2uac("/etc/kamailio/moh/moh.sln16", "-1");
			} else {
				rtpproxy_stop_stream2uac();
			}
		}
#!endif
	}
#!endif
	return;
}

######################################################################
# Route for handling Registrations:
######################################################################
route[REGISTER] {
#!ifdef WITH_RX	
	xlog("L_DBG","Subscribing to signalling bearer status\n");
	Rx_AAR_Register("location");
	switch ($avp(s:aar_return_code)) {
		case 1:
			xlog("L_DBG", "Diameter: AAR success on subscription to signalling\n");
			break;
		default:
			xlog("L_ERR", "Diameter: AAR failed on subscription to signalling\n");
			send_reply("403", "Can't register to QoS for signalling");
			exit;
	}
#!endif
#!ifdef WITH_NAT
	if (isflagset(FLT_NAT) || isflagset(FLT_IPV4)) {
		if (isflagset(FLT_IPV4))
			$var(nat) = "v4";
		else
			$var(nat) = "yes";
		if ($pr == "tls") {
			append_hf("Path: <sip:term@HOSTNAME:"+PORT+";received=\"sip:$si:$sp;transport=tls\";nat=$var(nat);lr>\r\n");
		} else if ($pr == "tcp") {
			append_hf("Path: <sip:term@HOSTNAME:"+PORT+";received=\"sip:$si:$sp;transport=tcp\";nat=$var(nat);lr>\r\n");
		} else {
			append_hf("Path: <sip:term@HOSTNAME:"+PORT+";received=sip:$si:$sp;nat=$var(nat);lr>\r\n");
		}
	} else
#!endif
		append_hf("Path: <sip:term@HOSTNAME:"+PORT+";lr>\r\n");

	append_hf("Supported: path\r\n");
	append_hf("Require: path\r\n");

	# Add a visited Network-ID-Header:
	if (is_present_hf("P-Visited-Network-ID")) {
		$var(new_hdr) = "NETWORKNAME, "+$hdr(P-Visited-Network-ID);
		append_hf("P-Visited-Network-ID: $var(new_hdr)\r\n");
	} else {
		append_hf("P-Visited-Network-ID: NETWORKNAME\r\n");
	}
	pcscf_save_pending("location");
	t_on_reply("REGISTER_reply");
	t_on_failure("REGISTER_failure");
	t_relay();
	exit;
}

######################################################################
# Replies for REGISTER requests:
######################################################################
onreply_route[REGISTER_reply]
{
	if (t_check_status("200")) {
		xlog("L_DBG","Saving location\n");
		pcscf_save("location");
   	}
	exit;
}

######################################################################
# Negative replies to REGISTER requests:
######################################################################
failure_route[REGISTER_failure]
{
	if (t_check_status("408"))
		send_reply("504","Server Time-Out");
}

######################################################################
# Originating, Intial Requests
######################################################################
route[Orig_Initial]
{
	xlog("L_DBG", "IMS: INSIDE ORIG_INITIAL\n");
	loose_route();

	t_newtran();

	if (!pcscf_is_registered("location")) {
		send_reply("403","Forbidden - You must register first with a S-CSCF");
		break;
	}
	if (!pcscf_follows_service_routes("location")){
		#Variant 1 - deny access to the network
		#send_reply("400","Bad Request - Not following indicated service routes");
		#break;
		#Variant 2 - enforce routes and let the dialog continue
		pcscf_force_service_routes("location");
	}

#!ifdef WITH_RX
	xlog("L_DBG","Diameter: Orig authorizing media via Rx\n");	
	Rx_AAR("location");
	if ($avp(s:aar_return_code) != 1) {
		xlog("L_ERR", "Diameter: AAR failed\n");
		send_reply("403", "QoS not authorized");
		exit;
	}
#!endif

	#prepend mo as user for record route
	$avp(RR_CUSTOM_USER_AVP)="mo";
	record_route();
   
	if (is_present_hf("P-Preferred-Identity") && pcscf_assert_identity("location", "$hdr(P-Preferred-Identity)")) {
		remove_hf("P-Preferred-Identity");
		append_hf("P-Asserted-Identity: $hdr(P-Preferred-Identity)\r\n");
	} else if (pcscf_assert_identity("location", "$fu")) {
		append_hf("P-Asserted-Identity: <$fu>\r\n");
	} else {
		append_hf("P-Asserted-Identity: <$pcscf_asserted_identity>\r\n");
	}

	# Do RTP-Relaying, if necessary:
	route(RTPPROXY_ORIG);
   
	set_dlg_profile("orig");
	t_on_reply("Orig_Initial_reply");
	
	if (!t_relay()) {
		send_reply("500","Error forwarding originating initial request");
		break;
	};

	break;
}

######################################################################
# Replies to the Initial Requests
######################################################################
onreply_route[Orig_Initial_reply]
{
	xlog("L_DBG", "route(RTPIMS: INSIDE ORIG_INITIAL_REPLY\n");
#!ifdef WITH_RX
	if (t_check_status("180|183|200")){
		xlog("L_DBG","Diameter: Orig authorizing media via Rx\n");	
		Rx_AAR("orig");
		if ($avp(s:aar_return_code) != 1) {
			xlog("L_ERR", "IMS: AAR failed Orig\n");
			dlg_terminate("all", "Sorry no QoS available");
		} else {
			xlog("L_DBG", "Diameter: Orig AAR success on media authorization\n");	
		} 
      		xlog("L_DBG", "IMS: Received 183/200 inside orig_initial_reply\n");
	}
#!endif
	# Note: We only do the RTP-Update for the successful case,
	#   the others simply time-out (if we would do otherwise, RTP-Relaying
	#   would fail for forked requests)

	# Do RTP-Relaying, if necessary:
	route(RTPPROXY_ORIG);
}

######################################################################
# Originating, Subsequent requests
######################################################################
route[Orig_Subsequent]
{
	xlog("L_DBG", "IMS: INSIDE ORIG_SUBSEQUENT\n");

	#TODO: need to check we are registered before we send request

	loose_route();

	#TODO: check we are following enforeced routes

	# Check for "sec-agree" in the Require header:
	if (is_present_hf("Require") && $hdr(Require) =~ ".*sec-agree.*") {
		# Remove the old Require-Header:
		remove_hf("Require");
		# Replace ", sec-agree" with ""
		$var(new_hdr) = $(hdr(Require){re.subst,/[, ]*sec-agree//gi});
		if ($(var(new_hdr){s.len}) > 0) {
			append_hf("Require: $var(new_hdr)\r\n");
		}
	}
	# Check for "sec-agree" in the Proxy-Require header:
	if (is_present_hf("Proxy-Require") && $hdr(Proxy-Require) =~ ".*sec-agree.*") {
		# Remove the old Proxy-Require-Header:		
		remove_hf("Proxy-Require");
		# Replace ", sec-agree" with ""
		$var(new_hdr) = $(hdr(Proxy-Require){re.subst,/[, ]*sec-agree//gi});
		if ($(var(new_hdr){s.len}) > 0) {
			append_hf("Proxy-Require: $var(new_hdr)\r\n");
		}
	}

	# Do RTP-Relaying, if necessary:
	route(RTPPROXY_ORIG);

	#TODO: remove security verification
	t_on_reply("Orig_Subsequent_reply");
	
	if (!t_relay()) {
		xlog("L_ERR", "Could not forward\n");
		send_reply("500","Error forwarding originating subsequent request");
		break;
	};
}

######################################################################
# Replies to Originating, Subsequent requests
######################################################################
onreply_route[Orig_Subsequent_reply]
{
	xlog("L_DBG", "IMS: INSIDE ORIG_SUBSEQUENT_reply and request is $rm from IP $si\n");

	# Do RTP-Relaying, if necessary:
	route(RTPPROXY_ORIG);
}

######################################################################
# Originating, Standalone requests
######################################################################
route[Orig_Standalone]
{
	xlog("L_DBG", "IMS: INSIDE ORIG_STANDALONE\n");
	loose_route();
	t_newtran();
	if (!pcscf_is_registered("location")) {
		send_reply("403","Forbidden - You must register first with a S-CSCF");
		break;
	}
	if (!pcscf_follows_service_routes("location")){
		#Variant 1 - deny access to the network
		#send_reply("400","Bad Request - Not following indicated service routes");
		#break;
		#Variant 2 - enforce routes and let the dialog continue
		pcscf_force_service_routes("location");
	}

	# add IBCF/THIG route here if required
	# Check for "sec-agree" in the Require header:
	if (is_present_hf("Require") && $hdr(Require) =~ ".*sec-agree.*") {
		# Remove the old Require-Header:
		remove_hf("Require");
		# Replace ", sec-agree" with ""
		$var(new_hdr) = $(hdr(Require){re.subst,/[, ]*sec-agree//gi});
		if ($(var(new_hdr){s.len}) > 0) {
			append_hf("Require: $var(new_hdr)\r\n");
		}
	}
	# Check for "sec-agree" in the Proxy-Require header:
	if (is_present_hf("Proxy-Require") && $hdr(Proxy-Require) =~ ".*sec-agree.*") {
		# Remove the old Proxy-Require-Header:		
		remove_hf("Proxy-Require");
		# Replace ", sec-agree" with ""
		$var(new_hdr) = $(hdr(Proxy-Require){re.subst,/[, ]*sec-agree//gi});
		if ($(var(new_hdr){s.len}) > 0) {
			append_hf("Proxy-Require: $var(new_hdr)\r\n");
		}
        }
	remove_hf("Security-Verify");
	#route(add_charging_vector);                     

        if (!t_relay()) {
                send_reply("500","Error forwarding originating standalone request");
                break;
        };

	break;
}

######################################################################
# Terminating, Initial requests
######################################################################
route[Term_Initial]
{
	xlog("L_DBG", "IMS: INSIDE TERM_INITIAL\n");
	loose_route();

	$avp(RR_CUSTOM_USER_AVP)="mt";
	record_route();

	set_dlg_profile("term");

	t_on_reply("Term_Initial_reply");
	t_on_failure("Term_Initial_failure");

#!ifdef WITH_RX
	xlog("L_DBG","Diameter: Orig authorizing media via Rx\n");	
	Rx_AAR("location");
	if ($avp(s:aar_return_code) != 1) {
		xlog("L_ERR", "Diameter: AAR failed\n");
		send_reply("403", "QoS not authorized");
		exit;
	}
#!endif
	
	# Do RTP-Relaying, if necessary:
	route(RTPPROXY_TERM);

	if (!t_relay()) {
		xlog("L_ERR", "Failure\n");
		send_reply("500","Error forwarding terminating initial request");
		break;
	};
}

######################################################################
# Replies to terminating, initial requests
######################################################################
onreply_route[Term_Initial_reply]
{
#!ifdef WITH_RX
	if (t_check_status("180|183|200")){
		xlog("L_DBG","Diameter Term authorizing media via Rx\n");
		if (!Rx_AAR("term")) {
			xlog("L_ERR", "IMS: AAR failed Term\n");
			dlg_terminate("all", "Sorry no QoS available");
		}  else {
			xlog("L_DBG", "Diameter: Term AAR success on media authorization\n");
		}
		xlog("L_DBG", "IMS: SENDING EARLY BYE\n");
	}
#!endif

	# Do RTP-Relaying, if necessary:
	route(RTPPROXY_TERM);
}

######################################################################
# Replies to terminating, initial requests
######################################################################
failure_route[Term_Initial_failure]
{
	if (t_is_canceled()) {
		exit;
	}
	if (t_check_status("408")) {
		send_reply("404","User offline");
		exit;
	}
}

######################################################################
# Terminating, Standalone requests
######################################################################
route[Term_Standalone]
{
	xlog("L_DBG", "IMS: INSIDE TERM_STANDALONE\n");
	# loose_route();          

	if (!t_relay()) {
		sl_send_reply("500","Error forwarding terminating standalone request");
		break;
	};
}

######################################################################
# Terminating, Subsequent requests
######################################################################
route[Term_Subsequent]
{
	xlog("L_DBG", "IMS: INSIDE TERM_SUBSEQUENT and request is $rm from IP $si\n");

	loose_route();

	# Check for "sec-agree" in the Require header:
	if (is_present_hf("Require") && $hdr(Require) =~ ".*sec-agree.*") {
		# Remove the old Require-Header:
		remove_hf("Require");
		# Replace ", sec-agree" with ""
		$var(new_hdr) = $(hdr(Require){re.subst,/[, ]*sec-agree//gi});
		if ($(var(new_hdr){s.len}) > 0) {
			append_hf("Require: $var(new_hdr)\r\n");
		}
	}
	# Check for "sec-agree" in the Proxy-Require header:
	if (is_present_hf("Proxy-Require") && $hdr(Proxy-Require) =~ ".*sec-agree.*") {
		# Remove the old Proxy-Require-Header:		
		remove_hf("Proxy-Require");
		# Replace ", sec-agree" with ""
		$var(new_hdr) = $(hdr(Proxy-Require){re.subst,/[, ]*sec-agree//gi});
		if ($(var(new_hdr){s.len}) > 0) {
			append_hf("Proxy-Require: $var(new_hdr)\r\n");
		}
        }
	remove_hf("Security-Verify");

	# Do RTP-Relaying, if necessary:
	route(RTPPROXY_TERM);

	# Use Reply route for optional RTP-Relay:
	t_on_reply("Term_Subsequent_reply");

	if (!t_relay()) {
		send_reply("500","Error forwarding terminating subsequent request");
		break;
	};
}

######################################################################
# Replies to terminating, Subsequent requests
######################################################################
onreply_route[Term_Subsequent_reply]
{
	xlog("L_DBG", "IMS: INSIDE TERM_SUBSEQUENT_reply and request is $rm from IP $si\n");

	# Do RTP-Relaying, if necessary:
	route(RTPPROXY_ORIG);
}



