1 // ANNA - Anna is Not Nothingness Anymore
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
5 // http://redmine.teslayout.com/projects/anna-suite
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
11 // * Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
13 // * Redistributions in binary form must reproduce the above
14 // copyright notice, this list of conditions and the following disclaimer
15 // in the documentation and/or other materials provided with the
17 // * Neither the name of the copyright holder nor the names of its
18 // contributors may be used to endorse or promote products derived from
19 // this software without specific prior written permission.
21 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 // Authors: eduardo.ramos.testillano@gmail.com
34 // cisco.tierra@gmail.com
38 #include <anna/diameter/codec/Message.hpp>
39 #include <anna/diameter/codec/Format.hpp>
41 #include <anna/diameter/codec/functions.hpp> // REQUIRED_WORDS
42 #include <anna/config/defines.hpp> // general types, decoding helpers (DECODE[2/3/4]BYTES_INDX_VALUETYPE), etc.
43 #include <anna/diameter/functions.hpp>
44 #include <anna/diameter/codec/functions.hpp> // REQUIRED_WORDS
45 #include <anna/diameter/codec/OamModule.hpp>
46 #include <anna/diameter/codec/Engine.hpp>
47 #include <anna/diameter/stack/Avp.hpp>
48 #include <anna/diameter/stack/Format.hpp>
49 #include <anna/diameter/stack/Dictionary.hpp>
50 #include <anna/diameter/stack/Engine.hpp>
51 #include <anna/core/functions.hpp>
52 #include <anna/core/util/RegularExpression.hpp>
53 #include <anna/diameter/helpers/base/defines.hpp>
55 #include <anna/core/tracing/Logger.hpp>
56 #include <anna/core/functions.hpp>
57 #include <anna/core/tracing/TraceMethod.hpp>
58 #include <anna/xml/xml.hpp>
66 using namespace anna::diameter::codec;
75 const int Message::HeaderLength(20);
76 const U8 Message::RBitMask(0x80);
77 const U8 Message::PBitMask(0x40);
78 const U8 Message::EBitMask(0x20);
79 const U8 Message::TBitMask(0x10);
84 //------------------------------------------------------------------------------
85 //----------------------------------------------------------- Message::Message()
86 //------------------------------------------------------------------------------
87 Message::Message() : a_forCode(true) {
92 //------------------------------------------------------------------------------
93 //----------------------------------------------------------- Message::Message()
94 //------------------------------------------------------------------------------
95 Message::Message(CommandId id) : a_forCode(true) {
101 //------------------------------------------------------------------------------
102 //---------------------------------------------------------- Message::~Message()
103 //------------------------------------------------------------------------------
104 Message::~Message() {
109 //------------------------------------------------------------------------------
110 //--------------------------------------------------------- Message::getEngine()
111 //------------------------------------------------------------------------------
112 Engine * Message::getEngine() const throw(anna::RuntimeException) {
113 return a_engine ? a_engine : (a_engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION));
117 //------------------------------------------------------------------------------
118 //-------------------------------------------------------- Message::initialize()
119 //------------------------------------------------------------------------------
120 void Message::initialize() throw() {
123 a_id = CommandId(0, false);
129 a_insertionPositionForChilds = 0;
134 //------------------------------------------------------------------------------
135 //------------------------------------------------------------- Message::clear()
136 //------------------------------------------------------------------------------
137 void Message::clear() throw(anna::RuntimeException) {
138 for(avp_iterator it = avp_begin(); it != avp_end(); it++) { /*avp(it)->clear(); */getEngine()->releaseAvp(Avp::avp(it)); }
149 //------------------------------------------------------------------------------
150 //----------------------------------------------------------- Message::flagsOK()
151 //------------------------------------------------------------------------------
152 bool Message::flagsOK(int &rc) const throw() {
153 // Dictionary stack command:
154 const stack::Command *stackCommand = getStackCommand();
157 anna::Logger::error("Impossible to decide if flags are correct because stack command is not identified. Assume flags ok", ANNA_FILE_LOCATION);
158 //rc = helpers::base::AVPVALUES__Result_Code::?????;
162 // DIAMETER_INVALID_HDR_BITS 3008
164 // A request was received whose bits in the Diameter header were set
165 // either to an invalid combination or to a value that is
166 // inconsistent with the Command Code's definition.
169 if(stackCommand->isRequest() != isRequest()) ok = false; // en teoria es imposible salir por aqui: blindado en la dtd
171 if(isRequest() && errorBit()) {
172 anna::Logger::error("E(rror) bit is not allowed at diameter requests", ANNA_FILE_LOCATION);
176 if(isAnswer() && potentiallyReTransmittedMessageBit()) {
177 anna::Logger::error("T(Potentially re-transmitted message) bit is not allowed at diameter answers", ANNA_FILE_LOCATION);
182 rc = helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_HDR_BITS;
186 // DIAMETER_INVALID_BIT_IN_HEADER 5013
188 // This error is returned when a reserved bit in the Diameter header
189 // is set to one (1) or the bits in the Diameter header are set
191 if((a_flags & 0x0f) != 0x00) {
192 anna::Logger::error("Any (or more than one) of the reserved message flags bit has been activated. Reserved bits must be null", ANNA_FILE_LOCATION);
193 rc = helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_BIT_IN_HEADER;
201 //------------------------------------------------------------------------------
202 //------------------------------------------------------------- Message::setId()
203 //------------------------------------------------------------------------------
204 void Message::setId(CommandId id, bool _clear) throw(anna::RuntimeException) {
205 // Clear class content:
210 // Dictionary stack command:
211 const stack::Command *stackCommand = getStackCommand(); // based on dictionary and a_id
213 // Dictionary flags for known types:
215 if(stackCommand->isRequest()) a_flags |= RBitMask;
217 if(a_id.second) a_flags |= RBitMask; else a_flags &= (~RBitMask);
222 //------------------------------------------------------------------------------
223 //------------------------------------------------------------- Message::setId()
224 //------------------------------------------------------------------------------
225 void Message::setId(const char *name) throw(anna::RuntimeException) {
226 setId(getEngine()->commandIdForName(name));
230 //------------------------------------------------------------------------------
231 //-------------------------------------------------- Message::setApplicationId()
232 //------------------------------------------------------------------------------
233 void Message::setApplicationId(U32 aid) throw() {
234 a_applicationId = aid;
236 // Default behaviour:
237 if (!getEngine()->hasSelectStackWithApplicationId()) return;
239 // Adapts for Application-ID stack identifier:
240 getEngine()->setDictionary(aid);
244 //------------------------------------------------------------------------------
245 //------------------------------------------------------------ Message::addAvp()
246 //------------------------------------------------------------------------------
247 Avp * Message::addAvp(const char *name) throw(anna::RuntimeException) {
248 return addAvp(getEngine()->avpIdForName(name));
252 //------------------------------------------------------------------------------
253 //--------------------------------------------------------- Message::removeAvp()
254 //------------------------------------------------------------------------------
255 bool Message::removeAvp(const char *name, int ocurrence) throw(anna::RuntimeException) {
256 return removeAvp(getEngine()->avpIdForName(name), ocurrence);
260 //------------------------------------------------------------------------------
261 //----------------------------------------------------------- Message::_getAvp()
262 //------------------------------------------------------------------------------
263 const Avp * Message::_getAvp(const char *name, int ocurrence, anna::Exception::Mode::_v emode) const throw(anna::RuntimeException) {
264 return getAvp(getEngine()->avpIdForName(name), ocurrence, emode);
268 //------------------------------------------------------------------------------
269 //---------------------------------------------------------- Message::countAvp()
270 //------------------------------------------------------------------------------
271 int Message::countAvp(const char *name) const throw(anna::RuntimeException) {
272 return countAvp(getEngine()->avpIdForName(name));
276 //------------------------------------------------------------------------------
277 //--------------------------------------------------------- Message::getLength()
278 //------------------------------------------------------------------------------
279 U24 Message::getLength() const throw() {
282 result = HeaderLength;
284 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) result += 4 * REQUIRED_WORDS(Avp::avp(it)->getLength());
290 //------------------------------------------------------------------------------
291 //------------------------------------------------------------ Message::decode()
292 //------------------------------------------------------------------------------
293 void Message::decode(const anna::DataBlock &db, Message *ptrAnswer) throw(anna::RuntimeException) {
296 anna::xml::Node root("Message::decode");
297 std::string trace = "DataBlock to decode:\n";
298 trace += db.asString();
299 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
302 // EXCEPTION MANAGEMENT IN THIS METHOD
303 // ===================================
305 // If an error ocurred, decoding will stop launching exception but we will catch it and go on with validation because perhaps
306 // the achieved message could be valid against all odds. Only fatal errors cause direct decoding exception (length problems
310 // Launch exception on first validation error (validateAll == false), or log warning reporting all validation errors when
311 // complete validation is desired (validateAll == true, engine default) launching a final exception like "the decoded message is invalid".
313 OamModule &oamModule = OamModule::instantiate();
315 if(db.getSize() < HeaderLength) {
316 oamModule.activateAlarm(OamModule::Alarm::MessageDecode__NotEnoughBytesToCoverMessageHeaderLength);
317 oamModule.count(OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageHeaderLength);
318 // DIAMETER_INVALID_MESSAGE_LENGTH; // no podr� construir un answer fiable, as� que no registro el result-code
319 throw anna::RuntimeException("Not enough bytes to cover message header length (20 bytes)", ANNA_FILE_LOCATION);
322 const char * buffer = db.getData();
325 // 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
326 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
327 // | Version | Message Length |
328 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
329 // | command flags | Command-Code |
330 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
331 // | Application-ID |
332 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
333 // | Hop-by-Hop Identifier |
334 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
335 // | End-to-End Identifier |
336 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
338 // +-+-+-+-+-+-+-+-+-+-+-+-+-
340 a_version = (S8)buffer[0];
342 U24 length = DECODE3BYTES_INDX_VALUETYPE(buffer, 1, U24); // total length including header fields
344 a_flags = (S8)buffer[4];
346 U24 code = DECODE3BYTES_INDX_VALUETYPE(buffer, 5, U24);
348 a_id = CommandId(code, requestBit() /* based on a_flags */);
350 setApplicationId(DECODE4BYTES_INDX_VALUETYPE(buffer, 8, U32)); // centralize set, because it could be used for stack selection.
352 a_hopByHop = DECODE4BYTES_INDX_VALUETYPE(buffer, 12, U32);
354 a_endToEnd = DECODE4BYTES_INDX_VALUETYPE(buffer, 16, U32);
356 // Only build answer for a request:
357 Message *answer = isRequest() ? ptrAnswer : NULL;
359 if(answer) answer->setHeaderToAnswer(*this);
362 if(db.getSize() < length) {
363 oamModule.activateAlarm(OamModule::Alarm::MessageDecode__NotEnoughBytesToCoverMessageLength);
364 oamModule.count(OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageLength);
366 if(answer) answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_MESSAGE_LENGTH);
368 throw anna::RuntimeException("Not enough bytes to cover message length", ANNA_FILE_LOCATION);
371 // Message identifier
372 // Flags could have been updated regarding dictionary, but during decoding we must respect buffer received:
373 a_flags = (S8)buffer[4];
374 // Avps start position:
375 const S8 * startData = buffer + HeaderLength;
376 U24 dataBytes = length - HeaderLength;
378 if(dataBytes < 8 /* minimum avp */) {
379 LOGDEBUG(anna::Logger::debug("Message empty (without avps)", ANNA_FILE_LOCATION));
385 anna::DataBlock db_aux;
387 // Parent information:
389 parent.setMessage(a_id);
392 while(avpPos < dataBytes) {
394 avp = getEngine()->allocateAvp();
395 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) */);
396 avp -> decode(db_aux, parent, answer);
397 } catch(anna::RuntimeException &ex) {
398 getEngine()->releaseAvp(avp);
400 anna::Logger::warning(ex.getText(), ANNA_FILE_LOCATION);
401 anna::Logger::warning("Although a decoding error was found, validation could be checked because message could be enough for the application", ANNA_FILE_LOCATION);
407 avpPos += 4 * REQUIRED_WORDS(avp->getLength());
411 Engine::FixMode::_v fmode = getEngine()->getFixMode();
413 if((fmode == Engine::FixMode::AfterDecoding) || (fmode == Engine::FixMode::Always)) fix();
417 std::string trace = "Message decoded:\n";
418 trace += asXMLString();
419 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
422 Engine::ValidationMode::_v vmode = getEngine()->getValidationMode();
424 if((vmode == Engine::ValidationMode::AfterDecoding) || (vmode == Engine::ValidationMode::Always))
426 throw anna::RuntimeException("The decoded message is invalid. See previous report on warning-level traces", ANNA_FILE_LOCATION);
430 //------------------------------------------------------------------------------
431 //--------------------------------------------------- Message::getStackCommand()
432 //------------------------------------------------------------------------------
433 const anna::diameter::stack::Command *Message::getStackCommand(CommandId id) const throw(anna::RuntimeException) {
434 const stack::Dictionary * dictionary = getEngine()->getDictionary();
435 return (dictionary ? (dictionary->getCommand(id)) : NULL);
439 //------------------------------------------------------------------------------
440 //----------------------------------------------------- Message::setResultCode()
441 //------------------------------------------------------------------------------
442 void Message::setResultCode(int rc) throw(anna::RuntimeException) {
443 if(isRequest()) return;
445 // Add Result-Code if not yet added. Even if validation depth is set to 'Complete',
446 // the Result-Code value will be the first found during the message analysis:
447 Avp *resultCodeAvp = getAvp(helpers::base::AVPID__Result_Code, 1, anna::Exception::Mode::Ignore);
450 addAvp(helpers::base::AVPID__Result_Code)->getUnsigned32()->setValue(rc);
451 else if(resultCodeAvp->getUnsigned32()->getValue() == helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS) // Only success could be replaced
452 resultCodeAvp->getUnsigned32()->setValue(rc);
455 setErrorBit(rc >= 3001 && rc <= 3010 /* protocol errors */);
459 //------------------------------------------------------------------------------
460 //----------------------------------------------------- Message::getResultCode()
461 //------------------------------------------------------------------------------
462 int Message::getResultCode() const throw() {
464 const Avp *resultCodeAvp = getAvp(helpers::base::AVPID__Result_Code, 1, anna::Exception::Mode::Ignore);
467 return resultCodeAvp->getUnsigned32()->getValue();
474 //------------------------------------------------------------------------------
475 //------------------------------------------------------ Message::setFailedAvp()
476 //------------------------------------------------------------------------------
477 void Message::setFailedAvp(const parent_t &parent, AvpId wrong, const char *wrongName) throw(anna::RuntimeException) {
479 if(isRequest()) return;
483 // 7.5. Failed-AVP AVP
485 // The Failed-AVP AVP (AVP Code 279) is of type Grouped and provides
486 // debugging information in cases where a request is rejected or not
487 // fully processed due to erroneous information in a specific AVP. The
488 // value of the Result-Code AVP will provide information on the reason
489 // for the Failed-AVP AVP. A Diameter answer message SHOULD contain an
490 // instance of the Failed-AVP AVP that corresponds to the error
491 // indicated by the Result-Code AVP. For practical purposes, this
492 // Failed-AVP would typically refer to the first AVP processing error
493 // that a Diameter node encounters.
495 // Although the Failed-AVP definition has cardinality 1* and Failed-AVP itself is defined in
496 // most of the command codes as *[Failed-AVP], i think this is not a deliberate ambiguity.
497 // Probably the RFC wants to give freedom to the application layer, but it is recommended to
498 // have only one child (wrong avp) inside a unique message Failed-AVP to ease the Result-Code
499 // correspondence. Anyway, this behaviour could be easily opened commenting condition block (*).
500 Avp *theFailedAvp = getAvp(helpers::base::AVPID__Failed_AVP, 1, anna::Exception::Mode::Ignore);
502 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));
506 // Section 7.5 RFC 6733: A Diameter message SHOULD contain one Failed-AVP AVP
507 theFailedAvp = addAvp(helpers::base::AVPID__Failed_AVP);
508 Avp *leaf = theFailedAvp;
511 std::string msg = "Adding to Failed-AVP, the wrong avp ";
512 msg += wrongName ? wrongName : (anna::diameter::functions::avpIdAsPairString(wrong));
513 msg += " found inside ";
514 msg += parent.asString();
516 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
519 std::vector<AvpId>::const_iterator it;
520 for(it = parent.AvpsId.begin(); it != parent.AvpsId.end(); it++)
521 leaf = leaf->addAvp(*it);
527 //------------------------------------------------------------------------------
528 //----------------------------------------------- Message::setStandardToAnswer()
529 //------------------------------------------------------------------------------
530 void Message::setStandardToAnswer(const Message &request, const std::string &originHost, const std::string &originRealm, int resultCode) throw() {
531 if(!request.getId().second) return;
534 setHeaderToAnswer(request);
535 // Session-Id if exists:
536 const Avp *reqSessionId = request.getAvp(helpers::base::AVPID__Session_Id, 1, anna::Exception::Mode::Ignore);
539 if(!getAvp(helpers::base::AVPID__Session_Id, 1, anna::Exception::Mode::Ignore))
540 addAvp(helpers::base::AVPID__Session_Id)->getUTF8String()->setValue(reqSessionId->getUTF8String()->getValue());
542 // Origin-Host & Realm
543 if(!getAvp(helpers::base::AVPID__Origin_Host, 1, anna::Exception::Mode::Ignore))
544 addAvp(helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(originHost);
546 if(!getAvp(helpers::base::AVPID__Origin_Realm, 1, anna::Exception::Mode::Ignore))
547 addAvp(helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(originRealm);
549 // Proxy-Info AVPs if exist, in the same order:
550 for(const_avp_iterator it = request.avp_begin(); it != request.avp_end(); it++)
551 if((*it).second->getId() == helpers::base::AVPID__Proxy_Info)
552 addAvp((*it).second);
554 // If no Result-Code was added is because all was ok, then application could detect another problem:
555 setResultCode(resultCode);
559 std::string msg = "Completed answer:\n";
560 msg += asXMLString();
561 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
566 //------------------------------------------------------------------------------
567 //--------------------------------------------------------------- Message::fix()
568 //------------------------------------------------------------------------------
569 void Message::fix() throw() {
570 // Dictionary stack command:
571 const stack::Command *stackCommand = getStackCommand();
574 LOGDEBUG(anna::Logger::debug("No dictionary command reference found. Cannot fix.", ANNA_FILE_LOCATION));
575 // Try to get to the first place the Session-ID (if exists) because...
576 // RFC 6733: All messages pertaining to a specific session MUST include only one Session-Id AVP ...
577 // ... When present, the Session-Id SHOULD appear immediately following the Diameter header
578 avp_iterator it = Avp::avp_find(a_avps, helpers::base::AVPID__Session_Id, 1 /* one and only */);
580 if(it != avp_end()) {
581 int sessionPos = (*it).first;
582 Avp *first = (*avp_begin()).second;
583 a_avps[0] = (*it).second; // Session-Id
584 a_avps[sessionPos] = first;
585 LOGDEBUG(anna::Logger::debug("Session-Id has been manually fixed to the first place", ANNA_FILE_LOCATION));
591 Avp::fix(a_avps, (find_container&)a_finds, a_insertionPositionForChilds, stackCommand->avprule_begin(), stackCommand->avprule_end());
595 //------------------------------------------------------------------------------
596 //------------------------------------------------------------- Message::valid()
597 //------------------------------------------------------------------------------
598 bool Message::valid(Message *ptrAnswer) const throw(anna::RuntimeException) {
600 OamModule &oamModule = OamModule::instantiate();
601 // Dictionary stack command:
602 const stack::Command *stackCommand = getStackCommand();
603 // Only build answer for a request:
604 Message *answer = isRequest() ? ptrAnswer : NULL;
606 if(answer) answer->setHeaderToAnswer(*this);
610 std::string me = anna::diameter::functions::commandIdAsPairString(a_id);
611 oamModule.activateAlarm(OamModule::Alarm::MessageValidation__UnknownOperation__s__UnableToValidate, STRING_WITH_QUOTATION_MARKS__C_STR(me));
612 oamModule.count(OamModule::Counter::MessageValidation__UnknownOperationUnableToValidate);
614 if(answer) answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_COMMAND_UNSUPPORTED);
616 getEngine()->validationAnomaly(anna::functions::asString("Unknown operation %s. Unable to validate", STRING_WITH_QUOTATION_MARKS__C_STR(me)));
620 // Parent information:
622 me.setMessage(a_id, stackCommand->getName().c_str());
624 //////////////////////////////
625 // Flags coherence checking //
626 //////////////////////////////
628 bool result = flagsOK(rc);
631 // OAM & Depth management
632 oamModule.activateAlarm(OamModule::Alarm::MessageValidation__Operation__s__HaveIncoherentFlags__d__, STRING_WITH_QUOTATION_MARKS__C_STR(me.asString()), (int)a_flags);
633 oamModule.count(OamModule::Counter::MessageValidation__OperationHaveIncoherentFlags);
635 if(answer) answer->setResultCode(rc);
637 getEngine()->validationAnomaly(anna::functions::asString("Operation %s have incoherent flags (%d)", STRING_WITH_QUOTATION_MARKS__C_STR(me.asString()), (int)a_flags));
643 result = Avp::validLevel(a_avps, stackCommand->avprule_begin(), stackCommand->avprule_end(), getEngine(), me, answer) && result;
645 ////////////////////////
646 // Childrens checking //
647 ////////////////////////
648 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++)
649 result = ((*it).second->valid(me, answer)) && result;
655 //------------------------------------------------------------------------------
656 //-------------------------------------------------------------- Message::code()
657 //------------------------------------------------------------------------------
658 const anna::DataBlock & Message::code() throw(anna::RuntimeException) {
660 Engine::ValidationMode::_v vmode = getEngine()->getValidationMode();
662 if((vmode == Engine::ValidationMode::BeforeCoding) || (vmode == Engine::ValidationMode::Always)) {
664 throw anna::RuntimeException("Try to encode an invalid message. See previous report on warning-level traces", ANNA_FILE_LOCATION);
668 Engine::FixMode::_v fmode = getEngine()->getFixMode();
670 if((fmode == Engine::FixMode::BeforeCoding) || (fmode == Engine::FixMode::Always)) fix();
674 std::string trace = "Message to code:\n";
675 trace += asXMLString();
676 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
679 U24 length = getLength();
681 a_forCode.allocate(length);
682 char* buffer = (char*)a_forCode.getData();
683 // Version and length
684 buffer[0] = (S8) a_version;
685 buffer[1] = (S8)(length >> 16);
686 buffer[2] = (S8)(length >> 8);
687 buffer[3] = (S8) length;
689 buffer[4] = (S8) a_flags;
690 buffer[5] = (S8)(a_id.first >> 16);
691 buffer[6] = (S8)(a_id.first >> 8);
692 buffer[7] = (S8) a_id.first;
694 buffer[8] = (S8)(a_applicationId >> 24);
695 buffer[9] = (S8)(a_applicationId >> 16);
696 buffer[10] = (S8)(a_applicationId >> 8);
697 buffer[11] = (S8) a_applicationId;
699 buffer[12] = (S8)(a_hopByHop >> 24);
700 buffer[13] = (S8)(a_hopByHop >> 16);
701 buffer[14] = (S8)(a_hopByHop >> 8);
702 buffer[15] = (S8) a_hopByHop;
704 buffer[16] = (S8)(a_endToEnd >> 24);
705 buffer[17] = (S8)(a_endToEnd >> 16);
706 buffer[18] = (S8)(a_endToEnd >> 8);
707 buffer[19] = (S8) a_endToEnd;
708 // Data start position:
709 int startDataPos = HeaderLength;
711 if(startDataPos == length) {
712 LOGDEBUG(anna::Logger::debug("There is no Avps to encode (only-header message)", ANNA_FILE_LOCATION));
715 S8 * dataPart = buffer + startDataPos;
716 int dataBytes; // not used but could be useful for checking (length - startDataPos)
717 // Each avp encoding will remain padding octets depending on format. In order to
718 // code avps colection (each avp will be multiple of 4) we clean the entire buffer
719 // to ensure padding (easier than custom-made for each format):
720 memset(dataPart, 0, length - startDataPos); // no estoy seguro de que el clear del DataBlock haga esto...
722 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) {
723 Avp::avp(it)->code(dataPart, dataBytes);
724 dataPart = dataPart + 4 * REQUIRED_WORDS(dataBytes);
730 std::string trace = "DataBlock encoded:\n";
731 trace += a_forCode.asString();
732 // trace += "\nAs continuous hexadecimal string:\n";
733 // trace += anna::functions::asHexString(a_forCode);
734 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
740 //------------------------------------------------------------------------------
741 //----------------------------------------------------- Message::fromXMLString()
742 //------------------------------------------------------------------------------
743 void Message::fromXMLString(const std::string &xmlString) throw(anna::RuntimeException) {
744 LOGDEBUG(anna::Logger::debug("Reading diameter message from xml string representation", ANNA_FILE_LOCATION));
745 anna::xml::DocumentMemory xmlDocument; // has private copy constructor defined but not implemented to avoid inhenrit/copy (is very heavy)
746 const anna::xml::Node *rootNode;
747 xmlDocument.initialize(xmlString.c_str());
748 rootNode = xmlDocument.parse(getEngine()->getDTD()); // Parsing: fail here if xml violates dtd
749 LOGDEBUG(anna::Logger::debug("Read OK from XML string representation", ANNA_FILE_LOCATION));
754 //------------------------------------------------------------------------------
755 //----------------------------------------------------------- Message::fromXML()
756 //------------------------------------------------------------------------------
757 void Message::fromXML(const anna::xml::Node* messageNode) throw(anna::RuntimeException) {
758 // <!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>
759 const anna::xml::Attribute *version, *name, *code, *flags, *pbit, *ebit, *tbit, *appid, *hbh, *ete;
760 version = messageNode->getAttribute("version", false /* no exception */);
761 name = messageNode->getAttribute("name", false /* no exception */);
762 code = messageNode->getAttribute("code", false /* no exception */);
763 flags = messageNode->getAttribute("flags", false /* no exception */);
764 pbit = messageNode->getAttribute("p-bit", false /* no exception */);
765 ebit = messageNode->getAttribute("e-bit", false /* no exception */);
766 tbit = messageNode->getAttribute("t-bit", false /* no exception */);
767 appid = messageNode->getAttribute("application-id"); // required
768 hbh = messageNode->getAttribute("hop-by-hop-id", false /* no exception */);
769 ete = messageNode->getAttribute("end-by-end-id", false /* no exception */);
777 i_aux = version->getIntegerValue();
779 if(i_aux < 0 || i_aux > 256) {
780 std::string msg = "Error processing avp <version '"; msg += version->getValue();
781 msg += "': out of range [0,256]";
782 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
789 // This is called before any operation which needs to know about the stack elements (this could set the dictionary)
790 setApplicationId(appid->getIntegerValue());
793 const stack::Dictionary * dictionary = getEngine()->getDictionary();
794 const stack::Command *stackCommand = NULL;
799 std::string msg = "Error processing command <name '"; msg += name->getValue();
800 msg += "'>: no dictionary available. Load one or use <'code' + 'flags'> instead of <'name'>";
801 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
804 stackCommand = dictionary->getCommand(name->getValue());
807 std::string msg = "Error processing command <name '"; msg += name->getValue();
808 msg += "'>: no command found for this identifier at available dictionary";
809 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
813 // Check attributes exclusiveness
814 if(name) { // compact mode
816 std::string msg = "Error processing command <name '"; msg += name->getValue();
817 msg += "'>: message attributes <'code' + 'flags'> are not allowed if <'name'> is provided";
818 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
821 setId(stackCommand->getId(), false /* don't clear */);
822 // 'P', 'E' and 'T' flags:
823 bool activateP = pbit ? (pbit->getValue() == "yes") : false;
824 bool activateE = ebit ? (ebit->getValue() == "yes") : false;
825 bool activateT = tbit ? (tbit->getValue() == "yes") : false;
827 if(activateP) a_flags |= PBitMask;
829 if(activateE) a_flags |= EBitMask;
831 if(activateT) a_flags |= TBitMask;
833 std::string s_code = code ? code->getValue() : "?";
834 std::string s_flags = flags ? flags->getValue() : "?";
836 if(!code || !flags) {
837 std::string msg = "Error processing command <code '"; msg += s_code;
838 msg += "' + flags '"; msg += s_flags;
839 msg += "'>: both must be provided if <'name'> don't";
840 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
843 if(pbit || ebit || tbit) {
844 std::string msg = "Error processing command <code '"; msg += s_code;
845 msg += "' + flags '"; msg += s_flags;
846 msg += "'>: neither of 'p-bit', 'e-bit' or 't-bit' fields are allowed if those are present";
847 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
851 i_aux = code->getIntegerValue();
854 std::string msg = "Error processing command <code '"; msg += s_code;
855 msg += "': negative values are not allowed";
856 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
861 i_aux = flags->getIntegerValue();
863 if(i_aux < 0 || i_aux > 256) {
864 std::string msg = "Error processing command <flags '"; msg += s_flags;
865 msg += "': out of range [0,256]";
866 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
870 int flagsBCK = a_flags;
872 a_id = CommandId(u_code, requestBit() /* based on a_flags */);
873 // Flags could have been updated regarding dictionary, but during parsing we must respect xml file:
879 u_aux = hbh->getIntegerValue();
883 std::string msg = "Error processing command <hop-by-hop-id '"; msg += hbh->getValue();
884 msg += "': negative values are not allowed";
885 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
894 u_aux = ete->getIntegerValue();
898 std::string msg = "Error processing command <end-to-end-id '"; msg += ete->getValue();
899 msg += "': negative values are not allowed";
900 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
909 for(anna::xml::Node::const_child_iterator it = messageNode->child_begin(); it != messageNode->child_end(); it++) {
910 std::string nodeName = (*it)->getName();
912 if(nodeName != "avp") {
913 std::string msg = "Unsupported message child node name '"; msg += nodeName;
914 msg += "': use 'avp'";
915 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
919 avp = getEngine()->allocateAvp();
921 } catch(anna::RuntimeException &ex) {
922 getEngine()->releaseAvp(avp);
931 //------------------------------------------------------------------------------
932 //----------------------------------------------------------- Message::loadXML()
933 //------------------------------------------------------------------------------
934 void Message::loadXML(const std::string & xmlPathFile) throw(anna::RuntimeException) {
936 std::string trace = "Loading diameter message from file '";
937 trace += xmlPathFile;
939 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
941 anna::xml::DocumentFile xmlDocument; // has private copy constructor defined but not implemented to avoid inhenrit/copy (is very heavy)
942 const anna::xml::Node *rootNode;
943 xmlDocument.initialize(xmlPathFile.c_str()); // fail here is i/o error
944 rootNode = xmlDocument.parse(getEngine()->getDTD()); // Parsing: fail here if xml violates dtd
946 std::string trace = "Loaded XML file (";
947 trace += xmlPathFile;
949 trace += anna::xml::Compiler().apply(rootNode);
950 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
956 //------------------------------------------------------------------------------
957 //------------------------------------------------------------- Message::asXML()
958 //------------------------------------------------------------------------------
959 anna::xml::Node* Message::asXML(anna::xml::Node* parent) const throw() {
960 // <!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>
961 anna::xml::Node* result = parent->createChild("message");
962 // Dictionary stack command:
963 const stack::Command *stackCommand = getStackCommand();
964 bool compactMode = stackCommand /*&& flagsOK()*/;
965 result->createAttribute("version", anna::functions::asString((int)a_version));
968 result->createAttribute("name", stackCommand->getName());
970 if(proxiableBit()) result->createAttribute("p-bit", "yes");
972 if(errorBit()) result->createAttribute("e-bit", "yes");
974 if(potentiallyReTransmittedMessageBit()) result->createAttribute("t-bit", "yes");
976 result->createAttribute("code", a_id.first);
977 result->createAttribute("flags", (int)a_flags);
980 result->createAttribute("application-id", anna::functions::asString(a_applicationId));
981 result->createAttribute("hop-by-hop-id", anna::functions::asString(a_hopByHop));
982 result->createAttribute("end-by-end-id", anna::functions::asString(a_endToEnd));
985 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) {
986 Avp::avp(it)->asXML(result);
993 //------------------------------------------------------------------------------
994 //------------------------------------------------------- Message::asXMLString()
995 //------------------------------------------------------------------------------
996 std::string Message::asXMLString() const throw() {
997 anna::xml::Node root("root");
998 return anna::xml::Compiler().apply(asXML(&root));
1002 //------------------------------------------------------------------------------
1003 //------------------------------------------------------------ Message::isLike()
1004 //------------------------------------------------------------------------------
1005 bool Message::isLike(const std::string &pattern) const throw() {
1006 anna::RegularExpression re(pattern);
1007 return re.isLike(asXMLString());