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() {
88 LOGWARNING(anna::Logger::warning("Ignored: you must assign a valid codec engine. If you want to set NULL engine, clear the message", ANNA_FILE_LOCATION));
92 if (a_engine && (engine != a_engine)) {
93 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));
101 //------------------------------------------------------------------------------
102 //--------------------------------------------------------- Message::getEngine()
103 //------------------------------------------------------------------------------
104 Engine * Message::getEngine() const throw(anna::RuntimeException) {
106 throw anna::RuntimeException("Invalid codec engine reference (NULL). Use setEngine() to set the corresponding codec engine", ANNA_FILE_LOCATION);
113 //------------------------------------------------------------------------------
114 //-------------------------------------------------------- Message::initialize()
115 //------------------------------------------------------------------------------
116 void Message::initialize() throw() {
118 a_id = CommandId(0, false);
124 a_insertionPositionForChilds = 0;
129 //------------------------------------------------------------------------------
130 //------------------------------------------------------------- Message::clear()
131 //------------------------------------------------------------------------------
132 void Message::clear(bool resetEngine) throw(anna::RuntimeException) {
133 for(avp_iterator it = avp_begin(); it != avp_end(); it++) { /*avp(it)->clear(); */getEngine()->releaseAvp(Avp::avp(it)); }
141 if (resetEngine) a_engine = NULL;
145 //------------------------------------------------------------------------------
146 //----------------------------------------------------------- Message::flagsOK()
147 //------------------------------------------------------------------------------
148 bool Message::flagsOK(int &rc) const throw() {
149 // Dictionary stack command:
150 const stack::Command *stackCommand = getStackCommand();
153 std::string msg = "Impossible to decide if flags are correct because stack command is not identified. Assume flags ok for Message ";
154 msg += anna::diameter::functions::commandIdAsPairString(a_id);
155 anna::Logger::error(msg, ANNA_FILE_LOCATION);
156 //rc = helpers::base::AVPVALUES__Result_Code::?????;
160 // DIAMETER_INVALID_HDR_BITS 3008
162 // A request was received whose bits in the Diameter header were set
163 // either to an invalid combination or to a value that is
164 // inconsistent with the Command Code's definition.
167 if(stackCommand->isRequest() != isRequest()) ok = false; // en teoria es imposible salir por aqui: blindado en la dtd
169 if(isRequest() && errorBit()) {
170 std::string msg = "E(rror) bit is not allowed at diameter requests as ";
171 msg += stackCommand->getName();
172 anna::Logger::error(msg, ANNA_FILE_LOCATION);
176 if(isAnswer() && potentiallyReTransmittedMessageBit()) {
177 std::string msg = "T(Potentially re-transmitted message) bit is not allowed at diameter answers as ";
178 msg += stackCommand->getName();
179 anna::Logger::error(msg, ANNA_FILE_LOCATION);
184 rc = helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_HDR_BITS;
188 // DIAMETER_INVALID_BIT_IN_HEADER 5013
190 // This error is returned when a reserved bit in the Diameter header
191 // is set to one (1) or the bits in the Diameter header are set
193 if((a_flags & 0x0f) != 0x00) {
194 std::string msg = "Any (or more than one) of the reserved message flags bit has been activated. Reserved bits must be null. Message is ";
195 msg += stackCommand->getName();
196 anna::Logger::error(msg, ANNA_FILE_LOCATION);
197 rc = helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_BIT_IN_HEADER;
205 //------------------------------------------------------------------------------
206 //------------------------------------------------------------- Message::setId()
207 //------------------------------------------------------------------------------
208 void Message::setId(CommandId id) throw(anna::RuntimeException) {
212 // Dictionary stack command:
213 const stack::Command *stackCommand = getStackCommand(); // based on dictionary and a_id
215 // Dictionary flags for known types:
217 if(stackCommand->isRequest()) a_flags |= RBitMask;
219 if(a_id.second) a_flags |= RBitMask; else a_flags &= (~RBitMask);
224 //------------------------------------------------------------------------------
225 //------------------------------------------------------------- Message::setId()
226 //------------------------------------------------------------------------------
227 void Message::setId(const char *name) throw(anna::RuntimeException) {
228 setId(getEngine()->commandIdForName(name));
232 //------------------------------------------------------------------------------
233 //-------------------------------------------------- Message::setApplicationId()
234 //------------------------------------------------------------------------------
235 void Message::setApplicationId(U32 aid) throw(anna::RuntimeException) {
236 a_applicationId = aid;
238 // Automatic engine configuration:
239 if (a_engine) return;
241 // Codec engine manager (a multithreaded application, normally does not achieve this point, because
242 // messages are prepared for each interface with the corresponding codec engine)
243 anna::diameter::codec::EngineManager &em = anna::diameter::codec::EngineManager::instantiate();
244 if (em.size() == 0) return;
245 if (em.selectFromApplicationId()) {
246 Engine *monostackEngine = em.getMonoStackCodecEngine();
247 if (monostackEngine) { a_engine = monostackEngine; return; }
248 a_engine = em.getCodecEngine(aid);
253 //------------------------------------------------------------------------------
254 //------------------------------------------------------------ Message::addAvp()
255 //------------------------------------------------------------------------------
256 Avp * Message::addAvp(const char *name) throw(anna::RuntimeException) {
257 return addAvp(getEngine()->avpIdForName(name));
261 //------------------------------------------------------------------------------
262 //------------------------------------------------------------ Message::addAvp()
263 //------------------------------------------------------------------------------
264 Avp * Message::addAvp(Avp * avp) throw() {
265 if(!avp) return NULL;
266 if (avp->getEngine() != getEngine()) return NULL;
272 //------------------------------------------------------------------------------
273 //--------------------------------------------------------- Message::removeAvp()
274 //------------------------------------------------------------------------------
275 bool Message::removeAvp(const char *name, int ocurrence) throw(anna::RuntimeException) {
276 return removeAvp(getEngine()->avpIdForName(name), ocurrence);
280 //------------------------------------------------------------------------------
281 //----------------------------------------------------------- Message::_getAvp()
282 //------------------------------------------------------------------------------
283 const Avp * Message::_getAvp(const char *name, int ocurrence, anna::Exception::Mode::_v emode) const throw(anna::RuntimeException) {
284 return getAvp(getEngine()->avpIdForName(name), ocurrence, emode);
288 //------------------------------------------------------------------------------
289 //---------------------------------------------------------- Message::countAvp()
290 //------------------------------------------------------------------------------
291 int Message::countAvp(const char *name) const throw(anna::RuntimeException) {
292 return countAvp(getEngine()->avpIdForName(name));
296 //------------------------------------------------------------------------------
297 //--------------------------------------------------------- Message::getLength()
298 //------------------------------------------------------------------------------
299 U24 Message::getLength() const throw() {
302 result = HeaderLength;
304 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) result += 4 * REQUIRED_WORDS(Avp::avp(it)->getLength());
310 //------------------------------------------------------------------------------
311 //------------------------------------------------------------ Message::decode()
312 //------------------------------------------------------------------------------
313 void Message::decode(const anna::DataBlock &db, Message *ptrAnswer) throw(anna::RuntimeException) {
316 anna::xml::Node root("Message::decode");
317 std::string trace = "DataBlock to decode:\n";
318 trace += db.asString();
319 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
321 clear(false /* respect engine */);
322 // EXCEPTION MANAGEMENT IN THIS METHOD
323 // ===================================
325 // If an error ocurred, decoding will stop launching exception but we will catch it and go on with validation because perhaps
326 // the achieved message could be valid against all odds. Only fatal errors cause direct decoding exception (length problems
330 // Launch exception on first validation error (validateAll == false), or log warning reporting all validation errors when
331 // complete validation is desired (validateAll == true, engine default) launching a final exception like "the decoded message is invalid".
333 OamModule &oamModule = OamModule::instantiate();
335 if(db.getSize() < HeaderLength) {
336 oamModule.activateAlarm(OamModule::Alarm::MessageDecode__NotEnoughBytesToCoverMessageHeaderLength);
337 oamModule.count(OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageHeaderLength);
338 // DIAMETER_INVALID_MESSAGE_LENGTH; // no podr� construir un answer fiable, as� que no registro el result-code
339 throw anna::RuntimeException("Not enough bytes to cover message header length (20 bytes)", ANNA_FILE_LOCATION);
342 const char * buffer = db.getData();
345 // 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
346 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
347 // | Version | Message Length |
348 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
349 // | command flags | Command-Code |
350 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
351 // | Application-ID |
352 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
353 // | Hop-by-Hop Identifier |
354 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
355 // | End-to-End Identifier |
356 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
358 // +-+-+-+-+-+-+-+-+-+-+-+-+-
360 a_version = (S8)buffer[0];
362 U24 length = DECODE3BYTES_INDX_VALUETYPE(buffer, 1, U24); // total length including header fields
364 a_flags = (S8)buffer[4];
366 U24 code = DECODE3BYTES_INDX_VALUETYPE(buffer, 5, U24);
368 a_id = CommandId(code, requestBit() /* based on a_flags */);
370 setApplicationId(DECODE4BYTES_INDX_VALUETYPE(buffer, 8, U32)); // centralize set, because it could be used for stack selection.
372 a_hopByHop = DECODE4BYTES_INDX_VALUETYPE(buffer, 12, U32);
374 a_endToEnd = DECODE4BYTES_INDX_VALUETYPE(buffer, 16, U32);
376 // Only build answer for a request:
377 Message *answer = isRequest() ? ptrAnswer : NULL;
379 if(answer) answer->setHeaderToAnswer(*this);
382 if(db.getSize() < length) {
383 oamModule.activateAlarm(OamModule::Alarm::MessageDecode__NotEnoughBytesToCoverMessageLength);
384 oamModule.count(OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageLength);
386 if(answer) answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_MESSAGE_LENGTH);
388 throw anna::RuntimeException("Not enough bytes to cover message length", ANNA_FILE_LOCATION);
391 // Message identifier
392 // Flags could have been updated regarding dictionary, but during decoding we must respect buffer received:
393 a_flags = (S8)buffer[4];
394 // Avps start position:
395 const S8 * startData = buffer + HeaderLength;
396 U24 dataBytes = length - HeaderLength;
398 if(dataBytes < 8 /* minimum avp */) {
399 LOGDEBUG(anna::Logger::debug("Message empty (without avps)", ANNA_FILE_LOCATION));
405 anna::DataBlock db_aux;
407 // Parent information:
409 parent.setMessage(a_id);
412 while(avpPos < dataBytes) {
414 avp = getEngine()->createAvp(NULL);
415 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) */);
416 avp -> decode(db_aux, parent, answer);
417 } catch(anna::RuntimeException &ex) {
418 getEngine()->releaseAvp(avp);
420 anna::Logger::warning(ex.getText(), ANNA_FILE_LOCATION);
421 anna::Logger::warning("Although a decoding error was found, validation could be checked because message could be enough for the application", ANNA_FILE_LOCATION);
427 avpPos += 4 * REQUIRED_WORDS(avp->getLength());
431 Engine::FixMode::_v fmode = getEngine()->getFixMode();
433 if((fmode == Engine::FixMode::AfterDecoding) || (fmode == Engine::FixMode::Always)) fix();
437 std::string trace = "Message decoded:\n";
438 trace += asXMLString();
439 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
442 Engine::ValidationMode::_v vmode = getEngine()->getValidationMode();
444 if((vmode == Engine::ValidationMode::AfterDecoding) || (vmode == Engine::ValidationMode::Always))
446 throw anna::RuntimeException("The decoded message is invalid. See previous report on warning-level traces", ANNA_FILE_LOCATION);
450 //------------------------------------------------------------------------------
451 //--------------------------------------------------- Message::getStackCommand()
452 //------------------------------------------------------------------------------
453 const anna::diameter::stack::Command *Message::getStackCommand(CommandId id) const throw(anna::RuntimeException) {
454 const stack::Dictionary * dictionary = getEngine()->getDictionary();
455 return (dictionary ? (dictionary->getCommand(id)) : NULL);
459 //------------------------------------------------------------------------------
460 //----------------------------------------------------- Message::setResultCode()
461 //------------------------------------------------------------------------------
462 void Message::setResultCode(int rc) throw(anna::RuntimeException) {
463 if(isRequest()) return;
465 // Add Result-Code if not yet added. Even if validation depth is set to 'Complete',
466 // the Result-Code value will be the first found during the message analysis:
467 Avp *resultCodeAvp = getAvp(helpers::base::AVPID__Result_Code, 1, anna::Exception::Mode::Ignore);
470 addAvp(helpers::base::AVPID__Result_Code)->getUnsigned32()->setValue(rc);
471 else if(resultCodeAvp->getUnsigned32()->getValue() == helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS) // Only success could be replaced
472 resultCodeAvp->getUnsigned32()->setValue(rc);
475 setErrorBit(rc >= 3001 && rc <= 3010 /* protocol errors */);
479 //------------------------------------------------------------------------------
480 //----------------------------------------------------- Message::getResultCode()
481 //------------------------------------------------------------------------------
482 int Message::getResultCode() const throw() {
484 const Avp *resultCodeAvp = getAvp(helpers::base::AVPID__Result_Code, 1, anna::Exception::Mode::Ignore);
487 return resultCodeAvp->getUnsigned32()->getValue();
494 //------------------------------------------------------------------------------
495 //------------------------------------------------------ Message::setFailedAvp()
496 //------------------------------------------------------------------------------
497 void Message::setFailedAvp(const parent_t &parent, AvpId wrong, const char *wrongName) throw(anna::RuntimeException) {
499 if(isRequest()) return;
503 // 7.5. Failed-AVP AVP
505 // The Failed-AVP AVP (AVP Code 279) is of type Grouped and provides
506 // debugging information in cases where a request is rejected or not
507 // fully processed due to erroneous information in a specific AVP. The
508 // value of the Result-Code AVP will provide information on the reason
509 // for the Failed-AVP AVP. A Diameter answer message SHOULD contain an
510 // instance of the Failed-AVP AVP that corresponds to the error
511 // indicated by the Result-Code AVP. For practical purposes, this
512 // Failed-AVP would typically refer to the first AVP processing error
513 // that a Diameter node encounters.
515 // Although the Failed-AVP definition has cardinality 1* and Failed-AVP itself is defined in
516 // most of the command codes as *[Failed-AVP], i think this is not a deliberate ambiguity.
517 // Probably the RFC wants to give freedom to the application layer, but it is recommended to
518 // have only one child (wrong avp) inside a unique message Failed-AVP to ease the Result-Code
519 // correspondence. Anyway, this behaviour could be easily opened by mean 'setSingleFailedAVP(false)'
520 Avp *theFailedAvp = getAvp(helpers::base::AVPID__Failed_AVP, 1, anna::Exception::Mode::Ignore);
522 if (getEngine()->getSingleFailedAVP()) {
523 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));
528 // Section 7.5 RFC 6733: A Diameter message SHOULD contain one Failed-AVP AVP
529 theFailedAvp = addAvp(helpers::base::AVPID__Failed_AVP);
530 Avp *leaf = theFailedAvp;
533 std::string msg = "Adding to Failed-AVP, the wrong avp ";
534 msg += wrongName ? wrongName : (anna::diameter::functions::avpIdAsPairString(wrong));
535 msg += " found inside ";
536 msg += parent.asString();
538 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
541 std::vector<AvpId>::const_iterator it;
542 for(it = parent.AvpsId.begin(); it != parent.AvpsId.end(); it++)
543 leaf = leaf->addAvp(*it);
549 //------------------------------------------------------------------------------
550 //----------------------------------------------- Message::setStandardToAnswer()
551 //------------------------------------------------------------------------------
552 void Message::setStandardToAnswer(const Message &request, const std::string &originHost, const std::string &originRealm, int resultCode) throw(anna::RuntimeException) {
553 if(!request.getId().second) return;
556 setHeaderToAnswer(request);
557 // Session-Id if exists:
558 const Avp *reqSessionId = request.getAvp(helpers::base::AVPID__Session_Id, 1, anna::Exception::Mode::Ignore);
561 if(!getAvp(helpers::base::AVPID__Session_Id, 1, anna::Exception::Mode::Ignore))
562 addAvp(helpers::base::AVPID__Session_Id)->getUTF8String()->setValue(reqSessionId->getUTF8String()->getValue());
564 // Origin-Host & Realm
565 if(!getAvp(helpers::base::AVPID__Origin_Host, 1, anna::Exception::Mode::Ignore))
566 addAvp(helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(originHost);
568 if(!getAvp(helpers::base::AVPID__Origin_Realm, 1, anna::Exception::Mode::Ignore))
569 addAvp(helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(originRealm);
571 // Proxy-Info AVPs if exist, in the same order:
572 for(const_avp_iterator it = request.avp_begin(); it != request.avp_end(); it++)
573 if((*it).second->getId() == helpers::base::AVPID__Proxy_Info)
574 addAvp((*it).second);
576 // If no Result-Code was added is because all was ok, then application could detect another problem:
577 setResultCode(resultCode);
581 std::string msg = "Completed answer:\n";
582 msg += asXMLString();
583 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
588 //------------------------------------------------------------------------------
589 //--------------------------------------------------------------- Message::fix()
590 //------------------------------------------------------------------------------
591 void Message::fix() throw() {
592 // Dictionary stack command:
593 const stack::Command *stackCommand = getStackCommand();
596 LOGDEBUG(anna::Logger::debug("No dictionary command reference found. Cannot fix.", ANNA_FILE_LOCATION));
597 // Try to get to the first place the Session-ID (if exists) because...
598 // RFC 6733: All messages pertaining to a specific session MUST include only one Session-Id AVP ...
599 // ... When present, the Session-Id SHOULD appear immediately following the Diameter header
600 avp_iterator it = Avp::avp_find(a_avps, helpers::base::AVPID__Session_Id, 1 /* one and only */);
602 if(it != avp_end()) {
603 int sessionPos = (*it).first;
604 Avp *first = (*avp_begin()).second;
605 a_avps[0] = (*it).second; // Session-Id
606 a_avps[sessionPos] = first;
607 LOGDEBUG(anna::Logger::debug("Session-Id has been manually fixed to the first place", ANNA_FILE_LOCATION));
613 Avp::fix(a_avps, (find_container&)a_finds, a_insertionPositionForChilds, stackCommand->avprule_begin(), stackCommand->avprule_end());
617 //------------------------------------------------------------------------------
618 //------------------------------------------------------------- Message::valid()
619 //------------------------------------------------------------------------------
620 bool Message::valid(Message *ptrAnswer) const throw(anna::RuntimeException) {
622 OamModule &oamModule = OamModule::instantiate();
623 // Dictionary stack command:
624 const stack::Command *stackCommand = getStackCommand();
625 // Only build answer for a request:
626 Message *answer = isRequest() ? ptrAnswer : NULL;
628 if(answer) answer->setHeaderToAnswer(*this);
632 std::string me = anna::diameter::functions::commandIdAsPairString(a_id);
633 oamModule.activateAlarm(OamModule::Alarm::MessageValidation__UnknownOperation__s__UnableToValidate, STRING_WITH_QUOTATION_MARKS__C_STR(me));
634 oamModule.count(OamModule::Counter::MessageValidation__UnknownOperationUnableToValidate);
636 if(answer) answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_COMMAND_UNSUPPORTED);
638 getEngine()->validationAnomaly(anna::functions::asString("Unknown operation %s. Unable to validate", STRING_WITH_QUOTATION_MARKS__C_STR(me)));
642 // Parent information:
644 me.setMessage(a_id, stackCommand->getName().c_str());
646 //////////////////////////////
647 // Flags coherence checking //
648 //////////////////////////////
650 bool result = flagsOK(rc);
653 // OAM & Depth management
654 oamModule.activateAlarm(OamModule::Alarm::MessageValidation__Operation__s__HaveIncoherentFlags__d__, STRING_WITH_QUOTATION_MARKS__C_STR(me.asString()), (int)a_flags);
655 oamModule.count(OamModule::Counter::MessageValidation__OperationHaveIncoherentFlags);
657 if(answer) answer->setResultCode(rc);
659 getEngine()->validationAnomaly(anna::functions::asString("Operation %s have incoherent flags (%d)", STRING_WITH_QUOTATION_MARKS__C_STR(me.asString()), (int)a_flags));
665 result = Avp::validLevel(a_avps, stackCommand->avprule_begin(), stackCommand->avprule_end(), getEngine(), me, answer) && result;
667 ////////////////////////
668 // Childrens checking //
669 ////////////////////////
670 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++)
671 result = ((*it).second->valid(me, answer)) && result;
677 //------------------------------------------------------------------------------
678 //-------------------------------------------------------------- Message::code()
679 //------------------------------------------------------------------------------
680 const anna::DataBlock & Message::code() throw(anna::RuntimeException) {
682 Engine::ValidationMode::_v vmode = getEngine()->getValidationMode();
684 if((vmode == Engine::ValidationMode::BeforeEncoding) || (vmode == Engine::ValidationMode::Always)) {
686 throw anna::RuntimeException("Try to encode an invalid message. See previous report on warning-level traces", ANNA_FILE_LOCATION);
690 Engine::FixMode::_v fmode = getEngine()->getFixMode();
692 if((fmode == Engine::FixMode::BeforeEncoding) || (fmode == Engine::FixMode::Always)) fix();
696 std::string trace = "Message to code:\n";
697 trace += asXMLString();
698 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
701 U24 length = getLength();
703 a_forCode.allocate(length);
704 char* buffer = (char*)a_forCode.getData();
705 // Version and length
706 buffer[0] = (S8) a_version;
707 buffer[1] = (S8)(length >> 16);
708 buffer[2] = (S8)(length >> 8);
709 buffer[3] = (S8) length;
711 buffer[4] = (S8) a_flags;
712 buffer[5] = (S8)(a_id.first >> 16);
713 buffer[6] = (S8)(a_id.first >> 8);
714 buffer[7] = (S8) a_id.first;
716 buffer[8] = (S8)(a_applicationId >> 24);
717 buffer[9] = (S8)(a_applicationId >> 16);
718 buffer[10] = (S8)(a_applicationId >> 8);
719 buffer[11] = (S8) a_applicationId;
721 buffer[12] = (S8)(a_hopByHop >> 24);
722 buffer[13] = (S8)(a_hopByHop >> 16);
723 buffer[14] = (S8)(a_hopByHop >> 8);
724 buffer[15] = (S8) a_hopByHop;
726 buffer[16] = (S8)(a_endToEnd >> 24);
727 buffer[17] = (S8)(a_endToEnd >> 16);
728 buffer[18] = (S8)(a_endToEnd >> 8);
729 buffer[19] = (S8) a_endToEnd;
730 // Data start position:
731 int startDataPos = HeaderLength;
733 if(startDataPos == length) {
734 LOGDEBUG(anna::Logger::debug("There is no Avps to encode (only-header message)", ANNA_FILE_LOCATION));
737 S8 * dataPart = buffer + startDataPos;
738 int dataBytes; // not used but could be useful for checking (length - startDataPos)
739 // Each avp encoding will remain padding octets depending on format. In order to
740 // code avps colection (each avp will be multiple of 4) we clean the entire buffer
741 // to ensure padding (easier than custom-made for each format):
742 memset(dataPart, 0, length - startDataPos); // no estoy seguro de que el clear del DataBlock haga esto...
744 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) {
745 Avp::avp(it)->code(dataPart, dataBytes);
746 dataPart = dataPart + 4 * REQUIRED_WORDS(dataBytes);
752 std::string trace = "DataBlock encoded:\n";
753 trace += a_forCode.asString();
754 // trace += "\nAs continuous hexadecimal string:\n";
755 // trace += anna::functions::asHexString(a_forCode);
756 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
761 //------------------------------------------------------------------------------
762 //----------------------------------------------------------- Message::loadXML()
763 //------------------------------------------------------------------------------
764 void Message::loadXML(const std::string &xmlPathFile) throw(anna::RuntimeException) {
766 anna::xml::DocumentFile xmlDocument;
767 anna::diameter::codec::functions::messageXmlDocumentFromXmlFile(xmlDocument, xmlPathFile);
768 fromXML(xmlDocument.getRootNode());
771 //------------------------------------------------------------------------------
772 //----------------------------------------------------------- Message::fromXML()
773 //------------------------------------------------------------------------------
774 void Message::fromXML(const anna::xml::Node* messageNode) throw(anna::RuntimeException) {
775 // <!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>
776 const anna::xml::Attribute *version, *name, *code, *flags, *pbit, *ebit, *tbit, *appid, *hbh, *ete;
777 version = messageNode->getAttribute("version", false /* no exception */);
778 name = messageNode->getAttribute("name", false /* no exception */);
779 code = messageNode->getAttribute("code", false /* no exception */);
780 flags = messageNode->getAttribute("flags", false /* no exception */);
781 pbit = messageNode->getAttribute("p-bit", false /* no exception */);
782 ebit = messageNode->getAttribute("e-bit", false /* no exception */);
783 tbit = messageNode->getAttribute("t-bit", false /* no exception */);
784 appid = messageNode->getAttribute("application-id"); // required
785 hbh = messageNode->getAttribute("hop-by-hop-id", false /* no exception */);
786 ete = messageNode->getAttribute("end-by-end-id", false /* no exception */);
791 clear(false /* respect engine */);
794 i_aux = version->getIntegerValue();
796 if(i_aux < 0 || i_aux > 256) {
797 std::string msg = "Error processing avp <version '"; msg += version->getValue();
798 msg += "': out of range [0,256]";
799 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
806 // This is called before any operation which needs to know about the stack elements (this could set the dictionary)
807 setApplicationId(appid->getIntegerValue());
810 const stack::Dictionary * dictionary = getEngine()->getDictionary();
811 const stack::Command *stackCommand = NULL;
816 std::string msg = "Error processing command <name '"; msg += name->getValue();
817 msg += "'>: no dictionary available. Load one or use <'code' + 'flags'> instead of <'name'>";
818 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
821 stackCommand = dictionary->getCommand(name->getValue());
824 std::string msg = "Error processing command <name '"; msg += name->getValue();
825 msg += "'>: no command found for this identifier at available dictionary";
826 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
830 // Check attributes exclusiveness
831 if(name) { // compact mode
833 std::string msg = "Error processing command <name '"; msg += name->getValue();
834 msg += "'>: message attributes <'code' + 'flags'> are not allowed if <'name'> is provided";
835 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
838 setId(stackCommand->getId());
840 // 'P', 'E' and 'T' flags:
841 bool activateP = pbit ? (pbit->getValue() == "yes") : false;
842 bool activateE = ebit ? (ebit->getValue() == "yes") : false;
843 bool activateT = tbit ? (tbit->getValue() == "yes") : false;
845 if(activateP) a_flags |= PBitMask;
847 if(activateE) a_flags |= EBitMask;
849 if(activateT) a_flags |= TBitMask;
851 std::string s_code = code ? code->getValue() : "?";
852 std::string s_flags = flags ? flags->getValue() : "?";
854 if(!code || !flags) {
855 std::string msg = "Error processing command <code '"; msg += s_code;
856 msg += "' + flags '"; msg += s_flags;
857 msg += "'>: both must be provided if <'name'> don't";
858 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
861 if(pbit || ebit || tbit) {
862 std::string msg = "Error processing command <code '"; msg += s_code;
863 msg += "' + flags '"; msg += s_flags;
864 msg += "'>: neither of 'p-bit', 'e-bit' or 't-bit' fields are allowed if those are present";
865 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
869 i_aux = code->getIntegerValue();
872 std::string msg = "Error processing command <code '"; msg += s_code;
873 msg += "': negative values are not allowed";
874 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
879 i_aux = flags->getIntegerValue();
881 if(i_aux < 0 || i_aux > 256) {
882 std::string msg = "Error processing command <flags '"; msg += s_flags;
883 msg += "': out of range [0,256]";
884 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
888 int flagsBCK = a_flags;
890 a_id = CommandId(u_code, requestBit() /* based on a_flags */);
891 // Flags could have been updated regarding dictionary, but during parsing we must respect xml file:
897 u_aux = hbh->getIntegerValue();
901 std::string msg = "Error processing command <hop-by-hop-id '"; msg += hbh->getValue();
902 msg += "': negative values are not allowed";
903 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
912 u_aux = ete->getIntegerValue();
916 std::string msg = "Error processing command <end-to-end-id '"; msg += ete->getValue();
917 msg += "': negative values are not allowed";
918 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
927 for(anna::xml::Node::const_child_iterator it = messageNode->child_begin(); it != messageNode->child_end(); it++) {
928 std::string nodeName = (*it)->getName();
930 if(nodeName != "avp") {
931 std::string msg = "Unsupported message child node name '"; msg += nodeName;
932 msg += "': use 'avp'";
933 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
937 avp = getEngine()->createAvp(NULL);
939 } catch(anna::RuntimeException &ex) {
940 getEngine()->releaseAvp(avp);
949 //------------------------------------------------------------------------------
950 //------------------------------------------------------------- Message::asXML()
951 //------------------------------------------------------------------------------
952 anna::xml::Node* Message::asXML(anna::xml::Node* parent) const throw() {
953 // <!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>
954 anna::xml::Node* result = parent->createChild("message");
955 // Dictionary stack command:
956 const stack::Command *stackCommand = getStackCommand();
957 bool compactMode = stackCommand /*&& flagsOK()*/;
958 result->createAttribute("version", anna::functions::asString((int)a_version));
961 result->createAttribute("name", stackCommand->getName());
963 if(proxiableBit()) result->createAttribute("p-bit", "yes");
965 if(errorBit()) result->createAttribute("e-bit", "yes");
967 if(potentiallyReTransmittedMessageBit()) result->createAttribute("t-bit", "yes");
969 result->createAttribute("code", a_id.first);
970 result->createAttribute("flags", (int)a_flags);
973 result->createAttribute("application-id", anna::functions::asString(a_applicationId));
974 result->createAttribute("hop-by-hop-id", anna::functions::asString(a_hopByHop));
975 result->createAttribute("end-by-end-id", anna::functions::asString(a_endToEnd));
978 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) {
979 Avp::avp(it)->asXML(result);
986 //------------------------------------------------------------------------------
987 //------------------------------------------------------- Message::asXMLString()
988 //------------------------------------------------------------------------------
989 std::string Message::asXMLString() const throw() {
990 anna::xml::Node root("root");
991 return anna::xml::Compiler().apply(asXML(&root));
995 //------------------------------------------------------------------------------
996 //------------------------------------------------------------ Message::isLike()
997 //------------------------------------------------------------------------------
998 bool Message::isLike(const std::string &pattern) const throw() {
999 anna::RegularExpression re(pattern);
1000 return re.isLike(asXMLString());