log_stderror=yes
listen=127.0.0.1
loadmodule "db_mysql/db_mysql.so"
loadmodule "tm/tm.so"
loadmodule "sl"
loadmodule "rr"
loadmodule "maxfwd"
loadmodule "textops"
loadmodule "xlog"
loadmodule "usrloc"
loadmodule "registrar"
loadmodule "pv"
loadmodule "jsonrpcs"
modparam("jsonrpcs", "transport", 2)
modparam("jsonrpcs", "fifo_name", "kamailio_rpc.fifo")

request_route {
	xlog("received by kamailio[$pp] at '$Tf' from $si:$sp, method: $(rm{s.tolower}), transport: $rP:$Ri:$rp, user agent: $ua\n");

	if !(route(39)) {
		xlog("L_ERR", "Error getting identity\n");
		exit;
	}
	xlog("L_ERR", "My identity: $avp(i:83)\n");
	$var(x) = "sip:" + $fU +"@" + $td;
	xlog("var(x): $var(x), MD5 var(x): $(var(x){s.md5})\n");

	if (!method=="REGISTER")
		record_route();

	if (loose_route()) {
		# mark routing logic in request
		append_hf("P-hint: rr-enforced\r\n");
		route(1);
	}

	if (!uri==myself) {
		append_hf("P-hint: outbound\r\n");
		route(1);
	}
	xlog("From header tag: $(hdr(From){param.value,tag})\n");
	
	if(is_method("REGISTER")) {
		if(is_present_hf("Expires")) {
			xlog("Expires header field present\n");
			if($(hdr(Expires){s.int}) > 0) {
				xlog("this is a registration\n");
			}
			if($(hdr(Expires){s.int}) == 0) {
				xlog("this is an unregistration\n");
			}
		}
		if(is_present_hf("Contact")) {
			xlog("Contact header field present\n");
			if ($(hdr(Contact){param.value,expires}{s.int}) > 0) {
				xlog("this is a registration\n");
			}
			if ($(ct{param.value,expires}{s.int}) == 0) {
				xlog("this is an unregistration\n");
			}
		}
	}

	if (uri==myself) {
		if (method=="REGISTER") {
			save("location");
			exit;
		}
		if (!lookup("location")) {
			sl_send_reply("404", "Not Found");
			exit;
		}
		append_hf("P-hint: usrloc applied\r\n");
	}

	route(1);
}

route[1] {
	if (!t_relay()) {
		sl_reply_error();
	}
	exit;
}

route[39] {
	if ($ai) {
		$avp(i:81)=$(ai{uri.user});
		$avp(i:82)=$(ai{uri.domain});
		$avp(i:83)=$ai;
		xlog("L_ERR", "Getting identity from P-Asserted-Identity header\n");
	} else if ($pu) {
		$avp(i:81)=$(pu{uri.user});
		$avp(i:82)=$(pu{uri.domain});
		$avp(i:83)=$pu;
		xlog("L_ERR", "Getting identity from P-Preferred-Identity header\n");
	} else if ($fU) {
		$avp(i:81)=$(fu{uri.user});
		$avp(i:82)=$(fu{uri.domain});
		$avp(i:83)=$fu;
		xlog("L_ERR", "Getting identity from FROM URI\n");
	} else {
		xlog("L_ERR", "No identity for $rm: $fu -> $ru\n");
		return;# -1;
	}

	return; #1;
}
