1 // ANNA - Anna is Not Nothingness Anymore //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo //
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 //
10 #include <anna/diameter/codec/Message.hpp>
11 #include <anna/diameter/codec/Format.hpp>
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>
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>
39 using namespace anna::diameter::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);
57 //------------------------------------------------------------------------------
58 //----------------------------------------------------------- Message::Message()
59 //------------------------------------------------------------------------------
60 Message::Message(Engine *engine) : a_engine(engine), a_forCode(true) {
65 //------------------------------------------------------------------------------
66 //----------------------------------------------------------- Message::Message()
67 //------------------------------------------------------------------------------
68 Message::Message(CommandId id, Engine *engine) : a_engine(engine), a_forCode(true) {
74 //------------------------------------------------------------------------------
75 //---------------------------------------------------------- Message::~Message()
76 //------------------------------------------------------------------------------
82 //------------------------------------------------------------------------------
83 //--------------------------------------------------------- Message::setEngine()
84 //------------------------------------------------------------------------------
85 void Message::setEngine(Engine *engine) throw() {
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));
96 //------------------------------------------------------------------------------
97 //--------------------------------------------------------- Message::getEngine()
98 //------------------------------------------------------------------------------
99 Engine * Message::getEngine() const throw(anna::RuntimeException) {
101 throw anna::RuntimeException("Invalid codec engine reference (NULL). Use setEngine() to set the corresponding codec engine", ANNA_FILE_LOCATION);
108 //------------------------------------------------------------------------------
109 //-------------------------------------------------------- Message::initialize()
110 //------------------------------------------------------------------------------
111 void Message::initialize() throw() {
113 a_id = CommandId(0, false);
119 a_insertionPositionForChilds = 0;
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)); }
139 //------------------------------------------------------------------------------
140 //----------------------------------------------------------- Message::flagsOK()
141 //------------------------------------------------------------------------------
142 bool Message::flagsOK(int &rc) const throw() {
143 // Dictionary stack command:
144 const stack::Command *stackCommand = getStackCommand();
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::?????;
152 // DIAMETER_INVALID_HDR_BITS 3008
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.
159 if(stackCommand->isRequest() != isRequest()) ok = false; // en teoria es imposible salir por aqui: blindado en la dtd
161 if(isRequest() && errorBit()) {
162 anna::Logger::error("E(rror) bit is not allowed at diameter requests", ANNA_FILE_LOCATION);
166 if(isAnswer() && potentiallyReTransmittedMessageBit()) {
167 anna::Logger::error("T(Potentially re-transmitted message) bit is not allowed at diameter answers", ANNA_FILE_LOCATION);
172 rc = helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_HDR_BITS;
176 // DIAMETER_INVALID_BIT_IN_HEADER 5013
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
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;
191 //------------------------------------------------------------------------------
192 //------------------------------------------------------------- Message::setId()
193 //------------------------------------------------------------------------------
194 void Message::setId(CommandId id) throw(anna::RuntimeException) {
198 // Dictionary stack command:
199 const stack::Command *stackCommand = getStackCommand(); // based on dictionary and a_id
201 // Dictionary flags for known types:
203 if(stackCommand->isRequest()) a_flags |= RBitMask;
205 if(a_id.second) a_flags |= RBitMask; else a_flags &= (~RBitMask);
210 //------------------------------------------------------------------------------
211 //------------------------------------------------------------- Message::setId()
212 //------------------------------------------------------------------------------
213 void Message::setId(const char *name) throw(anna::RuntimeException) {
214 setId(getEngine()->commandIdForName(name));
218 //------------------------------------------------------------------------------
219 //-------------------------------------------------- Message::setApplicationId()
220 //------------------------------------------------------------------------------
221 void Message::setApplicationId(U32 aid) throw(anna::RuntimeException) {
222 a_applicationId = aid;
224 // Automatic engine configuration:
225 if (a_engine) return;
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);
238 //------------------------------------------------------------------------------
239 //------------------------------------------------------------ Message::addAvp()
240 //------------------------------------------------------------------------------
241 Avp * Message::addAvp(const char *name) throw(anna::RuntimeException) {
242 return addAvp(getEngine()->avpIdForName(name));
246 //------------------------------------------------------------------------------
247 //------------------------------------------------------------ Message::addAvp()
248 //------------------------------------------------------------------------------
249 Avp * Message::addAvp(Avp * avp) throw() {
250 if(!avp) return NULL;
251 if (avp->getEngine() != getEngine()) return NULL;
257 //------------------------------------------------------------------------------
258 //--------------------------------------------------------- Message::removeAvp()
259 //------------------------------------------------------------------------------
260 bool Message::removeAvp(const char *name, int ocurrence) throw(anna::RuntimeException) {
261 return removeAvp(getEngine()->avpIdForName(name), ocurrence);
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);
273 //------------------------------------------------------------------------------
274 //---------------------------------------------------------- Message::countAvp()
275 //------------------------------------------------------------------------------
276 int Message::countAvp(const char *name) const throw(anna::RuntimeException) {
277 return countAvp(getEngine()->avpIdForName(name));
281 //------------------------------------------------------------------------------
282 //--------------------------------------------------------- Message::getLength()
283 //------------------------------------------------------------------------------
284 U24 Message::getLength() const throw() {
287 result = HeaderLength;
289 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) result += 4 * REQUIRED_WORDS(Avp::avp(it)->getLength());
295 //------------------------------------------------------------------------------
296 //------------------------------------------------------------ Message::decode()
297 //------------------------------------------------------------------------------
298 void Message::decode(const anna::DataBlock &db, Message *ptrAnswer) throw(anna::RuntimeException) {
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);
307 // EXCEPTION MANAGEMENT IN THIS METHOD
308 // ===================================
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
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".
318 OamModule &oamModule = OamModule::instantiate();
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);
327 const char * buffer = db.getData();
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 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
343 // +-+-+-+-+-+-+-+-+-+-+-+-+-
345 a_version = (S8)buffer[0];
347 U24 length = DECODE3BYTES_INDX_VALUETYPE(buffer, 1, U24); // total length including header fields
349 a_flags = (S8)buffer[4];
351 U24 code = DECODE3BYTES_INDX_VALUETYPE(buffer, 5, U24);
353 a_id = CommandId(code, requestBit() /* based on a_flags */);
355 setApplicationId(DECODE4BYTES_INDX_VALUETYPE(buffer, 8, U32)); // centralize set, because it could be used for stack selection.
357 a_hopByHop = DECODE4BYTES_INDX_VALUETYPE(buffer, 12, U32);
359 a_endToEnd = DECODE4BYTES_INDX_VALUETYPE(buffer, 16, U32);
361 // Only build answer for a request:
362 Message *answer = isRequest() ? ptrAnswer : NULL;
364 if(answer) answer->setHeaderToAnswer(*this);
367 if(db.getSize() < length) {
368 oamModule.activateAlarm(OamModule::Alarm::MessageDecode__NotEnoughBytesToCoverMessageLength);
369 oamModule.count(OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageLength);
371 if(answer) answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_MESSAGE_LENGTH);
373 throw anna::RuntimeException("Not enough bytes to cover message length", ANNA_FILE_LOCATION);
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;
383 if(dataBytes < 8 /* minimum avp */) {
384 LOGDEBUG(anna::Logger::debug("Message empty (without avps)", ANNA_FILE_LOCATION));
390 anna::DataBlock db_aux;
392 // Parent information:
394 parent.setMessage(a_id);
397 while(avpPos < dataBytes) {
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);
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);
412 avpPos += 4 * REQUIRED_WORDS(avp->getLength());
416 Engine::FixMode::_v fmode = getEngine()->getFixMode();
418 if((fmode == Engine::FixMode::AfterDecoding) || (fmode == Engine::FixMode::Always)) fix();
422 std::string trace = "Message decoded:\n";
423 trace += asXMLString();
424 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
427 Engine::ValidationMode::_v vmode = getEngine()->getValidationMode();
429 if((vmode == Engine::ValidationMode::AfterDecoding) || (vmode == Engine::ValidationMode::Always))
431 throw anna::RuntimeException("The decoded message is invalid. See previous report on warning-level traces", ANNA_FILE_LOCATION);
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);
444 //------------------------------------------------------------------------------
445 //----------------------------------------------------- Message::setResultCode()
446 //------------------------------------------------------------------------------
447 void Message::setResultCode(int rc) throw(anna::RuntimeException) {
448 if(isRequest()) return;
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);
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);
460 setErrorBit(rc >= 3001 && rc <= 3010 /* protocol errors */);
464 //------------------------------------------------------------------------------
465 //----------------------------------------------------- Message::getResultCode()
466 //------------------------------------------------------------------------------
467 int Message::getResultCode() const throw() {
469 const Avp *resultCodeAvp = getAvp(helpers::base::AVPID__Result_Code, 1, anna::Exception::Mode::Ignore);
472 return resultCodeAvp->getUnsigned32()->getValue();
479 //------------------------------------------------------------------------------
480 //------------------------------------------------------ Message::setFailedAvp()
481 //------------------------------------------------------------------------------
482 void Message::setFailedAvp(const parent_t &parent, AvpId wrong, const char *wrongName) throw(anna::RuntimeException) {
484 if(isRequest()) return;
488 // 7.5. Failed-AVP AVP
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.
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);
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));
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;
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();
523 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
526 std::vector<AvpId>::const_iterator it;
527 for(it = parent.AvpsId.begin(); it != parent.AvpsId.end(); it++)
528 leaf = leaf->addAvp(*it);
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;
541 setHeaderToAnswer(request);
542 // Session-Id if exists:
543 const Avp *reqSessionId = request.getAvp(helpers::base::AVPID__Session_Id, 1, anna::Exception::Mode::Ignore);
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());
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);
553 if(!getAvp(helpers::base::AVPID__Origin_Realm, 1, anna::Exception::Mode::Ignore))
554 addAvp(helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(originRealm);
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);
561 // If no Result-Code was added is because all was ok, then application could detect another problem:
562 setResultCode(resultCode);
566 std::string msg = "Completed answer:\n";
567 msg += asXMLString();
568 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
573 //------------------------------------------------------------------------------
574 //--------------------------------------------------------------- Message::fix()
575 //------------------------------------------------------------------------------
576 void Message::fix() throw() {
577 // Dictionary stack command:
578 const stack::Command *stackCommand = getStackCommand();
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 */);
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));
598 Avp::fix(a_avps, (find_container&)a_finds, a_insertionPositionForChilds, stackCommand->avprule_begin(), stackCommand->avprule_end());
602 //------------------------------------------------------------------------------
603 //------------------------------------------------------------- Message::valid()
604 //------------------------------------------------------------------------------
605 bool Message::valid(Message *ptrAnswer) const throw(anna::RuntimeException) {
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;
613 if(answer) answer->setHeaderToAnswer(*this);
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);
621 if(answer) answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_COMMAND_UNSUPPORTED);
623 getEngine()->validationAnomaly(anna::functions::asString("Unknown operation %s. Unable to validate", STRING_WITH_QUOTATION_MARKS__C_STR(me)));
627 // Parent information:
629 me.setMessage(a_id, stackCommand->getName().c_str());
631 //////////////////////////////
632 // Flags coherence checking //
633 //////////////////////////////
635 bool result = flagsOK(rc);
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);
642 if(answer) answer->setResultCode(rc);
644 getEngine()->validationAnomaly(anna::functions::asString("Operation %s have incoherent flags (%d)", STRING_WITH_QUOTATION_MARKS__C_STR(me.asString()), (int)a_flags));
650 result = Avp::validLevel(a_avps, stackCommand->avprule_begin(), stackCommand->avprule_end(), getEngine(), me, answer) && result;
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;
662 //------------------------------------------------------------------------------
663 //-------------------------------------------------------------- Message::code()
664 //------------------------------------------------------------------------------
665 const anna::DataBlock & Message::code() throw(anna::RuntimeException) {
667 Engine::ValidationMode::_v vmode = getEngine()->getValidationMode();
669 if((vmode == Engine::ValidationMode::BeforeEncoding) || (vmode == Engine::ValidationMode::Always)) {
671 throw anna::RuntimeException("Try to encode an invalid message. See previous report on warning-level traces", ANNA_FILE_LOCATION);
675 Engine::FixMode::_v fmode = getEngine()->getFixMode();
677 if((fmode == Engine::FixMode::BeforeEncoding) || (fmode == Engine::FixMode::Always)) fix();
681 std::string trace = "Message to code:\n";
682 trace += asXMLString();
683 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
686 U24 length = getLength();
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;
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;
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;
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;
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;
718 if(startDataPos == length) {
719 LOGDEBUG(anna::Logger::debug("There is no Avps to encode (only-header message)", ANNA_FILE_LOCATION));
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...
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);
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);
746 //------------------------------------------------------------------------------
747 //----------------------------------------------------------- Message::loadXML()
748 //------------------------------------------------------------------------------
749 void Message::loadXML(const std::string &xmlPathFile) throw(anna::RuntimeException) {
751 anna::xml::DocumentFile xmlDocument;
752 anna::diameter::codec::functions::messageXmlDocumentFromXmlFile(xmlDocument, xmlPathFile);
753 fromXML(xmlDocument.getRootNode());
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 */);
779 i_aux = version->getIntegerValue();
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);
791 // This is called before any operation which needs to know about the stack elements (this could set the dictionary)
792 setApplicationId(appid->getIntegerValue());
795 const stack::Dictionary * dictionary = getEngine()->getDictionary();
796 const stack::Command *stackCommand = NULL;
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);
806 stackCommand = dictionary->getCommand(name->getValue());
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);
815 // Check attributes exclusiveness
816 if(name) { // compact mode
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);
823 setId(stackCommand->getId());
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;
830 if(activateP) a_flags |= PBitMask;
832 if(activateE) a_flags |= EBitMask;
834 if(activateT) a_flags |= TBitMask;
836 std::string s_code = code ? code->getValue() : "?";
837 std::string s_flags = flags ? flags->getValue() : "?";
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);
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);
854 i_aux = code->getIntegerValue();
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);
864 i_aux = flags->getIntegerValue();
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);
873 int flagsBCK = a_flags;
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:
882 u_aux = hbh->getIntegerValue();
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);
897 u_aux = ete->getIntegerValue();
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);
912 for(anna::xml::Node::const_child_iterator it = messageNode->child_begin(); it != messageNode->child_end(); it++) {
913 std::string nodeName = (*it)->getName();
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);
922 avp = getEngine()->createAvp(NULL);
924 } catch(anna::RuntimeException &ex) {
925 getEngine()->releaseAvp(avp);
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));
946 result->createAttribute("name", stackCommand->getName());
948 if(proxiableBit()) result->createAttribute("p-bit", "yes");
950 if(errorBit()) result->createAttribute("e-bit", "yes");
952 if(potentiallyReTransmittedMessageBit()) result->createAttribute("t-bit", "yes");
954 result->createAttribute("code", a_id.first);
955 result->createAttribute("flags", (int)a_flags);
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));
963 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) {
964 Avp::avp(it)->asXML(result);
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));
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());