Base protocol codec for comm::Engine. Supported retransmissions
[anna.git] / source / diameter.comm / ServerSession.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
9 #include <anna/core/functions.hpp>
10 #include <anna/diameter/defines.hpp>
11 #include <anna/diameter/functions.hpp>
12 #include <anna/diameter/helpers/helpers.hpp>
13 #include <anna/diameter/codec/functions.hpp>
14 #include <anna/diameter/codec/Message.hpp>
15 #include <anna/diameter/helpers/base/functions.hpp>
16 #include <anna/time/functions.hpp>
17
18 // Local
19 #include <anna/diameter.comm/ServerSession.hpp>
20 #include <anna/diameter.comm/Engine.hpp>
21 #include <anna/diameter.comm/Entity.hpp>
22 #include <anna/diameter.comm/Response.hpp>
23 #include <anna/diameter.comm/Message.hpp>
24 #include <anna/diameter.comm/OamModule.hpp>
25 #include <anna/diameter.comm/ApplicationMessageOamModule.hpp>
26 #include <anna/diameter.comm/TimerManager.hpp>
27 #include <anna/diameter.comm/Timer.hpp>
28 #include <anna/diameter.comm/LocalServer.hpp>
29 #include <anna/diameter.comm/ServerSessionReceiver.hpp>
30 #include <anna/diameter.comm/ReceiverFactoryImpl.hpp>
31
32 #include <anna/app/functions.hpp>
33 #include <anna/comm/ClientSocket.hpp>
34 #include <anna/core/functions.hpp>
35 #include <anna/core/DataBlock.hpp>
36 #include <anna/core/tracing/Logger.hpp>
37 #include <anna/core/tracing/TraceMethod.hpp>
38 #include <anna/xml/Node.hpp>
39 #include <anna/timex/Engine.hpp>
40
41 // Standard
42 #include <stdlib.h> // rand()
43 #include <time.h>
44
45
46
47 using namespace std;
48 using namespace anna::diameter;
49 using namespace anna::diameter::comm;
50
51 //static
52 const anna::Millisecond ServerSession::DefaultAllowedInactivityTime(90000); // Inactivity timeout
53
54
55 ServerSession::ServerSession() : Session("diameter::comm::ServerSession", "Diameter Inactivity Detection Timer"),
56   a_receiverFactory(this),
57   a_cer(ClassCode::Bind),
58   a_dwr(ClassCode::ApplicationMessage) // realmente no es necesario, los Message son por defecto de aplicacion
59 { initialize(); }
60
61 void ServerSession::initialize() throw() {
62   Session::initialize();
63   a_parent = NULL;
64   a_clientSocket = NULL;
65   a_deprecated = false; // selected for remove (server session was lost due to event break connection)
66 }
67
68 //ServerSession::~ServerSession() {;}
69
70 void ServerSession::setClientSocket(anna::comm::ClientSocket *clientSocket) throw() {
71   a_clientSocket = clientSocket;
72   a_clientSocket->setReceiverFactory(a_receiverFactory);
73 }
74
75
76 const std::string& ServerSession::getAddress() const throw() {
77   return a_parent->getKey().first;
78 }
79
80 int ServerSession::getPort() const throw() {
81   return a_parent->getKey().second;
82 }
83
84
85 const Response* ServerSession::send(const Message* message) throw(anna::RuntimeException) {
86   LOGMETHOD(anna::TraceMethod traceMethod(a_className, "send", ANNA_FILE_LOCATION));
87
88   if(!message)
89     throw anna::RuntimeException("Cannot send a NULL message", ANNA_FILE_LOCATION);
90
91   // Command id:
92   bool isRequest;
93   diameter::CommandId cid = message->getCommandId(isRequest);
94   diameter::ApplicationId aid = message->getApplicationId();
95
96   LOGDEBUG(
97     std::string msg = "Sending diameter message: ";
98     msg += anna::diameter::functions::commandIdAsPairString(cid);
99     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
100   );
101
102   // Checkings:
103   if(a_deprecated) {
104     string msg(asString());
105     msg += " | ServerSession is deprecated and will be erased";
106     throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
107   }
108
109   if((a_state == State::Closed) && (cid != helpers::base::COMMANDID__Capabilities_Exchange_Answer)) {
110     string msg(asString());
111     msg += " | ServerSession is not bound";
112     throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
113   }
114
115   // CER/DWR are not sent from server-side:
116   if(cid == helpers::base::COMMANDID__Capabilities_Exchange_Request) {
117     string msg(asString());
118     msg += " | Trying to send CER: unexpected message from server-side";
119     throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
120   }
121
122   if(cid == helpers::base::COMMANDID__Device_Watchdog_Request) {
123     string msg(asString());
124     msg += " | Trying to send DWR: unexpected message from server-side";
125     throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
126   }
127
128   // Check states:
129   /*if (cid == helpers::base::COMMANDID__Capabilities_Exchange_Answer) {
130      if (a_state != State::Closed) {
131         string msg(asString());
132         msg += " | Discarding CEA on not closed state";
133         throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
134      }
135
136   } else*/ if(cid ==  helpers::base::COMMANDID__Device_Watchdog_Answer) {
137     if(a_state == State::WaitingDPA) {
138       string msg(asString());
139       msg += " | DWA is not sent on 'WaitingDPA' state";
140       //throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
141       LOGDEBUG(anna::Logger::debug(msg, ANNA_FILE_LOCATION));
142       return NULL;
143     }
144
145     if(a_state == State::Disconnecting) {
146       string msg(asString());
147       msg += " | DWA is not sent on 'Disconnecting' state";
148       //throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
149       LOGDEBUG(anna::Logger::debug(msg, ANNA_FILE_LOCATION));
150       return NULL;
151     }
152   } else if(cid ==  helpers::base::COMMANDID__Disconnect_Peer_Request) {
153     if(a_state == State::WaitingDPA) {
154       string msg(asString());
155       msg += " | Still waiting for DPR ack (DPA)";
156       throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
157     }
158
159     if(a_state == State::Disconnecting) {
160       string msg(asString());
161       msg += " | Server disconnection has already been initiated";
162       throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
163     }
164   } else {
165     if((a_state == State::WaitingDPA) || (a_state == State::Disconnecting)) {
166       if(cid != helpers::base::COMMANDID__Disconnect_Peer_Answer) {
167         LOGDEBUG(
168           string msg("diameter::comm::ServerSession::send | ");
169           msg += asString();
170           msg += " | Sents (request or answer) blocked to diameter client (disconnection in progress). Discarding ...";
171           anna::Logger::debug(msg, ANNA_FILE_LOCATION);
172         );
173         return NULL;
174       }
175     }
176   }
177
178   // Trace send operation:
179   LOGDEBUG(
180     string msg("diameter::comm::ServerSession::send | ");
181     msg += asString();
182     msg += " | ";
183     msg += message->asString();
184     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
185   );
186   bool fixed = false; // answers cannot be fixed
187   Message * message_nc = const_cast<Message*>(message);
188
189   if(isRequest) {
190     // Fixing indicator:
191     fixed = message_nc->fixRequestSequence(a_nextHopByHop, a_nextEndToEnd);
192     message_nc->updateRequestTimestampMs(); // statistics purposes (processing time for request type)
193   }
194
195   // Send message
196   try {
197     message->send(*this);
198
199     // Next hop by hop & end to end identifiers:
200     if(isRequest) generateNextSequences();
201
202     //   Transaction state
203     //         The Diameter protocol requires that agents maintain transaction
204     //         state, which is used for failover purposes.  Transaction state
205     //         implies that upon forwarding a request, the Hop-by-Hop identifier
206     //         is saved; the field is replaced with a locally unique identifier,
207     //         which is restored to its original value when the corresponding
208     //         answer is received.  The request's state is released upon receipt
209     //         of the answer.  A stateless agent is one that only maintains
210     //         transaction state.
211     //
212     updateOutgoingActivityTime();
213     // OAM
214     countSendings(cid, aid, true /* send ok */);
215     // Trace non-application messages:
216     LOGDEBUG(
217
218       if( (cid == helpers::base::COMMANDID__Device_Watchdog_Request) ||
219           (cid == helpers::base::COMMANDID__Disconnect_Peer_Request)) {
220         anna::Logger::debug("Sent DataBlock to XML representation:", ANNA_FILE_LOCATION);
221         try {
222           anna::diameter::codec::Message msg(a_engine->getBaseProtocolCodecEngine()); msg.decode(message->getBody()); /* decode to be traced */
223         }
224         catch(anna::RuntimeException &ex) {
225           std::string msg = ex.getText();
226           msg += " | Use diameter::comm::Engine::setBaseProtocolCodecEngine() to allow internal base protocol messages full tracing";
227           anna::Logger::debug(msg, ANNA_FILE_LOCATION);
228         }
229       }
230     );
231
232     // Restore sequences:
233     if(fixed) message_nc->restoreSequencesAfterFix();  // restore to application sequences after fix
234   } catch(anna::RuntimeException&) {
235     if(fixed) message_nc->restoreSequencesAfterFix();  // restore to application sequences after fix
236
237     // OAM
238     countSendings(cid, aid, false /* send no ok */);
239     throw;
240   }
241
242   // Renew states:
243   /*if (cid ==  helpers::base::COMMANDID__Capabilities_Exchange_Answer) {
244      setState(State::Bound); // Done at sendCEA if proceed
245
246   } else */if(cid ==  helpers::base::COMMANDID__Disconnect_Peer_Request) {
247     LOGWARNING(anna::Logger::warning("DPR has been sent to the peer (diameter client)", ANNA_FILE_LOCATION));
248     setState(State::WaitingDPA);
249   }
250
251   // Answers are not temporized:
252   if(!isRequest) return NULL;
253
254   // Request will have context responses:
255   Response* result(NULL);
256   result = Response::instance(message->getClassCode(), a_nextHopByHop - 1 /* current request sent to client */);
257   result->setRequest(message);
258   response_add(result);
259   return result;
260 }
261
262
263
264 bool ServerSession::unbind(bool forceDisconnect) throw(anna::RuntimeException) {
265   LOGMETHOD(anna::TraceMethod traceMethod(a_className, "unbind", ANNA_FILE_LOCATION));
266
267   if(a_state == State::Closed)
268     return false;
269
270   // Client socket:
271   anna::comm::ClientSocket * cs = a_clientSocket;
272   //anna::comm::ClientSocket * cs = const_cast<anna::comm::ClientSocket*>(a_clientSocket);
273
274   if(forceDisconnect) {
275     LOGDEBUG(anna::Logger::debug("Immediate disconnection (forceDisconnect)", ANNA_FILE_LOCATION));
276
277     if(cs) cs->requestClose();  // this will invoke finalize()
278
279     return true;
280   }
281
282 //   if (a_state == State::Disconnecting) {
283 //      LOGDEBUG(
284 //         string msg("diameter::comm::ServerSession::unbind | ");
285 //         msg += asString();
286 //         msg += " | Disconnection already in progress !";
287 //         anna::Logger::debug(msg, ANNA_FILE_LOCATION);
288 //      );
289 //      return false;
290 //   }
291 //
292 //
293 //   if (a_onDisconnect == OnDisconnect::IgnorePendings) {
294 //      LOGDEBUG(anna::Logger::debug("Immediate disconnection (IgnorePendings)", ANNA_FILE_LOCATION));
295 //
296 //      if (cs) cs->requestClose(); // this will invoke finalize()
297 //
298 //      return true;
299 //   }
300 //
301 //   if (getOTARequests() == 0) { // No pendings
302 //      LOGDEBUG(anna::Logger::debug("No pending answers. Perform client-session close.", ANNA_FILE_LOCATION));
303 //
304 //      if (cs) cs->requestClose(); // this will invoke finalize()
305 //
306 //      return true;
307 //   }
308   return false;
309 }
310
311 void ServerSession::eventPeerShutdown() throw() {
312   // Inform father server:
313   a_parent->eventPeerShutdown(this);
314 }
315
316 void ServerSession::eventRequestRetransmission(Message *request) throw() {
317   // Inform father server:
318   a_parent->eventRequestRetransmission(this, request);
319 }
320
321 void ServerSession::eventResponse(const Response& response) throw(anna::RuntimeException) {
322   // Inform father server:
323   a_parent->eventResponse(response);
324 }
325
326 void ServerSession::eventRequest(const anna::DataBlock &request) throw(anna::RuntimeException) {
327   // Inform father server:
328   a_parent->eventRequest(this, request);
329 }
330
331 void ServerSession::eventUnknownResponse(const anna::DataBlock& response) throw(anna::RuntimeException) {
332   // Inform father server:
333   a_parent->eventUnknownResponse(this, response);
334 }
335
336 void ServerSession::eventDPA(const anna::DataBlock& response) throw(anna::RuntimeException) {
337   // Inform father server:
338   a_parent->eventDPA(this, response);
339 }
340
341 //------------------------------------------------------------------------------------------
342 // Se invoca desde el diameter::comm::Receiver
343 //------------------------------------------------------------------------------------------
344 void ServerSession::receive(const anna::comm::Message& message)
345 throw(anna::RuntimeException) {
346   LOGMETHOD(anna::TraceMethod traceMethod(a_className, "receive", ANNA_FILE_LOCATION));
347   // Activity:
348   updateIncomingActivityTime();
349   activateTimer();
350   // Command id:
351   const anna::DataBlock & db = message.getBody();
352   diameter::CommandId cid = codec::functions::getCommandId(db);
353   bool isRequest = cid.second;
354   LOGDEBUG(
355     std::string msg = "Received diameter message: ";
356     msg += anna::diameter::functions::commandIdAsPairString(cid);
357     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
358
359     if( (cid == helpers::base::COMMANDID__Capabilities_Exchange_Request) ||
360         (cid.first == helpers::base::COMMANDID__Device_Watchdog_Request.first)) {
361       try {
362         anna::diameter::codec::Message dmsg(a_engine->getBaseProtocolCodecEngine()); dmsg.decode(db); /* decode to be traced */
363       }
364       catch(anna::RuntimeException &ex) {
365         std::string msg = ex.getText();
366         msg += " | Use diameter::comm::Engine::setBaseProtocolCodecEngine() to allow internal base protocol messages full tracing";
367         anna::Logger::debug(msg, ANNA_FILE_LOCATION);
368       }
369     }
370   );
371   // Main counters:
372   OamModule &oamModule = OamModule::instantiate();
373   oamModule.count(isRequest ? OamModule::Counter::RequestReceived : OamModule::Counter::AnswerReceived);
374   oamModule.count(isRequest ? OamModule::Counter::RequestReceivedOnServerSession : OamModule::Counter::AnswerReceivedOnServerSession);
375   // Statistic (size)
376   a_parent->updateReceivedMessageSizeStatisticConcept(message.getSize()); // only on reception (application could manage sent sizes)
377
378   if(isRequest) {
379     // Si recibo un request, el message solo tiene fiable el DataBlock. Como por defecto se construye como ApplicationMessage,
380     // el unico caso que no cuadraria seria la recepcion de un CER. Lo que hacemos es NO PROGRESAR NUNCA un CER (*).
381     // El DWR sin embargo, si podriamos progresarlo al ser de aplicacion, pero no les sirve para nada (**).
382     /////////////////////////////
383     // Here received a request //
384     /////////////////////////////
385
386     // Received CER
387     if(cid == helpers::base::COMMANDID__Capabilities_Exchange_Request) {
388       oamModule.count(OamModule::Counter::CERReceived);
389
390       if(a_state == State::Bound) {
391         LOGWARNING(anna::Logger::warning("Received another CER over already bound connection. Anyway, will be replied with CEA", ANNA_FILE_LOCATION));
392       }
393
394       a_cer.setBody(db);
395       sendCEA();
396       //activateTimer(); // Ya se invoca al inicio de este metodo ::receive
397       //bool changes = a_parent->refreshAvailability();
398       return; // (*)
399     }
400     // Received DWR
401     else if(cid == helpers::base::COMMANDID__Device_Watchdog_Request) {
402       oamModule.count(OamModule::Counter::DWRReceived);
403       a_dwr.setBody(db);
404       sendDWA();
405       return; // (**)
406     }
407     // Received DPR
408     else if(cid == helpers::base::COMMANDID__Disconnect_Peer_Request) {
409       oamModule.count(OamModule::Counter::DPRReceived);
410
411       if(a_state == State::Bound) {
412         a_dpr.setBody(db);
413         setState(State::Disconnecting);
414         LOGWARNING(anna::Logger::warning("DPR has been received from peer (diameter client)", ANNA_FILE_LOCATION));
415         // Ignore pending on server sessions:
416         /*if (getOTARequests() == 0) */sendDPA();
417         return; // DPR won't be informed because virtual readDPA is available for this
418       }
419     }
420
421     try {
422       // application message counters
423       ApplicationMessageOamModule::instantiate().count(cid.first, anna::diameter::codec::functions::getApplicationId(db), ApplicationMessageOamModule::Counter::Request_Received_AsServer);
424
425       eventRequest(db);
426     } catch(anna::RuntimeException& ex) {
427       ex.trace();
428     }
429
430     return;
431   }
432
433   /////////////////////////////
434   // Here received an answer //
435   /////////////////////////////
436   bool doUnbind = false;
437   int resultCode = 0;
438
439   try {
440     resultCode = helpers::base::functions::getResultCode(db);
441   } catch(anna::RuntimeException& ex) {
442     ex.trace();
443   }
444
445   // Received DPA
446   if(cid == helpers::base::COMMANDID__Disconnect_Peer_Answer) {
447     oamModule.count(OamModule::Counter::DPAReceived);
448
449     if(a_state == State::WaitingDPA) {
450       if(resultCode != helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS) {
451         LOGWARNING(anna::Logger::warning("Received DPA with non-success Result-Code. Ignoring and recovering Bound state", ANNA_FILE_LOCATION));
452         setState(State::Bound);
453       } else {
454         LOGWARNING(anna::Logger::warning("Received DPA With Result-Code = DIAMETER_SUCCESS. Disconnect now.", ANNA_FILE_LOCATION));
455         doUnbind = true;
456       }
457     }
458
459     eventDPA(db);
460
461   } else if(cid == helpers::base::COMMANDID__Device_Watchdog_Answer) {  // non usual (server should not send DWR's)
462     oamModule.count(OamModule::Counter::DWAReceived);
463   }
464
465   HopByHop hopByHop = codec::functions::getHopByHop(db); // context identification
466   Response* response = response_find(hopByHop);
467
468   // Out-of-context responses:
469   if(!response) {
470     // OAM
471     oamModule.count(OamModule::Counter::AnswerReceivedUnknown);
472     oamModule.count(OamModule::Counter::AnswerReceivedOnServerSessionUnknown);
473     oamModule.activateAlarm(OamModule::Alarm::AnswerReceivedOnServerSessionUnknown);
474
475     // application message counters
476     ApplicationMessageOamModule::instantiate().count(cid.first, anna::diameter::codec::functions::getApplicationId(db), ApplicationMessageOamModule::Counter::Answer_UnknownReceived_AsServer);
477
478     eventUnknownResponse(db);
479
480     string msg(asString());
481     msg += anna::functions::asString(" | Response received from client, for non registered context (HopByHop: %u)", hopByHop);
482     throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
483   }
484
485   response->setResultCode(Response::ResultCode::Success);
486   response->cancelTimer();
487   LOGDEBUG(
488     string msg("diameter::comm::ServerSession::receive | ");
489     msg += asString();
490     msg += " | Received answer";
491     msg += response->asString();
492     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
493   );
494   // Statistics
495   anna::Millisecond current = (anna::Millisecond)anna::functions::millisecond();
496   anna::Millisecond request = response->getRequest()->getRequestTimestampMs();
497   anna::Millisecond timeToAnswerMs = current - request;
498   a_parent->updateProcessingTimeStatisticConcept(timeToAnswerMs);
499   LOGDEBUG
500   (
501     std::string msg = "This diameter request context lasted ";
502     msg += anna::functions::asString(timeToAnswerMs);
503     msg += " milliseconds at diameter client (included network time)";
504     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
505   );
506   // Progress origin for tracking purposes on asyncronous boxes with both diameter interfaces (entities and clients)
507   Message * requestMessage = const_cast<Message*>(response->getRequest());
508   requestMessage->setRequestClientSessionKey(response->getRequest()->getRequestClientSessionKey()); // "" means unkown/unset
509
510   if(cid != helpers::base::COMMANDID__Disconnect_Peer_Answer) {
511     // don't progress DPA: unbind is automatically performed and not open to any application decision
512     try {
513       response->setMessage(&db);
514       // Restore received datablock
515       LOGDEBUG(
516         string msg("diameter::comm::ClientSession::receive | Restore answer to original request sequences (hop-by-hop = ");
517         msg += anna::functions::asString(response->getRequest()->getRequestHopByHop());
518         msg += ", end-to-end = ";
519         msg += anna::functions::asString(response->getRequest()->getRequestEndToEnd());
520         msg += ")";
521         anna::Logger::debug(msg, ANNA_FILE_LOCATION);
522       );
523       diameter::codec::functions::setHopByHop((anna::DataBlock&)db, response->getRequest()->getRequestHopByHop());
524       diameter::codec::functions::setEndToEnd((anna::DataBlock&)db, response->getRequest()->getRequestEndToEnd());
525
526       // application message counters
527       ApplicationMessageOamModule::instantiate().count(cid.first, anna::diameter::codec::functions::getApplicationId(db), ApplicationMessageOamModule::Counter::Answer_Received_AsServer);
528
529       eventResponse(*response);
530
531     } catch(anna::RuntimeException& ex) {
532       ex.trace();
533     }
534   }
535
536   response_erase(response);
537
538   // Unbind trigger
539   if(doUnbind)
540     unbind(true /* always immediate */);
541 }
542
543 void ServerSession::finalize() throw() {
544   LOGMETHOD(anna::TraceMethod traceMethod(a_className, "finalize", ANNA_FILE_LOCATION));
545   // Configuration overiddings
546   setOnDisconnect(OnDisconnect::IgnorePendings);
547   notifyOrphansOnExpiration(false);
548   // session will be idle after 'Session::finalize'
549   // (anyway at 99% of the cases, server session would be idle because is not usual to send request from diameter servers)
550   // Closing state won't be used on server-sessions
551   Session::finalize(); // sets closed state (unbind at closeServerSession won't repeat client socket close, because returns at the beginning)
552   // stops timers
553
554   // "delete this" indirecto (seria mas elegante borrar las server sessions deprecated mediante un temporizador de purgado)
555   try {
556     if(idle()) getParent()->closeServerSession(this);  // http://www.parashift.com/c++-faq-lite/delete-this.html
557   } catch(anna::RuntimeException& ex) {
558     ex.trace();
559   }
560
561   // Inform father local server (availability changes):
562   bool changes = getParent()->refreshAvailability();
563   // OAM
564   bool multipleConnections = (getParent()->getMaxConnections() > 1);
565   std::string socket = anna::functions::socketLiteralAsString(getAddress(), getPort());
566   OamModule &oamModule = OamModule::instantiate();
567
568   if(multipleConnections) {
569     oamModule.activateAlarm(OamModule::Alarm::LostConnectionForServerSessionAtLocalServer__s__ServerSessionId__d__, socket.c_str(), getSocketId());
570     oamModule.count(OamModule::Counter::LostConnectionForServerSession);
571   } else {
572     oamModule.activateAlarm(OamModule::Alarm::LostConnectionForServerSessionAtLocalServer__s__, socket.c_str());
573     oamModule.count(OamModule::Counter::LostConnectionForServerSession);
574   }
575 }
576
577
578
579 void ServerSession::sendCEA()
580 throw(anna::RuntimeException) {
581   LOGMETHOD(anna::TraceMethod traceMethod(a_className, "sendCEA", ANNA_FILE_LOCATION));
582   anna::DataBlock cea(true);
583   a_engine->readCEA(cea, a_cer.getBody()); // Asume that CEA is valid ...
584   // If one peer sends a CER message to another Peer and receiver does not have support for
585   //
586   //  1) any common application then it must return the CEA with Result-Code Avp set to DIAMETER_NO_COMMON_APPLICATION
587   //     and should disconnect the transport layer connection (automatically done by diameter::comm module).
588   //  2) no common security mechanism then it must return the CEA with Result-Code Avp set to DIAMETER_NO_COMMON_SECURITY
589   //     and should disconnect the transport layer connection (automatically done by diameter::comm module).
590   //  3) if CER is received from any unknown peer then receiver should discard the message, or send the CEA with the
591   //     Result-Code Avp set to DIAMETER_UNKNOWN_PEER.
592
593   if(cea.isEmpty()) {
594     LOGDEBUG(anna::Logger::debug("Empty CEA message. Remote client never will bound this connection at application level", ANNA_FILE_LOCATION));
595     LOGWARNING(anna::Logger::warning("Discarding received CER: cannot send empty CEA (consider to send CEA with Result-Code DIAMETER_UNKNOWN_PEER)", ANNA_FILE_LOCATION));
596     return;
597   }
598
599   Message msgCea;
600   msgCea.setBody(cea);
601   send(&msgCea);
602   // Here, CEA has been sent (no exception). Analize CEA Result-Code chosen:
603   int resultCode = 0;
604
605   try {
606     resultCode = helpers::base::functions::getResultCode(cea);
607   } catch(anna::RuntimeException& ex) {
608     ex.trace();
609   }
610
611   switch(resultCode) {
612   case helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS:
613     setState(State::Bound);
614     break;
615   case helpers::base::AVPVALUES__Result_Code::DIAMETER_NO_COMMON_APPLICATION:
616     LOGWARNING(anna::Logger::warning("DIAMETER_NO_COMMON_APPLICATION CEA Result-Code implies unbinding connection", ANNA_FILE_LOCATION));
617     unbind(true /* always immediate */); // no delegamos en un planning o similar
618     // Realmente el cliente diameter tambien deberia cerrar la conexion al recibir este Result-Code
619     break;
620   case helpers::base::AVPVALUES__Result_Code::DIAMETER_NO_COMMON_SECURITY:
621     LOGWARNING(anna::Logger::warning("DIAMETER_NO_COMMON_SECURITY CEA Result-Code implies unbinding connection", ANNA_FILE_LOCATION));
622     unbind(true /* always immediate */); // no delegamos en un planning o similar
623     // Realmente el cliente diameter tambien deberia cerrar la conexion al recibir este Result-Code
624     break;
625     // ...
626     // ...
627   }
628 }
629
630 void ServerSession::sendDWA()
631 throw(anna::RuntimeException) {
632   LOGMETHOD(anna::TraceMethod traceMethod(a_className, "sendDWA", ANNA_FILE_LOCATION));
633   anna::DataBlock dwa(true);
634   a_engine->readDWA(dwa, a_dwr.getBody()); // Asume that DWA is valid ...
635
636   if(dwa.isEmpty())
637     throw anna::RuntimeException("This diameter agent defines an empty DWA message. Remote client never will validate this connection health", ANNA_FILE_LOCATION);
638
639   Message msgDwa;
640   msgDwa.setBody(dwa);
641   send(&msgDwa);
642 }
643
644
645 //-------------------------------------------------------------------------
646 // Se invoca desde diameter::comm::Timer
647 //-------------------------------------------------------------------------
648 void ServerSession::expireResponse(diameter::comm::Response* response)
649 throw() {
650   LOGMETHOD(anna::TraceMethod traceMethod(a_className, "expireResponse", ANNA_FILE_LOCATION));
651   Session::expireResponse(response);
652   // OAM
653   OamModule &oamModule = OamModule::instantiate();
654   oamModule.count(OamModule::Counter::RequestSentExpired);
655   oamModule.count(OamModule::Counter::RequestSentOnServerSessionExpired);
656   oamModule.activateAlarm(OamModule::Alarm::RequestSentOnServerSessionExpired);
657 //   // "delete this" indirecto (seria mas elegante borrar las server sessions deprecated mediante un temporizador de purgado)
658 //   if (idle()) a_parent->eraseServerSession(*a_clientSocket); // http://www.parashift.com/c++-faq-lite/delete-this.html
659 }
660
661 std::string ServerSession::asString() const
662 throw() {
663   string result = Session::asString();
664   result += " | Parent Local Server: ";
665   result += anna::functions::socketLiteralAsString(getAddress(), getPort());
666   result += " | Client Socket: ";
667   result += a_clientSocket->asString();
668   // Diferente del timeout de ApplicationMessage:
669   result += " | Allowed inactivity time: ";
670   result += getTimeout().asString();
671   result += " | Deprecated: ";
672   result += (a_deprecated ? "yes" : "no");
673   return result += " }";
674 }
675
676 anna::xml::Node* ServerSession::asXML(anna::xml::Node* parent) const
677 throw() {
678   anna::xml::Node* result = Session::asXML(parent);
679   parent->createChild("diameter.comm.ServerSession");
680   result->createAttribute("ParentLocalServer", anna::functions::socketLiteralAsString(getAddress(), getPort()));
681   result->createAttribute("ClientSocket", a_clientSocket->asString());
682   // Diferente del timeout de ApplicationMessage:
683   result->createAttribute("AllowedInactivityTime", getTimeout().asString());
684   result->createAttribute("Deprecated", a_deprecated ? "yes" : "no");
685   return result;
686 }
687
688
689 //------------------------------------------------------------------------------
690 //------------------------------------------------------ ServerSession::expire()
691 //------------------------------------------------------------------------------
692 void ServerSession::expire(anna::timex::Engine *timeController) throw(anna::RuntimeException) {
693   LOGMETHOD(anna::TraceMethod traceMethod(a_className, "expire (inactivity check timer)", ANNA_FILE_LOCATION));
694   LOGWARNING(anna::Logger::warning("Detecting anomaly (too inactivity time) over server session. Resetting", ANNA_FILE_LOCATION));
695   // OAM
696   bool multipleConnections = (getParent()->getMaxConnections() > 1);
697   std::string socket = anna::functions::socketLiteralAsString(getAddress(), getPort());
698   OamModule &oamModule = OamModule::instantiate();
699
700   if(multipleConnections) {
701     oamModule.activateAlarm(OamModule::Alarm::UnbindConnectionForServerSessionAtLocalServer__s__ServerSessionId__d__DueToInactivityTimeAnomaly, socket.c_str(), getSocketId());
702     oamModule.count(OamModule::Counter::UnbindConnectionForServerSessionDueToInactivityTimeAnomaly);
703   } else {
704     oamModule.activateAlarm(OamModule::Alarm::UnbindConnectionForServerSessionAtLocalServer__s__DueToInactivityTimeAnomaly, socket.c_str());
705     oamModule.count(OamModule::Counter::UnbindConnectionForServerSessionDueToInactivityTimeAnomaly);
706   }
707
708   unbind(true /* always immediate */); // no delegamos en un planning o similar
709 }
710
711 void ServerSession::setAllowedInactivityTime(const anna::Millisecond & allowedInactivityTime) throw() {
712   setTimeout(allowedInactivityTime);
713 }
714
715 //------------------------------------------------------------------------------
716 //---------------------------------- ServerSession::updateIncomingActivityTime()
717 //------------------------------------------------------------------------------
718 void ServerSession::updateIncomingActivityTime() throw() {
719   Session::updateIncomingActivityTime();
720   a_parent->updateIncomingActivityTime();
721 }
722
723
724 //------------------------------------------------------------------------------
725 //---------------------------------- ServerSession::updateOutgoingActivityTime()
726 //------------------------------------------------------------------------------
727 void ServerSession::updateOutgoingActivityTime(void) throw() {
728   Session::updateOutgoingActivityTime();
729   a_parent->updateOutgoingActivityTime();
730 }
731
732
733 //------------------------------------------------------------------------------
734 //----------------------------------------------- ServerSession::countSendings()
735 //------------------------------------------------------------------------------
736 void ServerSession::countSendings(const diameter::CommandId & cid, unsigned int aid, bool ok)throw() {
737   OamModule &oamModule = OamModule::instantiate();
738   ApplicationMessageOamModule &appMsgOamModule = ApplicationMessageOamModule::instantiate();
739
740   bool isRequest = cid.second;
741
742   if(ok) {
743     // Main counters:
744     oamModule.count(isRequest ? OamModule::Counter::RequestSentOK : OamModule::Counter::AnswerSentOK);
745     oamModule.count(isRequest ? OamModule::Counter::RequestSentOnServerSessionOK : OamModule::Counter::AnswerSentOnServerSessionOK);
746
747     if(cid == helpers::base::COMMANDID__Capabilities_Exchange_Answer) oamModule.count(OamModule::Counter::CEASentOK);
748     else if(cid == helpers::base::COMMANDID__Device_Watchdog_Answer) oamModule.count(OamModule::Counter::DWASentOK);
749     else if(cid == helpers::base::COMMANDID__Device_Watchdog_Request) oamModule.count(OamModule::Counter::DWRSentOK);  // not usual
750     else if(cid == helpers::base::COMMANDID__Disconnect_Peer_Answer) oamModule.count(OamModule::Counter::DPASentOK);
751     else if(cid == helpers::base::COMMANDID__Disconnect_Peer_Request) oamModule.count(OamModule::Counter::DPRSentOK);
752     // Application messages:
753     else {
754       appMsgOamModule.count(cid.first, aid, isRequest ? ApplicationMessageOamModule::Counter::Request_SentOK_AsServer : ApplicationMessageOamModule::Counter::Answer_SentOK_AsServer);
755     }
756   } else {
757     // Main counters:
758     oamModule.count(isRequest ? OamModule::Counter::RequestSentNOK : OamModule::Counter::AnswerSentNOK);
759     oamModule.count(isRequest ? OamModule::Counter::RequestSentOnServerSessionNOK : OamModule::Counter::RequestSentOnServerSessionNOK);
760
761     if(cid == helpers::base::COMMANDID__Capabilities_Exchange_Answer) oamModule.count(OamModule::Counter::CEASentNOK);
762     else if(cid == helpers::base::COMMANDID__Device_Watchdog_Answer) oamModule.count(OamModule::Counter::DWASentNOK);
763     else if(cid == helpers::base::COMMANDID__Device_Watchdog_Request) oamModule.count(OamModule::Counter::DWRSentNOK);  // not usual
764     else if(cid == helpers::base::COMMANDID__Disconnect_Peer_Answer) oamModule.count(OamModule::Counter::DPASentNOK);
765     else if(cid == helpers::base::COMMANDID__Disconnect_Peer_Request) oamModule.count(OamModule::Counter::DPRSentNOK);
766     // Application messages:
767     else {
768       appMsgOamModule.count(cid.first, aid, isRequest ? ApplicationMessageOamModule::Counter::Request_SentNOK_AsServer : ApplicationMessageOamModule::Counter::Answer_SentNOK_AsServer);
769     }
770   }
771 }
772
773