Message cleared on demand (if you want to reuse and the codec engine may be different)
[anna.git] / source / diameter / codec / Message.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 // Local
10 #include <anna/diameter/codec/Message.hpp>
11 #include <anna/diameter/codec/Format.hpp>
12
13 #include <anna/diameter/codec/functions.hpp> // REQUIRED_WORDS
14 #include <anna/config/defines.hpp> // general types, decoding helpers (DECODE[2/3/4]BYTES_INDX_VALUETYPE), etc.
15 #include <anna/diameter/functions.hpp>
16 #include <anna/diameter/codec/functions.hpp> // REQUIRED_WORDS
17 #include <anna/diameter/codec/OamModule.hpp>
18 #include <anna/diameter/codec/Engine.hpp>
19 #include <anna/diameter/codec/EngineManager.hpp>
20 #include <anna/diameter/stack/Avp.hpp>
21 #include <anna/diameter/stack/Format.hpp>
22 #include <anna/diameter/stack/Dictionary.hpp>
23 #include <anna/diameter/stack/Engine.hpp>
24 #include <anna/core/functions.hpp>
25 #include <anna/core/util/RegularExpression.hpp>
26 #include <anna/diameter/helpers/base/defines.hpp>
27
28 #include <anna/core/tracing/Logger.hpp>
29 #include <anna/core/functions.hpp>
30 #include <anna/core/tracing/TraceMethod.hpp>
31 #include <anna/xml/xml.hpp>
32
33 // STL
34 #include <string>
35 #include <vector>
36
37
38 using namespace anna;
39 using namespace anna::diameter::codec;
40
41
42 //static
43 namespace anna {
44
45 namespace diameter {
46
47 namespace codec {
48 const int Message::HeaderLength(20);
49 const U8 Message::RBitMask(0x80);
50 const U8 Message::PBitMask(0x40);
51 const U8 Message::EBitMask(0x20);
52 const U8 Message::TBitMask(0x10);
53 }
54 }
55 }
56
57 //------------------------------------------------------------------------------
58 //----------------------------------------------------------- Message::Message()
59 //------------------------------------------------------------------------------
60 Message::Message(Engine *engine) : a_engine(engine), a_forCode(true) {
61   initialize();
62 }
63
64
65 //------------------------------------------------------------------------------
66 //----------------------------------------------------------- Message::Message()
67 //------------------------------------------------------------------------------
68 Message::Message(CommandId id, Engine *engine) : a_engine(engine), a_forCode(true) {
69   initialize();
70   setId(id);
71 }
72
73
74 //------------------------------------------------------------------------------
75 //---------------------------------------------------------- Message::~Message()
76 //------------------------------------------------------------------------------
77 Message::~Message() {
78   clear();
79 }
80
81
82 //------------------------------------------------------------------------------
83 //--------------------------------------------------------- Message::setEngine()
84 //------------------------------------------------------------------------------
85 void Message::setEngine(Engine *engine) throw() {
86
87   if (a_engine && engine != a_engine) {
88     LOGWARNING(anna::Logger::warning("Ignored: it is not a good practice to change the codec engine once assigned. Clear the message first to set the engine again.", ANNA_FILE_LOCATION));
89     return;
90   }
91
92   a_engine = engine;
93 }
94
95
96 //------------------------------------------------------------------------------
97 //--------------------------------------------------------- Message::getEngine()
98 //------------------------------------------------------------------------------
99 Engine * Message::getEngine() const throw(anna::RuntimeException) {
100   if(!a_engine)
101     throw anna::RuntimeException("Invalid codec engine reference (NULL). Use setEngine() to set the corresponding codec engine", ANNA_FILE_LOCATION);
102
103   return a_engine;
104
105 }
106
107
108 //------------------------------------------------------------------------------
109 //-------------------------------------------------------- Message::initialize()
110 //------------------------------------------------------------------------------
111 void Message::initialize() throw() {
112   a_version = 1;
113   a_id = CommandId(0, false);
114   a_flags = 0x00;
115   a_applicationId = 0;
116   a_hopByHop = 0;
117   a_endToEnd = 0;
118   //a_avps.clear();
119   a_insertionPositionForChilds = 0;
120   //a_finds.clear();
121 }
122
123
124 //------------------------------------------------------------------------------
125 //------------------------------------------------------------- Message::clear()
126 //------------------------------------------------------------------------------
127 void Message::clear() throw(anna::RuntimeException) {
128   for(avp_iterator it = avp_begin(); it != avp_end(); it++) { /*avp(it)->clear(); */getEngine()->releaseAvp(Avp::avp(it)); }
129
130   a_avps.clear();
131   a_forCode.clear();
132   // Cache system:
133   a_finds.clear();
134   // Initialize:
135   initialize();
136 }
137
138
139 //------------------------------------------------------------------------------
140 //----------------------------------------------------------- Message::flagsOK()
141 //------------------------------------------------------------------------------
142 bool Message::flagsOK(int &rc) const throw() {
143   // Dictionary stack command:
144   const stack::Command *stackCommand = getStackCommand();
145
146   if(!stackCommand) {
147     anna::Logger::error("Impossible to decide if flags are correct because stack command is not identified. Assume flags ok", ANNA_FILE_LOCATION);
148     //rc = helpers::base::AVPVALUES__Result_Code::?????;
149     return true;
150   };
151
152   // DIAMETER_INVALID_HDR_BITS 3008
153   //
154   //      A request was received whose bits in the Diameter header were set
155   //      either to an invalid combination or to a value that is
156   //      inconsistent with the Command Code's definition.
157   bool ok = true;
158
159   if(stackCommand->isRequest() != isRequest()) ok = false;  // en teoria es imposible salir por aqui: blindado en la dtd
160
161   if(isRequest() && errorBit()) {
162     anna::Logger::error("E(rror) bit is not allowed at diameter requests", ANNA_FILE_LOCATION);
163     ok = false;
164   }
165
166   if(isAnswer() && potentiallyReTransmittedMessageBit()) {
167     anna::Logger::error("T(Potentially re-transmitted message) bit is not allowed at diameter answers", ANNA_FILE_LOCATION);
168     ok = false;
169   }
170
171   if(!ok) {
172     rc = helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_HDR_BITS;
173     return false;
174   }
175
176   // DIAMETER_INVALID_BIT_IN_HEADER 5013
177   //
178   //      This error is returned when a reserved bit in the Diameter header
179   //      is set to one (1) or the bits in the Diameter header are set
180   //      incorrectly.
181   if((a_flags & 0x0f) != 0x00) {
182     anna::Logger::error("Any (or more than one) of the reserved message flags bit has been activated. Reserved bits must be null", ANNA_FILE_LOCATION);
183     rc = helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_BIT_IN_HEADER;
184     return false;
185   }
186
187   return true;
188 }
189
190
191 //------------------------------------------------------------------------------
192 //------------------------------------------------------------- Message::setId()
193 //------------------------------------------------------------------------------
194 void Message::setId(CommandId id) throw(anna::RuntimeException) {
195
196   // Id assignment:
197   a_id = id;
198   // Dictionary stack command:
199   const stack::Command *stackCommand = getStackCommand(); // based on dictionary and a_id
200
201   // Dictionary flags for known types:
202   if(stackCommand) {
203     if(stackCommand->isRequest()) a_flags |= RBitMask;
204   } else {
205     if(a_id.second) a_flags |= RBitMask; else a_flags &= (~RBitMask);
206   }
207 }
208
209
210 //------------------------------------------------------------------------------
211 //------------------------------------------------------------- Message::setId()
212 //------------------------------------------------------------------------------
213 void Message::setId(const char *name) throw(anna::RuntimeException) {
214   setId(getEngine()->commandIdForName(name));
215 }
216
217
218 //------------------------------------------------------------------------------
219 //-------------------------------------------------- Message::setApplicationId()
220 //------------------------------------------------------------------------------
221 void Message::setApplicationId(U32 aid) throw(anna::RuntimeException) {
222   a_applicationId = aid;
223
224   // Automatic engine configuration:
225   if (a_engine) return;
226
227   // Codec engine manager (a multithreaded application, normally does not achieve this point, because
228   // messages are prepared for each interface with the corresponding codec engine)
229   anna::diameter::codec::EngineManager &em = anna::diameter::codec::EngineManager::instantiate();
230   if (em.selectFromApplicationId()) {
231     Engine *monostackEngine = em.getMonoStackCodecEngine();
232     if (monostackEngine) { a_engine = monostackEngine; return; }
233     a_engine = em.getCodecEngine(aid);
234   }
235 }
236
237
238 //------------------------------------------------------------------------------
239 //------------------------------------------------------------ Message::addAvp()
240 //------------------------------------------------------------------------------
241 Avp * Message::addAvp(const char *name) throw(anna::RuntimeException) {
242   return addAvp(getEngine()->avpIdForName(name));
243 }
244
245
246 //------------------------------------------------------------------------------
247 //------------------------------------------------------------ Message::addAvp()
248 //------------------------------------------------------------------------------
249 Avp * Message::addAvp(Avp * avp) throw() {
250   if(!avp) return NULL;
251   if (avp->getEngine() != getEngine()) return NULL;
252   addChild(avp);
253   return avp;
254 }
255
256
257 //------------------------------------------------------------------------------
258 //--------------------------------------------------------- Message::removeAvp()
259 //------------------------------------------------------------------------------
260 bool Message::removeAvp(const char *name, int ocurrence) throw(anna::RuntimeException) {
261   return removeAvp(getEngine()->avpIdForName(name), ocurrence);
262 }
263
264
265 //------------------------------------------------------------------------------
266 //----------------------------------------------------------- Message::_getAvp()
267 //------------------------------------------------------------------------------
268 const Avp * Message::_getAvp(const char *name, int ocurrence, anna::Exception::Mode::_v emode) const throw(anna::RuntimeException) {
269   return getAvp(getEngine()->avpIdForName(name), ocurrence, emode);
270 }
271
272
273 //------------------------------------------------------------------------------
274 //---------------------------------------------------------- Message::countAvp()
275 //------------------------------------------------------------------------------
276 int Message::countAvp(const char *name) const throw(anna::RuntimeException) {
277   return countAvp(getEngine()->avpIdForName(name));
278 }
279
280
281 //------------------------------------------------------------------------------
282 //--------------------------------------------------------- Message::getLength()
283 //------------------------------------------------------------------------------
284 U24 Message::getLength() const throw() {
285   U24 result;
286   // Header length:
287   result = HeaderLength;
288
289   for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) result += 4 * REQUIRED_WORDS(Avp::avp(it)->getLength());
290
291   return result;
292 }
293
294
295 //------------------------------------------------------------------------------
296 //------------------------------------------------------------ Message::decode()
297 //------------------------------------------------------------------------------
298 void Message::decode(const anna::DataBlock &db, Message *ptrAnswer) throw(anna::RuntimeException) {
299   // Trace
300   LOGDEBUG(
301       anna::xml::Node root("Message::decode");
302   std::string trace = "DataBlock to decode:\n";
303   trace += db.asString();
304   anna::Logger::debug(trace, ANNA_FILE_LOCATION);
305   );
306   clear();
307   // EXCEPTION MANAGEMENT IN THIS METHOD
308   // ===================================
309   // DECODE PHASE
310   // If an error ocurred, decoding will stop launching exception but we will catch it and go on with validation because perhaps
311   //  the achieved message could be valid against all odds. Only fatal errors cause direct decoding exception (length problems
312   //  at header).
313   //
314   // VALIDATION PHASE
315   // Launch exception on first validation error (validateAll == false), or log warning reporting all validation errors when
316   //  complete validation is desired (validateAll == true, engine default) launching a final exception like "the decoded message is invalid".
317   // OAM
318   OamModule &oamModule = OamModule::instantiate();
319
320   if(db.getSize() < HeaderLength) {
321     oamModule.activateAlarm(OamModule::Alarm::MessageDecode__NotEnoughBytesToCoverMessageHeaderLength);
322     oamModule.count(OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageHeaderLength);
323     // DIAMETER_INVALID_MESSAGE_LENGTH; // no podr� construir un answer fiable, as� que no registro el result-code
324     throw anna::RuntimeException("Not enough bytes to cover message header length (20 bytes)", ANNA_FILE_LOCATION);
325   }
326
327   const char * buffer = db.getData();
328
329   //         0                   1                   2                   3
330   //         0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
331   //        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
332   //        |    Version    |                 Message Length                |
333   //        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
334   //        | command flags |                  Command-Code                 |
335   //        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
336   //        |                         Application-ID                        |
337   //        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
338   //        |                      Hop-by-Hop Identifier                    |
339   //        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
340   //        |                      End-to-End Identifier                    |
341   //        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
342   //        |  AVPs ...
343   //        +-+-+-+-+-+-+-+-+-+-+-+-+-
344   // Header fields:
345   a_version = (S8)buffer[0];
346
347   U24 length = DECODE3BYTES_INDX_VALUETYPE(buffer, 1, U24); // total length including header fields
348
349   a_flags = (S8)buffer[4];
350
351   U24 code = DECODE3BYTES_INDX_VALUETYPE(buffer, 5, U24);
352
353   a_id = CommandId(code, requestBit() /* based on a_flags */);
354
355   setApplicationId(DECODE4BYTES_INDX_VALUETYPE(buffer, 8, U32)); // centralize set, because it could be used for stack selection.
356
357   a_hopByHop = DECODE4BYTES_INDX_VALUETYPE(buffer, 12, U32);
358
359   a_endToEnd = DECODE4BYTES_INDX_VALUETYPE(buffer, 16, U32);
360
361   // Only build answer for a request:
362   Message *answer = isRequest() ? ptrAnswer : NULL;
363
364   if(answer) answer->setHeaderToAnswer(*this);
365
366   // Length check:
367   if(db.getSize() < length) {
368     oamModule.activateAlarm(OamModule::Alarm::MessageDecode__NotEnoughBytesToCoverMessageLength);
369     oamModule.count(OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageLength);
370
371     if(answer) answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_MESSAGE_LENGTH);
372
373     throw anna::RuntimeException("Not enough bytes to cover message length", ANNA_FILE_LOCATION);
374   }
375
376   // Message identifier
377   // Flags could have been updated regarding dictionary, but during decoding we must respect buffer received:
378   a_flags = (S8)buffer[4];
379   // Avps start position:
380   const S8 * startData = buffer + HeaderLength;
381   U24 dataBytes = length - HeaderLength;
382
383   if(dataBytes < 8 /* minimum avp */) {
384     LOGDEBUG(anna::Logger::debug("Message empty (without avps)", ANNA_FILE_LOCATION));
385     return;
386   }
387
388   int avpPos = 0;
389   Avp* avp;
390   anna::DataBlock db_aux;
391
392   // Parent information:
393   parent_t parent;
394   parent.setMessage(a_id);
395
396
397   while(avpPos < dataBytes) {
398     try {
399       avp =  getEngine()->createAvp(NULL);
400       db_aux.assign(startData + avpPos, dataBytes - avpPos /* is valid to pass total length (indeed i don't know the real avp length) because it will be limited and this has deep copy disabled (no memory is reserved) */);
401       avp -> decode(db_aux, parent, answer);
402     } catch(anna::RuntimeException &ex) {
403       getEngine()->releaseAvp(avp);
404       LOGWARNING(
405           anna::Logger::warning(ex.getText(), ANNA_FILE_LOCATION);
406       anna::Logger::warning("Although a decoding error was found, validation could be checked because message could be enough for the application", ANNA_FILE_LOCATION);
407       );
408       break;
409     }
410
411     addChild(avp);
412     avpPos += 4 * REQUIRED_WORDS(avp->getLength());
413   }
414
415   // Post-Fixing
416   Engine::FixMode::_v fmode = getEngine()->getFixMode();
417
418   if((fmode == Engine::FixMode::AfterDecoding) || (fmode == Engine::FixMode::Always)) fix();
419
420   // Trace
421   LOGDEBUG(
422       std::string trace = "Message decoded:\n";
423   trace += asXMLString();
424   anna::Logger::debug(trace, ANNA_FILE_LOCATION);
425   );
426   // Post-Validation
427   Engine::ValidationMode::_v vmode = getEngine()->getValidationMode();
428
429   if((vmode == Engine::ValidationMode::AfterDecoding) || (vmode == Engine::ValidationMode::Always))
430     if(!valid(answer))
431       throw anna::RuntimeException("The decoded message is invalid. See previous report on warning-level traces", ANNA_FILE_LOCATION);
432 }
433
434
435 //------------------------------------------------------------------------------
436 //--------------------------------------------------- Message::getStackCommand()
437 //------------------------------------------------------------------------------
438 const anna::diameter::stack::Command *Message::getStackCommand(CommandId id) const throw(anna::RuntimeException) {
439   const stack::Dictionary * dictionary = getEngine()->getDictionary();
440   return (dictionary ? (dictionary->getCommand(id)) : NULL);
441 }
442
443
444 //------------------------------------------------------------------------------
445 //----------------------------------------------------- Message::setResultCode()
446 //------------------------------------------------------------------------------
447 void Message::setResultCode(int rc) throw(anna::RuntimeException) {
448   if(isRequest()) return;
449
450   // Add Result-Code if not yet added. Even if validation depth is set to 'Complete',
451   // the Result-Code value will be the first found during the message analysis:
452   Avp *resultCodeAvp = getAvp(helpers::base::AVPID__Result_Code, 1, anna::Exception::Mode::Ignore);
453
454   if(!resultCodeAvp)
455     addAvp(helpers::base::AVPID__Result_Code)->getUnsigned32()->setValue(rc);
456   else if(resultCodeAvp->getUnsigned32()->getValue() == helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS)  // Only success could be replaced
457     resultCodeAvp->getUnsigned32()->setValue(rc);
458
459   // Error bit:
460   setErrorBit(rc >= 3001 && rc <= 3010 /* protocol errors */);
461 }
462
463
464 //------------------------------------------------------------------------------
465 //----------------------------------------------------- Message::getResultCode()
466 //------------------------------------------------------------------------------
467 int Message::getResultCode() const throw() {
468   if(isAnswer()) {
469     const Avp *resultCodeAvp = getAvp(helpers::base::AVPID__Result_Code, 1, anna::Exception::Mode::Ignore);
470
471     if(resultCodeAvp)
472       return resultCodeAvp->getUnsigned32()->getValue();
473   }
474
475   return -1;
476 }
477
478
479 //------------------------------------------------------------------------------
480 //------------------------------------------------------ Message::setFailedAvp()
481 //------------------------------------------------------------------------------
482 void Message::setFailedAvp(const parent_t &parent, AvpId wrong, const char *wrongName) throw(anna::RuntimeException) {
483
484   if(isRequest()) return;
485
486   // RFC 6733:
487   //
488   //  7.5.  Failed-AVP AVP
489   //
490   //     The Failed-AVP AVP (AVP Code 279) is of type Grouped and provides
491   //     debugging information in cases where a request is rejected or not
492   //     fully processed due to erroneous information in a specific AVP.  The
493   //     value of the Result-Code AVP will provide information on the reason
494   //     for the Failed-AVP AVP.  A Diameter answer message SHOULD contain an
495   //     instance of the Failed-AVP AVP that corresponds to the error
496   //     indicated by the Result-Code AVP.  For practical purposes, this
497   //     Failed-AVP would typically refer to the first AVP processing error
498   //     that a Diameter node encounters.
499
500   // Although the Failed-AVP definition has cardinality 1* and Failed-AVP itself is defined in
501   // most of the command codes as *[Failed-AVP], i think this is not a deliberate ambiguity.
502   // Probably the RFC wants to give freedom to the application layer, but it is recommended to
503   // have only one child (wrong avp) inside a unique message Failed-AVP to ease the Result-Code
504   // correspondence. Anyway, this behaviour could be easily  opened by mean 'setSingleFailedAVP(false)'
505   Avp *theFailedAvp = getAvp(helpers::base::AVPID__Failed_AVP, 1, anna::Exception::Mode::Ignore);
506   if (theFailedAvp) {
507     if (getEngine()->getSingleFailedAVP()) {
508       LOGDEBUG(anna::Logger::debug("Failed-AVP has already been added. RFC 6733 Section 7.5 recommends to store only the first error found", ANNA_FILE_LOCATION));
509       return;
510     }
511   }
512
513   // Section 7.5 RFC 6733: A Diameter message SHOULD contain one Failed-AVP AVP
514   theFailedAvp = addAvp(helpers::base::AVPID__Failed_AVP);
515   Avp *leaf = theFailedAvp;
516
517   LOGDEBUG(
518       std::string msg = "Adding to Failed-AVP, the wrong avp ";
519   msg += wrongName ? wrongName : (anna::diameter::functions::avpIdAsPairString(wrong));
520   msg += " found inside ";
521   msg += parent.asString();
522
523   anna::Logger::debug(msg, ANNA_FILE_LOCATION);
524   );
525
526   std::vector<AvpId>::const_iterator it;
527   for(it = parent.AvpsId.begin(); it != parent.AvpsId.end(); it++)
528     leaf = leaf->addAvp(*it);
529
530   leaf->addAvp(wrong);
531 }
532
533
534 //------------------------------------------------------------------------------
535 //----------------------------------------------- Message::setStandardToAnswer()
536 //------------------------------------------------------------------------------
537 void Message::setStandardToAnswer(const Message &request, const std::string &originHost, const std::string &originRealm, int resultCode) throw(anna::RuntimeException) {
538   if(!request.getId().second) return;
539
540   // Message header:
541   setHeaderToAnswer(request);
542   // Session-Id if exists:
543   const Avp *reqSessionId = request.getAvp(helpers::base::AVPID__Session_Id, 1, anna::Exception::Mode::Ignore);
544
545   if(reqSessionId)
546     if(!getAvp(helpers::base::AVPID__Session_Id, 1, anna::Exception::Mode::Ignore))
547       addAvp(helpers::base::AVPID__Session_Id)->getUTF8String()->setValue(reqSessionId->getUTF8String()->getValue());
548
549   // Origin-Host & Realm
550   if(!getAvp(helpers::base::AVPID__Origin_Host, 1, anna::Exception::Mode::Ignore))
551     addAvp(helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(originHost);
552
553   if(!getAvp(helpers::base::AVPID__Origin_Realm, 1, anna::Exception::Mode::Ignore))
554     addAvp(helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(originRealm);
555
556   // Proxy-Info AVPs if exist, in the same order:
557   for(const_avp_iterator it = request.avp_begin(); it != request.avp_end(); it++)
558     if((*it).second->getId() == helpers::base::AVPID__Proxy_Info)
559       addAvp((*it).second);
560
561   // If no Result-Code was added is because all was ok, then application could detect another problem:
562   setResultCode(resultCode);
563   // Fix:
564   fix();
565   LOGDEBUG(
566       std::string msg = "Completed answer:\n";
567   msg += asXMLString();
568   anna::Logger::debug(msg, ANNA_FILE_LOCATION);
569   );
570 }
571
572
573 //------------------------------------------------------------------------------
574 //--------------------------------------------------------------- Message::fix()
575 //------------------------------------------------------------------------------
576 void Message::fix() throw() {
577   // Dictionary stack command:
578   const stack::Command *stackCommand = getStackCommand();
579
580   if(!stackCommand) {
581     LOGDEBUG(anna::Logger::debug("No dictionary command reference found. Cannot fix.", ANNA_FILE_LOCATION));
582     // Try to get to the first place the Session-ID (if exists) because...
583     // RFC 6733: All messages pertaining to a specific session MUST include only one Session-Id AVP ...
584     //           ... When present, the Session-Id SHOULD appear immediately following the Diameter header
585     avp_iterator it = Avp::avp_find(a_avps, helpers::base::AVPID__Session_Id, 1 /* one and only */);
586
587     if(it != avp_end()) {
588       int sessionPos = (*it).first;
589       Avp *first = (*avp_begin()).second;
590       a_avps[0] = (*it).second; // Session-Id
591       a_avps[sessionPos] = first;
592       LOGDEBUG(anna::Logger::debug("Session-Id has been manually fixed to the first place", ANNA_FILE_LOCATION));
593     }
594
595     return;
596   }
597
598   Avp::fix(a_avps, (find_container&)a_finds, a_insertionPositionForChilds, stackCommand->avprule_begin(), stackCommand->avprule_end());
599 }
600
601
602 //------------------------------------------------------------------------------
603 //------------------------------------------------------------- Message::valid()
604 //------------------------------------------------------------------------------
605 bool Message::valid(Message *ptrAnswer) const throw(anna::RuntimeException) {
606   // OAM
607   OamModule &oamModule = OamModule::instantiate();
608   // Dictionary stack command:
609   const stack::Command *stackCommand = getStackCommand();
610   // Only build answer for a request:
611   Message *answer = isRequest() ? ptrAnswer : NULL;
612
613   if(answer) answer->setHeaderToAnswer(*this);
614
615   if(!stackCommand) {
616     // OAM
617     std::string me = anna::diameter::functions::commandIdAsPairString(a_id);
618     oamModule.activateAlarm(OamModule::Alarm::MessageValidation__UnknownOperation__s__UnableToValidate, STRING_WITH_QUOTATION_MARKS__C_STR(me));
619     oamModule.count(OamModule::Counter::MessageValidation__UnknownOperationUnableToValidate);
620
621     if(answer) answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_COMMAND_UNSUPPORTED);
622
623     getEngine()->validationAnomaly(anna::functions::asString("Unknown operation %s. Unable to validate", STRING_WITH_QUOTATION_MARKS__C_STR(me)));
624     return false;
625   }
626
627   // Parent information:
628   parent_t me;
629   me.setMessage(a_id, stackCommand->getName().c_str());
630
631   //////////////////////////////
632   // Flags coherence checking //
633   //////////////////////////////
634   int rc;
635   bool result = flagsOK(rc);
636
637   if(!result) {
638     // OAM & Depth management
639     oamModule.activateAlarm(OamModule::Alarm::MessageValidation__Operation__s__HaveIncoherentFlags__d__, STRING_WITH_QUOTATION_MARKS__C_STR(me.asString()), (int)a_flags);
640     oamModule.count(OamModule::Counter::MessageValidation__OperationHaveIncoherentFlags);
641
642     if(answer) answer->setResultCode(rc);
643
644     getEngine()->validationAnomaly(anna::functions::asString("Operation %s have incoherent flags (%d)", STRING_WITH_QUOTATION_MARKS__C_STR(me.asString()), (int)a_flags));
645   }
646
647   ////////////////////
648   // Level checking //
649   ////////////////////
650   result = Avp::validLevel(a_avps, stackCommand->avprule_begin(), stackCommand->avprule_end(), getEngine(), me, answer) && result;
651
652   ////////////////////////
653   // Childrens checking //
654   ////////////////////////
655   for(const_avp_iterator it = avp_begin(); it != avp_end(); it++)
656     result = ((*it).second->valid(me, answer)) && result;
657
658   return result;
659 }
660
661
662 //------------------------------------------------------------------------------
663 //-------------------------------------------------------------- Message::code()
664 //------------------------------------------------------------------------------
665 const anna::DataBlock & Message::code() throw(anna::RuntimeException) {
666   // Pre-Validation
667   Engine::ValidationMode::_v vmode = getEngine()->getValidationMode();
668
669   if((vmode == Engine::ValidationMode::BeforeEncoding) || (vmode == Engine::ValidationMode::Always)) {
670     if(!valid())
671       throw anna::RuntimeException("Try to encode an invalid message. See previous report on warning-level traces", ANNA_FILE_LOCATION);
672   }
673
674   // Pre-Fixing
675   Engine::FixMode::_v fmode = getEngine()->getFixMode();
676
677   if((fmode == Engine::FixMode::BeforeEncoding) || (fmode == Engine::FixMode::Always)) fix();
678
679   // Trace
680   LOGDEBUG(
681       std::string trace = "Message to code:\n";
682   trace += asXMLString();
683   anna::Logger::debug(trace, ANNA_FILE_LOCATION);
684   );
685   // Memory allocation
686   U24 length = getLength();
687   a_forCode.clear();
688   a_forCode.allocate(length);
689   char* buffer = (char*)a_forCode.getData();
690   // Version and length
691   buffer[0] = (S8) a_version;
692   buffer[1] = (S8)(length >> 16);
693   buffer[2] = (S8)(length >> 8);
694   buffer[3] = (S8) length;
695   // Flags and code
696   buffer[4] = (S8) a_flags;
697   buffer[5] = (S8)(a_id.first >> 16);
698   buffer[6] = (S8)(a_id.first >> 8);
699   buffer[7] = (S8) a_id.first;
700   // Application Id
701   buffer[8] = (S8)(a_applicationId >> 24);
702   buffer[9] = (S8)(a_applicationId >> 16);
703   buffer[10] = (S8)(a_applicationId >> 8);
704   buffer[11] = (S8) a_applicationId;
705   // Hob by hop
706   buffer[12] = (S8)(a_hopByHop >> 24);
707   buffer[13] = (S8)(a_hopByHop >> 16);
708   buffer[14] = (S8)(a_hopByHop >> 8);
709   buffer[15] = (S8) a_hopByHop;
710   // End to end
711   buffer[16] = (S8)(a_endToEnd >> 24);
712   buffer[17] = (S8)(a_endToEnd >> 16);
713   buffer[18] = (S8)(a_endToEnd >> 8);
714   buffer[19] = (S8) a_endToEnd;
715   // Data start position:
716   int startDataPos = HeaderLength;
717
718   if(startDataPos == length) {
719     LOGDEBUG(anna::Logger::debug("There is no Avps to encode (only-header message)", ANNA_FILE_LOCATION));
720   } else {
721     // Data part:
722     S8 * dataPart = buffer + startDataPos;
723     int dataBytes; // not used but could be useful for checking (length - startDataPos)
724     // Each avp encoding will remain padding octets depending on format. In order to
725     //  code avps colection (each avp will be multiple of 4) we clean the entire buffer
726     //  to ensure padding (easier than custom-made for each format):
727     memset(dataPart, 0, length - startDataPos); // no estoy seguro de que el clear del DataBlock haga esto...
728
729     for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) {
730       Avp::avp(it)->code(dataPart, dataBytes);
731       dataPart = dataPart + 4 * REQUIRED_WORDS(dataBytes);
732     }
733   }
734
735   // Trace
736   LOGDEBUG(
737       std::string trace = "DataBlock encoded:\n";
738   trace += a_forCode.asString();
739   //      trace += "\nAs continuous hexadecimal string:\n";
740   //      trace += anna::functions::asHexString(a_forCode);
741   anna::Logger::debug(trace, ANNA_FILE_LOCATION);
742   );
743   return a_forCode;
744 }
745
746 //------------------------------------------------------------------------------
747 //----------------------------------------------------------- Message::loadXML()
748 //------------------------------------------------------------------------------
749 void Message::loadXML(const std::string &xmlPathFile) throw(anna::RuntimeException) {
750
751   anna::xml::DocumentFile xmlDocument;
752   anna::diameter::codec::functions::messageXmlDocumentFromXmlFile(xmlDocument, xmlPathFile);
753   fromXML(xmlDocument.getRootNode());
754 }
755
756 //------------------------------------------------------------------------------
757 //----------------------------------------------------------- Message::fromXML()
758 //------------------------------------------------------------------------------
759 void Message::fromXML(const anna::xml::Node* messageNode) throw(anna::RuntimeException) {
760   // <!ATTLIST message version CDATA #IMPLIED name CDATA #IMPLIED code CDATA #IMPLIED flags CDATA #IMPLIED p-bit (yes | no) #IMPLIED e-bit (yes | no) #IMPLIED t-bit (yes | no) #IMPLIED application-id CDATA #REQUIRED hop-by-hop-id CDATA #IMPLIED end-by-end-id CDATA #IMPLIED>
761   const anna::xml::Attribute *version, *name, *code, *flags, *pbit, *ebit, *tbit, *appid, *hbh, *ete;
762   version = messageNode->getAttribute("version", false /* no exception */);
763   name = messageNode->getAttribute("name", false /* no exception */);
764   code = messageNode->getAttribute("code", false /* no exception */);
765   flags = messageNode->getAttribute("flags", false /* no exception */);
766   pbit = messageNode->getAttribute("p-bit", false /* no exception */);
767   ebit = messageNode->getAttribute("e-bit", false /* no exception */);
768   tbit = messageNode->getAttribute("t-bit", false /* no exception */);
769   appid = messageNode->getAttribute("application-id"); // required
770   hbh = messageNode->getAttribute("hop-by-hop-id", false /* no exception */);
771   ete = messageNode->getAttribute("end-by-end-id", false /* no exception */);
772   int i_aux;
773   unsigned int u_aux;
774
775   // Clear the message
776   clear();
777
778   if(version) {
779     i_aux = version->getIntegerValue();
780
781     if(i_aux < 0 || i_aux > 256) {
782       std::string msg = "Error processing avp <version '"; msg += version->getValue();
783       msg += "': out of range [0,256]";
784       throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
785     }
786
787     a_version = i_aux;
788   }
789
790   // Application-id
791   // This is called before any operation which needs to know about the stack elements (this could set the dictionary)
792   setApplicationId(appid->getIntegerValue());
793
794   // Dictionary
795   const stack::Dictionary * dictionary = getEngine()->getDictionary();
796   const stack::Command *stackCommand = NULL;
797
798   // Compact mode
799   if(name) {
800     if(!dictionary) {
801       std::string msg = "Error processing command <name '"; msg += name->getValue();
802       msg += "'>: no dictionary available. Load one or use <'code' + 'flags'> instead of <'name'>";
803       throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
804     }
805
806     stackCommand = dictionary->getCommand(name->getValue());
807
808     if(!stackCommand) {
809       std::string msg = "Error processing command <name '"; msg += name->getValue();
810       msg += "'>: no command found for this identifier at available dictionary";
811       throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
812     }
813   }
814
815   // Check attributes exclusiveness
816   if(name) {  // compact mode
817     if(code || flags) {
818       std::string msg = "Error processing command <name '"; msg += name->getValue();
819       msg += "'>: message attributes <'code' + 'flags'> are not allowed if <'name'> is provided";
820       throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
821     }
822
823     setId(stackCommand->getId());
824
825     // 'P', 'E' and 'T' flags:
826     bool activateP = pbit ? (pbit->getValue() == "yes") : false;
827     bool activateE = ebit ? (ebit->getValue() == "yes") : false;
828     bool activateT = tbit ? (tbit->getValue() == "yes") : false;
829
830     if(activateP) a_flags |= PBitMask;
831
832     if(activateE) a_flags |= EBitMask;
833
834     if(activateT) a_flags |= TBitMask;
835   } else {
836     std::string s_code = code ? code->getValue() : "?";
837     std::string s_flags = flags ? flags->getValue() : "?";
838
839     if(!code || !flags) {
840       std::string msg = "Error processing command <code '"; msg += s_code;
841       msg += "' + flags '"; msg += s_flags;
842       msg += "'>: both must be provided if <'name'> don't";
843       throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
844     }
845
846     if(pbit || ebit || tbit) {
847       std::string msg = "Error processing command <code '"; msg += s_code;
848       msg += "' + flags '"; msg += s_flags;
849       msg += "'>: neither of 'p-bit', 'e-bit' or 't-bit' fields are allowed if those are present";
850       throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
851     }
852
853     // Code check
854     i_aux = code->getIntegerValue();
855
856     if(i_aux < 0) {
857       std::string msg = "Error processing command <code '"; msg += s_code;
858       msg += "': negative values are not allowed";
859       throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
860     }
861
862     U24 u_code = i_aux;
863     // Flags check
864     i_aux = flags->getIntegerValue();
865
866     if(i_aux < 0 || i_aux > 256) {
867       std::string msg = "Error processing command <flags '"; msg += s_flags;
868       msg += "': out of range [0,256]";
869       throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
870     }
871
872     a_flags = i_aux;
873     int flagsBCK = a_flags;
874     // Final assignments
875     a_id = CommandId(u_code, requestBit() /* based on a_flags */);
876     // Flags could have been updated regarding dictionary, but during parsing we must respect xml file:
877     a_flags = flagsBCK;
878   }
879
880   // Hob-by-hop-id
881   if(hbh) {
882     u_aux = hbh->getIntegerValue();
883
884     /*
885     if(u_aux < 0) {
886       std::string msg = "Error processing command <hop-by-hop-id '"; msg += hbh->getValue();
887       msg += "': negative values are not allowed";
888       throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
889     }
890      */
891   } else u_aux = 0;
892
893   setHopByHop(u_aux);
894
895   // End-to-end-id
896   if(ete) {
897     u_aux = ete->getIntegerValue();
898
899     /*
900     if(u_aux < 0) {
901       std::string msg = "Error processing command <end-to-end-id '"; msg += ete->getValue();
902       msg += "': negative values are not allowed";
903       throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
904     }
905      */
906   } else u_aux = 0;
907
908   setEndToEnd(u_aux);
909   // Childrens
910   Avp *avp;
911
912   for(anna::xml::Node::const_child_iterator it = messageNode->child_begin(); it != messageNode->child_end(); it++) {
913     std::string nodeName = (*it)->getName();
914
915     if(nodeName != "avp") {
916       std::string msg = "Unsupported message child node name '"; msg += nodeName;
917       msg += "': use 'avp'";
918       throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
919     }
920
921     try {
922       avp =  getEngine()->createAvp(NULL);
923       avp -> fromXML(*it);
924     } catch(anna::RuntimeException &ex) {
925       getEngine()->releaseAvp(avp);
926       throw ex;
927     }
928
929     addAvp(avp);
930   }
931 }
932
933
934 //------------------------------------------------------------------------------
935 //------------------------------------------------------------- Message::asXML()
936 //------------------------------------------------------------------------------
937 anna::xml::Node* Message::asXML(anna::xml::Node* parent) const throw() {
938   // <!ATTLIST message version CDATA #IMPLIED name CDATA #IMPLIED code CDATA #IMPLIED flags CDATA #IMPLIED application-id CDATA #REQUIRED hop-by-hop-id CDATA #IMPLIED end-by-end-id CDATA #IMPLIED>
939   anna::xml::Node* result = parent->createChild("message");
940   // Dictionary stack command:
941   const stack::Command *stackCommand = getStackCommand();
942   bool compactMode = stackCommand /*&& flagsOK()*/;
943   result->createAttribute("version", anna::functions::asString((int)a_version));
944
945   if(compactMode) {
946     result->createAttribute("name", stackCommand->getName());
947
948     if(proxiableBit()) result->createAttribute("p-bit", "yes");
949
950     if(errorBit()) result->createAttribute("e-bit", "yes");
951
952     if(potentiallyReTransmittedMessageBit()) result->createAttribute("t-bit", "yes");
953   } else {
954     result->createAttribute("code", a_id.first);
955     result->createAttribute("flags", (int)a_flags);
956   }
957
958   result->createAttribute("application-id", anna::functions::asString(a_applicationId));
959   result->createAttribute("hop-by-hop-id", anna::functions::asString(a_hopByHop));
960   result->createAttribute("end-by-end-id", anna::functions::asString(a_endToEnd));
961
962   // Avps:
963   for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) {
964     Avp::avp(it)->asXML(result);
965   }
966
967   return result;
968 }
969
970
971 //------------------------------------------------------------------------------
972 //------------------------------------------------------- Message::asXMLString()
973 //------------------------------------------------------------------------------
974 std::string Message::asXMLString() const throw() {
975   anna::xml::Node root("root");
976   return anna::xml::Compiler().apply(asXML(&root));
977 }
978
979
980 //------------------------------------------------------------------------------
981 //------------------------------------------------------------ Message::isLike()
982 //------------------------------------------------------------------------------
983 bool Message::isLike(const std::string &pattern) const throw() {
984   anna::RegularExpression re(pattern);
985   return re.isLike(asXMLString());
986 }