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