d00724b80f038aa7fb0ddb20f5fd1880ae61cdbc
[anna.git] / source / diameter.comm / Engine.cpp
1 // ANNA - Anna is Not Nothingness Anymore                                                         //
2 //                                                                                                //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo                         //
4 //                                                                                                //
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 //
7
8 // Standard
9 #include <stdlib.h> // rand()
10
11
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>
19 #include <anna/diameter.comm/Transport.hpp>
20 #include <anna/diameter.comm/Engine.hpp>
21 #include <anna/diameter.comm/Entity.hpp>
22 #include <anna/diameter.comm/Server.hpp>
23 #include <anna/diameter.comm/ClientSession.hpp>
24 #include <anna/diameter.comm/LocalServer.hpp>
25 #include <anna/core/functions.hpp>
26 #include <anna/diameter/internal/sccs.hpp>
27 #include <anna/diameter.comm/OamModule.hpp>
28 #include <anna/diameter/codec/functions.hpp>
29 #include <anna/diameter/helpers/base/functions.hpp>
30 #include <anna/diameter/helpers/helpers.hpp>
31 #include <anna/diameter/codec/Message.hpp>
32 #include <anna/diameter/codec/Avp.hpp>
33 #include <anna/diameter.comm/Response.hpp>
34
35 // STD
36 #include <map>
37
38 using namespace std;
39 using namespace anna::diameter;
40
41
42 namespace anna {
43   namespace diameter {
44     namespace stack {
45       class Dictionary;
46     }
47   }
48 }
49
50 comm::Engine::Engine(const char *className, const stack::Dictionary *baseProtocolDictionary) :
51   anna::app::Component(className),
52   a_autoBind(true),
53   a_availableForEntities(false),
54   a_availableForLocalServers(false),
55   a_cer(true),
56   a_dwr(true),
57 //      a_cea(true),
58 //      a_dwa(true),
59   a_watchdogPeriod(ClientSession::DefaultWatchdogPeriod),
60   a_maxConnectionDelay(anna::comm::ClientSocket::DefaultMaxConnectionDelay /* 200 ms*/),
61   a_numberOfClientSessionsPerServer(1),
62   a_baseProtocolCodecEngine((std::string("baseProtocolCodecEngine_for_") + std::string(className)).c_str(), baseProtocolDictionary)
63 {
64   anna::diameter::sccs::activate();
65   a_originRealm = anna::functions::getDomainname();
66   a_originHost = anna::functions::getHostname();
67   a_ceaPathfile = "";
68
69   // Internal base protocol codec engine:
70   a_baseProtocolCodecEngine.setValidationMode(anna::diameter::codec::Engine::ValidationMode::Always); // default was: after decoding
71 }
72
73
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.
79 }
80
81
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); }
86
87
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);
91   }
92
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);
95   }
96
97   a_cer = cer;
98   a_dwr = dwr;
99 }
100
101 void comm::Engine::setClientCERandDWR(const std::string & cer, const std::string & dwr) throw(anna::RuntimeException) {
102
103   // Check for base protocol codec engine health:
104   assertBaseProtocolHealth();
105
106   // Build CER
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 = getOriginHostName();
120   std::string OR = getOriginRealmName();
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;
125
126   if (cer != "") {
127     try {
128       diameterCER.loadXML(cer);
129     } catch(anna::RuntimeException &ex) {
130       //ex.trace();
131       encodeDefault = true;
132       LOGWARNING(anna::Logger::warning("CER file not found or unable to parse. Encoding harcoded default version ...", ANNA_FILE_LOCATION));
133     }
134   }
135   else {
136     encodeDefault = true;
137   }
138
139   if(encodeDefault) {
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);
148   }
149
150   // Build DWR
151   //   <DWR>  ::= < Diameter Header: 280, REQ >
152   //              { Origin-Host }
153   //              { Origin-Realm }
154   anna::diameter::codec::Message diameterDWR(getBaseProtocolCodecEngine());
155   encodeDefault = false;
156
157   if (dwr != "") {
158     try {
159       diameterDWR.loadXML(dwr);
160     } catch(anna::RuntimeException &ex) {
161       //ex.trace();
162       encodeDefault = true;
163       LOGWARNING(anna::Logger::warning("DWR file not found or unable to parse. Encoding harcoded default version ...", ANNA_FILE_LOCATION));
164     }
165   }
166   else {
167     encodeDefault = true;
168   }
169
170   if(encodeDefault) {
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);
175   }
176
177   // Assignment for internal encoded versions:
178   setClientCERandDWR(diameterCER.code(), diameterDWR.code());
179 }
180
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);
184   }
185
186   a_watchdogPeriod = wp;
187 }
188
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());
193
194   for(it = it_min; it != it_max; it++) {
195     server_iterator ii = server_find(*it);
196
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);
199   }
200
201   // Check repetitions:
202   std::map < socket_t, int/*dummy*/ > auxMap;
203
204   for(it = it_min; it != it_max; it++) auxMap[(*it)] = 0;
205
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);
208 }
209
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");
214
215   if(socketList.size() == 0)
216     throw anna::RuntimeException("diameter::comm::Engine::createEntity Address/Port server list provided is empty", ANNA_FILE_LOCATION);
217
218   // Proteccion antes de reservar memoria para una entidad (allocateEntity):
219   checkEntityCollision(socketList);
220
221   if((result = allocateEntity()) == NULL)
222     throw anna::RuntimeException("diameter::comm::Engine::allocateEntity returns NULL (perhaps virtual method was not implemented)", ANNA_FILE_LOCATION);
223
224   // Initialize:
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());
236   int count = 1;
237
238   for(it = it_min; it != it_max; it++) {
239     result->addServer(*it);
240
241     if(count == 1) result->a_primarySocketLiteral = anna::functions::socketLiteralAsString((*it).first, (*it).second);
242
243     if(count == 2) result->a_secondarySocketLiteral = anna::functions::socketLiteralAsString((*it).first, (*it).second);
244
245     count++;
246   }
247
248   a_entities.insert(entity_value_type(key, result));
249   LOGDEBUG(
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);
254   );
255   return result;
256 }
257
258
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);
265
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);
268
269   if((result = allocateLocalServer()) == NULL)
270     throw anna::RuntimeException("diameter::comm::Engine::allocateLocalServer returns NULL (perhaps virtual method was not implemented)", ANNA_FILE_LOCATION);
271
272   result->setEngine(this); // lo podia haber asignado en el allocateLocalServer (no importa)
273   result->setKey(key);
274   result->setCategory(category);
275   result->setDescription(description);
276   result->setAllowedInactivityTime(allowedInactivityTime);
277   result->initializeStatisticResources();
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));
282   LOGDEBUG(
283     string msg("diameter::comm::Engine::createLocalServer | ");
284     msg += result->asString();
285     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
286   );
287 //   // Listen: (*)
288 //   /*if (a_autoListen) */result->enable(); // creates server socket
289   result->setMaxConnections(maxConnections); // (*) this enables the listen port ... or not
290   return result;
291 }
292
293
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) {
296   socket_v dualList;
297   dualList.push_back(socket_t(addr1, port1));
298   dualList.push_back(socket_t(addr2, port2));
299   return (createEntity(dualList, description));
300 }
301
302
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");
307
308   if((result = allocateServer()) == NULL)
309     throw anna::RuntimeException("diameter::comm::Engine::allocateServer returns NULL", ANNA_FILE_LOCATION);
310
311   // Initialize:
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->initializeStatisticResources();
319
320   for(int k = 0; k < a_numberOfClientSessionsPerServer; k++)
321     result->addClientSession(k);
322
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);
329 //      );
330   return result;
331 }
332
333
334 // Lohacemos privado
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");
339
340   if((result = allocateClientSession()) == NULL)
341     throw anna::RuntimeException("diameter::comm::Engine::allocateClientSession returns NULL", ANNA_FILE_LOCATION);
342
343   // Initialize:
344   result->initialize(); // warning: recycler does not initialize its objects and at least...
345   // Assignments (it could be done at allocate):
346
347   if((a_cer.isEmpty()) || (a_dwr.isEmpty()))
348     throw anna::RuntimeException("Must define valid CER and DWR messages by mean setClientCERandDWR()", ANNA_FILE_LOCATION);
349
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(); // despues de asignar el server y el socketId (sequences are seed-based by mean exclusive hash)
356   result->a_engine = this;
357   clientSession_key key = ClientSession::getKey(server->getAddress(), server->getPort(), socketId);
358   a_clientSessions.insert(clientSession_value_type(key, result));
359 //      LOGDEBUG( Lo comento, porque ya se tracea en el createEntity
360 //         string msg("diameter::comm::Engine::createClientSession | ");
361 //         msg += result->asString();
362 //         msg += anna::functions::asText(" | AutoBind: ", a_autoBind);
363 //         anna::Logger::debug(msg, ANNA_FILE_LOCATION);
364 //      );
365   // Creation:
366   anna::comm::Network& network = anna::comm::Network::instantiate();
367   result->a_server = network.resolveServer(server->getAddress().c_str(), server->getPort(), true /* autoRecovery */,
368                      result->a_receiverFactory, &anna::diameter::comm::Transport::getFactory(),
369                      anna::comm::Network::Port::Multiple, anna::comm::Network::DoConnect::No /* (*) */);
370   // Delay time on tcp connect:
371   result->a_server->setMaxConnectionDelay(a_maxConnectionDelay); // (*)
372
373   // Bind:
374   if(a_autoBind) result->bind();
375
376   return result;
377 }
378
379
380 bool comm::Engine::broadcastEntities(const Message* message) throw(anna::RuntimeException) {
381   LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "broadcastEntities", ANNA_FILE_LOCATION));
382   bool allok = true;
383   bool ok;
384
385   for(entity_iterator it = entity_begin(), maxii = entity_end(); it != maxii; it ++) {
386     try {
387       ok = entity(it)->broadcast(message);
388
389       if(!ok) allok = false;
390     } catch(anna::RuntimeException &ex) {
391       ex.trace();
392       allok = false;
393     }
394   }
395
396   return allok;
397 }
398
399 bool comm::Engine::broadcastLocalServers(const Message* message) throw(anna::RuntimeException) {
400   LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "broadcastLocalServers", ANNA_FILE_LOCATION));
401   bool allok = true;
402   bool ok;
403
404   for(localServer_iterator it = localServer_begin(), maxii = localServer_end(); it != maxii; it ++) {
405     try {
406       ok = localServer(it)->broadcast(message);
407
408       if(!ok) allok = false;
409     } catch(anna::RuntimeException &ex) {
410       ex.trace();
411       allok = false;
412     }
413   }
414
415   return allok;
416 }
417
418 bool comm::Engine::bind() throw(anna::RuntimeException) {
419   LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "bind", ANNA_FILE_LOCATION));
420   bool result = true; // all OK return
421
422   for(entity_iterator it = entity_begin(), maxii = entity_end(); it != maxii; it ++) {
423     try {
424       entity(it)->bind();
425     } catch(anna::RuntimeException &ex) {
426       ex.trace();
427       result = false;
428     }
429   }
430
431   return result;
432 }
433
434 comm::ClientSession* comm::Engine::findClientSession(const std::string & addr, int port, int socketId, anna::Exception::Mode::_v emode)
435 throw(anna::RuntimeException) {
436   return findClientSession(ClientSession::getKey(addr, port, socketId), emode);
437 }
438
439 comm::ClientSession* comm::Engine::findClientSession(const std::string & key, anna::Exception::Mode::_v emode)
440 throw(anna::RuntimeException) {
441   anna::Guard guard(this, "anna::diameter::comm::Engine::findClientSession");
442   clientSession_iterator ii = clientSession_find(key);
443
444   if(ii != clientSession_end())
445     return clientSession(ii);
446
447   if(emode != anna::Exception::Mode::Ignore) {
448     string msg("diameter::comm::Engine::findClientSession | [addr:port|socketId] = ");
449     msg += key;
450     msg += " | ClientSession not found";
451     anna::RuntimeException ex(msg, ANNA_FILE_LOCATION);
452
453     if(emode == anna::Exception::Mode::Throw)
454       throw ex;
455
456     ex.trace();
457   }
458
459   return NULL;
460 }
461
462
463 comm::Server* comm::Engine::findServer(const std::string & addr, int port, anna::Exception::Mode::_v emode)
464 throw(anna::RuntimeException) {
465   anna::Guard guard(this, "anna::diameter::comm::Engine::findServer");
466   server_iterator ii = server_find(server_key(addr, port));
467
468   if(ii != server_end())
469     return server(ii);
470
471   if(emode != anna::Exception::Mode::Ignore) {
472     string msg("diameter::comm::Engine::findServer | addr: ");
473     msg += addr;
474     msg += anna::functions::asText(" | port: ", port);
475     msg += " | Server not found";
476     anna::RuntimeException ex(msg, ANNA_FILE_LOCATION);
477
478     if(emode == anna::Exception::Mode::Throw)
479       throw ex;
480
481     ex.trace();
482   }
483
484   return NULL;
485 }
486
487 comm::Entity* comm::Engine::findEntity(const socket_v & socketList, anna::Exception::Mode::_v emode)
488 throw(anna::RuntimeException) {
489   anna::Guard guard(this, "anna::diameter::comm::Engine::findEntity");
490   entity_key key(getEntityKey(socketList));
491   entity_iterator ii = entity_find(key);
492
493   if(ii != entity_end())
494     return entity(ii);
495
496   if(emode != anna::Exception::Mode::Ignore) {
497     string msg("diameter::comm::Engine::findEntity | socket list: ");
498     msg += key;
499     msg += " | Entity not found";
500     anna::RuntimeException ex(msg, ANNA_FILE_LOCATION);
501
502     if(emode == anna::Exception::Mode::Throw)
503       throw ex;
504
505     ex.trace();
506   }
507
508   return NULL;
509 }
510
511 comm::Entity* comm::Engine::findEntity(const std::string & addr1, int port1, const std::string & addr2, int port2, anna::Exception::Mode::_v emode)
512 throw(anna::RuntimeException) {
513   socket_v dualList;
514   dualList.push_back(socket_t(addr1, port1));
515   dualList.push_back(socket_t(addr2, port2));
516   return (findEntity(dualList, emode));
517 }
518
519
520 //Entity* Engine::findEntity(int category, anna::Exception::Mode::_v emode)
521 //throw(anna::RuntimeException) {
522 //
523 //   Entity *entity;
524 //
525 //   for (entity_iterator it = entity_begin(), maxii = entity_end(); it != maxii; it ++) {
526 //      entity = entity(it);
527 //      if (entity->getCategory() == category) return entity;
528 //   }
529 //
530 //   return NULL;
531 //}
532
533
534 comm::LocalServer* comm::Engine::findLocalServer(const std::string & addr, int port, anna::Exception::Mode::_v emode)
535 throw(anna::RuntimeException) {
536   anna::Guard guard(this, "anna::diameter::comm::Engine::findLocalServer");
537   socket_t key(addr, port);
538   localServer_iterator ii = localServer_find(key);
539
540   if(ii != localServer_end())
541     return localServer(ii);
542
543   if(emode != anna::Exception::Mode::Ignore) {
544     string msg("diameter::comm::Engine::findLocalServer | addr: ");
545     msg += addr;
546     msg += anna::functions::asText(" | port: ", port);
547     msg += " | LocalServer not found";
548     anna::RuntimeException ex(msg, ANNA_FILE_LOCATION);
549
550     if(emode == anna::Exception::Mode::Throw)
551       throw ex;
552
553     ex.trace();
554   }
555
556   return NULL;
557 }
558
559
560 comm::ServerSession* comm::Engine::findServerSession(int socketId, anna::Exception::Mode::_v emode) throw(anna::RuntimeException) {
561   anna::Guard guard(this, "anna::diameter::comm::Engine::findServerSession");
562   ServerSession *result;
563
564   // Search at each local server:
565   for(localServer_iterator it = localServer_begin(), maxii = localServer_end(); it != maxii; it ++) {
566     result = localServer(it)->findServerSession(socketId, anna::Exception::Mode::Ignore);
567
568     if(result) return result;
569   }
570
571   if(emode != anna::Exception::Mode::Ignore) {
572     string msg("diameter::comm::Engine::findServerSession | socketId: ");
573     msg += anna::functions::asString(socketId);
574     msg += " | ServerSession not found";
575     anna::RuntimeException ex(msg, ANNA_FILE_LOCATION);
576
577     if(emode == anna::Exception::Mode::Throw)
578       throw ex;
579
580     ex.trace();
581   }
582
583   return NULL;
584 }
585
586
587 void comm::Engine::closeClientSession(comm::ClientSession* clientSession, bool destroy)
588 throw(anna::RuntimeException) {
589   if(clientSession == NULL)
590     return;
591
592   LOGDEBUG(
593     string msg("diameter::comm::Engine::closeClientSession | ");
594     msg += clientSession->asString();
595     msg += " | Destroy: ";
596     msg += (destroy ? "yes" : "no");
597     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
598   );
599   anna::Guard guard(this, "anna::diameter::comm::Engine::closeClientSession");
600   clientSession_iterator ii = clientSession_find(clientSession->getKey());
601
602   if(ii == clientSession_end())
603     return;
604
605   try {
606     clientSession->setState(ClientSession::State::Closing);
607
608     if(destroy) clientSession->setAutoRecovery(false);
609
610     clientSession->unbind(destroy /* destroy needs to perform immediate close */);
611
612     if(!destroy) return;
613
614     releaseClientSession(clientSession);
615   } catch(anna::RuntimeException& ex) {
616     ex.trace();
617   }
618
619   a_clientSessions.erase(ii);
620 }
621
622
623
624
625 void comm::Engine::closeServer(comm::Server* server, bool destroy)
626 throw(anna::RuntimeException) {
627   if(server == NULL)
628     return;
629
630   LOGDEBUG(
631     string msg("diameter::comm::Engine::closeServer | ");
632     msg += server->asString();
633     msg += " | Destroy: ";
634     msg += (destroy ? "yes" : "no");
635     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
636   );
637   anna::Guard guard(this, "anna::diameter::comm::Engine::closeServer");
638   server_iterator ii = server_find(server->a_socket);
639
640   if(ii == server_end())
641     return;
642
643   try {
644     server->close(destroy);
645
646     if(!destroy) return;
647
648     releaseServer(server);
649   } catch(anna::RuntimeException& ex) {
650     ex.trace();
651   }
652
653   a_servers.erase(ii);
654 }
655
656
657 void comm::Engine::closeEntity(comm::Entity* entity, bool destroy)
658 throw(anna::RuntimeException) {
659   if(entity == NULL)
660     return;
661
662   LOGDEBUG(
663     string msg("diameter::comm::Engine::closeEntity | ");
664     msg += entity->asString();
665     msg += " | Destroy: ";
666     msg += (destroy ? "yes" : "no");
667     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
668   );
669   anna::Guard guard(this, "anna::diameter::comm::Engine::closeEntity");
670   entity_iterator ii = entity_find(entity->a_socketListLiteral);
671
672   if(ii == entity_end())
673     return;
674
675   try {
676     entity->close(destroy);
677
678     if(!destroy) return;
679
680     if(!entity->idle()) { entity->setDeprecated(true); return; }
681
682     releaseEntity(entity);
683   } catch(anna::RuntimeException& ex) {
684     ex.trace();
685   }
686
687   a_entities.erase(ii);
688 }
689
690
691
692 void comm::Engine::closeLocalServer(comm::LocalServer* localServer, bool destroy)
693 throw(anna::RuntimeException) {
694   if(localServer == NULL)
695     return;
696
697   LOGDEBUG(
698     string msg("diameter::comm::Engine::closeLocalServer | ");
699     msg += localServer->asString();
700     msg += " | Destroy: ";
701     msg += (destroy ? "yes" : "no");
702     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
703   );
704   anna::Guard guard(this, "anna::diameter::comm::Engine::closeLocalServer");
705   localServer_iterator ii = localServer_find(localServer->getKey());
706
707   if(ii == localServer_end())
708     return;
709
710   try {
711     localServer->close();
712
713     if(!destroy) return;
714
715     releaseLocalServer(localServer);
716   } catch(anna::RuntimeException& ex) {
717     ex.trace();
718   }
719
720   a_localServers.erase(ii);
721 }
722
723
724
725 void comm::Engine::closeEntities(bool destroy) throw(anna::RuntimeException) {
726   LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "closeEntities", ANNA_FILE_LOCATION));
727   anna::Guard guard(this, "anna::diameter::comm::Engine::closeEntities");
728
729   for(entity_iterator it = entity_begin(), maxii = entity_end(); it != maxii; it ++)
730     closeEntity(entity(it), destroy);
731 }
732
733 void comm::Engine::closeLocalServers(bool destroy) throw(anna::RuntimeException) {
734   LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "closeLocalServers", ANNA_FILE_LOCATION));
735   anna::Guard guard(this, "anna::diameter::comm::Engine::closeLocalServers");
736
737   for(localServer_iterator it = localServer_begin(), maxii = localServer_end(); it != maxii; it ++)
738     closeLocalServer(localServer(it), destroy);
739 }
740
741 void comm::Engine::eraseDeprecatedIdleEntities() throw() {
742   LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "eraseDeprecatedIdleEntities", ANNA_FILE_LOCATION));
743   Entity *et;
744
745   for(entity_iterator it = entity_begin(), maxii = entity_end(); it != maxii; it ++) {
746     et = entity(it);
747
748     if(et->isDeprecated() && et->idle()) closeEntity(et, true /* destroy */);
749   }
750 }
751
752 int comm::Engine::getOTARequestsForEntities() const throw() {
753   int result = 0;
754
755   for(const_entity_iterator it = entity_begin(), maxii = entity_end(); it != maxii; it ++)
756     result += entity(it)->getOTARequests();
757
758   return result;
759 }
760
761 int comm::Engine::getOTARequestsForLocalServers() const throw() {
762   int result = 0;
763
764   for(const_localServer_iterator it = localServer_begin(), maxii = localServer_end(); it != maxii; it ++)
765     result += localServer(it)->getOTARequests();
766
767   return result;
768 }
769
770
771 void comm::Engine::setOriginRealmName(const std::string & originRealmName) throw() {
772   a_originRealm = ((originRealmName != "") ? originRealmName : anna::functions::getDomainname());
773 }
774
775
776 void comm::Engine::setOriginHostName(const std::string & originHostName) throw() {
777   a_originHost = ((originHostName != "") ? originHostName : anna::functions::getHostname());
778 }
779
780
781
782 void comm::Engine::raiseAutoRecovery(bool autoRecovery) throw(anna::RuntimeException) {
783   LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "raiseAutoRecovery", ANNA_FILE_LOCATION));
784
785   for(entity_iterator it = entity_begin(), maxii = entity_end(); it != maxii; it ++)
786     entity(it)->raiseAutoRecovery(autoRecovery);
787 }
788
789 void comm::Engine::do_stop()
790 throw() {
791   LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "do_stop", ANNA_FILE_LOCATION));
792   close(true /* destroy */);
793 }
794
795 std::string comm::Engine::asString(void) const throw() {
796   std::string trace;
797   trace =  "\n================================";
798   trace += "\nDiameter comm Engine information";
799   trace += "\n================================";
800   trace += "\nAutoBind: ";
801   trace += a_autoBind ? "yes" : "no";
802   trace += "\nMaxConnectionDelay: ";
803   trace += a_maxConnectionDelay.asString();
804   trace += "\nAvailable for entities: ";
805   trace += a_availableForEntities ? "yes" : "no";
806   trace += "\nAvailable for local servers: ";
807   trace += a_availableForLocalServers ? "yes" : "no";
808   trace += "\nOTA requests: ";
809   trace += anna::functions::asString("%d%s", getOTARequests(), idle() ? " (idle)" : "");
810   trace += "\nOTA requests for entities: ";
811   trace += anna::functions::asString("%d%s", getOTARequestsForEntities(), idleForEntities() ? " (idle)" : "");
812   trace += "\nOTA requests for local servers: ";
813   trace += anna::functions::asString("%d%s", getOTARequestsForLocalServers(), idleForLocalServers() ? " (idle)" : "");
814   // Entities
815   trace += "\nNumber of entities: ";
816   trace += anna::functions::asString(a_entities.size());
817
818   for(const_entity_iterator it = entity_begin(); it != entity_end(); it++) {
819     trace += "\n";
820     trace += entity(it)->asString();
821   }
822
823   // Server sockets
824   trace += "\nNumber of LocalServers: ";
825   trace += anna::functions::asString(a_localServers.size());
826
827   for(const_localServer_iterator it = localServer_begin(); it != localServer_end(); it++) {
828     trace += "\n";
829     trace += localServer(it)->asString();
830   }
831
832   return trace;
833 }
834
835
836 anna::xml::Node* comm::Engine::asXML(anna::xml::Node* parent) const
837 throw() {
838   parent = anna::app::Component::asXML(parent);
839   anna::xml::Node* result = parent->createChild("diameter.comm.Engine");
840   result->createAttribute("AutoBind", a_autoBind ? "yes" : "no");
841   result->createAttribute("MaxConnectionDelay", a_maxConnectionDelay.asString());
842   result->createAttribute("AvailableForEntities", a_availableForEntities ? "yes" : "no");
843   result->createAttribute("AvailableForLocalServers", a_availableForLocalServers ? "yes" : "no");
844   result->createAttribute("OTArequests", anna::functions::asString("%d%s", getOTARequests(), idle() ? " (idle)" : ""));
845   result->createAttribute("OTArequestsForEntities", anna::functions::asString("%d%s", getOTARequestsForEntities(), idleForEntities() ? " (idle)" : ""));
846   result->createAttribute("OTArequestsForLocalServers", anna::functions::asString("%d%s", getOTARequestsForLocalServers(), idleForLocalServers() ? " (idle)" : ""));
847   result->createAttribute("NumberOfEntities", a_entities.size());
848   anna::xml::Node* entities = result->createChild("Engine.Entities");
849
850   for(const_entity_iterator it = entity_begin(); it != entity_end(); it++)
851     entity(it)->asXML(entities);
852
853   result->createAttribute("NumberOfLocalServers", a_localServers.size());
854   anna::xml::Node* localServers = result->createChild("Engine.LocalServers");
855
856   for(const_localServer_iterator it = localServer_begin(); it != localServer_end(); it++)
857     localServer(it)->asXML(localServers);
858
859   // DRA Basics
860   // Aspect:
861   //  <Engine.RemoteRealm Name="afNodeHostRealm.com">
862   //     <Engine.RemoteRealmHost Name="afNodeHostname.afNodeHostRealm.com" ServerSession="localhost:3868|ServerSessionId:4"/>
863   //  </Engine.RemoteRealm>
864   //  <Engine.RemoteRealm Name="ggsnNodeHostRealm.com">
865   //     <Engine.RemoteRealmHost Name="ggsnNodeHostname.ggsnNodeHostRealm.com" ServerSession="localhost:3868|ServerSessionId:6"/>
866   //  </Engine.RemoteRealm>
867   for (dr_dh_server_sessions_it_t drit = a_dr_dh_server_sessions.begin(); drit != a_dr_dh_server_sessions.end(); drit++) {
868     anna::xml::Node* remoteRealm = result->createChild("Engine.RemoteRealm");
869     remoteRealm->createAttribute("Name", drit->first);
870     dh_server_sessions_map_t *dhServerSessions = (dh_server_sessions_map_t *)&(drit->second);
871     for (dh_server_sessions_it_t dhit = dhServerSessions->begin(); dhit != dhServerSessions->end(); dhit++) {
872       anna::xml::Node* remoteRealmHost = remoteRealm->createChild("Engine.RemoteRealmHost");
873       remoteRealmHost->createAttribute("Name", dhit->first);
874       server_sessions_vector_t *serverSessions = (server_sessions_vector_t *)&(dhit->second);
875       for (server_sessions_it_t ssit = serverSessions->begin(); ssit != serverSessions->end(); ssit++) {
876         std::string socket = anna::functions::socketLiteralAsString((*ssit)->getAddress(), (*ssit)->getPort());
877         std::string ss_desc = socket + anna::functions::asString("|ServerSessionId:%d", (*ssit)->getSocketId());
878         remoteRealmHost->createAttribute("ServerSession", ss_desc);
879       }
880     }
881   }
882
883   return result;
884 }
885
886 comm::Engine::clientSession_iterator comm::Engine::clientSession_find(const clientSession_key &key) throw() {
887   return a_clientSessions.find(key);
888 }
889
890 comm::Engine::server_iterator comm::Engine::server_find(const server_key &key) throw() {
891   return a_servers.find(key);
892 }
893
894 comm::Engine::entity_iterator comm::Engine::entity_find(const entity_key &key) throw() {
895   return a_entities.find(key);
896 }
897
898 comm::Engine::localServer_iterator comm::Engine::localServer_find(const socket_t &key) throw() {
899   return a_localServers.find(key);
900 }
901
902 comm::Engine::entity_key comm::Engine::getEntityKey(const std::string & addr1, int port1, const std::string & addr2, int port2) const throw() {
903   socket_v dualList;
904   dualList.push_back(socket_t(addr1, port1));
905   dualList.push_back(socket_t(addr2, port2));
906   return (getEntityKey(dualList));
907 }
908
909 comm::Engine::entity_key comm::Engine::getEntityKey(const socket_v &v) const throw() {
910   std::string result;
911   socket_v::const_iterator it;
912   socket_v::const_iterator it_min(v.begin());
913   socket_v::const_iterator it_max(v.end());
914
915   for(it = it_min; it != it_max; it++) {
916     result += anna::functions::socketLiteralAsString((*it).first, (*it).second);
917     result += " ";
918   }
919
920   result.erase(result.size() - 1, 1);  // remove last space
921   return result;
922 }
923
924
925 void comm::Engine::availabilityLostForEntities() throw() {
926   a_availableForEntities = false;
927   LOGDEBUG(
928     std::string msg = "diameter::comm::Engine { Origin-Realm: ";
929     msg += getOriginRealmName();
930     msg += " | Origin-Host: ";
931     msg += getOriginHostName();
932     msg += " } has lost its availability for entities";
933     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
934   );
935   // OAM
936   OamModule &oamModule = OamModule::instantiate();
937   oamModule.activateAlarm(OamModule::Alarm::c_LostAvailabilityOverEntitiesForEngineWithClassName__s__, getClassName());
938   oamModule.count(OamModule::Counter::LostAvailabilityOverEngineForEntities);
939   // Virtual
940   availabilityLostForEntities(this);
941 }
942
943
944 void comm::Engine::availabilityRecoveredForEntities() throw() {
945   a_availableForEntities = true;
946   LOGDEBUG(
947     std::string msg = "diameter::comm::Engine { Origin-Realm: ";
948     msg += getOriginRealmName();
949     msg += " | Origin-Host: ";
950     msg += getOriginHostName();
951     msg += " } has recovered its availability for entities";
952     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
953   );
954   // OAM
955   OamModule &oamModule = OamModule::instantiate();
956   oamModule.cancelAlarm(OamModule::Alarm::c_LostAvailabilityOverEntitiesForEngineWithClassName__s__, getClassName());
957   oamModule.count(OamModule::Counter::RecoveredAvailabilityOverEngineForEntities);
958   // Virtual
959   availabilityRecoveredForEntities(this);
960 }
961
962
963 void comm::Engine::availabilityLostForLocalServers() throw() {
964   a_availableForLocalServers = false;
965   LOGDEBUG(
966     std::string msg = "diameter::comm::Engine { Origin-Realm: ";
967     msg += getOriginRealmName();
968     msg += " | Origin-Host: ";
969     msg += getOriginHostName();
970     msg += " } has lost its availability for local servers";
971     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
972   );
973   // OAM
974   OamModule &oamModule = OamModule::instantiate();
975   oamModule.activateAlarm(OamModule::Alarm::c_LostAvailabilityOverLocalServersForEngineWithClassName__s__, getClassName());
976   oamModule.count(OamModule::Counter::LostAvailabilityOverEngineForLocalServers);
977   // Virtual
978   availabilityLostForLocalServers(this);
979 }
980
981
982 void comm::Engine::availabilityRecoveredForLocalServers() throw() {
983   a_availableForLocalServers = true;
984   LOGDEBUG(
985     std::string msg = "diameter::comm::Engine { Origin-Realm: ";
986     msg += getOriginRealmName();
987     msg += " | Origin-Host: ";
988     msg += getOriginHostName();
989     msg += " } has recovered its availability for local servers";
990     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
991   );
992   // OAM
993   OamModule &oamModule = OamModule::instantiate();
994   oamModule.cancelAlarm(OamModule::Alarm::c_LostAvailabilityOverLocalServersForEngineWithClassName__s__, getClassName());
995   oamModule.count(OamModule::Counter::RecoveredAvailabilityOverEngineForLocalServers);
996   // Virtual
997   availabilityRecoveredForLocalServers(this);
998 }
999
1000
1001 bool comm::Engine::refreshAvailabilityForEntities() throw() {
1002   // Here available
1003   if(a_availableForEntities) {  // check not-bound state for all client-sessions:
1004     bool isolate = true;
1005
1006     for(const_entity_iterator it = entity_begin(); it != entity_end(); it++)
1007       if(entity(it)->isAvailable()) { isolate = false; break; }
1008
1009     if(isolate) {
1010       availabilityLostForEntities();
1011       return true;
1012     }
1013
1014     return false;
1015   }
1016
1017   // Here not available
1018   for(const_entity_iterator it = entity_begin(); it != entity_end(); it++)
1019     if(entity(it)->isAvailable()) {
1020       availabilityRecoveredForEntities();
1021       return true;
1022     }
1023
1024   return false;
1025 }
1026
1027 bool comm::Engine::refreshAvailabilityForLocalServers() throw() {
1028   // Here available
1029   if(a_availableForLocalServers) {  // check not-bound state for all client-sessions:
1030     bool isolate = true;
1031
1032     for(const_localServer_iterator it = localServer_begin(); it != localServer_end(); it++)
1033       if(localServer(it)->isAvailable()) { isolate = false; break; }
1034
1035     if(isolate) {
1036       availabilityLostForLocalServers();
1037       return true;
1038     }
1039
1040     return false;
1041   }
1042
1043   // Here not available
1044   for(const_localServer_iterator it = localServer_begin(); it != localServer_end(); it++)
1045     if(localServer(it)->isAvailable()) {
1046       availabilityRecoveredForLocalServers();
1047       return true;
1048     }
1049
1050   return false;
1051 }
1052
1053
1054 void comm::Engine::readDPA(anna::DataBlock &dpa, const anna::DataBlock & dpr) throw() {
1055
1056   // Check for base protocol codec engine health:
1057   try {
1058     assertBaseProtocolHealth();
1059   }
1060   catch(anna::RuntimeException &ex) {
1061     ex.trace();
1062     return;
1063   }
1064
1065   // Default DPA implementation:
1066   //
1067   //   'Disconnect-Peer-Answer' (282,answer)
1068   //        {Result-Code}...................................(268,0)
1069   //        {Origin-Host}...................................(264,0)
1070   //        {Origin-Realm}..................................(296,0)
1071   //        [Error-Message].................................(281,0)
1072   //       *[Failed-AVP]....................................(279,0)
1073   try {
1074     anna::diameter::codec::Message diameterDPA(getBaseProtocolCodecEngine());
1075     anna::diameter::codec::Avp avpRC(getBaseProtocolCodecEngine());
1076     anna::diameter::codec::Avp avpOH(getBaseProtocolCodecEngine());
1077     anna::diameter::codec::Avp avpOR(getBaseProtocolCodecEngine());
1078     // Message header
1079     diameterDPA.setId(anna::diameter::helpers::base::COMMANDID__Disconnect_Peer_Answer);
1080     diameterDPA.setVersion(1);
1081     diameterDPA.setApplicationId(codec::functions::getApplicationId(dpr));
1082     diameterDPA.setHopByHop(codec::functions::getHopByHop(dpr));
1083     diameterDPA.setEndToEnd(codec::functions::getEndToEnd(dpr));
1084     // Result-Code
1085     avpRC.setId(anna::diameter::helpers::base::AVPID__Result_Code);
1086     avpRC.setMandatoryBit();
1087     avpRC.getUnsigned32()->setValue(helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS);
1088     // Origin-Host
1089     avpOH.setId(anna::diameter::helpers::base::AVPID__Origin_Host);
1090     avpOH.setMandatoryBit();
1091     avpOH.getDiameterIdentity()->fromPrintableString(a_originHost.c_str());
1092     // Origin-Realm
1093     avpOR.setId(anna::diameter::helpers::base::AVPID__Origin_Realm);
1094     avpOR.setMandatoryBit();
1095     avpOR.getDiameterIdentity()->fromPrintableString(a_originRealm.c_str());
1096     diameterDPA.addAvp(&avpRC);
1097     diameterDPA.addAvp(&avpOH);
1098     diameterDPA.addAvp(&avpOR);
1099     // Encode
1100     dpa = diameterDPA.code();
1101   } catch(anna::RuntimeException &ex) {
1102     std::string msg = ex.getText();
1103     msg += " | Use diameter::comm::Engine::setBaseProtocolCodecEngine() to allow internal base protocol messages encoding (unable to answer with DPA)";
1104     anna::Logger::error(msg, ANNA_FILE_LOCATION);
1105     //throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1106   }
1107 }
1108
1109
1110 void comm::Engine::readCEA(anna::DataBlock &cea, const anna::DataBlock &cer) throw() {
1111
1112   // Check for base protocol codec engine health:
1113   assertBaseProtocolHealth();
1114
1115   if (a_ceaPathfile != "") {
1116     anna::diameter::codec::Message diameterCEA(getBaseProtocolCodecEngine());
1117
1118     try {
1119       diameterCEA.loadXML(a_ceaPathfile);
1120       diameterCEA.setHopByHop(anna::diameter::codec::functions::getHopByHop(cer));
1121       diameterCEA.setEndToEnd(anna::diameter::codec::functions::getEndToEnd(cer));
1122       cea = diameterCEA.code();
1123
1124     } catch(anna::RuntimeException &ex) {
1125       ex.trace();
1126       LOGWARNING(anna::Logger::warning("CEA file not found or unable to parse. Encoding harcoded default version ...", ANNA_FILE_LOCATION));
1127       //return anna::diameter::comm::Engine::readCEA(cea, cer);
1128       // will fail with empty cea
1129       }
1130
1131     return;
1132   }
1133
1134   // Default CEA implementation:
1135   //
1136   //   'Capabilities-Exchange-Answer' (257,answer)
1137   //        {Result-Code}...................................(268,0)
1138   //        {Origin-Host}...................................(264,0)
1139   //        {Origin-Realm}..................................(296,0)
1140   //      1*{Host-IP-Address}...............................(257,0)
1141   //        {Vendor-Id}.....................................(266,0)
1142   //        {Product-Name}..................................(269,0)
1143   //        [Origin-State-Id]...............................(278,0)
1144   //        [Error-Message].................................(281,0)
1145   //       *[Failed-AVP]....................................(279,0)
1146   //       *[Supported-Vendor-Id]...........................(265,0)
1147   //       *[Auth-Application-Id]...........................(258,0)
1148   //       *[Inband-Security-Id]............................(299,0)
1149   //       *[Acct-Application-Id]...........................(259,0)
1150   //        [Vendor-Specific-Application-Id]................(260,0)
1151   //        [Firmware-Revision].............................(267,0)
1152   //       *[AVP]...........................................(0,0)
1153   try {
1154     anna::diameter::codec::Message diameterCEA(getBaseProtocolCodecEngine());
1155     anna::diameter::codec::Avp avpRC(getBaseProtocolCodecEngine());
1156     anna::diameter::codec::Avp avpOH(getBaseProtocolCodecEngine());
1157     anna::diameter::codec::Avp avpOR(getBaseProtocolCodecEngine());
1158     // Message header
1159     diameterCEA.setId(anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Answer);
1160     diameterCEA.setVersion(1);
1161     diameterCEA.setApplicationId(codec::functions::getApplicationId(cer));
1162     diameterCEA.setHopByHop(codec::functions::getHopByHop(cer));
1163     diameterCEA.setEndToEnd(codec::functions::getEndToEnd(cer));
1164     // Result-Code
1165     avpRC.setId(anna::diameter::helpers::base::AVPID__Result_Code);
1166     avpRC.setMandatoryBit();
1167     avpRC.getUnsigned32()->setValue(helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS); // re-implementations could analyze CER to accept or not
1168     // Origin-Host
1169     avpOH.setId(anna::diameter::helpers::base::AVPID__Origin_Host);
1170     avpOH.setMandatoryBit();
1171     avpOH.getDiameterIdentity()->fromPrintableString(a_originHost.c_str());
1172     // Origin-Realm
1173     avpOR.setId(anna::diameter::helpers::base::AVPID__Origin_Realm);
1174     avpOR.setMandatoryBit();
1175     avpOR.getDiameterIdentity()->fromPrintableString(a_originRealm.c_str());
1176     diameterCEA.addAvp(&avpRC);
1177     diameterCEA.addAvp(&avpOH);
1178     diameterCEA.addAvp(&avpOR);
1179     // Host-IP-Address
1180     std::string hostIP = anna::functions::getHostnameIP(); // Address
1181     diameterCEA.addAvp(anna::diameter::helpers::base::AVPID__Host_IP_Address)->getAddress()->fromPrintableString(hostIP.c_str());
1182     // Vendor-Id
1183     int vendorId = anna::diameter::helpers::VENDORID__tgpp; // Unsigned32
1184     diameterCEA.addAvp(anna::diameter::helpers::base::AVPID__Vendor_Id)->getUnsigned32()->setValue(vendorId);
1185     // Product-Name
1186     std::string productName = "Diameter Server"; // UTF8String
1187     diameterCEA.addAvp(anna::diameter::helpers::base::AVPID__Product_Name)->getUTF8String()->setValue(productName);
1188     // Encode
1189     cea = diameterCEA.code();
1190   } catch(anna::RuntimeException &ex) {
1191     std::string msg = ex.getText();
1192     msg += " | Use diameter::comm::Engine::setBaseProtocolCodecEngine() to allow internal base protocol messages encoding (unable to answer with CEA)";
1193     anna::Logger::error(msg, ANNA_FILE_LOCATION);
1194     //throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1195   }
1196 }
1197
1198 void comm::Engine::manageDrDhServerSession(ServerSession *ss, bool register_or_desregister) throw() {
1199
1200   // Decode CER (TODO: use raw buffer helpers)
1201   std::string destinationRealm, destinationHost;
1202   codec::Message codecMsg(getBaseProtocolCodecEngine());
1203   try {
1204     codecMsg.decode(ss->a_cer);
1205     destinationRealm = codecMsg.getAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->getValue();
1206     destinationHost = codecMsg.getAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->getValue();
1207   }
1208   catch(anna::RuntimeException &ex) {
1209     ex.trace();
1210     return;
1211   }
1212
1213   dr_dh_server_sessions_nc_it_t drit = a_dr_dh_server_sessions.find(destinationRealm);
1214   if (drit != a_dr_dh_server_sessions.end()) { // found
1215     dh_server_sessions_map_t *dhServerSessions = (dh_server_sessions_map_t *)&(drit->second);
1216     dh_server_sessions_nc_it_t dhit = dhServerSessions->find(destinationHost);
1217     if (dhit != dhServerSessions->end()) { // found
1218       server_sessions_vector_t *serverSessions = (server_sessions_vector_t *)&(dhit->second);
1219       if (register_or_desregister) { // REGISTER
1220         serverSessions->push_back(ss);
1221       }
1222       else { // DESREGISTER
1223         // Sequential search the specific server session:
1224         for (server_sessions_nc_it_t ssit = serverSessions->begin(); ssit != serverSessions->end(); ssit++) {
1225           if ((*ssit)->getAddress() != ss->getAddress()) continue;
1226           if ((*ssit)->getPort() != ss->getPort()) continue;
1227           if ((*ssit)->getSocketId() != ss->getSocketId()) continue;
1228           serverSessions->erase(ssit);  // if it is the last server session removed in DR-DH path, the XML will show this tree empty
1229                                         // (it could be a hint for past registerings):
1230                                         //          <Engine.RemoteRealm Name="afNodeHostRealm.com">
1231                                         //             <Engine.RemoteRealmHost Name="afNodeHostname.afNodeHostRealm.com"/>
1232                                         //          </Engine.RemoteRealm>
1233                                         //          <Engine.RemoteRealm Name="ggsnNodeHostRealm.com">
1234                                         //             <Engine.RemoteRealmHost Name="ggsnNodeHostname.ggsnNodeHostRealm.com"/>
1235                                         //          </Engine.RemoteRealm>
1236
1237           break;
1238         }
1239       }
1240     }
1241     else {
1242       if (!register_or_desregister) return; // strange (host not found)
1243       server_sessions_vector_t ssVector;
1244       ssVector.push_back(ss);
1245       (*dhServerSessions)[destinationHost] = ssVector;
1246     }
1247   }
1248   else {
1249     if (!register_or_desregister) return; // strange (realm not found)
1250     server_sessions_vector_t ssVector;
1251     ssVector.push_back(ss);
1252     dh_server_sessions_map_t dhServerSessions;
1253     dhServerSessions[destinationHost] = ssVector;
1254     a_dr_dh_server_sessions[destinationRealm] = dhServerSessions;
1255   }
1256 }
1257
1258 void comm::Engine::readDWA(anna::DataBlock &dwa, const anna::DataBlock & dwr) throw() {
1259
1260   // Check for base protocol codec engine health:
1261   assertBaseProtocolHealth();
1262
1263   // Default DWA implementation:
1264   //
1265   //   'Device-Watchdog-Answer' (280,answer)
1266   //        {Result-Code}...................................(268,0)
1267   //        {Origin-Host}...................................(264,0)
1268   //        {Origin-Realm}..................................(296,0)
1269   //        [Error-Message].................................(281,0)
1270   //       *[Failed-AVP]....................................(279,0)
1271   //        [Origin-State-Id]...............................(278,0)
1272   try {
1273     anna::diameter::codec::Message diameterDWA(getBaseProtocolCodecEngine());
1274     anna::diameter::codec::Avp avpRC(getBaseProtocolCodecEngine());
1275     anna::diameter::codec::Avp avpOH(getBaseProtocolCodecEngine());
1276     anna::diameter::codec::Avp avpOR(getBaseProtocolCodecEngine());
1277     // Message header
1278     diameterDWA.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Answer);
1279     diameterDWA.setVersion(1);
1280     diameterDWA.setApplicationId(codec::functions::getApplicationId(dwr));
1281     diameterDWA.setHopByHop(codec::functions::getHopByHop(dwr));
1282     diameterDWA.setEndToEnd(codec::functions::getEndToEnd(dwr));
1283     // Result-Code
1284     avpRC.setId(anna::diameter::helpers::base::AVPID__Result_Code);
1285     avpRC.setMandatoryBit();
1286     avpRC.getUnsigned32()->setValue(helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS);
1287     // Origin-Host
1288     avpOH.setId(anna::diameter::helpers::base::AVPID__Origin_Host);
1289     avpOH.setMandatoryBit();
1290     avpOH.getDiameterIdentity()->fromPrintableString(a_originHost.c_str());
1291     // Origin-Realm
1292     avpOR.setId(anna::diameter::helpers::base::AVPID__Origin_Realm);
1293     avpOR.setMandatoryBit();
1294     avpOR.getDiameterIdentity()->fromPrintableString(a_originRealm.c_str());
1295     diameterDWA.addAvp(&avpRC);
1296     diameterDWA.addAvp(&avpOH);
1297     diameterDWA.addAvp(&avpOR);
1298     // Encode
1299     dwa = diameterDWA.code();
1300   } catch(anna::RuntimeException &ex) {
1301     std::string msg = ex.getText();
1302     msg += " | Use diameter::comm::Engine::setBaseProtocolCodecEngine() to allow internal base protocol messages encoding (unable to answer with DWA)";
1303     anna::Logger::error(msg, ANNA_FILE_LOCATION);
1304     //throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1305   }
1306 }
1307
1308 void comm::Engine::resetStatistics() throw() {
1309   for(server_iterator it = server_begin(), maxii = server_end(); it != maxii; it ++)
1310     server(it)->resetStatistics();
1311
1312   for(localServer_iterator it = localServer_begin(), maxii = localServer_end(); it != maxii; it ++)
1313     localServer(it)->resetStatistics();
1314 }
1315
1316 void comm::Engine::do_initialize() throw(RuntimeException) {
1317   LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "do_initialize", ANNA_FILE_LOCATION));
1318   LOGDEBUG(anna::Logger::debug("Nothing special done on component initialization", ANNA_FILE_LOCATION));
1319 }
1320
1321 void comm::Engine::lazyInitialize() throw(RuntimeException) {
1322   LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "lazyInitialize", ANNA_FILE_LOCATION));
1323   anna::app::Component::initialize(); // this will invoke do_initialize
1324 }
1325
1326 // Not tested yet
1327 const comm::Response* comm::Engine::sendRealmHost(const Message* message, const std::string &destinationRealm, const std::string &destinationHost) throw(anna::RuntimeException) {
1328
1329   if (destinationRealm == "")
1330     throw anna::RuntimeException("Unable to resolve the destination: empty provided Destination-Realm name", ANNA_FILE_LOCATION);
1331
1332   // Get the server sessions which fulfill the restrictions:
1333   dr_dh_server_sessions_it_t drit = a_dr_dh_server_sessions.find(destinationRealm);
1334   if (drit == a_dr_dh_server_sessions.end())
1335     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);
1336
1337   dh_server_sessions_map_t *dhServerSessions = (dh_server_sessions_map_t *)&(drit->second);
1338   // randomize between all server sessions for all hosts:
1339   dh_server_sessions_nc_it_t dhit;
1340   int hostsN = dhServerSessions->size();
1341   if (hostsN == 0) // avoids next division by cero (rand() % 0)
1342     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);
1343
1344   if (destinationHost == "") {
1345     // in this case, randomize the host:
1346     dhit = dhServerSessions->begin();
1347     int randomHostIndx = rand() % hostsN; // number between 0 and the number of hosts - 1
1348     std::advance (dhit, randomHostIndx);
1349   }
1350   else {
1351     dhit = dhServerSessions->find(destinationHost);
1352     if (dhit == dhServerSessions->end())
1353       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);
1354   }
1355
1356   // Now, randomize the available server sessions:
1357   server_sessions_vector_t *serverSessions = (server_sessions_vector_t *)&(dhit->second);
1358   int serverSessionN = serverSessions->size();
1359   if (serverSessionN == 0) { // avoids next division by cero (rand() % 0)
1360     std::string aux = "";
1361     if (destinationHost != "") { aux = "to Destination-Host '"; aux += destinationHost; aux += "'"; }
1362     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());
1363     throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1364   }
1365
1366   server_sessions_nc_it_t ssit = serverSessions->begin();
1367   int randomServerSessionIndx = rand() % serverSessionN; // number between 0 and the number of server sessions - 1
1368   std::advance (ssit, randomServerSessionIndx);
1369   return (*ssit)->send(message);
1370 }