1 // ANNA - Anna is Not Nothingness Anymore //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo //
5 // See project site at http://redmine.teslayout.com/projects/anna-suite //
6 // See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE //
9 #include <stdlib.h> // rand()
12 #include <anna/diameter.comm/Engine.hpp>
13 #include <anna/core/tracing/Logger.hpp>
14 #include <anna/core/tracing/TraceMethod.hpp>
15 #include <anna/xml/Node.hpp>
16 #include <anna/comm/Network.hpp>
17 #include <anna/comm/Host.hpp>
18 #include <anna/comm/ClientSocket.hpp>
20 #include <anna/diameter.comm/Transport.hpp>
21 #include <anna/diameter.comm/Engine.hpp>
22 #include <anna/diameter.comm/Entity.hpp>
23 #include <anna/diameter.comm/Server.hpp>
24 #include <anna/diameter.comm/ClientSession.hpp>
25 #include <anna/diameter.comm/LocalServer.hpp>
26 #include <anna/core/functions.hpp>
27 #include <anna/diameter/internal/sccs.hpp>
28 #include <anna/diameter.comm/OamModule.hpp>
29 #include <anna/diameter/codec/functions.hpp>
30 #include <anna/diameter/helpers/base/functions.hpp>
31 #include <anna/diameter/helpers/helpers.hpp>
32 #include <anna/diameter/codec/Message.hpp>
33 #include <anna/diameter/codec/Avp.hpp>
34 #include <anna/diameter.comm/Response.hpp>
40 using namespace anna::diameter;
51 comm::Engine::Engine(const char *className, const stack::Dictionary *baseProtocolDictionary) :
52 anna::app::Component(className),
54 a_availableForEntities(false),
55 a_availableForLocalServers(false),
60 a_watchdogPeriod(ClientSession::DefaultWatchdogPeriod),
61 a_maxConnectionDelay(anna::comm::ClientSocket::DefaultMaxConnectionDelay /* 200 ms*/),
62 a_numberOfClientSessionsPerServer(1),
63 a_baseProtocolCodecEngine((std::string("baseProtocolCodecEngine_for_") + std::string(className)).c_str(), baseProtocolDictionary)
65 anna::diameter::sccs::activate();
66 a_realm = anna::functions::getDomainname();
67 a_host = anna::functions::getHostname();
69 // Internal base protocol codec engine:
70 a_baseProtocolCodecEngine.setValidationMode(anna::diameter::codec::Engine::ValidationMode::Always); // default was: after decoding
74 void comm::Engine::assertBaseProtocolHealth() throw(anna::RuntimeException) {
75 if (!getBaseProtocolCodecEngine()->getDictionary())
76 throw anna::RuntimeException("Invalid diameter::comm::Engine object: base protocol dictionary provided on constructor was NULL", ANNA_FILE_LOCATION);
77 // it would be interesting to check and identify certain base protocol elements in the dictionary ...
78 // but these things will be checked in runtime and will fail if they should.
82 comm::Server* comm::Engine::allocateServer() throw() { return a_serversRecycler.create(); }
83 void comm::Engine::releaseServer(Server *server) throw() { a_serversRecycler.release(server); }
84 comm::ClientSession* comm::Engine::allocateClientSession() throw() { return a_clientSessionsRecycler.create(); }
85 void comm::Engine::releaseClientSession(ClientSession *clientSession) throw() { a_clientSessionsRecycler.release(clientSession); }
88 void comm::Engine::setClientCERandDWR(const anna::DataBlock & cer, const anna::DataBlock & dwr) throw(anna::RuntimeException) {
89 if(codec::functions::getCommandId(cer) != helpers::base::COMMANDID__Capabilities_Exchange_Request) {
90 throw anna::RuntimeException("The message provided as 'CER' is not a Capabilities-Exchange-Request", ANNA_FILE_LOCATION);
93 if(codec::functions::getCommandId(dwr) != helpers::base::COMMANDID__Device_Watchdog_Request) {
94 throw anna::RuntimeException("The message provided as 'DWR' is not a Device-Watchdog-Request", ANNA_FILE_LOCATION);
101 void comm::Engine::setClientCERandDWR(const std::string & cer, const std::string & dwr) throw(anna::RuntimeException) {
103 // Check for base protocol codec engine health:
104 assertBaseProtocolHealth();
107 // <CER> ::= < Diameter Header: 257, REQ >
108 // { Origin-Host } 264 diameterIdentity
109 // { Origin-Realm } 296 idem
110 // 1* { Host-IP-Address } 257, address
111 // { Vendor-Id } 266 Unsigned32
112 // { Product-Name } 269 UTF8String
113 // [Origin-State-Id] 278 Unsigned32
114 // * [ Supported-Vendor-Id ] 265 Unsigned32
115 // * [ Auth-Application-Id ] 258 Unsigned32
116 // * [Acct-Application-Id] 259 Unsigned32
117 anna::diameter::codec::Message diameterCER(getBaseProtocolCodecEngine());
118 int applicationId = 0 /*anna::diameter::helpers::APPID__3GPP_Rx*/; // Unsigned32
119 std::string OH = getHost();
120 std::string OR = getRealm();
121 std::string hostIP = anna::functions::getHostnameIP(); // Address
122 int vendorId = anna::diameter::helpers::VENDORID__tgpp; // Unsigned32
123 std::string productName = "ANNA Diameter Client"; // UTF8String
124 bool encodeDefault = false;
128 diameterCER.loadXML(cer);
129 } catch(anna::RuntimeException &ex) {
131 encodeDefault = true;
132 LOGWARNING(anna::Logger::warning("CER file not found or unable to parse. Encoding harcoded default version ...", ANNA_FILE_LOCATION));
136 encodeDefault = true;
140 diameterCER.setId(anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request);
141 diameterCER.setApplicationId(applicationId);
142 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
143 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
144 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Host_IP_Address)->getAddress()->fromPrintableString(hostIP.c_str()); // supported by Address class, anyway is better to provide "1|<ip address>"
145 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Vendor_Id)->getUnsigned32()->setValue(vendorId);
146 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Product_Name)->getUTF8String()->setValue(productName);
147 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Auth_Application_Id)->getUnsigned32()->setValue(applicationId);
151 // <DWR> ::= < Diameter Header: 280, REQ >
154 anna::diameter::codec::Message diameterDWR(getBaseProtocolCodecEngine());
155 encodeDefault = false;
159 diameterDWR.loadXML(dwr);
160 } catch(anna::RuntimeException &ex) {
162 encodeDefault = true;
163 LOGWARNING(anna::Logger::warning("DWR file not found or unable to parse. Encoding harcoded default version ...", ANNA_FILE_LOCATION));
167 encodeDefault = true;
171 diameterDWR.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Request);
172 diameterDWR.setApplicationId(applicationId);
173 diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
174 diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
177 // Assignment for internal encoded versions:
178 setClientCERandDWR(diameterCER.code(), diameterDWR.code());
181 void comm::Engine::setWatchdogPeriod(const anna::Millisecond & wp) throw(anna::RuntimeException) {
182 if(wp < ClientSession::DefaultWatchdogPeriod) {
183 throw anna::RuntimeException(anna::functions::asString("Please set watchdog period over %s", ClientSession::DefaultWatchdogPeriod.asString().c_str()), ANNA_FILE_LOCATION);
186 a_watchdogPeriod = wp;
189 void comm::Engine::checkEntityCollision(const socket_v &v) throw(anna::RuntimeException) {
190 socket_v::const_iterator it;
191 socket_v::const_iterator it_min(v.begin());
192 socket_v::const_iterator it_max(v.end());
194 for(it = it_min; it != it_max; it++) {
195 server_iterator ii = server_find(*it);
197 if(ii != server_end())
198 throw anna::RuntimeException("diameter::comm::Engine::checkEntityCollision: Server is already reserved by a former created entity. Use another", ANNA_FILE_LOCATION);
201 // Check repetitions:
202 std::map < socket_t, int/*dummy*/ > auxMap;
204 for(it = it_min; it != it_max; it++) auxMap[(*it)] = 0;
206 if(auxMap.size() != v.size())
207 throw anna::RuntimeException("diameter::comm::Engine::checkEntityCollision: Provided addresses list (sockets) must have all items different", ANNA_FILE_LOCATION);
210 comm::Entity* comm::Engine::createEntity(const socket_v & socketList, const std::string &description)
211 throw(anna::RuntimeException) {
212 Entity* result(NULL);
213 anna::Guard guard(this, "anna::diameter::comm::Engine::createEntity");
215 if(socketList.size() == 0)
216 throw anna::RuntimeException("diameter::comm::Engine::createEntity Address/Port server list provided is empty", ANNA_FILE_LOCATION);
218 // Proteccion antes de reservar memoria para una entidad (allocateEntity):
219 checkEntityCollision(socketList);
221 if((result = allocateEntity()) == NULL)
222 throw anna::RuntimeException("diameter::comm::Engine::allocateEntity returns NULL (perhaps virtual method was not implemented)", ANNA_FILE_LOCATION);
225 result->initialize(); // warning: recycler does not initialize its objects and at least, is important to empty servers vector.
226 // Assignments (it could be done at allocate):
227 result->setEngine(this); // lo podia haber asignado en el allocateEntity (no importa)
228 result->setMaxServers(socketList.size());
229 result->setDescription(description);
230 entity_key key(getEntityKey(socketList));
231 result->a_socketListLiteral = key;
232 // Create associated servers:
233 socket_v::const_iterator it;
234 socket_v::const_iterator it_min(socketList.begin());
235 socket_v::const_iterator it_max(socketList.end());
238 for(it = it_min; it != it_max; it++) {
239 result->addServer(*it);
241 if(count == 1) result->a_primarySocketLiteral = anna::functions::socketLiteralAsString((*it).first, (*it).second);
243 if(count == 2) result->a_secondarySocketLiteral = anna::functions::socketLiteralAsString((*it).first, (*it).second);
248 a_entities.insert(entity_value_type(key, result));
250 string msg("diameter::comm::Engine::createEntity | ");
251 msg += result->asString();
252 msg += anna::functions::asText(" | AutoBind: ", a_autoBind);
253 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
259 comm::LocalServer *comm::Engine::createLocalServer(const std::string & addr, int port, int maxConnections, const anna::Millisecond & allowedInactivityTime, int category, const std::string & description)
260 throw(anna::RuntimeException) {
261 LocalServer* result(NULL);
262 anna::Guard guard(this, "anna::diameter::comm::Engine::createLocalServer");
263 // Proteccion antes de reservar memoria para un LocalServer
264 socket_t key(addr, port);
266 if(a_localServers.find(key) != a_localServers.end())
267 throw anna::RuntimeException("LocalServer is already reserved by a former created access point. Cannot create again", ANNA_FILE_LOCATION);
269 if((result = allocateLocalServer()) == NULL)
270 throw anna::RuntimeException("diameter::comm::Engine::allocateLocalServer returns NULL (perhaps virtual method was not implemented)", ANNA_FILE_LOCATION);
272 result->setEngine(this); // lo podia haber asignado en el allocateLocalServer (no importa)
274 result->setCategory(category);
275 result->setDescription(description);
276 result->setAllowedInactivityTime(allowedInactivityTime);
277 result->initializeStatisticConcepts();
278 // Los saco con metodos virtuales readXXX del motor:
279 // if ((a_cea.isEmpty()) || (a_dwa.isEmpty()))
280 // throw anna::RuntimeException("Must define valid CEA and DWA messages by mean setCEAandDWA()", ANNA_FILE_LOCATION);
281 a_localServers.insert(localServer_value_type(key, result));
283 string msg("diameter::comm::Engine::createLocalServer | ");
284 msg += result->asString();
285 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
288 // /*if (a_autoListen) */result->enable(); // creates server socket
289 result->setMaxConnections(maxConnections); // (*) this enables the listen port ... or not
294 comm::Entity* comm::Engine::createEntity(const std::string & addr1, int port1, const std::string & addr2, int port2, const std::string &description)
295 throw(anna::RuntimeException) {
297 dualList.push_back(socket_t(addr1, port1));
298 dualList.push_back(socket_t(addr2, port2));
299 return (createEntity(dualList, description));
303 comm::Server* comm::Engine::createServer(Entity *entity, const socket_t & socket)
304 throw(anna::RuntimeException) {
305 Server* result(NULL);
306 anna::Guard guard(this, "anna::diameter::comm::Engine::createServer");
308 if((result = allocateServer()) == NULL)
309 throw anna::RuntimeException("diameter::comm::Engine::allocateServer returns NULL", ANNA_FILE_LOCATION);
312 result->initialize(); // warning: recycler does not initialize its objects and at least, is important to empty client-sessions vector.
313 // Assignments (it could be done at allocate):
314 result->a_parent = entity;
315 result->a_socket = socket;
316 result->setMaxClientSessions(a_numberOfClientSessionsPerServer /* engine */);
317 result->a_engine = this;
318 result->initializeStatisticConcepts();
320 for(int k = 0; k < a_numberOfClientSessionsPerServer; k++)
321 result->addClientSession(k);
323 a_servers.insert(server_value_type(socket, result));
324 // LOGDEBUG( Lo comento, porque ya se tracea en el createEntity
325 // string msg("diameter::comm::Engine::resolveServer | ");
326 // msg += result->asString();
327 // msg += anna::functions::asText(" | AutoBind: ", a_autoBind);
328 // anna::Logger::debug(msg, ANNA_FILE_LOCATION);
335 comm::ClientSession* comm::Engine::createClientSession(Server *server, int socketId)
336 throw(anna::RuntimeException) {
337 ClientSession* result(NULL);
338 anna::Guard guard(this, "anna::diameter::comm::Engine::createClientSession");
340 if((result = allocateClientSession()) == NULL)
341 throw anna::RuntimeException("diameter::comm::Engine::allocateClientSession returns NULL", ANNA_FILE_LOCATION);
344 result->initialize(); // warning: recycler does not initialize its objects and at least...
345 // Assignments (it could be done at allocate):
347 if((a_cer.isEmpty()) || (a_dwr.isEmpty()))
348 throw anna::RuntimeException("Must define valid CER and DWR messages by mean setCERandDWR()", ANNA_FILE_LOCATION);
350 result->a_cer.setBody(a_cer);
351 result->a_dwr.setBody(a_dwr);
352 result->setWatchdogPeriod(a_watchdogPeriod);
353 result->a_parent = server;
354 result->a_socketId = socketId;
355 result->initializeSequences(); // despu�s de asignar el server y el socketId (*)
356 // (*) Las secuencias se basan en la semilla: srand(::time(NULL) + anna::functions::exclusiveHash(anna::functions::asString("%s:%d|%d", getAddress().c_str(), getPort(), a_socketId)));
357 result->a_engine = this;
358 clientSession_key key = ClientSession::getKey(server->getAddress(), server->getPort(), socketId);
359 a_clientSessions.insert(clientSession_value_type(key, result));
360 // LOGDEBUG( Lo comento, porque ya se tracea en el createEntity
361 // string msg("diameter::comm::Engine::createClientSession | ");
362 // msg += result->asString();
363 // msg += anna::functions::asText(" | AutoBind: ", a_autoBind);
364 // anna::Logger::debug(msg, ANNA_FILE_LOCATION);
367 anna::comm::Network& network = anna::comm::Network::instantiate();
368 result->a_server = network.resolveServer(server->getAddress().c_str(), server->getPort(), true /* autoRecovery */,
369 result->a_receiverFactory, &anna::diameter::comm::Transport::getFactory(),
370 anna::comm::Network::Port::Multiple, anna::comm::Network::DoConnect::No /* (*) */);
371 // Delay time on tcp connect:
372 result->a_server->setMaxConnectionDelay(a_maxConnectionDelay); // (*)
375 if(a_autoBind) result->bind();
381 bool comm::Engine::broadcastEntities(const Message* message) throw(anna::RuntimeException) {
382 LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "broadcastEntities", ANNA_FILE_LOCATION));
386 for(entity_iterator it = entity_begin(), maxii = entity_end(); it != maxii; it ++) {
388 ok = entity(it)->broadcast(message);
390 if(!ok) allok = false;
391 } catch(anna::RuntimeException &ex) {
400 bool comm::Engine::broadcastLocalServers(const Message* message) throw(anna::RuntimeException) {
401 LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "broadcastLocalServers", ANNA_FILE_LOCATION));
405 for(localServer_iterator it = localServer_begin(), maxii = localServer_end(); it != maxii; it ++) {
407 ok = localServer(it)->broadcast(message);
409 if(!ok) allok = false;
410 } catch(anna::RuntimeException &ex) {
419 bool comm::Engine::bind() throw(anna::RuntimeException) {
420 LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "bind", ANNA_FILE_LOCATION));
421 bool result = true; // all OK return
423 for(entity_iterator it = entity_begin(), maxii = entity_end(); it != maxii; it ++) {
426 } catch(anna::RuntimeException &ex) {
435 comm::ClientSession* comm::Engine::findClientSession(const std::string & addr, int port, int socketId, anna::Exception::Mode::_v emode)
436 throw(anna::RuntimeException) {
437 return findClientSession(ClientSession::getKey(addr, port, socketId), emode);
440 comm::ClientSession* comm::Engine::findClientSession(const std::string & key, anna::Exception::Mode::_v emode)
441 throw(anna::RuntimeException) {
442 anna::Guard guard(this, "anna::diameter::comm::Engine::findClientSession");
443 clientSession_iterator ii = clientSession_find(key);
445 if(ii != clientSession_end())
446 return clientSession(ii);
448 if(emode != anna::Exception::Mode::Ignore) {
449 string msg("diameter::comm::Engine::findClientSession | [addr:port|socketId] = ");
451 msg += " | ClientSession not found";
452 anna::RuntimeException ex(msg, ANNA_FILE_LOCATION);
454 if(emode == anna::Exception::Mode::Throw)
464 comm::Server* comm::Engine::findServer(const std::string & addr, int port, anna::Exception::Mode::_v emode)
465 throw(anna::RuntimeException) {
466 anna::Guard guard(this, "anna::diameter::comm::Engine::findServer");
467 server_iterator ii = server_find(server_key(addr, port));
469 if(ii != server_end())
472 if(emode != anna::Exception::Mode::Ignore) {
473 string msg("diameter::comm::Engine::findServer | addr: ");
475 msg += anna::functions::asText(" | port: ", port);
476 msg += " | Server not found";
477 anna::RuntimeException ex(msg, ANNA_FILE_LOCATION);
479 if(emode == anna::Exception::Mode::Throw)
488 comm::Entity* comm::Engine::findEntity(const socket_v & socketList, anna::Exception::Mode::_v emode)
489 throw(anna::RuntimeException) {
490 anna::Guard guard(this, "anna::diameter::comm::Engine::findEntity");
491 entity_key key(getEntityKey(socketList));
492 entity_iterator ii = entity_find(key);
494 if(ii != entity_end())
497 if(emode != anna::Exception::Mode::Ignore) {
498 string msg("diameter::comm::Engine::findEntity | socket list: ");
500 msg += " | Entity not found";
501 anna::RuntimeException ex(msg, ANNA_FILE_LOCATION);
503 if(emode == anna::Exception::Mode::Throw)
512 comm::Entity* comm::Engine::findEntity(const std::string & addr1, int port1, const std::string & addr2, int port2, anna::Exception::Mode::_v emode)
513 throw(anna::RuntimeException) {
515 dualList.push_back(socket_t(addr1, port1));
516 dualList.push_back(socket_t(addr2, port2));
517 return (findEntity(dualList, emode));
521 //Entity* Engine::findEntity(int category, anna::Exception::Mode::_v emode)
522 //throw(anna::RuntimeException) {
526 // for (entity_iterator it = entity_begin(), maxii = entity_end(); it != maxii; it ++) {
527 // entity = entity(it);
528 // if (entity->getCategory() == category) return entity;
535 comm::LocalServer* comm::Engine::findLocalServer(const std::string & addr, int port, anna::Exception::Mode::_v emode)
536 throw(anna::RuntimeException) {
537 anna::Guard guard(this, "anna::diameter::comm::Engine::findLocalServer");
538 socket_t key(addr, port);
539 localServer_iterator ii = localServer_find(key);
541 if(ii != localServer_end())
542 return localServer(ii);
544 if(emode != anna::Exception::Mode::Ignore) {
545 string msg("diameter::comm::Engine::findLocalServer | addr: ");
547 msg += anna::functions::asText(" | port: ", port);
548 msg += " | LocalServer not found";
549 anna::RuntimeException ex(msg, ANNA_FILE_LOCATION);
551 if(emode == anna::Exception::Mode::Throw)
561 comm::ServerSession* comm::Engine::findServerSession(int socketId, anna::Exception::Mode::_v emode) throw(anna::RuntimeException) {
562 anna::Guard guard(this, "anna::diameter::comm::Engine::findServerSession");
563 ServerSession *result;
565 // Search at each local server:
566 for(localServer_iterator it = localServer_begin(), maxii = localServer_end(); it != maxii; it ++) {
567 result = localServer(it)->findServerSession(socketId, anna::Exception::Mode::Ignore);
569 if(result) return result;
572 if(emode != anna::Exception::Mode::Ignore) {
573 string msg("diameter::comm::Engine::findServerSession | socketId: ");
574 msg += anna::functions::asString(socketId);
575 msg += " | ServerSession not found";
576 anna::RuntimeException ex(msg, ANNA_FILE_LOCATION);
578 if(emode == anna::Exception::Mode::Throw)
588 void comm::Engine::closeClientSession(comm::ClientSession* clientSession, bool destroy)
589 throw(anna::RuntimeException) {
590 if(clientSession == NULL)
594 string msg("diameter::comm::Engine::closeClientSession | ");
595 msg += clientSession->asString();
596 msg += " | Destroy: ";
597 msg += (destroy ? "yes" : "no");
598 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
600 anna::Guard guard(this, "anna::diameter::comm::Engine::closeClientSession");
601 clientSession_iterator ii = clientSession_find(clientSession->getKey());
603 if(ii == clientSession_end())
607 clientSession->setState(ClientSession::State::Closing);
609 if(destroy) clientSession->setAutoRecovery(false);
611 clientSession->unbind(destroy /* destroy needs to perform immediate close */);
615 releaseClientSession(clientSession);
616 } catch(anna::RuntimeException& ex) {
620 a_clientSessions.erase(ii);
626 void comm::Engine::closeServer(comm::Server* server, bool destroy)
627 throw(anna::RuntimeException) {
632 string msg("diameter::comm::Engine::closeServer | ");
633 msg += server->asString();
634 msg += " | Destroy: ";
635 msg += (destroy ? "yes" : "no");
636 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
638 anna::Guard guard(this, "anna::diameter::comm::Engine::closeServer");
639 server_iterator ii = server_find(server->a_socket);
641 if(ii == server_end())
645 server->close(destroy);
649 releaseServer(server);
650 } catch(anna::RuntimeException& ex) {
658 void comm::Engine::closeEntity(comm::Entity* entity, bool destroy)
659 throw(anna::RuntimeException) {
664 string msg("diameter::comm::Engine::closeEntity | ");
665 msg += entity->asString();
666 msg += " | Destroy: ";
667 msg += (destroy ? "yes" : "no");
668 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
670 anna::Guard guard(this, "anna::diameter::comm::Engine::closeEntity");
671 entity_iterator ii = entity_find(entity->a_socketListLiteral);
673 if(ii == entity_end())
677 entity->close(destroy);
681 if(!entity->idle()) { entity->setDeprecated(true); return; }
683 releaseEntity(entity);
684 } catch(anna::RuntimeException& ex) {
688 a_entities.erase(ii);
693 void comm::Engine::closeLocalServer(comm::LocalServer* localServer, bool destroy)
694 throw(anna::RuntimeException) {
695 if(localServer == NULL)
699 string msg("diameter::comm::Engine::closeLocalServer | ");
700 msg += localServer->asString();
701 msg += " | Destroy: ";
702 msg += (destroy ? "yes" : "no");
703 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
705 anna::Guard guard(this, "anna::diameter::comm::Engine::closeLocalServer");
706 localServer_iterator ii = localServer_find(localServer->getKey());
708 if(ii == localServer_end())
712 localServer->close();
716 releaseLocalServer(localServer);
717 } catch(anna::RuntimeException& ex) {
721 a_localServers.erase(ii);
726 void comm::Engine::closeEntities(bool destroy) throw(anna::RuntimeException) {
727 LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "closeEntities", ANNA_FILE_LOCATION));
728 anna::Guard guard(this, "anna::diameter::comm::Engine::closeEntities");
730 for(entity_iterator it = entity_begin(), maxii = entity_end(); it != maxii; it ++)
731 closeEntity(entity(it), destroy);
734 void comm::Engine::closeLocalServers(bool destroy) throw(anna::RuntimeException) {
735 LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "closeLocalServers", ANNA_FILE_LOCATION));
736 anna::Guard guard(this, "anna::diameter::comm::Engine::closeLocalServers");
738 for(localServer_iterator it = localServer_begin(), maxii = localServer_end(); it != maxii; it ++)
739 closeLocalServer(localServer(it), destroy);
742 void comm::Engine::eraseDeprecatedIdleEntities() throw() {
743 LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "eraseDeprecatedIdleEntities", ANNA_FILE_LOCATION));
746 for(entity_iterator it = entity_begin(), maxii = entity_end(); it != maxii; it ++) {
749 if(et->isDeprecated() && et->idle()) closeEntity(et, true /* destroy */);
753 int comm::Engine::getOTARequestsForEntities() const throw() {
756 for(const_entity_iterator it = entity_begin(), maxii = entity_end(); it != maxii; it ++)
757 result += entity(it)->getOTARequests();
762 int comm::Engine::getOTARequestsForLocalServers() const throw() {
765 for(const_localServer_iterator it = localServer_begin(), maxii = localServer_end(); it != maxii; it ++)
766 result += localServer(it)->getOTARequests();
772 void comm::Engine::setRealm(const std::string & name) throw() {
773 a_realm = ((name != "") ? name : anna::functions::getDomainname());
777 void comm::Engine::setHost(const std::string & name) throw() {
778 a_host = ((name != "") ? name : anna::functions::getHostname());
783 void comm::Engine::raiseAutoRecovery(bool autoRecovery) throw(anna::RuntimeException) {
784 LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "raiseAutoRecovery", ANNA_FILE_LOCATION));
786 for(entity_iterator it = entity_begin(), maxii = entity_end(); it != maxii; it ++)
787 entity(it)->raiseAutoRecovery(autoRecovery);
790 void comm::Engine::do_stop()
792 LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "do_stop", ANNA_FILE_LOCATION));
793 close(true /* destroy */);
796 std::string comm::Engine::asString(void) const throw() {
798 trace = "\n================================";
799 trace += "\nDiameter comm Engine information";
800 trace += "\n================================";
801 trace += "\nAutoBind: ";
802 trace += a_autoBind ? "yes" : "no";
803 trace += "\nMaxConnectionDelay: ";
804 trace += a_maxConnectionDelay.asString();
805 trace += "\nAvailable for entities: ";
806 trace += a_availableForEntities ? "yes" : "no";
807 trace += "\nAvailable for local servers: ";
808 trace += a_availableForLocalServers ? "yes" : "no";
809 trace += "\nOTA requests: ";
810 trace += anna::functions::asString("%d%s", getOTARequests(), idle() ? " (idle)" : "");
811 trace += "\nOTA requests for entities: ";
812 trace += anna::functions::asString("%d%s", getOTARequestsForEntities(), idleForEntities() ? " (idle)" : "");
813 trace += "\nOTA requests for local servers: ";
814 trace += anna::functions::asString("%d%s", getOTARequestsForLocalServers(), idleForLocalServers() ? " (idle)" : "");
816 trace += "\nNumber of entities: ";
817 trace += anna::functions::asString(a_entities.size());
819 for(const_entity_iterator it = entity_begin(); it != entity_end(); it++) {
821 trace += entity(it)->asString();
825 trace += "\nNumber of LocalServers: ";
826 trace += anna::functions::asString(a_localServers.size());
828 for(const_localServer_iterator it = localServer_begin(); it != localServer_end(); it++) {
830 trace += localServer(it)->asString();
837 anna::xml::Node* comm::Engine::asXML(anna::xml::Node* parent) const
839 parent = anna::app::Component::asXML(parent);
840 anna::xml::Node* result = parent->createChild("diameter.comm.Engine");
841 result->createAttribute("AutoBind", a_autoBind ? "yes" : "no");
842 result->createAttribute("MaxConnectionDelay", a_maxConnectionDelay.asString());
843 result->createAttribute("AvailableForEntities", a_availableForEntities ? "yes" : "no");
844 result->createAttribute("AvailableForLocalServers", a_availableForLocalServers ? "yes" : "no");
845 result->createAttribute("OTArequests", anna::functions::asString("%d%s", getOTARequests(), idle() ? " (idle)" : ""));
846 result->createAttribute("OTArequestsForEntities", anna::functions::asString("%d%s", getOTARequestsForEntities(), idleForEntities() ? " (idle)" : ""));
847 result->createAttribute("OTArequestsForLocalServers", anna::functions::asString("%d%s", getOTARequestsForLocalServers(), idleForLocalServers() ? " (idle)" : ""));
848 result->createAttribute("NumberOfEntities", a_entities.size());
849 anna::xml::Node* entities = result->createChild("Engine.Entities");
851 for(const_entity_iterator it = entity_begin(); it != entity_end(); it++)
852 entity(it)->asXML(entities);
854 result->createAttribute("NumberOfLocalServers", a_localServers.size());
855 anna::xml::Node* localServers = result->createChild("Engine.LocalServers");
857 for(const_localServer_iterator it = localServer_begin(); it != localServer_end(); it++)
858 localServer(it)->asXML(localServers);
862 // <Engine.RemoteRealm Name="afNodeHostRealm.com">
863 // <Engine.RemoteRealmHost Name="afNodeHostname.afNodeHostRealm.com" ServerSession="localhost:3868|ServerSessionId:4"/>
864 // </Engine.RemoteRealm>
865 // <Engine.RemoteRealm Name="ggsnNodeHostRealm.com">
866 // <Engine.RemoteRealmHost Name="ggsnNodeHostname.ggsnNodeHostRealm.com" ServerSession="localhost:3868|ServerSessionId:6"/>
867 // </Engine.RemoteRealm>
868 for (dr_dh_server_sessions_it_t drit = a_dr_dh_server_sessions.begin(); drit != a_dr_dh_server_sessions.end(); drit++) {
869 anna::xml::Node* remoteRealm = result->createChild("Engine.RemoteRealm");
870 remoteRealm->createAttribute("Name", drit->first);
871 dh_server_sessions_map_t *dhServerSessions = (dh_server_sessions_map_t *)&(drit->second);
872 for (dh_server_sessions_it_t dhit = dhServerSessions->begin(); dhit != dhServerSessions->end(); dhit++) {
873 anna::xml::Node* remoteRealmHost = remoteRealm->createChild("Engine.RemoteRealmHost");
874 remoteRealmHost->createAttribute("Name", dhit->first);
875 server_sessions_vector_t *serverSessions = (server_sessions_vector_t *)&(dhit->second);
876 for (server_sessions_it_t ssit = serverSessions->begin(); ssit != serverSessions->end(); ssit++) {
877 std::string socket = anna::functions::socketLiteralAsString((*ssit)->getAddress(), (*ssit)->getPort());
878 std::string ss_desc = socket + anna::functions::asString("|ServerSessionId:%d", (*ssit)->getSocketId());
879 remoteRealmHost->createAttribute("ServerSession", ss_desc);
887 comm::Engine::clientSession_iterator comm::Engine::clientSession_find(const clientSession_key &key) throw() {
888 return a_clientSessions.find(key);
891 comm::Engine::server_iterator comm::Engine::server_find(const server_key &key) throw() {
892 return a_servers.find(key);
895 comm::Engine::entity_iterator comm::Engine::entity_find(const entity_key &key) throw() {
896 return a_entities.find(key);
899 comm::Engine::localServer_iterator comm::Engine::localServer_find(const socket_t &key) throw() {
900 return a_localServers.find(key);
903 comm::Engine::entity_key comm::Engine::getEntityKey(const std::string & addr1, int port1, const std::string & addr2, int port2) const throw() {
905 dualList.push_back(socket_t(addr1, port1));
906 dualList.push_back(socket_t(addr2, port2));
907 return (getEntityKey(dualList));
910 comm::Engine::entity_key comm::Engine::getEntityKey(const socket_v &v) const throw() {
912 socket_v::const_iterator it;
913 socket_v::const_iterator it_min(v.begin());
914 socket_v::const_iterator it_max(v.end());
916 for(it = it_min; it != it_max; it++) {
917 result += anna::functions::socketLiteralAsString((*it).first, (*it).second);
921 result.erase(result.size() - 1, 1); // remove last space
922 //return anna::functions::exclusiveHash(result);
927 void comm::Engine::availabilityLostForEntities() throw() {
928 a_availableForEntities = false;
930 std::string msg = "diameter::comm::Engine { Realm: ";
932 msg += " } has lost its availability for entities";
933 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
936 OamModule &oamModule = OamModule::instantiate();
937 oamModule.activateAlarm(OamModule::Alarm::c_LostAvailabilityOverEntitiesForEngineWithClassName__s__, getClassName());
938 oamModule.count(OamModule::Counter::LostAvailabilityOverEngineForEntities);
940 availabilityLostForEntities(this);
944 void comm::Engine::availabilityRecoveredForEntities() throw() {
945 a_availableForEntities = true;
947 std::string msg = "diameter::comm::Engine { Realm: ";
949 msg += " } has recovered its availability for entities";
950 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
953 OamModule &oamModule = OamModule::instantiate();
954 oamModule.cancelAlarm(OamModule::Alarm::c_LostAvailabilityOverEntitiesForEngineWithClassName__s__, getClassName());
955 oamModule.count(OamModule::Counter::RecoveredAvailabilityOverEngineForEntities);
957 availabilityRecoveredForEntities(this);
961 void comm::Engine::availabilityLostForLocalServers() throw() {
962 a_availableForLocalServers = false;
964 std::string msg = "diameter::comm::Engine { Realm: ";
966 msg += " } has lost its availability for local servers";
967 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
970 OamModule &oamModule = OamModule::instantiate();
971 oamModule.activateAlarm(OamModule::Alarm::c_LostAvailabilityOverLocalServersForEngineWithClassName__s__, getClassName());
972 oamModule.count(OamModule::Counter::LostAvailabilityOverEngineForLocalServers);
974 availabilityLostForLocalServers(this);
978 void comm::Engine::availabilityRecoveredForLocalServers() throw() {
979 a_availableForLocalServers = true;
981 std::string msg = "diameter::comm::Engine { Realm: ";
983 msg += " } has recovered its availability for local servers";
984 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
987 OamModule &oamModule = OamModule::instantiate();
988 oamModule.cancelAlarm(OamModule::Alarm::c_LostAvailabilityOverLocalServersForEngineWithClassName__s__, getClassName());
989 oamModule.count(OamModule::Counter::RecoveredAvailabilityOverEngineForLocalServers);
991 availabilityRecoveredForLocalServers(this);
995 bool comm::Engine::refreshAvailabilityForEntities() throw() {
997 if(a_availableForEntities) { // check not-bound state for all client-sessions:
1000 for(const_entity_iterator it = entity_begin(); it != entity_end(); it++)
1001 if(entity(it)->isAvailable()) { isolate = false; break; }
1004 availabilityLostForEntities();
1011 // Here not available
1012 for(const_entity_iterator it = entity_begin(); it != entity_end(); it++)
1013 if(entity(it)->isAvailable()) {
1014 availabilityRecoveredForEntities();
1021 bool comm::Engine::refreshAvailabilityForLocalServers() throw() {
1023 if(a_availableForLocalServers) { // check not-bound state for all client-sessions:
1024 bool isolate = true;
1026 for(const_localServer_iterator it = localServer_begin(); it != localServer_end(); it++)
1027 if(localServer(it)->isAvailable()) { isolate = false; break; }
1030 availabilityLostForLocalServers();
1037 // Here not available
1038 for(const_localServer_iterator it = localServer_begin(); it != localServer_end(); it++)
1039 if(localServer(it)->isAvailable()) {
1040 availabilityRecoveredForLocalServers();
1048 void comm::Engine::readDPA(anna::DataBlock &dpa, const anna::DataBlock & dpr) throw() {
1050 // Check for base protocol codec engine health:
1051 assertBaseProtocolHealth();
1053 // Default DPA implementation:
1055 // 'Disconnect-Peer-Answer' (282,answer)
1056 // {Result-Code}...................................(268,0)
1057 // {Origin-Host}...................................(264,0)
1058 // {Origin-Realm}..................................(296,0)
1059 // [Error-Message].................................(281,0)
1060 // *[Failed-AVP]....................................(279,0)
1062 anna::diameter::codec::Message diameterDPA(getBaseProtocolCodecEngine());
1063 anna::diameter::codec::Avp avpRC(getBaseProtocolCodecEngine());
1064 anna::diameter::codec::Avp avpOH(getBaseProtocolCodecEngine());
1065 anna::diameter::codec::Avp avpOR(getBaseProtocolCodecEngine());
1067 diameterDPA.setId(anna::diameter::helpers::base::COMMANDID__Disconnect_Peer_Answer);
1068 diameterDPA.setVersion(1);
1069 diameterDPA.setApplicationId(codec::functions::getApplicationId(dpr));
1070 diameterDPA.setHopByHop(codec::functions::getHopByHop(dpr));
1071 diameterDPA.setEndToEnd(codec::functions::getEndToEnd(dpr));
1073 avpRC.setId(anna::diameter::helpers::base::AVPID__Result_Code);
1074 avpRC.setMandatoryBit();
1075 avpRC.getUnsigned32()->setValue(helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS);
1077 avpOH.setId(anna::diameter::helpers::base::AVPID__Origin_Host);
1078 avpOH.setMandatoryBit();
1079 avpOH.getDiameterIdentity()->fromPrintableString(a_host.c_str());
1081 avpOR.setId(anna::diameter::helpers::base::AVPID__Origin_Realm);
1082 avpOR.setMandatoryBit();
1083 avpOR.getDiameterIdentity()->fromPrintableString(a_realm.c_str());
1084 diameterDPA.addAvp(&avpRC);
1085 diameterDPA.addAvp(&avpOH);
1086 diameterDPA.addAvp(&avpOR);
1088 dpa = diameterDPA.code();
1089 } catch(anna::RuntimeException &ex) {
1090 std::string msg = ex.getText();
1091 msg += " | Use diameter::comm::Engine::setBaseProtocolCodecEngine() to allow internal base protocol messages encoding (unable to answer with DPA)";
1092 anna::Logger::error(msg, ANNA_FILE_LOCATION);
1093 //throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1098 void comm::Engine::readCEA(anna::DataBlock &cea, const anna::DataBlock & cer) throw() {
1100 // Check for base protocol codec engine health:
1101 assertBaseProtocolHealth();
1103 // Default CEA implementation:
1105 // 'Capabilities-Exchange-Answer' (257,answer)
1106 // {Result-Code}...................................(268,0)
1107 // {Origin-Host}...................................(264,0)
1108 // {Origin-Realm}..................................(296,0)
1109 // 1*{Host-IP-Address}...............................(257,0)
1110 // {Vendor-Id}.....................................(266,0)
1111 // {Product-Name}..................................(269,0)
1112 // [Origin-State-Id]...............................(278,0)
1113 // [Error-Message].................................(281,0)
1114 // *[Failed-AVP]....................................(279,0)
1115 // *[Supported-Vendor-Id]...........................(265,0)
1116 // *[Auth-Application-Id]...........................(258,0)
1117 // *[Inband-Security-Id]............................(299,0)
1118 // *[Acct-Application-Id]...........................(259,0)
1119 // [Vendor-Specific-Application-Id]................(260,0)
1120 // [Firmware-Revision].............................(267,0)
1121 // *[AVP]...........................................(0,0)
1123 anna::diameter::codec::Message diameterCEA(getBaseProtocolCodecEngine());
1124 anna::diameter::codec::Avp avpRC(getBaseProtocolCodecEngine());
1125 anna::diameter::codec::Avp avpOH(getBaseProtocolCodecEngine());
1126 anna::diameter::codec::Avp avpOR(getBaseProtocolCodecEngine());
1128 diameterCEA.setId(anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Answer);
1129 diameterCEA.setVersion(1);
1130 diameterCEA.setApplicationId(codec::functions::getApplicationId(cer));
1131 diameterCEA.setHopByHop(codec::functions::getHopByHop(cer));
1132 diameterCEA.setEndToEnd(codec::functions::getEndToEnd(cer));
1134 avpRC.setId(anna::diameter::helpers::base::AVPID__Result_Code);
1135 avpRC.setMandatoryBit();
1136 avpRC.getUnsigned32()->setValue(helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS); // re-implementations could analyze CER to accept or not
1138 avpOH.setId(anna::diameter::helpers::base::AVPID__Origin_Host);
1139 avpOH.setMandatoryBit();
1140 avpOH.getDiameterIdentity()->fromPrintableString(a_host.c_str());
1142 avpOR.setId(anna::diameter::helpers::base::AVPID__Origin_Realm);
1143 avpOR.setMandatoryBit();
1144 avpOR.getDiameterIdentity()->fromPrintableString(a_realm.c_str());
1145 diameterCEA.addAvp(&avpRC);
1146 diameterCEA.addAvp(&avpOH);
1147 diameterCEA.addAvp(&avpOR);
1149 std::string hostIP = anna::functions::getHostnameIP(); // Address
1150 diameterCEA.addAvp(anna::diameter::helpers::base::AVPID__Host_IP_Address)->getAddress()->fromPrintableString(hostIP.c_str());
1152 int vendorId = anna::diameter::helpers::VENDORID__tgpp; // Unsigned32
1153 diameterCEA.addAvp(anna::diameter::helpers::base::AVPID__Vendor_Id)->getUnsigned32()->setValue(vendorId);
1155 std::string productName = "OCS Diameter Server"; // UTF8String
1156 diameterCEA.addAvp(anna::diameter::helpers::base::AVPID__Product_Name)->getUTF8String()->setValue(productName);
1158 cea = diameterCEA.code();
1159 } catch(anna::RuntimeException &ex) {
1160 std::string msg = ex.getText();
1161 msg += " | Use diameter::comm::Engine::setBaseProtocolCodecEngine() to allow internal base protocol messages encoding (unable to answer with CEA)";
1162 anna::Logger::error(msg, ANNA_FILE_LOCATION);
1163 //throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1167 void comm::Engine::manageDrDhServerSession(ServerSession *ss, bool register_or_desregister) throw() {
1169 // Decode CER (TODO: use raw buffer helpers)
1170 std::string destinationRealm, destinationHost;
1171 codec::Message codecMsg(getBaseProtocolCodecEngine());
1173 codecMsg.decode(ss->a_cer);
1174 destinationRealm = codecMsg.getAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->getValue();
1175 destinationHost = codecMsg.getAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->getValue();
1177 catch(anna::RuntimeException &ex) {
1182 dr_dh_server_sessions_nc_it_t drit = a_dr_dh_server_sessions.find(destinationRealm);
1183 if (drit != a_dr_dh_server_sessions.end()) { // found
1184 dh_server_sessions_map_t *dhServerSessions = (dh_server_sessions_map_t *)&(drit->second);
1185 dh_server_sessions_nc_it_t dhit = dhServerSessions->find(destinationHost);
1186 if (dhit != dhServerSessions->end()) { // found
1187 server_sessions_vector_t *serverSessions = (server_sessions_vector_t *)&(dhit->second);
1188 if (register_or_desregister) { // REGISTER
1189 serverSessions->push_back(ss);
1191 else { // DESREGISTER
1192 // Sequential search the specific server session:
1193 for (server_sessions_nc_it_t ssit = serverSessions->begin(); ssit != serverSessions->end(); ssit++) {
1194 if ((*ssit)->getAddress() != ss->getAddress()) continue;
1195 if ((*ssit)->getPort() != ss->getPort()) continue;
1196 if ((*ssit)->getSocketId() != ss->getSocketId()) continue;
1197 serverSessions->erase(ssit); // if it is the last server session removed in DR-DH path, the XML will show this tree empty
1198 // (it could be a hint for past registerings):
1199 // <Engine.RemoteRealm Name="afNodeHostRealm.com">
1200 // <Engine.RemoteRealmHost Name="afNodeHostname.afNodeHostRealm.com"/>
1201 // </Engine.RemoteRealm>
1202 // <Engine.RemoteRealm Name="ggsnNodeHostRealm.com">
1203 // <Engine.RemoteRealmHost Name="ggsnNodeHostname.ggsnNodeHostRealm.com"/>
1204 // </Engine.RemoteRealm>
1211 if (!register_or_desregister) return; // strange (host not found)
1212 server_sessions_vector_t ssVector;
1213 ssVector.push_back(ss);
1214 (*dhServerSessions)[destinationHost] = ssVector;
1218 if (!register_or_desregister) return; // strange (realm not found)
1219 server_sessions_vector_t ssVector;
1220 ssVector.push_back(ss);
1221 dh_server_sessions_map_t dhServerSessions;
1222 dhServerSessions[destinationHost] = ssVector;
1223 a_dr_dh_server_sessions[destinationRealm] = dhServerSessions;
1227 void comm::Engine::readDWA(anna::DataBlock &dwa, const anna::DataBlock & dwr) throw() {
1229 // Check for base protocol codec engine health:
1230 assertBaseProtocolHealth();
1232 // Default DWA implementation:
1234 // 'Device-Watchdog-Answer' (280,answer)
1235 // {Result-Code}...................................(268,0)
1236 // {Origin-Host}...................................(264,0)
1237 // {Origin-Realm}..................................(296,0)
1238 // [Error-Message].................................(281,0)
1239 // *[Failed-AVP]....................................(279,0)
1240 // [Origin-State-Id]...............................(278,0)
1242 anna::diameter::codec::Message diameterDWA(getBaseProtocolCodecEngine());
1243 anna::diameter::codec::Avp avpRC(getBaseProtocolCodecEngine());
1244 anna::diameter::codec::Avp avpOH(getBaseProtocolCodecEngine());
1245 anna::diameter::codec::Avp avpOR(getBaseProtocolCodecEngine());
1247 diameterDWA.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Answer);
1248 diameterDWA.setVersion(1);
1249 diameterDWA.setApplicationId(codec::functions::getApplicationId(dwr));
1250 diameterDWA.setHopByHop(codec::functions::getHopByHop(dwr));
1251 diameterDWA.setEndToEnd(codec::functions::getEndToEnd(dwr));
1253 avpRC.setId(anna::diameter::helpers::base::AVPID__Result_Code);
1254 avpRC.setMandatoryBit();
1255 avpRC.getUnsigned32()->setValue(helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS);
1257 avpOH.setId(anna::diameter::helpers::base::AVPID__Origin_Host);
1258 avpOH.setMandatoryBit();
1259 avpOH.getDiameterIdentity()->fromPrintableString(a_host.c_str());
1261 avpOR.setId(anna::diameter::helpers::base::AVPID__Origin_Realm);
1262 avpOR.setMandatoryBit();
1263 avpOR.getDiameterIdentity()->fromPrintableString(a_realm.c_str());
1264 diameterDWA.addAvp(&avpRC);
1265 diameterDWA.addAvp(&avpOH);
1266 diameterDWA.addAvp(&avpOR);
1268 dwa = diameterDWA.code();
1269 } catch(anna::RuntimeException &ex) {
1270 std::string msg = ex.getText();
1271 msg += " | Use diameter::comm::Engine::setBaseProtocolCodecEngine() to allow internal base protocol messages encoding (unable to answer with DWA)";
1272 anna::Logger::error(msg, ANNA_FILE_LOCATION);
1273 //throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1277 void comm::Engine::resetStatistics() throw() {
1278 for(server_iterator it = server_begin(), maxii = server_end(); it != maxii; it ++)
1279 server(it)->resetStatistics();
1281 for(localServer_iterator it = localServer_begin(), maxii = localServer_end(); it != maxii; it ++)
1282 localServer(it)->resetStatistics();
1285 void comm::Engine::do_initialize() throw(RuntimeException) {
1286 LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "do_initialize", ANNA_FILE_LOCATION));
1287 LOGDEBUG(anna::Logger::debug("Nothing special done on component initialization", ANNA_FILE_LOCATION));
1290 void comm::Engine::lazyInitialize() throw(RuntimeException) {
1291 LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "lazyInitialize", ANNA_FILE_LOCATION));
1292 anna::app::Component::initialize(); // this will invoke do_initialize
1296 const comm::Response* comm::Engine::sendRealmHost(const Message* message, const std::string &destinationRealm, const std::string &destinationHost) throw(anna::RuntimeException) {
1298 if (destinationRealm == "")
1299 throw anna::RuntimeException("Unable to resolve the destination: empty provided Destination-Realm name", ANNA_FILE_LOCATION);
1301 // Get the server sessions which fulfill the restrictions:
1302 dr_dh_server_sessions_it_t drit = a_dr_dh_server_sessions.find(destinationRealm);
1303 if (drit == a_dr_dh_server_sessions.end())
1304 throw anna::RuntimeException(anna::functions::asString("Unable to resolve the destination: Destination-Realm name is not registered (no remote clients have been connected to '%s')", destinationRealm.c_str()), ANNA_FILE_LOCATION);
1306 dh_server_sessions_map_t *dhServerSessions = (dh_server_sessions_map_t *)&(drit->second);
1307 // randomize between all server sessions for all hosts:
1308 dh_server_sessions_nc_it_t dhit;
1309 int hostsN = dhServerSessions->size();
1310 if (hostsN == 0) // avoids next division by cero (rand() % 0)
1311 throw anna::RuntimeException(anna::functions::asString("Unable to resolve the destination: neither Destination-Host currently connected to Destination-Realm '%s'", destinationRealm.c_str()), ANNA_FILE_LOCATION);
1313 if (destinationHost == "") {
1314 // in this case, randomize the host:
1315 dhit = dhServerSessions->begin();
1316 int randomHostIndx = rand() % hostsN; // number between 0 and the number of hosts - 1
1317 std::advance (dhit, randomHostIndx);
1320 dhit = dhServerSessions->find(destinationHost);
1321 if (dhit == dhServerSessions->end())
1322 throw anna::RuntimeException(anna::functions::asString("Unable to resolve the destination: Destination-Host '%s' is not registered for Destination-Realm '%s'", destinationHost.c_str(), destinationRealm.c_str()), ANNA_FILE_LOCATION);
1325 // Now, randomize the available server sessions:
1326 server_sessions_vector_t *serverSessions = (server_sessions_vector_t *)&(dhit->second);
1327 int serverSessionN = serverSessions->size();
1328 if (serverSessionN == 0) { // avoids next division by cero (rand() % 0)
1329 std::string aux = "";
1330 if (destinationHost != "") { aux = "to Destination-Host '"; aux += destinationHost; aux += "'"; }
1331 std::string msg = anna::functions::asString("Unable to resolve the destination: neither server session currently connected%s within Destination-Realm '%s'", aux.c_str(), destinationRealm.c_str());
1332 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1335 server_sessions_nc_it_t ssit = serverSessions->begin();
1336 int randomServerSessionIndx = rand() % serverSessionN; // number between 0 and the number of server sessions - 1
1337 std::advance (ssit, randomServerSessionIndx);
1338 return (*ssit)->send(message);