debug=3         # debug level (cmd line: -dddddddddd)
#memdbg=100
#fork=yes
#log_stderror=no	# (cmd line: -E)
#memlog=5 # memory debug log level
#log_facility=LOG_LOCAL0 # sets the facility used for logging (see syslog(3))

check_via=no	# (cmd. line: -v)
dns=no           # (cmd. line: -r)
rev_dns=no      # (cmd. line: -R)
port=5060
children=2
alias="example.com"
alias="t-online.de"

#user=ser
#group=ser
#open_fd_limit=1024 # sets the open file descriptors limit
mhomed=yes  # useful for multihomed hosts, small performance penalty

#disable_tcp=yes 
tcp_accept_aliases=yes # accepts the tcp alias via option (see NEWS)
#tcp_poll_method="sigio_rt"

tcp_send_timeout=1
tcp_children=32
tcp_connect_timeout=1
tcp_connection_lifetime=600
tcp_max_connections=50000

# ------------------ module loading ----------------------------------

# Uncomment this if you want to use SQL database
loadmodule "/usr/lib/ser/modules/xcap.so"
loadmodule "/usr/lib/ser/modules/sl.so"
loadmodule "/usr/lib/ser/modules/avp.so"
loadmodule "/usr/lib/ser/modules/avpops.so"
loadmodule "/usr/lib/ser/modules/tm.so"
loadmodule "/usr/lib/ser/modules/rr.so"
loadmodule "/usr/lib/ser/modules/maxfwd.so"
loadmodule "/usr/lib/ser/modules/usrloc.so"
loadmodule "/usr/lib/ser/modules/registrar.so"
loadmodule "/usr/lib/ser/modules/textops.so"
loadmodule "/usr/lib/ser/modules/mysql.so"
loadmodule "/usr/lib/ser/modules/dialog.so"
loadmodule "/usr/lib/ser/modules/rls.so"
loadmodule "/usr/lib/ser/modules/pa.so"
loadmodule "/usr/lib/ser/modules/presence_b2b.so"
loadmodule "/usr/lib/ser/modules/uri.so"
loadmodule "/usr/lib/ser/modules/uri_db.so"
loadmodule "/usr/lib/ser/modules/domain.so"
loadmodule "/usr/lib/ser/modules/fifo.so"
loadmodule "/usr/lib/ser/modules/xmlrpc.so"
loadmodule "/usr/lib/ser/modules/xlog.so"
#loadmodule "/usr/lib/ser/modules/unixsock.so"

# binrpc
loadmodule "/usr/lib/ser/modules/ctl.so"

# Uncomment this if you want digest authentication
# mysql.so must be loaded !
loadmodule "/usr/lib/ser/modules/auth.so"
loadmodule "/usr/lib/ser/modules/auth_db.so"
loadmodule "/usr/lib/ser/modules/msilo.so"

# ----------------- setting module-specific parameters ---------------

# modparam("msilo","registrar","sip:registrar@example.com")
modparam("msilo","use_contact",0)
modparam("msilo","expire_time",7200)

# -- usrloc params --

# -- auth params --
# Uncomment if you are using auth module
#
modparam("auth_db", "calculate_ha1", yes)
#
# If you set "calculate_ha1" parameter to yes (which true in this config), 
# uncomment also the following parameter)
#
modparam("auth_db", "password_column", "password")

# -- rr params --
# add value to ;lr param to make some broken UAs happy
modparam("rr", "enable_full_lr", 1)

modparam("rls", "min_expiration", 300)
modparam("rls", "max_expiration", 300)
modparam("rls", "default_expiration", 300)
modparam("rls", "expiration_timer_period", 30)
modparam("rls", "auth", "none")
modparam("rls", "reduce_xcap_needs", 1)
modparam("rls", "db_mode", 1)
modparam("rls", "timer_interval", 10)
modparam("rls", "max_notifications_at_once", 100);
modparam("rls", "max_list_nesting_level", 4);

modparam("pa", "use_db", 1)
# allow storing authorization requests for offline users into database
modparam("pa", "use_offline_winfo", 1)
# how often try to remove old stored authorization requests
modparam("pa", "offline_winfo_timer", 600)
# how long stored authorization requests live
modparam("pa", "offline_winfo_expiration", 600)
# mode of PA authorization: none, implicit or xcap
modparam("pa", "auth", "xcap")
# do not authorize watcherinfo subscriptions
modparam("pa", "winfo_auth", "none")
# use only published information if set to 0
modparam("pa", "use_callbacks", 1)
# don't accept internal subscriptions from RLS, ...
modparam("pa", "accept_internal_subscriptions", 0)
# maximum value of Expires for subscriptions
modparam("pa", "max_subscription_expiration", 300)
# maximum value of Expires for publications
modparam("pa", "max_publish_expiration", 300)
# how often test if something changes and send NOTIFY
modparam("pa", "timer_interval", 1)
modparam("pa", "async_auth_queries", 0)
modparam("pa", "auth_rules_refresh_time", 60)
modparam("pa", "max_auth_requests_per_tick", 1000)
modparam("pa", "ignore_408_on_notify", 1)
#modparam("pa", "pres_rules_file", "presence-rules.xml")
#experimental:
#modparam("pa", "subscribe_to_users", 1);
#modparam("pa", "pa_subscription_uri", "sip:presence-server@example.com");


# route for generated SUBSCRIBE requests for presence
#modparam("presence_b2b", "presence_route", "<sip:127.0.0.1;transport=tcp;lr>")
modparam("presence_b2b", "presence_outbound_proxy", "sip:127.0.0.1;transport=tcp")
#modparam("presence_b2b", "presence_outbound_proxy", "sip:127.0.0.1")
# waiting time from error to new attempt about SUBSCRIBE
modparam("presence_b2b", "on_error_retry_time", 60)
# how long wait for NOTIFY with Subscription-Status=terminated after unsubscribe
modparam("presence_b2b", "wait_for_term_notify", 33)
# how long before expiration send renewal SUBSCRIBE request
modparam("presence_b2b", "resubscribe_delta", 30)
# minimal time to send renewal SUBSCRIBE request from receiving previous response
modparam("presence_b2b", "min_resubscribe_time", 60)
# default expiration timeout
modparam("presence_b2b", "default_expiration", 3600)
# process internal subscriptions to presence events
modparam("presence_b2b", "handle_presence_subscriptions", 1)
#additional headers for presence
#modparam("presence_b2b", "additional_presence_headers", "P-Generated: yes\r\nP-Regenerated: no\r\n")
# randomized SUBSCRIBE requests?
modparam("presence_b2b", "max_subscribe_delay", 10)

#modparam("usrloc", "reg_avp_flag", "regavps")
modparam("usrloc", "db_mode", 0)

modparam("domain", "db_mode", 1)
modparam("domain", "load_domain_attrs", 1)
#modparam("domain|uri_db|acc|auth_db|usrloc|msilo|rls|pa", "db_url", "mysql://ser:heslo@spsdb:3306/ser")
modparam("domain|uri_db|acc|auth_db|usrloc|msilo|rls|pa", "db_url", "mysql://ser:heslo@127.0.0.1:3306/ser")

modparam("fifo", "fifo_file", "/tmp/ser_fifo")

#modparam("xcap", "xcap_root", "http://pulpuk/xcap")
modparam("xcap", "xcap_root", "http://localhost/xcap")

# -------------------------  request routing logic -------------------

# main routing logic

avpflags regavps;

route{
	# XML RPC
	if (method == "POST" ||  method == "GET") {
		dispatch_rpc();
		break;
	}

	# initial sanity checks -- messages with
	# max_forwards==0, or excessively long requests
	if (!mf_process_maxfwd_header("10")) {
		sl_send_reply("483","Too Many Hops");
		break;
	};
	if (msg:len >=  max_len ) {
		sl_send_reply("513", "Message too big");
		break;
	};
	
	# we record-route all messages -- to make sure that
	# subsequent messages will go through our proxy; that's
	# particularly good if upstream and downstream entities
	# use different transport protocol
	if (!method=="REGISTER") record_route();	

	# subsequent messages within a dialog should take the
	# path determined by record-routing
	if (loose_route()) {
		# mark routing logic in request
		append_hf("P-hint: rr-enforced\r\n"); 
		route(1);
		break;
	};
					
					
#	lookup_domain("To");
#	lookup_user("To");
#			
#	xlog("L_ERR", "Dispatch request %rm to: %tu from: %fu\n");
#	ds_select_new("1", "3");  /* request uri */
#	sl_send_reply("302", "Moved temporarily");
#	break;

	if (!lookup_domain("$td", "@to.uri.host")) {
		xlog("L_ERR", "Unknown domain to: %tu from: %fu\n");
		route(1);
		break;
	}

#	xlog("L_INFO", "xcap_root: %$t.xcap_root\n");
	
	if (method=="SUBSCRIBE") {
#		if ((@msg.supported=~"eventlist")) {
#			xlog("L_ERR","!!! Support for event lists: %@msg.supported\n");
#		}
#		else {
#			xlog("L_ERR","!!! NON-Support for event lists: %@msg.supported\n");
#		}

		if (search("^(From|f):.*sip:presence-server@test-domain")) {
			log(1,"subscription from PA!\n");
			# subscriptions from PA to user !!!
			if (!lookup("location")) {
				sl_send_reply("404", "Not Found");
				break;
			};
		#	append_hf("P-hint: usrloc applied\r\n"); 
			route(1);
			drop;
		};
		
		if (!t_newtran()) {
			sl_reply_error();
			break;
		};
		
		if (@to.tag=="") { 
			# only for new subscriptions (with empty to tag)

			if (lookup_user("$tu.uid", "@to.uri")) {
				# existing user -> it is subscription to PA

				# xcap parameters
#					set_xcap_root("hTTp://localhost/xcap");
#					set_xcap_filename("pres.xml");
#					xlog("L_INFO", "Hopla\n");
				
				$xcap_root = "pokus";
#				set_xcap_root("http://nekde.nic.cz");
				set_xcap_filename("pre.xml");

				xlog("L_ERR", "XCAP_ROOT before: %$xcap_root\n");
				if (handle_subscription("registrar")) {
					xlog("L_ERR", "XCAP_ROOT after: %$xcap_root\n");
					break;

					if ((@msg.event=~"presence\.winfo")) {
						# new watcher info subscription
						# sends one watcher info NOTIFY message with all saved authorization requests
						#xlog("L_ERR", "dumping stored winfo to %fu\n");
						dump_stored_winfo("registrar", "presence");
					}
					else {
						# new presence subscription
						#if ((@msg.event=~"presence") && check_subscription_status("pending")) {
						if ((@msg.event=~"presence")) {
							# if offline user and new pending subscription 
							if (!target_online("registrar")) {
								#xlog("L_ERR", "storing 'pending' winfo to: %tu, from: %fu\n");
								store_winfo("registrar");
							}
						}
					}
				}
				break;
			}
			
			if ((@msg.supported=~"eventlist")) {
				# such user doesn't exist and Supported header field
				#    -> probably RLS subscription
				
				#set_xcap_root("HttP://LOCALhost/xcap");
				
				if (lookup_domain("$fd", "@from.uri.host")) {
					if (lookup_user("$fu.uid","@from.uri")) {
						if (is_simple_rls_target("$uid-list")) {
						# if (is_simple_rls_target("contact-list")) {
							# log(1, "it is simple subscription!\n");
							# takes From UID and makes XCAP query for user's 
							# list named "default"
							if (!query_resource_list("default")) {
								t_reply("404", "No such user list");
								break;
							}
						}
						else {
							if (is_simple_rls_target("contact-list")) {
								if (!query_resource_list("testing")) {
									t_reply("404", "No such user contact list");
									break;
								}
							}
						}
					}
				}
			
				if (!have_flat_list()) {
					# query_resource_list failed or was not called
					# do standard RLS query according to To/AOR
					if (!query_rls_services()) {
						log(1, "XCAP query failed\n");
						t_reply("404", "No such list URI");
						break;
					}
				}
			
				# uncomment this if you want to authenticate first SUBSCRIBE request to resource list
#					if (!proxy_authenticate("example.com", "credentials")) {
#						proxy_challenge( "example.com", "0");
#						break;
#					};	
				
				handle_rls_subscription("1");
			}
			else {
				# not resource list subscription -> invalid user
				#xlog("L_ERR", "subscription to invalid user %tu\n");
				t_reply("404", "User not found");
			}
			
			break;
		}
		else {
			# renewal subscriptions - try to handle it as RLS and if failed, handle it as PA subscription
			# FIXME: better will be test like existing_rls_subscription() 
			#        and existing_subscription("registrar")
			if (!handle_rls_subscription("0")) {
				lookup_user("$tu.uid", "@to.uri"); # needed to get correct UID (internal call converts it to lowercase!)
				handle_subscription("registrar");
			}
			break;
		}
	};

	if (method=="NOTIFY") {
		if (search("^(To|t):.*sip:presence-server@test-domain")) {
			log(1,"notify to PA!\n");
			# notification to PA from user !!!
			if (!t_newtran()) {
			   log(1, "newtran error\n");
			   sl_reply_error();
			   break;
			};
			# handle notification sent in internal subscriptions (presence_b2b)
			if (!handle_notify()) {
				t_reply("481", "Unable to handle notification for PA");
			}
			break;
		}
	};
		
	# get user (common for all other messages than SUBSCRIBE)
	if (!lookup_user("$tu.uid", "@to.uri")) {
		xlog("L_ERR", "Unknown user, To: %tu?");
		# break;
		#append_hf("P-hint: unknown user\r\n"); 
		sl_send_reply("404", "Unknown user");
		#route(1);
		break;
	}
	
	if (method=="PUBLISH") {
		if (!t_newtran()) {
#			   log(1, "newtran error\n");
		   sl_reply_error();
		   break;
		};
		handle_publish("registrar");

		# deliver messages to online user
		# TODO: only if user goes from offline to online?
		if (target_online("registrar")) {
			# log(1, "Dumping stored messages\n");
			# dump stored messages - route it through myself (otherwise routed via DNS!)
			if (m_dump("sip:127.0.0.1")) {
				#xlog("L_ERR", "MSILO: offline messages for %fu dumped\n");
				break;
			}
		}

		break;
	};

	if (method=="NOTIFY") {
		if (!t_newtran()) {
		   log(1, "newtran error\n");
		   sl_reply_error();
		   break;
		};
		# handle notification sent in internal subscriptions (presence_b2b)
		if (!handle_notify()) {
			t_reply("481", "Unable to handle notification");
		}
		break;
	};
	
	if (method=="MESSAGE") {

		if (authorize_message("im-rules.xml")) {
			
			# use usrloc for delivery
			if (lookup("location")) {
			
				#log(1, "Delivering MESSAGE using usrloc\n");
				t_on_failure("1");
				if (!t_relay()) {
					sl_reply_error();
				}
				
				break;
			}
			else {
				# store messages for offline user
				#xlog("L_ERR", "MSILO: storing MESSAGE for %tu\n");
				
				if (!t_newtran()) {
				   log(1, "newtran error\n");
				   sl_reply_error();
				   break;
				};

				# store only text messages NOT isComposing... !
				if (search("^(Content-Type|c):.*application/im-iscomposing\+xml.*")) {
					#log(1, "it is only isComposing message - ignored\n");
					t_reply("202", "Ignored");
					break;
				}
				
				if (m_store("0", "sip:127.0.0.1")) {
#	                #log(1, "MSILO: offline message stored\n");
					if (!t_reply("202", "Accepted")) {
						sl_reply_error();
					};
				} else {
					log(1, "MSILO: error storing offline message\n");
					if (!t_reply("503", "Service Unavailable")) {
						sl_reply_error();
					};
				};
				break;
			}
			break;
		}
		else {
			# log(1, "unauthorized message\n");
			sl_reply("403", "Forbidden");
		}
		break;
	}
	
	if (method=="REGISTER") {
		# uncomment this if you want to authenticate REGISTER request
#			if (!www_authenticate("example.com", "credentials")) {
#				www_challenge( "example.com", "0");
#				break;
#			};
	
		$t.a = @msg.cseq;
		setavpflag("$t.a","regavps");
		save("location");
		
		# dump stored messages - route it through myself (otherwise routed via DNS!)
		if (m_dump("sip:127.0.0.1")) {
			#xlog("L_ERR", "MSILO: offline messages for %fu dumped\n");
			break;
		}
		break;
	};

	# native SIP destinations are handled using our USRLOC DB
	t_on_branch("1");
	if (!lookup("location")) {
		sl_send_reply("404", "Not Found");
		break;
	};
#	append_hf("P-hint: usrloc applied\r\n"); 
	route(1);
}

branch_route[1]
{
#	xlog("L_ERR", "on_branch: to: %tu, from: %fu\n");
#	xlog("L_ERR", "ruri: %ru uid: %$t.uid\n");
	read_reg_avps("location", "$t.uid");
	xlog("L_ERR", "$t.a = %$t.a");
}
route[1] 
{
	# send it out now; use stateful forwarding as it works reliably
	# even for UDP2TCP
	if (!t_relay()) {
		sl_reply_error();
	};
}


failure_route[1] {
	# forwarding failed -- check if the request was a MESSAGE
	if (!method=="MESSAGE") { break; };
	#log(1, "MSILO: MESSAGE forward failed - storing it\n");
	
    # we have changed the R-URI with the contact address, ignore it now
	if (m_store("0", "")) {
		t_reply("202", "Accepted");
	} else {
		log(1, "MSILO: offline message NOT stored\n");
		t_reply("503", "Service Unavailable");
	};
}
