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