debug=3         # debug level (cmd line: -dddddddddd)
#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="test-domain.com"

#user=ser
#group=ser
#open_fd_limit=1024 # sets the open file descriptors limit
mhomed=yes  # usefull 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"

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

# Uncomment this if you want to use SQL database
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"

# 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@test-domain.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", "plain_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", 200)
modparam("rls", "max_expiration", 300)
modparam("rls", "default_expiration", 300)
modparam("rls", "auth", "none")
modparam("rls", "xcap_root", "http://localhost/xcap")
modparam("rls", "reduce_xcap_needs", 1)
modparam("rls", "db_mode", 0)
modparam("rls", "db_url", "mysql://ser:heslo@localhost:3306/ser")

modparam("pa", "use_db", 0)
# 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)
modparam("pa", "db_url", "mysql://ser:heslo@localhost:3306/ser")
# mode of PA authorization: none, implicit or xcap
modparam("pa", "auth", "xcap")
modparam("pa", "auth_xcap_root", "http://localhost/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", 600)
# maximum value of Expires for publications
modparam("pa", "max_publish_expiration", 120)
# how often test if something changes and send NOTIFY
modparam("pa", "timer_interval", 10)

# route for generated SUBSCRIBE requests for presence
modparam("presence_b2b", "presence_route", "<sip:127.0.0.1;transport=tcp;lr>")
# waiting time from error to new attepmt 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)

modparam("usrloc", "db_mode", 0)
modparam("domain", "db_mode", 1)
modparam("domain|uri_db|acc|auth_db|usrloc|msilo", "db_url", "mysql://ser:heslo@localhost:3306/ser")

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

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

# main routing logic

route{
	# XML RPC
	if (method == "POST" ||  method == "GET") {
		create_via();
		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 withing 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;
	};

	# if the request is for other domain use UsrLoc
	# (in case, it does not work, use the following command
	# with proper names and addresses in it)
	if (uri==myself) {
	
		if (!lookup_domain("To")) {
			xlog("L_ERR", "Unknown domain to: %tu from: %fu\n");
			route(1);
			break;
		}
		
		if (method=="SUBSCRIBE") {
			if (!t_newtran()) {
				sl_reply_error();
				break;
			};
			
			if (@to.tag=="") { 
				# only for new subscriptions (with empty to tag)

				if (lookup_user("To")) {
					# existing user -> it is subscription to PA
					if (handle_subscription("registrar")) {
						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") && (%subscription_status=="pending")) {
								# if offline user and new pending subscription 
								if (!target_online("registrar")) {
									#%subscription_status="waiting"; # store it as waiting subscription
									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
				
					if (lookup_domain("From")) {
						if (lookup_user("From")) {
							if (is_simple_rls_target("$uid-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;
								}
							}
						}
					}
				
					if (!have_flat_list()) {
						# query_resource_list failed or was not called
						# do standard RLS query acording 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("test-domain.com", "credentials")) {
#						proxy_challenge( "test-domain.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")) {
					handle_subscription("registrar");
				}
				break;
			}
		};

		# get user (common for all other messages than SUBSCRIBE)
		if (!lookup_user("To")) {
			# log(1, "Unknown user - message should be forwarded?");
#			# break;
			append_hf("P-hint: unknown user\r\n"); 
			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;
		};
	
 		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("http://localhost/xcap")) {
				
				# 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("test-domain.com", "credentials")) {
#				www_challenge( "test-domain.com", "0");
#				break;
#			};
			
			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;
		};

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

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