module-router.cc 38.2 KB
Newer Older
1
/*
2 3
	Flexisip, a flexible SIP proxy server with media capabilities.
	Copyright (C) 2010-2015  Belledonne Communications SARL, All rights reserved.
4

5 6 7 8
	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as
	published by the Free Software Foundation, either version 3 of the
	License, or (at your option) any later version.
9

10 11 12 13
	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Affero General Public License for more details.
14

15 16
	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
*/
18

19 20
#include <flexisip/module-router.hh>
#include <flexisip/logmanager.hh>
21
#include <sofia-sip/sip_status.h>
22

23
using namespace std;
24
using namespace flexisip;
25

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
void ModuleRouter::onDeclare(GenericStruct *mc) {
	ConfigItemDescriptor configs[] = {
		{Boolean, "use-global-domain", "Store and retrieve contacts without using the domain.", "false"},
		{Boolean, "fork", "Fork messages to all registered devices", "true"},
		{Boolean, "stateful",
			"Force forking and thus the creation of an outgoing transaction even when only one contact found", "true"},
		{Boolean, "fork-late", "Fork invites to late registers", "false"},
		{Boolean, "fork-no-global-decline", "All the forked have to decline in order to decline the caller invite",
			"false"},
		{Boolean, "treat-decline-as-urgent",
			"Treat 603 Declined answers as urgent. Only relevant if fork-no-global-decline is set to true.", "false"},
		{Boolean, "treat-all-as-urgent", "During a fork procedure, treat all failure response as urgent", "false"},
		{Integer, "call-fork-timeout", "Maximum time for a call fork to try to reach a callee, in seconds.", "90"},
		{Integer, "call-fork-urgent-timeout",
			"Maximum time before delivering urgent responses during a call fork, in seconds. "
			"The typical fork process requires to wait the best response from all branches before transmitting it to "
			"the client. "
			"However some error responses are retryable immediately (like 415 unsupported media, 401, 407) thus it is "
			"painful for the client to need to wait the end of the transaction time (32 seconds) for these error "
			"codes.",
			"5"},
47
		{Integer, "call-fork-current-branches-timeout", "Maximum time in seconds before trying the next branches with lower priorities",
48 49 50 51 52 53 54 55
			"10"},
		{Integer, "call-push-response-timeout", "Optional timer to detect lack of push response, in seconds.", "0"},
		{Boolean, "message-fork-late", "Fork messages to client registering lately. ", "true"},
		{Integer, "message-delivery-timeout", "Maximum duration for delivering a text message. This property applies only"
			" if message-fork-late if set to true, otherwise the duration can't exceed the normal transaction duration.", "3600"},
		{Integer, "message-accept-timeout",
			"Maximum duration for accepting a text message if no response is received from any recipients."
			" This property is meaningful when message-fork-late is set to true.", "15"},
56 57
		{String, "fallback-route", "Default route to apply when the recipient is unreachable, given as a SIP URI, for"
			" example: sip:example.org;transport=tcp (without surrounding brakets)", ""},
58 59 60 61 62 63 64 65 66 67 68 69 70 71
		{Boolean, "allow-target-factorization",
			"During a call forking, allow several INVITEs going to the same next hop to be grouped into "
			"a single one. A proprietary custom header 'X-target-uris' is added to the INVITE to indicate the final "
			"targets of the "
			"INVITE.",
			"false"},
		{String, "generated-contact-route",
			"Generate a contact from the TO header and route it to the above destination. [sip:host:port]", ""},
		{String, "generated-contact-expected-realm",
			"Require presence of authorization header for specified realm. [Realm]", ""},
		{Boolean, "generate-contact-even-on-filled-aor", "Generate a contact route even on filled AOR.", "false"},
		{Boolean, "remove-to-tag", "Remove to tag from 183, 180, and 101 responses to workaround buggy gateways",
			"false"},
		{String, "preroute", "Rewrite username with given value.", ""},
72 73 74
		{Boolean, "resolve-routes", "Whether or not to resolve next hope in route header against registrar database."
			" This is an extension to RFC3261, and should not be used unless in some specific deployment cases."
			" A next hope in route header is otherwise resolved through standard DNS procedure by the Forward module.", "false"},
75 76 77 78 79 80 81 82 83 84 85 86
		{Boolean, "parent-domain-fallback", "Whether or not to fallback to the parent domain if there is no fallback route set and the recipient is unreachable", "false"},
		config_item_end};
	mc->addChildrenValues(configs);

	mStats.mCountForks = mc->createStats("count-forks", "Number of forks");
	mStats.mCountForkTransactions =
		mc->createStats("count-fork-transactions", "Number of outgoing transaction created for forking");

	mStats.mCountNonForks = mc->createStat("count-non-forked", "Number of non forked invites.");
	mStats.mCountLocalActives =
		mc->createStat("count-local-registered-users", "Number of users currently registered through this server.");
}
87

88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
void ModuleRouter::onLoad(const GenericStruct *mc) {
	GenericStruct *cr = GenericManager::get()->getRoot();
	const GenericStruct *mReg = cr->get<GenericStruct>("module::Registrar");

	mDomains = mReg->get<ConfigStringList>("reg-domains")->read();
	mStateful = mc->get<ConfigBoolean>("stateful");
	mFork = mc->get<ConfigBoolean>("fork")->read();
	if (mStateful && !mFork) {
		LOGI("Stateful router implies fork=true");
		mFork = true;
	}
	mGeneratedContactRoute = mc->get<ConfigString>("generated-contact-route")->read();
	mExpectedRealm = mc->get<ConfigString>("generated-contact-expected-realm")->read();
	mGenerateContactEvenOnFilledAor = mc->get<ConfigBoolean>("generate-contact-even-on-filled-aor")->read();

	//Forking configuration for INVITEs
	mForkCfg = make_shared<ForkContextConfig>();
	mForkCfg->mForkLate = mc->get<ConfigBoolean>("fork-late")->read();
	mForkCfg->mTreatAllErrorsAsUrgent = mc->get<ConfigBoolean>("treat-all-as-urgent")->read();
	mForkCfg->mForkNoGlobalDecline = mc->get<ConfigBoolean>("fork-no-global-decline")->read();
	mForkCfg->mUrgentTimeout = mc->get<ConfigInt>("call-fork-urgent-timeout")->read();
	mForkCfg->mPushResponseTimeout = mc->get<ConfigInt>("call-push-response-timeout")->read();
	mForkCfg->mDeliveryTimeout = mc->get<ConfigInt>("call-fork-timeout")->read();
	mForkCfg->mTreatDeclineAsUrgent = mc->get<ConfigBoolean>("treat-decline-as-urgent")->read();
	mForkCfg->mRemoveToTag = mc->get<ConfigBoolean>("remove-to-tag")->read();
	mForkCfg->mCurrentBranchesTimeout = mc->get<ConfigInt>("call-fork-current-branches-timeout")->read();

	//Forking configuration for MESSAGEs
	mMessageForkCfg = make_shared<ForkContextConfig>();
	mMessageForkCfg->mForkLate = mc->get<ConfigBoolean>("message-fork-late")->read();
	mMessageForkCfg->mDeliveryTimeout = mc->get<ConfigInt>("message-delivery-timeout")->read();
	mMessageForkCfg->mUrgentTimeout = mc->get<ConfigInt>("message-accept-timeout")->read();

	//Forking configuration for other kind of requests.
	mOtherForkCfg = make_shared<ForkContextConfig>();
	mOtherForkCfg->mTreatAllErrorsAsUrgent = false;
	mOtherForkCfg->mForkLate = false;
	mOtherForkCfg->mDeliveryTimeout = 30;

	mUseGlobalDomain = mc->get<ConfigBoolean>("use-global-domain")->read();

	mPreroute = mc->get<ConfigString>("preroute")->read();
	mAllowDomainRegistrations = cr->get<GenericStruct>("inter-domain-connections")
									->get<ConfigBoolean>("accept-domain-registrations")
									->read();
	mAllowTargetFactorization = mc->get<ConfigBoolean>("allow-target-factorization")->read();
	mResolveRoutes = mc->get<ConfigBoolean>("resolve-routes")->read();
	mFallbackRoute = mc->get<ConfigString>("fallback-route")->read();
	mFallbackParentDomain = mc->get<ConfigBoolean>("parent-domain-fallback")->read();
137 138

	if (!mFallbackRoute.empty()){
139
		mFallbackRouteParsed = sipUrlMake(getHome(), mFallbackRoute.c_str());
Simon Morlat's avatar
Simon Morlat committed
140
		if (!mFallbackRouteParsed) LOGF("Bad value [%s] for fallback-route in module::Router.", mFallbackRoute.c_str());
141
	}
142
}
143

144 145
void ModuleRouter::sendReply(shared_ptr<RequestSipEvent> &ev, int code, const char *reason, int warn_code,
							 const char *warning) {
146
	const shared_ptr<MsgSip> &ms = ev->getMsgSip();
147 148
	sip_t *sip = ms->getSip();
	sip_warning_t *warn = NULL;
149

150 151 152 153
	if (sip->sip_request->rq_method == sip_method_invite) {
		shared_ptr<CallLog> calllog = ev->getEventLog<CallLog>();
		if (calllog) {
			calllog->setStatusCode(code, reason);
154
			calllog->setCompleted();
155
		}
156 157 158 159
	} else if (sip->sip_request->rq_method == sip_method_message) {
		shared_ptr<MessageLog> mlog = ev->getEventLog<MessageLog>();
		if (mlog) {
			mlog->setStatusCode(code, reason);
160 161 162
			mlog->setCompleted();
		}
	}
163 164
	if (warn_code != 0) {
		warn = sip_warning_format(ev->getHome(), "%i %s \"%s\"", warn_code, mAgent->getPublicIp().c_str(), warning);
165
	}
166 167 168
	if (warn) {
		ev->reply(code, reason, SIPTAG_SERVER_STR(getAgent()->getServerString()), SIPTAG_WARNING(warn), TAG_END());
	} else {
169 170
		ev->reply(code, reason, SIPTAG_SERVER_STR(getAgent()->getServerString()), TAG_END());
	}
171 172
}

173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
string ModuleRouter::routingKey(const url_t *sipUri) {
	ostringstream oss;
	if (sipUri->url_user) {
		if (!mPreroute.empty() && strcmp(sipUri->url_user, mPreroute.c_str()) != 0) {
			oss << "merged"
				<< "@"; // all users but preroute are merged
		} else {
			oss << sipUri->url_user << "@";
		}
	}
	if (mUseGlobalDomain) {
		oss << "merged";
	} else {
		oss << sipUri->url_host;
	}
	return oss.str();
}

191 192 193 194
/**
 * Check if the contact is in one via.
 * Avoid to check a contact information that already known
 */
195
static bool contactUrlInVia(const url_t *url, sip_via_t *via) {
196 197 198 199 200 201 202 203 204 205 206 207 208 209
	while (via != NULL) {
		if (via->v_host && url->url_host && !strcmp(via->v_host, url->url_host)) {
			const char *port1 = (via->v_port) ? via->v_port : "5060";
			const char *port2 = (url->url_port) ? url->url_port : "5060";
			if (!strcmp(port1, port2))
				return true;
		}
		via = via->v_next;
	}

	return false;
}

bool ModuleRouter::rewriteContactUrl(const shared_ptr<MsgSip> &ms, const url_t *ct_url, const char *route) {
210 211
	sip_t *sip = ms->getSip();
	su_home_t *home = ms->getHome();
212 213 214 215 216 217 218 219 220

	if (!contactUrlInVia(ct_url, sip->sip_via)) {
		/*sanity check on the contact address: might be '*' or whatever useless information*/
		if (ct_url->url_host != NULL && ct_url->url_host[0] != '\0') {
			LOGD("ModuleRouter: found contact information in database, rewriting request uri");
			/*rewrite request-uri */
			sip->sip_request->rq_url[0] = *url_hdup(home, ct_url);
			if (route && 0 != strcmp(mAgent->getPreferredRoute().c_str(), route)) {
				LOGD("This flexisip instance is not responsible for contact %s:%s:%s -> %s",
221 222
					 ct_url->url_user ? ct_url->url_user : "", ct_url->url_host ? ct_url->url_host : "",
					 ct_url->url_params ? ct_url->url_params : "", route);
223
				cleanAndPrependRoute(mAgent, ms->getMsg(), sip, sip_route_make(home, route));
224 225 226 227 228 229 230 231 232 233 234 235
			}
			// Back to work
			return true;
		} else {
			LOGW("Unrouted request because of incorrect address of record.");
		}
	} else {
		LOGW("Contact is already routed");
	}
	return false;
}

236 237 238 239 240
bool ModuleRouter::lateDispatch(const shared_ptr<RequestSipEvent> &ev, const shared_ptr<ExtendedContact> &contact,
							shared_ptr<ForkContext> context, const string &targetUris) {
	return dispatch(ev, contact, context, targetUris);
}

241 242
bool ModuleRouter::dispatch(const shared_ptr<RequestSipEvent> &ev, const shared_ptr<ExtendedContact> &contact,
							shared_ptr<ForkContext> context, const string &targetUris) {
243
	const shared_ptr<MsgSip> &ms = ev->getMsgSip();
244
	time_t now = getCurrentTime();
245
	sip_contact_t *ct = contact->toSofiaContact(ms->getHome(), now);
246
	url_t *dest = ct->m_url;
247

248

249
	/*sanity check on the contact address: might be '*' or whatever useless information*/
250
	if (dest->url_host == NULL || dest->url_host[0] == '\0') {
251 252 253 254
		LOGW("Unrouted request because of incorrect address of contact");
		return false;
	}

255
	char *contact_url_string = url_as_string(ms->getHome(), dest);
256
	shared_ptr<RequestSipEvent> new_ev;
257 258 259 260 261
	if (context) {
		// duplicate the SIP event
		new_ev = make_shared<RequestSipEvent>(ev);
	} else {
		new_ev = ev;
262 263
	}
	auto new_msgsip = new_ev->getMsgSip();
264 265 266
	msg_t *new_msg = new_msgsip->getMsg();
	sip_t *new_sip = new_msgsip->getSip();

267
	// Convert path to routes
268
	sip_route_t *routes = contact->toSofiaRoute(new_ev->getHome());
269 270
	if (!contact->mUsedAsRoute) {
		if (targetUris.empty()) {
271 272
			/* Rewrite request-uri */
			new_sip->sip_request->rq_url[0] = *url_hdup(msg_home(new_msg), dest);
273 274 275 276
		} // else leave the request uri as it is, the X-target-uris header will give the resolved destinations.
		  // the cleaning of push notif params will be done just before forward
	} else {
		// leave the request uri as it is, but append a route for the final destination
277
		sip_route_t *final_route = sip_route_create(new_msgsip->getHome(), dest, NULL);
278
		if (!url_has_param(final_route->r_url, "lr")) {
279 280
			url_param_add(new_msgsip->getHome(), final_route->r_url, "lr");
		}
281 282 283 284

		if (routes == NULL)
			routes = final_route;
		else {
285
			sip_route_t *r = routes;
286
			while (r->r_next != NULL) {
287 288 289 290 291
				r = r->r_next;
			}
			r->r_next = final_route;
		}
	}
292 293 294 295 296 297 298 299
	if (!contact->mIsFallback){
		/* If the original request received contained a X-Target-Uris, it shall be removed now, except
		 * in the case where we send to a fallback route, because in this case the actual resolution of the X-Target-Uris is 
		 * actually not done at all. */
		sip_unknown_t *h = ModuleToolbox::getCustomHeaderByName(new_ev->getMsgSip()->getSip(), "X-Target-Uris");
		if (h) sip_header_remove(new_ev->getMsgSip()->getMsg(), new_ev->getMsgSip()->getSip(), (sip_header_t *)h);
	}
	
300 301 302
	if (!targetUris.empty()) {
		sip_header_insert(new_msg, new_sip, (sip_header_t *)sip_unknown_format(msg_home(new_msg), "X-Target-Uris: %s",
																			   targetUris.c_str()));
303
	}
304
	new_sip->sip_route = NULL;
305
	cleanAndPrependRoute(getAgent(), new_msg, new_sip, routes);
306 307

	if (context) {
308
		context->addBranch(new_ev, contact);
309
		SLOGD << "Fork to " << contact_url_string;
310 311 312 313 314 315 316
	} else {
		LOGD("Dispatch to %s", contact_url_string);
	}

	return true;
}

317
void ModuleRouter::onContactRegistered(const string &uid, const shared_ptr<Record> &aor, const url_t *sipUri) {
318 319 320
	SofiaAutoHome home;
	sip_path_t *path = NULL;
	sip_contact_t *contact = NULL;
Erwan Croze's avatar
Erwan Croze committed
321

322 323 324 325 326
	if (aor == NULL) {
		SLOGE << "aor was null...";
		return;
	}

327 328
	if (!mForkCfg->mForkLate && !mMessageForkCfg->mForkLate)
		return;
329
	if (!sipUri)
330
		return; // nothing to do
331

332 333
	char sipUriRef[256] = {0};
	url_t urlcopy = *sipUri;
334

335 336
	if (mUseGlobalDomain) {
		urlcopy.url_host = "merged";
337
	}
338
	url_e(sipUriRef, sizeof(sipUriRef) - 1, &urlcopy);
339

340
	// Find all contexts
Guillaume Beraudo's avatar
Guillaume Beraudo committed
341 342 343
	const string key(routingKey(sipUri));
	auto range = mForks.equal_range(key.c_str());
	SLOGD << "Searching for fork context with key " << key;
344

345
	const shared_ptr<ExtendedContact> ec = aor->extractContactByUniqueId(uid);
346
	if (ec) {
347
		contact = ec->toSofiaContact(home.home(), ec->mExpireAt - 1);
348
		path = ec->toSofiaRoute(home.home());
349

350
		// First use sipURI
351
		for (auto it = range.first; it != range.second; ++it) {
352
			shared_ptr<ForkContext> context = it->second;
353
			if (context->onNewRegister(contact->m_url, uid)) {
354
				SLOGD << "Found a pending context for key " << key << ": " << context.get();
355
				lateDispatch(context->getEvent(), ec, context, "");
356 357
			} else
				LOGD("Found a pending context but not interested in this new register.");
358
		}
359 360 361 362 363 364
	}

	// If not found find in aliases
	const auto contacts = aor->getExtendedContacts();
	for (auto it = contacts.begin(); it != contacts.end(); ++it) {
		const shared_ptr<ExtendedContact> ec = *it;
365 366
		if (!ec || !ec->mAlias)
			continue;
367 368

		// Find all contexts
369
		contact = ec->toSofiaContact(home.home(), ec->mExpireAt - 1);
370
		path = ec->toSofiaRoute(home.home());
371
		auto rang = mForks.equal_range(ExtendedContact::urlToString(ec->mSipContact->m_url));
372
		for (auto ite = rang.first; ite != rang.second; ++ite) {
373
			shared_ptr<ForkContext> context = ite->second;
374
			if (context->onNewRegister(contact->m_url, uid)) {
375
				LOGD("Found a pending context for contact %s: %p", ExtendedContact::urlToString(ec->mSipContact->m_url).c_str(), context.get());
376
				auto stlpath = Record::route_to_stl(path);
377
				lateDispatch(context->getEvent(), ec, context, "");
378 379 380 381 382
			}
		}
	}
}

383
bool ModuleRouter::makeGeneratedContactRoute(shared_ptr<RequestSipEvent> &ev, const shared_ptr<Record> &aor,
384
											 list<shared_ptr<ExtendedContact>> &ec_list) {
385
	if (!mGeneratedContactRoute.empty() && (!aor || mGenerateContactEvenOnFilledAor)) {
386 387
		const shared_ptr<MsgSip> &ms = ev->getMsgSip();
		sip_t *sip = ms->getSip();
388
		const url_t *to = ms->getSip()->sip_to->a_url;
389
		shared_ptr<ExtendedContact> gwECt = make_shared<ExtendedContact>(to, mGeneratedContactRoute.c_str());
390 391 392

		// This contact is a proxy which will challenge us with a known Realm
		const char *nextProxyRealm = mExpectedRealm.empty() ? to->url_host : mExpectedRealm.c_str();
393 394
		if (ms->getSip()->sip_request->rq_method == sip_method_invite &&
			!ModuleToolbox::findAuthorizationForRealm(ms->getHome(), sip->sip_proxy_authorization, nextProxyRealm)) {
395 396 397 398 399
			LOGD("No authorization header %s found in request, forwarding request only to proxy", nextProxyRealm);
			if (rewriteContactUrl(ms, to, mGeneratedContactRoute.c_str())) {
				shared_ptr<OutgoingTransaction> transaction = ev->createOutgoingTransaction();
				shared_ptr<string> thisProxyRealm(make_shared<string>(to->url_host));
				transaction->setProperty("this_proxy_realm", thisProxyRealm);
400 401
				shared_ptr<RequestSipEvent> new_ev = make_shared<RequestSipEvent>(ev);
				getAgent()->injectRequestEvent(new_ev);
402
				return true;
403 404 405 406 407
			}
		} else {
			LOGD("Authorization header %s found", nextProxyRealm);
		}
		LOGD("Added generated contact to %s@%s through %s", to->url_user, to->url_host, mGeneratedContactRoute.c_str());
408
		ec_list.push_back(gwECt);
409
	}
410 411
	return false;
}
412

413 414
struct ForkDestination {
	ForkDestination() : mSipContact(NULL) {
415
	}
416 417
	ForkDestination(sip_contact_t *ct, const shared_ptr<ExtendedContact> &exContact, const string &targetUris)
		: mSipContact(ct), mExtendedContact(exContact), mTargetUris(targetUris) {
418
	}
419
	sip_contact_t *mSipContact;
420 421 422 423
	shared_ptr<ExtendedContact> mExtendedContact;
	string mTargetUris;
};

424 425 426 427
class ForkGroupSorter {
  public:
	ForkGroupSorter(const list<pair<sip_contact_t *, shared_ptr<ExtendedContact>>> &usable_contacts)
		: mAllContacts(usable_contacts) {
428
	}
429
	void makeGroups() {
430 431
		SofiaAutoHome home;
		/*first step, eliminate adjacent contacts, they cannot be factorized*/
432 433
		for (auto it = mAllContacts.begin(); it != mAllContacts.end();) {
			if ((*it).second->mPath.size() < 2) {
434
				/*this is a "direct" destination, nothing to do*/
435
				mDestinations.emplace_back(ForkDestination((*it).first, (*it).second, ""));
436
				it = mAllContacts.erase(it);
437 438
			} else
				++it;
439 440
		}
		/*second step, form groups with non-adjacent contacts*/
441 442
		for (auto it = mAllContacts.begin(); it != mAllContacts.end();) {
			list<pair<sip_contact_t *, shared_ptr<ExtendedContact>>>::iterator sameDestinationIt;
443 444 445
			ForkDestination dest;
			ostringstream targetUris;
			bool foundGroup = false;
446

447 448
			dest.mSipContact = (*it).first;
			dest.mExtendedContact = (*it).second;
449
			targetUris << "<" << *dest.mExtendedContact->toSofiaUrlClean(home.home()) << ">";
450
			url_t *url = url_make(home.home(), (*it).second->mPath.back().c_str());
451
			// remove it and now search for other contacts that have the same route.
452
			it = mAllContacts.erase(it);
453
			while ((sameDestinationIt = findDestination(url)) != mAllContacts.end()) {
454
				targetUris << ", <" << *(*sameDestinationIt).second->toSofiaUrlClean(home.home()) << ">";
455 456 457
				mAllContacts.erase(sameDestinationIt);
				foundGroup = true;
			}
458 459
			if (foundGroup) {
				// a group was formed
460 461 462 463 464 465 466
				LOGD("A group with targetUris %s was formed", targetUris.str().c_str());
				dest.mTargetUris = targetUris.str();
				it = mAllContacts.begin();
			}
			mDestinations.emplace_back(dest);
		}
	}
467 468
	void makeDestinations() {
		for (auto it = mAllContacts.begin(); it != mAllContacts.end(); ++it) {
469
			mDestinations.emplace_back(ForkDestination((*it).first, (*it).second, ""));
470 471
		}
	}
472
	const list<ForkDestination> &getDestinations() const {
473 474
		return mDestinations;
	}
475 476 477

  private:
	list<pair<sip_contact_t *, shared_ptr<ExtendedContact>>>::iterator findDestination(const url_t *url) {
478
		SofiaAutoHome home;
479 480
		// LOGD("findDestination(): looking for %s", url_as_string(home.home(), url));
		for (auto it = mAllContacts.begin(); it != mAllContacts.end(); ++it) {
481
			url_t *it_route = url_make(home.home(), (*it).second->mPath.back().c_str());
482 483
			// LOGD("findDestination(): seeing %s", url_as_string(home.home(), it_route));
			if (url_cmp(it_route, url) == 0) {
484 485 486 487 488 489
				return it;
			}
		}
		return mAllContacts.end();
	}
	list<ForkDestination> mDestinations;
490
	list<pair<sip_contact_t *, shared_ptr<ExtendedContact>>> mAllContacts;
491 492
};

493
void ModuleRouter::routeRequest(shared_ptr<RequestSipEvent> &ev, const shared_ptr<Record> &aor, const url_t *sipUri) {
494 495 496
	const shared_ptr<MsgSip> &ms = ev->getMsgSip();
	sip_t *sip = ms->getSip();
	list<shared_ptr<ExtendedContact>> contacts;
497
	list<pair<sip_contact_t *, shared_ptr<ExtendedContact>>> usable_contacts;
498
	bool isInvite = false;
499 500 501

	if (!aor && mGeneratedContactRoute.empty()) {
		LOGD("This user isn't registered (no aor).");
502
		SLOGUE << "User " << url_as_string(ms->getHome(), sipUri) << " isn't registered (no aor)";
503
		sendReply(ev, SIP_404_NOT_FOUND);
504 505 506
		return;
	}

507 508 509
	// _Copy_ list of extended contacts
	if (aor)
		contacts = aor->getExtendedContacts();
510

511 512 513 514 515 516
	time_t now = getCurrentTime();

	// Eventually generate a fake contact for a proxy and handle it directly.
	if (makeGeneratedContactRoute(ev, aor, contacts))
		return;

517 518
	// now, create the list of usable contacts to fork to
	bool nonSipsFound = false;
519 520
	for (auto it = contacts.begin(); it != contacts.end(); ++it) {
		const shared_ptr<ExtendedContact> &ec = *it;
521
		sip_contact_t *ct = ec->toSofiaContact(ms->getHome(), now);
522
		if (!ct) {
523
			SLOGE << "Can't create sip_contact of " << ec->mSipContact->m_url;
524 525
			continue;
		}
526 527 528 529 530
		// If it's not a message, verify if it's really expired
		if (sip->sip_request->rq_method != sip_method_message && (ec->getExpireNotAtMessage() < now)) {
			LOGD("Sip_contact of %s is expired", url_as_string(ms->getHome(),ec->mSipContact->m_url));
			continue;
		}
531
		if (sip->sip_request->rq_url->url_type == url_sips && ct->m_url->url_type != url_sips) {
532
			/* https://tools.ietf.org/html/rfc5630 */
533
			nonSipsFound = true;
534 535 536
			LOGD("Not dispatching request to non-sips target.");
			continue;
		}
537 538 539
		if (ec->mUsedAsRoute && ModuleToolbox::viaContainsUrl(sip->sip_via, ct->m_url)) {
			LOGD("Skip destination to %s, because the message is coming from here already.",
				 url_as_string(ms->getHome(), ct->m_url));
540 541
			continue;
		}
542
		usable_contacts.push_back(make_pair(ct, ec));
543
	}
544

545
	if (usable_contacts.size() == 0) {
546
		if (nonSipsFound) {
547
			/*rfc5630 5.3*/
548
			SLOGUE << "Not dispatching request because SIPS not allowed for " << url_as_string(ms->getHome(), sipUri);
549
			sendReply(ev, SIP_480_TEMPORARILY_UNAVAILABLE, 380, "SIPS not allowed");
550
		} else {
551
			LOGD("This user isn't registered (no valid contact).");
552
			SLOGUE << "User " << url_as_string(ms->getHome(), sipUri) << " isn't registered (no valid contact)";
553
			sendReply(ev, SIP_404_NOT_FOUND);
554 555 556 557
		}
		return;
	}
	/*now we can create a fork context and dispatch the message to all branches*/
558

559 560 561 562 563 564 565 566 567 568 569
	if (!mFork) {
		mStats.mCountNonForks->incr();
	} else {
		mStats.mCountForks->incrStart();
	}

	// Init context if needed
	shared_ptr<ForkContext> context;
	if (mFork) {
		if (sip->sip_request->rq_method == sip_method_invite) {
			context = make_shared<ForkCallContext>(getAgent(), ev, mForkCfg, this);
570
			isInvite = true;
571 572 573 574 575
		} else if (
			(sip->sip_request->rq_method == sip_method_message) &&
			!(sip->sip_content_type && strcasecmp(sip->sip_content_type->c_type, "application/im-iscomposing+xml") == 0) &&
			!(sip->sip_expires && sip->sip_expires->ex_delta == 0)
		) {
576
			// Use the basic fork context for "im-iscomposing+xml" messages to prevent storing useless messages
577
			context = make_shared<ForkMessageContext>(getAgent(), ev, mMessageForkCfg, this);
578
		} else if (sip->sip_request->rq_method == sip_method_refer &&
579 580 581
				   (sip->sip_refer_to != NULL && msg_params_find(sip->sip_refer_to->r_params, "text") != NULL)) {
			// Use the message fork context only for refers that are text to prevent storing useless refers
			context = make_shared<ForkMessageContext>(getAgent(), ev, mMessageForkCfg, this);
582
		} else {
583
			context = make_shared<ForkBasicContext>(getAgent(), ev, mOtherForkCfg, this);
584
		}
585
		if (context) {
586
			if (context->getConfig()->mForkLate) {
587
				const string key(routingKey(sipUri));
588
				context->addKey(key);
589
				mForks.insert(make_pair(key, context));
590
				if (mForks.count(key) == 1) {
591 592 593
					auto listener = make_shared<OnContactRegisteredListener>(this, sipUri);
					context->setContactRegisteredListener(listener);
					RegistrarDb::get()->subscribe(key, listener);
594
				}
595
				SLOGD << "Add fork " << context.get() << " to store with key '" << key << "'";
596 597
			}
		}
598
	}
599
	// now sort usable_contacts to form groups, if grouping is allowed
600
	ForkGroupSorter sorter(usable_contacts);
601
	if (isInvite && mAllowTargetFactorization) {
602
		sorter.makeGroups();
603
	} else {
604 605
		sorter.makeDestinations();
	}
606 607
	const list<ForkDestination> &destinations = sorter.getDestinations();

608 609
	for (auto it = destinations.begin(); it != destinations.end(); ++it) {
		sip_contact_t *ct = (*it).mSipContact;
610
		const shared_ptr<ExtendedContact> &ec = (*it).mExtendedContact;
611
		const string &targetUris = (*it).mTargetUris;
612

613
		if (!ec->mAlias) {
614
			if (dispatch(ev, ec, context, targetUris)) {
615 616
				if (!mFork)
					break;
617 618
			}
		} else {
619
			if (mFork && context->getConfig()->mForkLate && isManagedDomain(ct->m_url)) {
620
				sip_contact_t *temp_ctt = sip_contact_create(ms->getHome(), (url_string_t*)ec->mSipContact->m_url, NULL);
621

622 623 624
				if (mUseGlobalDomain) {
					temp_ctt->m_url->url_host = "merged";
					temp_ctt->m_url->url_port = NULL;
625
				}
626
				const string key(routingKey(temp_ctt->m_url));
627
				context->addKey(key);
628
				mForks.insert(make_pair(key, context));
629
				if (mForks.count(key) == 1) {
630 631 632
					auto listener = make_shared<OnContactRegisteredListener>(this, temp_ctt->m_url);
					context->setContactRegisteredListener(listener);
					RegistrarDb::get()->subscribe(key, listener);
633
				}
634
				LOGD("Add fork %p to store with key '%s' because it is an alias", context.get(), key.c_str());
635
			} else {
636
				if (dispatch(ev, ec, context, targetUris)) {
637 638
					if (!mFork)
						break;
639 640
				}
			}
641 642
		}
	}
643 644

	context->start();
645 646
}

Erwan Croze's avatar
Erwan Croze committed
647
class PreroutingFetcher : public ContactUpdateListener,
648 649
						  public enable_shared_from_this<PreroutingFetcher>,
						  private ModuleToolbox {
Guillaume Beraudo's avatar
Guillaume Beraudo committed
650 651
	friend class ModuleRouter;
	shared_ptr<RequestSipEvent> mEv;
Erwan Croze's avatar
Erwan Croze committed
652
	shared_ptr<ContactUpdateListener> mListener;
653
	vector<string> mPreroutes;
Guillaume Beraudo's avatar
Guillaume Beraudo committed
654 655
	int pending;
	bool error;
656
	shared_ptr<Record> m_record;
657 658

  public:
Guillaume Beraudo's avatar
Guillaume Beraudo committed
659
	PreroutingFetcher(ModuleRouter *module, shared_ptr<RequestSipEvent> ev,
Erwan Croze's avatar
Erwan Croze committed
660
					  const shared_ptr<ContactUpdateListener> &listener, const vector<string> &preroutes)
661
		: mEv(ev), mListener(listener), mPreroutes(preroutes) {
Guillaume Beraudo's avatar
Guillaume Beraudo committed
662 663
		pending = 0;
		error = false;
664
		m_record = make_shared<Record>(nullptr);
Guillaume Beraudo's avatar
Guillaume Beraudo committed
665
	}
666

Guillaume Beraudo's avatar
Guillaume Beraudo committed
667 668 669 670 671
	~PreroutingFetcher() {
	}

	void fetch() {
		const char *domain = mEv->getSip()->sip_to->a_url->url_host;
672 673
		if (isNumeric(domain))
			SLOGE << "Not handled: to is ip at " << __LINE__;
Guillaume Beraudo's avatar
Guillaume Beraudo committed
674

675
		pending += mPreroutes.size();
Guillaume Beraudo's avatar
Guillaume Beraudo committed
676 677
		for (auto it = mPreroutes.cbegin(); it != mPreroutes.cend(); ++it) {
			url_t *target = url_format(mEv->getHome(), "sip:%s@%s", it->c_str(), domain);
678
			RegistrarDb::get()->fetch(target, this->shared_from_this(), true);
Guillaume Beraudo's avatar
Guillaume Beraudo committed
679 680
		}
	}
681

682
	void onRecordFound(const shared_ptr<Record> &r) override{
Guillaume Beraudo's avatar
Guillaume Beraudo committed
683 684 685 686 687 688 689 690
		--pending;
		if (r != NULL) {
			const auto &ctlist = r->getExtendedContacts();
			for (auto it = ctlist.begin(); it != ctlist.end(); ++it)
				m_record->pushContact(*it);
		}
		checkFinished();
	}
Simon Morlat's avatar
Simon Morlat committed
691
	void onError() override{
Guillaume Beraudo's avatar
Guillaume Beraudo committed
692 693 694 695 696
		--pending;
		error = true;
		checkFinished();
	}

Simon Morlat's avatar
Simon Morlat committed
697
	void onInvalid() override{
698 699 700 701 702
		--pending;
		error = true;
		checkFinished();
	}

Simon Morlat's avatar
Simon Morlat committed
703
	void onContactUpdated(const shared_ptr<ExtendedContact> &ec) override{
Erwan Croze's avatar
Erwan Croze committed
704 705
	}

Guillaume Beraudo's avatar
Guillaume Beraudo committed
706
	void checkFinished() {
707 708 709 710 711 712
		if (pending != 0)
			return;
		if (error)
			mListener->onError();
		else
			mListener->onRecordFound(m_record);
Guillaume Beraudo's avatar
Guillaume Beraudo committed
713 714 715
	}
};

Erwan Croze's avatar
Erwan Croze committed
716
class TargetUriListFetcher : public ContactUpdateListener,
717 718
							 public enable_shared_from_this<TargetUriListFetcher>,
							 private ModuleToolbox {
719 720
	friend class ModuleRouter;
	shared_ptr<RequestSipEvent> mEv;
Erwan Croze's avatar
Erwan Croze committed
721
	shared_ptr<ContactUpdateListener> mListener;
722
	sip_route_t *mUriList; /*it is parsed as a route but is not a route*/
723
	int mPending;
724
	shared_ptr<Record> mRecord;
725
	bool mError;
726 727 728

  public:
	TargetUriListFetcher(ModuleRouter *module, const shared_ptr<RequestSipEvent> &ev,
Erwan Croze's avatar
Erwan Croze committed
729
						 const shared_ptr<ContactUpdateListener> &listener, sip_unknown_t *target_uris)
730
		: mEv(ev), mListener(listener) {
731 732
		mPending = 0;
		mError = false;
733
		mRecord = make_shared<Record>(nullptr);
734
		if (target_uris && target_uris->un_value) {
735 736 737 738 739 740 741 742 743 744
			/*the X-target-uris header is parsed like a route, as it is a list of URIs*/
			mUriList = sip_route_make(mEv->getHome(), target_uris->un_value);
		}
	}

	~TargetUriListFetcher() {
	}

	void fetch(bool allowDomainRegistrations, bool recursive) {
		sip_route_t *iter;
Simon Morlat's avatar
Simon Morlat committed
745
		/*compute the number of asynchronous queries we are going to make, to later know when we are done.*/
746
		for (iter = mUriList; iter != NULL; iter = iter->r_next) {
747
			mPending++;
Simon Morlat's avatar
Simon Morlat committed
748 749 750
		}
		/*start the queries for all uris of the target uri list*/
		for (iter = mUriList; iter != NULL; iter = iter->r_next) {
751
			RegistrarDb::get()
752
				->fetch(iter->r_url, this->shared_from_this(), allowDomainRegistrations, recursive);
753 754 755
		}
	}

756
	void onRecordFound(const shared_ptr<Record> &r) override{
757
		--mPending;
758 759 760
		if (r != NULL) {
			const auto &ctlist = r->getExtendedContacts();
			for (auto it = ctlist.begin(); it != ctlist.end(); ++it)
761
				mRecord->pushContact(*it);
762 763 764
		}
		checkFinished();
	}
Simon Morlat's avatar
Simon Morlat committed
765
	void onError() override{
766 767
		--mPending;
		mError = true;
768 769 770
		checkFinished();
	}

Simon Morlat's avatar
Simon Morlat committed
771
	void onInvalid() override{
772 773
		--mPending;
		mError = true;
774 775 776
		checkFinished();
	}

Simon Morlat's avatar
Simon Morlat committed
777
	void onContactUpdated(const shared_ptr<ExtendedContact> &ec) override{
Erwan Croze's avatar
Erwan Croze committed
778 779
	}

780
	void checkFinished() {
781 782
		if (mPending != 0)
			return;
783
		if (mError){
784
			mListener->onError();
785
		}else{
786
			if (mRecord->count() > 0){
787 788 789
				/*also add aliases in the ExtendedContact list for the searched AORs, so that they are added to the ForkMap.*/
				sip_route_t *iter;
				for (iter = mUriList; iter != NULL; iter = iter->r_next) {
790

791 792 793 794 795 796 797
					shared_ptr<ExtendedContact> alias = make_shared<ExtendedContact>(iter->r_url, "");
					alias->mAlias = true;
					mRecord->pushContact(alias);
				}
			}
			mListener->onRecordFound(mRecord);
		}
798 799 800
	}
};

Erwan Croze's avatar
Erwan Croze committed
801
class OnFetchForRoutingListener : public ContactUpdateListener {
802 803 804 805
	friend class ModuleRouter;
	ModuleRouter *mModule;
	shared_ptr<RequestSipEvent> mEv;
	url_t *mSipUri;
806 807 808 809

  public:
	OnFetchForRoutingListener(ModuleRouter *module, shared_ptr<RequestSipEvent> ev, const url_t *sipuri)
		: mModule(module), mEv(ev) {
810
		if (!ev->isSuspended()) ev->suspendProcessing();
811
		mSipUri = url_hdup(mEv->getMsgSip()->getHome(), sipuri);
812
		const sip_t *sip = ev->getMsgSip()->getSip();
813
		if (sip->sip_request->rq_method == sip_method_invite) {
814
			ev->setEventLog(make_shared<CallLog>(sip));
815 816
		}
	}
817 818
	void onRecordFound(const shared_ptr<Record> &arg) override{
		shared_ptr<Record> r = arg;
819
		const string &fallbackRoute = mModule->getFallbackRoute();
820

821 822 823
		if (r == nullptr){
			r = make_shared<Record>(mSipUri);
		}
824 825

		if (!mModule->isManagedDomain(mSipUri)) {
826
			shared_ptr<ExtendedContact> contact = make_shared<ExtendedContact>(mSipUri, "");
827 828
			r->pushContact(contact);

829
			SLOGD << "Record [" << r << "] Original request URI added because domain is not managed: " << *contact;
830 831
		}

832
		if (!fallbackRoute.empty()) {
833
			if (!ModuleToolbox::viaContainsUrlHost(mEv->getMsgSip()->getSip()->sip_via, mModule->getFallbackRouteParsed())) {
834
				shared_ptr<ExtendedContact> fallback = make_shared<ExtendedContact>(mSipUri, fallbackRoute, 0.0);
835
				fallback->mIsFallback = true;
836 837 838 839 840
				r->pushContact(fallback);
				SLOGD << "Record [" << r << "] Fallback route '" << fallbackRoute << "' added: " << *fallback;
			}else{
				SLOGD << "Not adding fallback route '" << fallbackRoute << "' to avoid loop because request is coming from there already.";
			}
841 842
		}

843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
		if (r->count() == 0 && mModule->isFallbackToParentDomainEnabled()) {
			string host = mSipUri->url_host;
			size_t pos = host.find('.');
			size_t end = host.length();
			if (pos == string::npos) {
				SLOGE << "Host URL doesn't have any subdomain: " << host;
				mModule->routeRequest(mEv, r, mSipUri);
				return;
			} else {
				host = host.substr(pos + 1, end - (pos + 1)); // Gets the host without the first subdomain
			}

			url_t *url = url_format(mEv->getHome(), "sip:%s@%s", mSipUri->url_user, host.c_str());
			SLOGD << "Record [" << r << "] empty, trying to route to parent domain: '" << url_as_string(mEv->getHome(), url);

			auto onRoutingListener = make_shared<OnFetchForRoutingListener>(mModule, mEv, mSipUri);
			RegistrarDb::get()->fetch(url, onRoutingListener, mModule->isDomainRegistrationAllowed(), true);
		} else {
			mModule->routeRequest(mEv, r, mSipUri);
		}
863
	}
Simon Morlat's avatar
Simon Morlat committed
864
	void onError() override{
865
		mModule->sendReply(mEv, SIP_500_INTERNAL_SERVER_ERROR);
866
	}
867

Simon Morlat's avatar
Simon Morlat committed
868
	void onInvalid() override{
869 870
		LOGD("OnFetchForRoutingListener::onInvalid : 400 - Replayed CSeq");
		mModule->sendReply(mEv, 400, "Replayed CSeq");
871
	}
Erwan Croze's avatar
Erwan Croze committed
872

Simon Morlat's avatar
Simon Morlat committed
873
	void onContactUpdated(const shared_ptr<ExtendedContact> &ec) override{
Erwan Croze's avatar
Erwan Croze committed
874
	}
875 876
};

877
vector<string> ModuleRouter::split(const char *data, const char *delim) {
878
	const char *p;
Guillaume Beraudo's avatar
Guillaume Beraudo committed
879 880
	vector<string> res;
	char *s = strdup(data);
881 882
	char *saveptr = NULL;
	for (p = strtok_r(s, delim, &saveptr); p; p = strtok_r(NULL, delim, &saveptr)) {
Guillaume Beraudo's avatar
Guillaume Beraudo committed
883 884 885 886 887 888
		res.push_back(p);
	}
	free(s);
	return res;
}

889
void ModuleRouter::onRequest(shared_ptr<RequestSipEvent> &ev) {
890 891 892 893
	const shared_ptr<MsgSip> &ms = ev->getMsgSip();
	sip_t *sip = ms->getSip();

	// Handle SipEvent associated with a Stateful transaction
894
	if (sip->sip_request->rq_method == sip_method_cancel) {
895 896
		ForkContext::processCancel(ev);
		return;
897 898
	}

899 900 901 902 903 904 905 906
	// Don't route registers
	if (sip->sip_request->rq_method == sip_method_register)
		return;

	if (mResolveRoutes) {
		sip_route_t *iterator = sip->sip_route;
		while (iterator != NULL) {
			sip_route_t *route = iterator;
907
			if (getAgent()->isUs(route->r_url)) {
908 909 910 911 912 913 914 915 916 917 918
				SLOGD << "Route header found " << url_as_string(ms->getHome(), route->r_url) << " and is us, continuing";
			} else {
				SLOGD << "Route header found " << url_as_string(ms->getHome(), route->r_url) << " but not us, forwarding";
				url_t *sipurl = sip->sip_request->rq_url;
				auto onRoutingListener = make_shared<OnFetchForRoutingListener>(this, ev, sipurl);
				RegistrarDb::get()->fetch(sipurl, onRoutingListener, mAllowDomainRegistrations, true);
				return;
			}
			iterator = iterator->r_next;
		}
	} else if (sip->sip_route != NULL && !getAgent()->isUs(sip->sip_route->r_url)) {
919 920
		SLOGD << "Route header found " << url_as_string(ms->getHome(), sip->sip_route->r_url)
			  << " but not us, skipping";
jehan's avatar
jehan committed
921 922 923
		return;
	}

924
	/*see if we can route other requests */
925 926
	/*
	 * 	ACKs shall not have their request uri rewritten:
927 928
		- they can be for us (in response to a 407 for invite)
		- they can be for the a remote peer, in which case they will have the correct contact address in the request uri
929
	*/
930 931 932
	/* When we accept * as domain we need to test ip4/ipv6 */
	if (sip->sip_request->rq_method != sip_method_ack && sip->sip_to != NULL && sip->sip_to->a_tag == NULL) {
		url_t *sipurl = sip->sip_request->rq_url;
933
		if (sipurl->url_host && isManagedDomain(sipurl)) {
Guillaume Beraudo's avatar
Guillaume Beraudo committed
934
			LOGD("Fetch for url %s.", url_as_string(ms->getHome(), sipurl));
935 936
			// Go stateful to stop retransmissions
			ev->createIncomingTransaction();
Simon Morlat's avatar
Simon Morlat committed
937
			sendReply(ev, SIP_100_TRYING);
Guillaume Beraudo's avatar
Guillaume Beraudo committed
938
			auto onRoutingListener = make_shared<OnFetchForRoutingListener>(this, ev, sipurl);
Erwan Croze's avatar
Erwan Croze committed
939

940 941 942 943 944
			if (mPreroute.empty()) {
				/*the unstandard X-Target-Uris header gives us a list of SIP uri to which the request is to be forked.*/
				sip_unknown_t *h = ModuleToolbox::getCustomHeaderByName(ev->getSip(), "X-Target-Uris");
				if (!h) {
					RegistrarDb::get()->fetch(sipurl, onRoutingListener, mAllowDomainRegistrations, true);
Guillaume Beraudo's avatar
Guillaume Beraudo committed
945
				} else {
946 947
					auto fetcher = make_shared<TargetUriListFetcher>(this, ev, onRoutingListener, h);
					fetcher->fetch(mAllowDomainRegistrations, true);
Guillaume Beraudo's avatar
Guillaume Beraudo committed
948
				}
949
			} else {
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967
				/*The preroute request uri param does more or less the same thing as the above X-Target-Uris header,
				* but was designed in more ancient times. The domain name is deduced from the request-uri.
				* It is kept for backward compatibility but the X-Target-Uris method is prefered*/
				char preroute_param[20];
				if (url_param(sipurl->url_params, "preroute", preroute_param, sizeof(preroute_param))) {
					if (strchr(preroute_param, '@')) {
						SLOGE << "Prerouting contains at symbol" << preroute_param;
						return;
					}
					SLOGD << "Prerouting to provided " << preroute_param;
					vector<string> tokens = split(preroute_param, ":");
					auto prFetcher = make_shared<PreroutingFetcher>(this, ev, onRoutingListener, tokens);
					prFetcher->fetch();
				} else {
					SLOGD << "Prerouting to " << mPreroute;
					url_t *prerouteUrl = url_format(ev->getHome(), "sip:%s@%s", mPreroute.c_str(), sipurl->url_host);
					RegistrarDb::get()->fetch(prerouteUrl, onRoutingListener, true);
				}
Guillaume Beraudo's avatar
Guillaume Beraudo committed
968
			}
969 970 971 972
		}
	}
}

973
void ModuleRouter::onResponse(shared_ptr<ResponseSipEvent> &ev) {
Simon Morlat's avatar
Simon Morlat committed
974
	ForkContext::processResponse(ev);
975 976
}

977
void ModuleRouter::onForkContextFinished(shared_ptr<ForkContext> ctx) {
978
	if (!ctx->getConfig()->mForkLate) return;
979

980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
	list<string> keys = ctx->getKeys();
	for (list<string>::iterator it=keys.begin(); it != keys.end(); ++it) {
		string key = *it;
		LOGD("Looking at fork contexts with key %s", key.c_str());

		int count = 0;
		int removed = 0;
		auto range = mForks.equal_range(key.c_str());
		for (auto it = range.first; it != range.second;) {
			count++;
			if (it->second == ctx) {
				LOGD("Remove fork %s from store", it->first.c_str());
				mStats.mCountForks->incrFinish();
				auto cur_it = it;
				++it;
				// for some reason the multimap erase does not return the next iterator !
				mForks.erase(cur_it);
				removed++;
				// do not break, because a single fork context might appear several time in the map because of aliases.
			} else {
				++it;
			}
		}
		if (count == removed && count > 0) {
Sylvain Berfini's avatar
Sylvain Berfini committed
1004
			RegistrarDb::get()->unsubscribe(key, ctx->getContactRegisteredListener());
1005
		}
1006
	}
1007 1008
}

1009 1010 1011 1012 1013 1014
ModuleInfo<ModuleRouter> ModuleRouter::sInfo(
	"Router",
	"The ModuleRouter module routes requests for domains it manages.",
	{ "ContactRouteInserter" },
	ModuleInfoBase::ModuleOid::Router
);