#!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 FLT_MO 5

#!define DLG_TIMEOUT_AVP "i:1"
#!define RR_CUSTOM_USER_AVP "i:2"
#!define NATHELPER_RECEIVED_AVP "i:3"
#!define DISPATCHER_DST_AVP "i:4"
#!define DISPATCHER_GRP_AVP "i:5"
#!define DISPATCHER_CNT_AVP "i:6"

system.shutdownmode = 0 desc "System shutdown mode"

####### Global Parameters #########
#!ifdef WITH_DEBUG
debug=2
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 prefer IPv6:
dns_try_ipv6=yes
# DNS-Based failover
use_dns_failover=yes
# Query NAPTR-Records as well:
dns_try_naptr=no

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_WEBSOCKET
#!ifndef WITH_TCP
#!define WITH_TCP
#!endif
#!ifndef TCP_PROCESSES
# Number of TCP Processes
#!define TCP_PROCESSES 10
#!endif
#!endif

#!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

#!define DISPATCHER_LIST_IMS "1"
#!ifdef WITH_SBC
#!define DISPATCHER_LIST_SBC "2"
#!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

tcp_accept_no_cl=yes
tcp_rd_buf_size=16384

#!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 "tmx"

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"
loadmodule "sdpops.so"

#!ifdef DB_URL
loadmodule "db_mysql"
#!ifdef DB_URL2
loadmodule "db_cluster"
#!endif
#!endif

#!ifdef WITH_REGINFO
loadmodule "pua.so"
#!endif

# 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

loadmodule "htable"

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

#!ifdef WITH_NAT
loadmodule "path"
loadmodule "rtpengine"
loadmodule "nathelper"
#!endif

#!ifdef WITH_WEBSOCKET
loadmodule "xhttp.so"
loadmodule "websocket.so"
#!endif

#!ifdef WITH_NATPING
loadmodule "nat_traversal"
#!endif

# ----------------- setting module-specific parameters ---------------
#!ifdef DB_URL2
# ----- db_cluster params -----
modparam("db_cluster", "connection", DB_URL)
modparam("db_cluster", "connection", DB_URL2)
modparam("db_cluster", "cluster", "cluster1=>con1=2s2s;con2=1s1s")
#!endif

# ----- 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", 0)

# ----- 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)")

# -- usrloc params --
#!ifdef DB_URL
#!ifdef DB_URL2
modparam("ims_usrloc_pcscf", "db_url", "cluster://cluster1")
#!else
modparam("ims_usrloc_pcscf", "db_url", DB_URL)
#!endif
modparam("ims_usrloc_pcscf", "db_mode", 1)
#!endif
modparam("ims_usrloc_pcscf", "hashing_type", 2)
modparam("ims_usrloc_pcscf", "lookup_check_received", 1)
modparam("ims_usrloc_pcscf", "enable_debug_file", 0)
modparam("ims_registrar_pcscf", "is_registered_fallback2ip", 2)


#!ifdef WITH_REGINFO
modparam("ims_registrar_pcscf", "subscribe_to_reginfo", 1)
modparam("ims_registrar_pcscf", "publish_reginfo", 1)
#!else
modparam("ims_registrar_pcscf", "subscribe_to_reginfo", 0)
modparam("ims_registrar_pcscf", "publish_reginfo", 0)
#!endif

# -- pua params --
#!ifdef WITH_REGINFO
#!ifdef DB_URL
#!ifdef DB_URL2
modparam("pua", "db_url", "cluster://cluster1")
#!else
modparam("pua", "db_url", DB_URL)
#!endif
#!endif
#!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", 45)
modparam("pike", "remove_latency", 4)

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

# ----------------- Settings for Dispatcher ---------------
modparam("dispatcher", "list_file", "/etc/kamailio/dispatcher.list")

# Dispatcher: Enable Failover-Support
modparam("dispatcher", "flags", 2)
# Dispatcher: Overwrite Destination address, if required.
modparam("dispatcher", "force_dst", 1)
# AVP's required for Fail-Over-Support:
modparam("dispatcher", "dst_avp", "$avp(DISPATCHER_DST_AVP)")
modparam("dispatcher", "grp_avp", "$avp(DISPATCHER_GRP_AVP)")
modparam("dispatcher", "cnt_avp", "$avp(DISPATCHER_CNT_AVP)")
# Try to recover disabled destinations every 15 seconds.
modparam("dispatcher", "ds_ping_interval", 15)
# Actively query the gateways:
modparam("dispatcher", "ds_probing_mode", 1)

#!endif

# ----- htable params -----
#!ifdef WITH_IMS_HDR_CACHE
modparam("htable", "htable", "serviceroutes=>size=16;autoexpire=14400;")
modparam("htable", "htable", "associateduris=>size=16;autoexpire=14400;")
#!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-ng params -----
modparam("rtpengine", "rtpengine_sock", RTPPROXY_ADDRESS)
modparam("path", "use_received", 1)
#!endif

#!ifdef WITH_NATPING
# ----- nat_traversal params -----
# If another keepalive is wanted, this is the place
modparam("nat_traversal", "keepalive_interval", 20)
# 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("$rm ($fu ($si:$sp) to $tu, $ci)\n");
##!endif

#!ifdef WITH_WEBSOCKET
	if (($Rp == MY_WS_PORT || $Rp == MY_WSS_PORT) && !(proto == WS || proto == WSS)) {
		xlog("L_WARN", "Websocket-request received on SIP/$Rp\n");
		sl_send_reply("403", "Forbidden");
		exit;
	}
#!endif

	# per request initial checks
	route(REQINIT);

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

	#Set DLG flag to track dialogs using dialog2
	if (is_method("INVITE"))
		setflag(FLT_DIALOG);
	
	# Check for Subsequent requests:
	if (has_totag()) {
		# sequential request withing a dialog should
		# take the path determined by record-routing
		if (loose_route()) {
			if ($route_uri =~ "sip:mo@.*") {
				setflag(FLT_MO);
			}
			if(!isdsturiset()) {
				handle_ruri_alias();
			}
			# RTP-Relay, if necessary
			route(RTPPROXY);
			t_relay();
		} else {
			if ( is_method("ACK") ) {
				if ( t_check_trans() ) {
					# no loose-route, but stateful ACK;
					# must be an ACK after a 487
					# or e.g. 404 from upstream server
					t_relay();
					exit;
				} else {
					# ACK without matching transaction ... ignore and discard
					exit;
				}
			}
			sl_send_reply("404","Not here");
		}
		exit;

	}

	### only initial requests (no To tag)
	# CANCEL processing
	if (is_method("CANCEL")) {
		if (t_check_trans())
			t_relay();
		exit;
	}

	# Check for Re-Transmissions
	t_check_trans();

	if (is_method("REGISTER")) {
		route(REGISTER);
		exit;
	}

	if (is_method("NOTIFY") && (uri==myself)) {
		route(NOTIFY);
		exit;
	}

	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;
	}

	if (!ds_is_from_list()) {
		# Originating from Subscriber:
		route(Orig_Initial);
	} else {
		# Terminating to Subscriber:
		route(Term_Initial);
	}
	exit;
}

#!ifdef WITH_WEBSOCKET
event_route[xhttp:request] {
	set_reply_close();
	set_reply_no_connect();
	
	if ($Rp != MY_WS_PORT
#!ifdef WITH_TLS
	    && $Rp != MY_WSS_PORT
#!endif
	) {
		xlog("L_WARN", "HTTP request received on $Rp\n");
		xhttp_reply("403", "Forbidden", "", "");
		exit;
	}

	if ($hdr(Upgrade)=~"websocket"
			&&  in_list("Upgrade", $hdr(Connection), ",")
			&& $rm=~"GET") {

		# Validate Host - make sure the client is using the correct
		# alias for WebSockets
		if ($hdr(Host) == $null || !is_myself("sip:" + $hdr(Host))) {
			xlog("L_WARN", "Bad host $hdr(Host)\n");
			xhttp_reply("403", "Forbidden", "", "");
			exit;
		}

#!ifdef WEBSOCKET_WEBSERVER
		# Validate Origin - make sure the client is from the authorised website
		if ($hdr(Origin) != "http://"+WEBSOCKET_WEBSERVER
#!ifdef WITH_TLS
		  && $hdr(Origin) != "https://"+WEBSOCKET_WEBSERVER
#!endif
		) {
			xlog("L_WARN", "Unauthorised client $hdr(Origin)\n");
			xhttp_reply("403", "Forbidden", "", "");
			exit;
		}
#!endif

		# ws_handle_handshake() exits (no further configuration file
		# processing of the request) when complete.
		if (ws_handle_handshake()) {
			# Optional... cache some information about the
			# successful connection
			exit;
		}
	}

	# xhttp_reply("200", "OK", "text/html", "<html><body>Wrong URL $hu</body></html>");
	xhttp_reply("404", "Not Found", "", "");
}

event_route[websocket:closed] {
	xlog("L_INFO", "WebSocket connection from $si:$sp has closed\n");
}
#!endif

######################################################################
# 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
			xlog("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;
		}
	}
        if ((uri == myself) && !ds_is_from_list()) {
                xlog("L_ALERT","ALERT: Request to myself: $ru from $fu (IP:$si:$sp), Blocking\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) || (uri == "sip:NETWORKNAME"))) {
		options_reply();
		exit;
	}	
	
	# Ignore Re-Transmits:
	if (t_lookup_request()) {
		exit;
	}

	if (is_method("INVITE|REGISTER")) {
		send_reply("100", "Trying");
	}
}

######################################################################
# 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
	force_rport();
	if (nat_uac_test("19") && !ds_is_from_list()) {
		if(is_method("INVITE|SUBSCRIBE|UPDATE")) {
			set_contact_alias();
		}
		setflag(FLT_NAT);
		if (is_method("REGISTER")) {
			set_contact_alias();
#!ifdef WITH_NATPING
			xlog("L_DBG", "Enabling keep-alive\n");
	        	nat_keepalive();
#!endif
		}
	}
#!ifdef FORCE_RTPRELAY
	if (!ds_is_from_list()) {
		setflag(FLT_NAT);
	}
#!endif
#!endif
	return;
}

######################################################################
# Route for RTPProxy control (Originating Requests)
######################################################################
route[RTPPROXY] {
#!ifdef WITH_DEBUG
	if (is_request())
		xlog("REQUEST: $rm $ru ($si:$sp, $ci)\n");
	else
		xlog("REPLY: $rs $rr ($rm, $si:$sp, $ci)\n");
#!endif

#!ifdef WITH_NAT
	if (is_request() && !isflagset(FLT_NAT)) {
		if(check_route_param("nat=yes")) {
			setflag(FLT_NAT);
		}
	}
	if !(isflagset(FLT_NAT))
		return;

	if (is_request()) {
		if (!has_totag()) {
			add_rr_param(";nat=yes");
		}
	}

	if (is_reply() && !ds_is_from_list()) 
		add_contact_alias();

#!ifdef RTPPROXY_ADDRESS
	if(!t_is_set("onreply_route"))
		t_on_reply("RTPPROXY_reply");

	if (is_reply() && !(status=~"[12][0-9][0-9]"))
		return;

	## P-RTP-Stats snippet for Kamailio/RTPProxy
	if (is_method("BYE") && is_reply())
		return;
	
	if(!has_body("application/sdp"))
		return;

	if (isflagset(FLT_MO)) {
		append_hf("X-RTP: mo\r\n");
		if (sdp_get_line_startswith("$avp(mline)", "m=")) {
			if (is_request()) {
				if (is_direction("downstream")) {
					if ($avp(mline) =~ "SAVPF") {
						$avp(rtpproxy_offer_flags) = "replace-origin replace-session-connection ICE=remove RTP AVP";
						$avp(rtpproxy_answer_flags) = "trust-address replace-origin replace-session-connection ICE=force SRTP AVPF";
						add_rr_param(";rtp=SAVPF");
					} else {
						$avp(rtpproxy_offer_flags) = "replace-origin replace-session-connection ICE=remove";
						$avp(rtpproxy_answer_flags) = "trust-address replace-origin replace-session-connection ICE=force";
					}
				} else {
					if(check_route_param("rtp=SAVPF")) {
						$avp(rtpproxy_offer_flags) = "trust-address replace-origin replace-session-connection ICE=remove RTP AVP";
						$avp(rtpproxy_answer_flags) = "trust-address replace-origin replace-session-connection ICE=force SRTP AVPF";
						add_rr_param(";rtp=SAVPF");
					} else {
						$avp(rtpproxy_offer_flags) = "replace-origin replace-session-connection ICE=remove";
						$avp(rtpproxy_answer_flags) = "trust-address replace-origin replace-session-connection ICE=force";
					}
				}
			}
##!ifdef WITH_DEBUG
			#xlog("$$avp(mline) = $avp(mline)\n");
			#xlog("$$avp(rtpproxy_offer_flags) = $avp(rtpproxy_offer_flags)\n");
			#xlog("$$avp(rtpproxy_answer_flags) = $avp(rtpproxy_answer_flags)\n");
##!endif
			if (is_request() && is_direction("downstream")) rtpengine_manage($avp(rtpproxy_offer_flags));
			else rtpengine_manage($avp(rtpproxy_answer_flags));
		} else {
			# Mobile Originating (User to network)
			if (is_request() && is_direction("downstream")) rtpengine_manage("replace-origin replace-session-connection ICE=force");
			else rtpengine_manage("trust-address replace-origin replace-session-connection ICE=force");
		}
	} else {
		if (is_present_hf("X-RTP")) {
			remove_hf("X-RTP");
		} else {
			# Mobile Terminating (Network to User)
			if (is_request() && is_direction("downstream")) rtpengine_manage("trust-address replace-origin replace-session-connection ICE=remove");
			else rtpengine_manage("replace-origin replace-session-connection ICE=remove");
		}
	}
#!endif
#!endif
	return;
}

# Replies for RTPPROXY
######################################################################
onreply_route[RTPPROXY_reply]
{
	# Do RTP-Relaying, if necessary:
	if (status=~"[12][0-9][0-9]")
		route(RTPPROXY);
}


######################################################################
######################################################################
## REGISTER Handling
######################################################################
######################################################################

# Route for handling Registrations:
######################################################################
route[REGISTER] {
	if (is_present_hf("Contact"))
		pcscf_save_pending("location");
	t_on_reply("REGISTER_reply");
	t_on_failure("REGISTER_failure");

#!ifdef WITH_RX	
	xlog("L_DBG","Subscribing to signalling bearer status\n");

	Rx_AAR_Register("REG_AAR_REPLY", "location");
	switch ($retcode) {
		case -1:
			# There was an error sending the AAR-Request:
			xlog("L_ERR", "Diameter: AAR failed on subscription to signalling\n");
			send_reply("403", "Can't register to QoS for signalling");
			exit;
			break;
		case 0:
			# We are waiting for an async reply, just exit here.
			exit;
			break;
		case 1:
			# We did not need to send AAR, so just continue as normal
			route(REGISTER_CONTINUE);
			break;
	}
	exit;
}

route[REG_AAR_REPLY] {
	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;
	}
	# Proceed with Registering:
	route(REGISTER_CONTINUE);
}

route[REGISTER_CONTINUE] {
#!endif
#!ifndef WITH_SBC
#!ifdef WITH_WEBSOCKET
	if (($Rp == MY_WS_PORT || $Rp == MY_WSS_PORT) && (proto == WS || proto == WSS)) {
		$var(ws_transport) = "ws="+$pr+";";
	} else {
		$var(ws_transport) = "";
	}
#!else
	$var(ws_transport) = "";
#!endif

#!ifdef WITH_NAT
	if (isflagset(FLT_NAT)) {
		append_hf("Path: <sip:term@HOSTNAME:"+PORT+";nat=yes;received=sip:$si:$sp;$var(ws_transport)lr>\r\n");
	} else
#!endif
		append_hf("Path: <sip:term@HOSTNAME:"+PORT+";$var(ws_transport)lr>\r\n");

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

	# 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");
	}
#!ifdef WITH_SBC
	# Choose an SBC to send the call to:
	if (!ds_select_dst(DISPATCHER_LIST_SBC, "4")) {
		send_reply("503", "Service Unavailable (SBC failure)");
		exit;
	}
#!endif

	t_relay();
	exit;
}

# Replies for REGISTER requests:
######################################################################
onreply_route[REGISTER_reply]
{
#!ifdef WITH_IMS_HDR_CACHE
	if (is_present_hf("Service-Route")) {
		$sht(serviceroutes=>$ci) = $hdr(Service-Route);
	} else {
		if ($sht(serviceroutes=>$ci) != $null) {
			append_hf("Service-Route: $sht(serviceroutes=>$ci)\r\n");
			msg_apply_changes();
		}
	}
	if (is_present_hf("P-Associated-URI")) {
		$sht(associateduris=>$ci) = $hdr(P-Associated-URI);
	} else {
		if ($sht(associateduris=>$ci) != $null) {
			append_hf("P-Associated-URI: $sht(associateduris=>$ci)\r\n");
			msg_apply_changes();
		}
	}
#!endif
	if (t_check_status("200")) {
		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 requests
######################################################################
######################################################################

######################################################################
# Originating, Intial Requests
######################################################################
route[Orig_Initial]
{
	# Process route headers, if any:
	loose_route();
	if (!pcscf_is_registered("location")) {
		send_reply("403","Forbidden - You must register first with a S-CSCF");
		break;
	}

	# We do not trust the user, let's remove the P-Asserted-Identity, if any:
	remove_hf("P-Asserted-Identity");
	remove_hf("P-Preferred-Identity");

	if (is_present_hf("P-Preferred-Identity") && pcscf_assert_identity("location", "$hdr(P-Preferred-Identity)")) {
		append_hf("P-Asserted-Identity: $hdr(P-Preferred-Identity)\r\n");
	} else if (is_present_hf("P-Asserted-Identity") && pcscf_assert_identity("location", "$hdr(P-Asserted-Identity)")) {
		append_hf("P-Asserted-Identity: $hdr(P-Asserted-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");
	}

	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_SBC
	# Apply changes to this message
	msg_apply_changes();
	# Copy Route-Header:
	append_hf("P-Route: $(hdr(Route){nameaddr.uri})\r\n");
#!endif

	# 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");


#!ifdef WITH_RX
	xlog("L_DBG","Diameter: Orig authorizing media via Rx\n");	
	if(Rx_AAR("ORIG_SESSION_AAR","orig","",-1)==0){
		exit;
	}
}

route[ORIG_SESSION_AAR] {
	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:
	setflag(FLT_MO);
	route(RTPPROXY);

	#prepend mo as user for record route
	$avp(RR_CUSTOM_USER_AVP)="mo";

	# Do Record-Route for this request:
	record_route();

	set_dlg_profile("orig");
	t_on_reply("Orig_Initial_reply");
	
#!ifdef WITH_SBC
	# Choose an SBC to send the call to:
	if (!ds_select_dst(DISPATCHER_LIST_SBC, "4")) {
		send_reply("503", "Service Unavailable (SBC failure)");
		exit;
	}
#!endif

	t_relay();

	break;
}

######################################################################
# Replies to the Initial Requests
######################################################################
onreply_route[Orig_Initial_reply]
{
#!ifdef WITH_WEBSOCKET
	if (($Rp == MY_WS_PORT || $Rp == MY_WSS_PORT) && !(proto == WS || proto == WSS)) {
		xlog("L_WARN", "Websocket/SIP response received on $Rp\n");
		drop;
	}
#!endif
#!ifdef WITH_RX
	if (t_check_status("180|183|200")){
		xlog("L_DBG","Diameter: Orig authorizing media via Rx\n");	
		if(Rx_AAR("ORIG_SESSION_AAR_REPLY","orig","",-1)==0){
			exit;
		}
	}
}

route[ORIG_SESSION_AAR_REPLY] {
	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");	
	} 
#!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:
	if (status=~"[12][0-9][0-9]")
		route(RTPPROXY);
}

######################################################################
######################################################################
## Terminating requests
######################################################################
######################################################################

# Terminating, Initial requests
######################################################################
route[Term_Initial]
{
	loose_route();

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

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

	if(!isdsturiset()) {
		handle_ruri_alias();
		if ($rc == 1) {
			setflag(FLT_NAT);
		}
	}
	# Do RTP-Relaying, if necessary:
	resetflag(FLT_MO);
	route(RTPPROXY);

#!ifdef WITH_RX
	xlog("L_DBG","Diameter: Term authorizing media via Rx\n");	
	if(Rx_AAR("TERM_SESSION_AAR","term","",-1)==0){
		exit;
	}
}

route[TERM_SESSION_AAR] {
	if ($avp(s:aar_return_code) != 1) {
		xlog("L_ERR", "Diameter: AAR failed\n");
		send_reply("403", "QoS not authorized");
		exit;
	}
#!endif
	t_relay();
}

# Replies to terminating, initial requests
######################################################################
onreply_route[Term_Initial_reply]
{
#!ifdef WITH_WEBSOCKET
	if (($Rp == MY_WS_PORT || $Rp == MY_WSS_PORT) && !(proto == WS || proto == WSS)) {
		xlog("L_WARN", "Websocket/SIP response received on $Rp\n");
		drop;
	}
#!endif
#!ifdef FALSE
	if (t_check_status("183")||t_check_status("200")){
		if (!pcscf_is_registered("location")) {
			xlog("L_DBG", "IMS: INSIDE TERM_INITIAL_REPLY: can't find contact [$ct] in P-CSCF usrloc\n");
			send_reply("403","Forbidden - not registered with P-CSCF");
			break;
		}
		#asserted identity header       
		if (pcscf_assert_called_identity("location")) {
			xlog("L_DBG", "P-Called-Party-ID asserted");
		} else {
			xlog("L_DBG", "P-Called-Party-ID not asserted - using default " + "$pcscf_asserted_identity");
			append_hf("P-Asserted-Identity: <$pcscf_asserted_identity>\r\n");
		}
		if(is_present_hf("P-Preferred-Identity")) {
			remove_hf("P-Preferred-Identity");
		}
		msg_apply_changes();
	}
#!endif

#!ifdef WITH_RX
	if (t_check_status("180|183|200")){
		xlog("L_DBG","Diameter: Orig authorizing media via Rx\n");	
		if(Rx_AAR("TERM_SESSION_AAR_REPLY","term","",-1)==0){
			exit;
		}
	}
}

route[TERM_SESSION_AAR_REPLY] {
	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:
	if (status=~"[12][0-9][0-9]")
		route(RTPPROXY);
}

# 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;
	}
}

######################################################################
######################################################################
## Inter-System Communications
######################################################################
######################################################################

# Notify Route:                                                     #
#####################################################################
route[NOTIFY]
{
	xlog("L_DBG", "IMS: INSIDE NOTIFY\n");
	if (reginfo_handle_notify("location")) {
		send_reply("200","OK - P-CSCF processed notification");
		break;
	} else {
		t_reply("500","Error encountered while processing notification");
		break;
	}
}