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/stack/Avp.hpp>
20 #include <anna/diameter/stack/Format.hpp>
21 #include <anna/diameter/stack/Dictionary.hpp>
22 #include <anna/diameter/stack/Engine.hpp>
23 #include <anna/core/functions.hpp>
24 #include <anna/core/util/RegularExpression.hpp>
25 #include <anna/diameter/helpers/base/defines.hpp>
27 #include <anna/core/tracing/Logger.hpp>
28 #include <anna/core/functions.hpp>
29 #include <anna/core/tracing/TraceMethod.hpp>
30 #include <anna/xml/xml.hpp>
38 using namespace anna::diameter::codec;
47 const int Message::HeaderLength(20);
48 const U8 Message::RBitMask(0x80);
49 const U8 Message::PBitMask(0x40);
50 const U8 Message::EBitMask(0x20);
51 const U8 Message::TBitMask(0x10);
56 //------------------------------------------------------------------------------
57 //----------------------------------------------------------- Message::Message()
58 //------------------------------------------------------------------------------
59 Message::Message() : a_forCode(true) {
64 //------------------------------------------------------------------------------
65 //----------------------------------------------------------- Message::Message()
66 //------------------------------------------------------------------------------
67 Message::Message(CommandId id) : a_forCode(true) {
73 //------------------------------------------------------------------------------
74 //---------------------------------------------------------- Message::~Message()
75 //------------------------------------------------------------------------------
81 //------------------------------------------------------------------------------
82 //--------------------------------------------------------- Message::getEngine()
83 //------------------------------------------------------------------------------
84 Engine * Message::getEngine() const throw(anna::RuntimeException) {
85 return a_engine ? a_engine : (a_engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION));
89 //------------------------------------------------------------------------------
90 //-------------------------------------------------------- Message::initialize()
91 //------------------------------------------------------------------------------
92 void Message::initialize() throw() {
95 a_id = CommandId(0, false);
101 a_insertionPositionForChilds = 0;
106 //------------------------------------------------------------------------------
107 //------------------------------------------------------------- Message::clear()
108 //------------------------------------------------------------------------------
109 void Message::clear() throw(anna::RuntimeException) {
110 for(avp_iterator it = avp_begin(); it != avp_end(); it++) { /*avp(it)->clear(); */getEngine()->releaseAvp(Avp::avp(it)); }
121 //------------------------------------------------------------------------------
122 //----------------------------------------------------------- Message::flagsOK()
123 //------------------------------------------------------------------------------
124 bool Message::flagsOK(int &rc) const throw() {
125 // Dictionary stack command:
126 const stack::Command *stackCommand = getStackCommand();
129 anna::Logger::error("Impossible to decide if flags are correct because stack command is not identified. Assume flags ok", ANNA_FILE_LOCATION);
130 //rc = helpers::base::AVPVALUES__Result_Code::?????;
134 // DIAMETER_INVALID_HDR_BITS 3008
136 // A request was received whose bits in the Diameter header were set
137 // either to an invalid combination or to a value that is
138 // inconsistent with the Command Code's definition.
141 if(stackCommand->isRequest() != isRequest()) ok = false; // en teoria es imposible salir por aqui: blindado en la dtd
143 if(isRequest() && errorBit()) {
144 anna::Logger::error("E(rror) bit is not allowed at diameter requests", ANNA_FILE_LOCATION);
148 if(isAnswer() && potentiallyReTransmittedMessageBit()) {
149 anna::Logger::error("T(Potentially re-transmitted message) bit is not allowed at diameter answers", ANNA_FILE_LOCATION);
154 rc = helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_HDR_BITS;
158 // DIAMETER_INVALID_BIT_IN_HEADER 5013
160 // This error is returned when a reserved bit in the Diameter header
161 // is set to one (1) or the bits in the Diameter header are set
163 if((a_flags & 0x0f) != 0x00) {
164 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);
165 rc = helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_BIT_IN_HEADER;
173 //------------------------------------------------------------------------------
174 //------------------------------------------------------------- Message::setId()
175 //------------------------------------------------------------------------------
176 void Message::setId(CommandId id, bool _clear) throw(anna::RuntimeException) {
177 // Clear class content:
182 // Dictionary stack command:
183 const stack::Command *stackCommand = getStackCommand(); // based on dictionary and a_id
185 // Dictionary flags for known types:
187 if(stackCommand->isRequest()) a_flags |= RBitMask;
189 if(a_id.second) a_flags |= RBitMask; else a_flags &= (~RBitMask);
194 //------------------------------------------------------------------------------
195 //------------------------------------------------------------- Message::setId()
196 //------------------------------------------------------------------------------
197 void Message::setId(const char *name) throw(anna::RuntimeException) {
198 setId(getEngine()->commandIdForName(name));
202 //------------------------------------------------------------------------------
203 //-------------------------------------------------- Message::setApplicationId()
204 //------------------------------------------------------------------------------
205 void Message::setApplicationId(U32 aid) throw() {
206 a_applicationId = aid;
208 // Default behaviour:
209 if (!getEngine()->hasSelectStackWithApplicationId()) return;
211 // Adapts for Application-ID stack identifier:
212 getEngine()->setDictionary(aid);
216 //------------------------------------------------------------------------------
217 //------------------------------------------------------------ Message::addAvp()
218 //------------------------------------------------------------------------------
219 Avp * Message::addAvp(const char *name) throw(anna::RuntimeException) {
220 return addAvp(getEngine()->avpIdForName(name));
224 //------------------------------------------------------------------------------
225 //--------------------------------------------------------- Message::removeAvp()
226 //------------------------------------------------------------------------------
227 bool Message::removeAvp(const char *name, int ocurrence) throw(anna::RuntimeException) {
228 return removeAvp(getEngine()->avpIdForName(name), ocurrence);
232 //------------------------------------------------------------------------------
233 //----------------------------------------------------------- Message::_getAvp()
234 //------------------------------------------------------------------------------
235 const Avp * Message::_getAvp(const char *name, int ocurrence, anna::Exception::Mode::_v emode) const throw(anna::RuntimeException) {
236 return getAvp(getEngine()->avpIdForName(name), ocurrence, emode);
240 //------------------------------------------------------------------------------
241 //---------------------------------------------------------- Message::countAvp()
242 //------------------------------------------------------------------------------
243 int Message::countAvp(const char *name) const throw(anna::RuntimeException) {
244 return countAvp(getEngine()->avpIdForName(name));
248 //------------------------------------------------------------------------------
249 //--------------------------------------------------------- Message::getLength()
250 //------------------------------------------------------------------------------
251 U24 Message::getLength() const throw() {
254 result = HeaderLength;
256 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) result += 4 * REQUIRED_WORDS(Avp::avp(it)->getLength());
262 //------------------------------------------------------------------------------
263 //------------------------------------------------------------ Message::decode()
264 //------------------------------------------------------------------------------
265 void Message::decode(const anna::DataBlock &db, Message *ptrAnswer) throw(anna::RuntimeException) {
268 anna::xml::Node root("Message::decode");
269 std::string trace = "DataBlock to decode:\n";
270 trace += db.asString();
271 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
274 // EXCEPTION MANAGEMENT IN THIS METHOD
275 // ===================================
277 // If an error ocurred, decoding will stop launching exception but we will catch it and go on with validation because perhaps
278 // the achieved message could be valid against all odds. Only fatal errors cause direct decoding exception (length problems
282 // Launch exception on first validation error (validateAll == false), or log warning reporting all validation errors when
283 // complete validation is desired (validateAll == true, engine default) launching a final exception like "the decoded message is invalid".
285 OamModule &oamModule = OamModule::instantiate();
287 if(db.getSize() < HeaderLength) {
288 oamModule.activateAlarm(OamModule::Alarm::MessageDecode__NotEnoughBytesToCoverMessageHeaderLength);
289 oamModule.count(OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageHeaderLength);
290 // DIAMETER_INVALID_MESSAGE_LENGTH; // no podr� construir un answer fiable, as� que no registro el result-code
291 throw anna::RuntimeException("Not enough bytes to cover message header length (20 bytes)", ANNA_FILE_LOCATION);
294 const char * buffer = db.getData();
297 // 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
298 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
299 // | Version | Message Length |
300 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
301 // | command flags | Command-Code |
302 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
303 // | Application-ID |
304 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
305 // | Hop-by-Hop Identifier |
306 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
307 // | End-to-End Identifier |
308 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
310 // +-+-+-+-+-+-+-+-+-+-+-+-+-
312 a_version = (S8)buffer[0];
314 U24 length = DECODE3BYTES_INDX_VALUETYPE(buffer, 1, U24); // total length including header fields
316 a_flags = (S8)buffer[4];
318 U24 code = DECODE3BYTES_INDX_VALUETYPE(buffer, 5, U24);
320 a_id = CommandId(code, requestBit() /* based on a_flags */);
322 setApplicationId(DECODE4BYTES_INDX_VALUETYPE(buffer, 8, U32)); // centralize set, because it could be used for stack selection.
324 a_hopByHop = DECODE4BYTES_INDX_VALUETYPE(buffer, 12, U32);
326 a_endToEnd = DECODE4BYTES_INDX_VALUETYPE(buffer, 16, U32);
328 // Only build answer for a request:
329 Message *answer = isRequest() ? ptrAnswer : NULL;
331 if(answer) answer->setHeaderToAnswer(*this);
334 if(db.getSize() < length) {
335 oamModule.activateAlarm(OamModule::Alarm::MessageDecode__NotEnoughBytesToCoverMessageLength);
336 oamModule.count(OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageLength);
338 if(answer) answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_MESSAGE_LENGTH);
340 throw anna::RuntimeException("Not enough bytes to cover message length", ANNA_FILE_LOCATION);
343 // Message identifier
344 // Flags could have been updated regarding dictionary, but during decoding we must respect buffer received:
345 a_flags = (S8)buffer[4];
346 // Avps start position:
347 const S8 * startData = buffer + HeaderLength;
348 U24 dataBytes = length - HeaderLength;
350 if(dataBytes < 8 /* minimum avp */) {
351 LOGDEBUG(anna::Logger::debug("Message empty (without avps)", ANNA_FILE_LOCATION));
357 anna::DataBlock db_aux;
359 // Parent information:
361 parent.setMessage(a_id);
364 while(avpPos < dataBytes) {
366 avp = getEngine()->allocateAvp();
367 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) */);
368 avp -> decode(db_aux, parent, answer);
369 } catch(anna::RuntimeException &ex) {
370 getEngine()->releaseAvp(avp);
372 anna::Logger::warning(ex.getText(), ANNA_FILE_LOCATION);
373 anna::Logger::warning("Although a decoding error was found, validation could be checked because message could be enough for the application", ANNA_FILE_LOCATION);
379 avpPos += 4 * REQUIRED_WORDS(avp->getLength());
383 Engine::FixMode::_v fmode = getEngine()->getFixMode();
385 if((fmode == Engine::FixMode::AfterDecoding) || (fmode == Engine::FixMode::Always)) fix();
389 std::string trace = "Message decoded:\n";
390 trace += asXMLString();
391 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
394 Engine::ValidationMode::_v vmode = getEngine()->getValidationMode();
396 if((vmode == Engine::ValidationMode::AfterDecoding) || (vmode == Engine::ValidationMode::Always))
398 throw anna::RuntimeException("The decoded message is invalid. See previous report on warning-level traces", ANNA_FILE_LOCATION);
402 //------------------------------------------------------------------------------
403 //--------------------------------------------------- Message::getStackCommand()
404 //------------------------------------------------------------------------------
405 const anna::diameter::stack::Command *Message::getStackCommand(CommandId id) const throw(anna::RuntimeException) {
406 const stack::Dictionary * dictionary = getEngine()->getDictionary();
407 return (dictionary ? (dictionary->getCommand(id)) : NULL);
411 //------------------------------------------------------------------------------
412 //----------------------------------------------------- Message::setResultCode()
413 //------------------------------------------------------------------------------
414 void Message::setResultCode(int rc) throw(anna::RuntimeException) {
415 if(isRequest()) return;
417 // Add Result-Code if not yet added. Even if validation depth is set to 'Complete',
418 // the Result-Code value will be the first found during the message analysis:
419 Avp *resultCodeAvp = getAvp(helpers::base::AVPID__Result_Code, 1, anna::Exception::Mode::Ignore);
422 addAvp(helpers::base::AVPID__Result_Code)->getUnsigned32()->setValue(rc);
423 else if(resultCodeAvp->getUnsigned32()->getValue() == helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS) // Only success could be replaced
424 resultCodeAvp->getUnsigned32()->setValue(rc);
427 setErrorBit(rc >= 3001 && rc <= 3010 /* protocol errors */);
431 //------------------------------------------------------------------------------
432 //----------------------------------------------------- Message::getResultCode()
433 //------------------------------------------------------------------------------
434 int Message::getResultCode() const throw() {
436 const Avp *resultCodeAvp = getAvp(helpers::base::AVPID__Result_Code, 1, anna::Exception::Mode::Ignore);
439 return resultCodeAvp->getUnsigned32()->getValue();
446 //------------------------------------------------------------------------------
447 //------------------------------------------------------ Message::setFailedAvp()
448 //------------------------------------------------------------------------------
449 void Message::setFailedAvp(const parent_t &parent, AvpId wrong, const char *wrongName) throw(anna::RuntimeException) {
451 if(isRequest()) return;
455 // 7.5. Failed-AVP AVP
457 // The Failed-AVP AVP (AVP Code 279) is of type Grouped and provides
458 // debugging information in cases where a request is rejected or not
459 // fully processed due to erroneous information in a specific AVP. The
460 // value of the Result-Code AVP will provide information on the reason
461 // for the Failed-AVP AVP. A Diameter answer message SHOULD contain an
462 // instance of the Failed-AVP AVP that corresponds to the error
463 // indicated by the Result-Code AVP. For practical purposes, this
464 // Failed-AVP would typically refer to the first AVP processing error
465 // that a Diameter node encounters.
467 // Although the Failed-AVP definition has cardinality 1* and Failed-AVP itself is defined in
468 // most of the command codes as *[Failed-AVP], i think this is not a deliberate ambiguity.
469 // Probably the RFC wants to give freedom to the application layer, but it is recommended to
470 // have only one child (wrong avp) inside a unique message Failed-AVP to ease the Result-Code
471 // correspondence. Anyway, this behaviour could be easily opened commenting condition block (*).
472 Avp *theFailedAvp = getAvp(helpers::base::AVPID__Failed_AVP, 1, anna::Exception::Mode::Ignore);
474 LOGDEBUG(anna::Logger::debug("Failed-AVP has already been added. RFC 6733 Section 7.5 recommends to store only the first error found", ANNA_FILE_LOCATION));
478 // Section 7.5 RFC 6733: A Diameter message SHOULD contain one Failed-AVP AVP
479 theFailedAvp = addAvp(helpers::base::AVPID__Failed_AVP);
480 Avp *leaf = theFailedAvp;
483 std::string msg = "Adding to Failed-AVP, the wrong avp ";
484 msg += wrongName ? wrongName : (anna::diameter::functions::avpIdAsPairString(wrong));
485 msg += " found inside ";
486 msg += parent.asString();
488 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
491 std::vector<AvpId>::const_iterator it;
492 for(it = parent.AvpsId.begin(); it != parent.AvpsId.end(); it++)
493 leaf = leaf->addAvp(*it);
499 //------------------------------------------------------------------------------
500 //----------------------------------------------- Message::setStandardToAnswer()
501 //------------------------------------------------------------------------------
502 void Message::setStandardToAnswer(const Message &request, const std::string &originHost, const std::string &originRealm, int resultCode) throw() {
503 if(!request.getId().second) return;
506 setHeaderToAnswer(request);
507 // Session-Id if exists:
508 const Avp *reqSessionId = request.getAvp(helpers::base::AVPID__Session_Id, 1, anna::Exception::Mode::Ignore);
511 if(!getAvp(helpers::base::AVPID__Session_Id, 1, anna::Exception::Mode::Ignore))
512 addAvp(helpers::base::AVPID__Session_Id)->getUTF8String()->setValue(reqSessionId->getUTF8String()->getValue());
514 // Origin-Host & Realm
515 if(!getAvp(helpers::base::AVPID__Origin_Host, 1, anna::Exception::Mode::Ignore))
516 addAvp(helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(originHost);
518 if(!getAvp(helpers::base::AVPID__Origin_Realm, 1, anna::Exception::Mode::Ignore))
519 addAvp(helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(originRealm);
521 // Proxy-Info AVPs if exist, in the same order:
522 for(const_avp_iterator it = request.avp_begin(); it != request.avp_end(); it++)
523 if((*it).second->getId() == helpers::base::AVPID__Proxy_Info)
524 addAvp((*it).second);
526 // If no Result-Code was added is because all was ok, then application could detect another problem:
527 setResultCode(resultCode);
531 std::string msg = "Completed answer:\n";
532 msg += asXMLString();
533 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
538 //------------------------------------------------------------------------------
539 //--------------------------------------------------------------- Message::fix()
540 //------------------------------------------------------------------------------
541 void Message::fix() throw() {
542 // Dictionary stack command:
543 const stack::Command *stackCommand = getStackCommand();
546 LOGDEBUG(anna::Logger::debug("No dictionary command reference found. Cannot fix.", ANNA_FILE_LOCATION));
547 // Try to get to the first place the Session-ID (if exists) because...
548 // RFC 6733: All messages pertaining to a specific session MUST include only one Session-Id AVP ...
549 // ... When present, the Session-Id SHOULD appear immediately following the Diameter header
550 avp_iterator it = Avp::avp_find(a_avps, helpers::base::AVPID__Session_Id, 1 /* one and only */);
552 if(it != avp_end()) {
553 int sessionPos = (*it).first;
554 Avp *first = (*avp_begin()).second;
555 a_avps[0] = (*it).second; // Session-Id
556 a_avps[sessionPos] = first;
557 LOGDEBUG(anna::Logger::debug("Session-Id has been manually fixed to the first place", ANNA_FILE_LOCATION));
563 Avp::fix(a_avps, (find_container&)a_finds, a_insertionPositionForChilds, stackCommand->avprule_begin(), stackCommand->avprule_end());
567 //------------------------------------------------------------------------------
568 //------------------------------------------------------------- Message::valid()
569 //------------------------------------------------------------------------------
570 bool Message::valid(Message *ptrAnswer) const throw(anna::RuntimeException) {
572 OamModule &oamModule = OamModule::instantiate();
573 // Dictionary stack command:
574 const stack::Command *stackCommand = getStackCommand();
575 // Only build answer for a request:
576 Message *answer = isRequest() ? ptrAnswer : NULL;
578 if(answer) answer->setHeaderToAnswer(*this);
582 std::string me = anna::diameter::functions::commandIdAsPairString(a_id);
583 oamModule.activateAlarm(OamModule::Alarm::MessageValidation__UnknownOperation__s__UnableToValidate, STRING_WITH_QUOTATION_MARKS__C_STR(me));
584 oamModule.count(OamModule::Counter::MessageValidation__UnknownOperationUnableToValidate);
586 if(answer) answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_COMMAND_UNSUPPORTED);
588 getEngine()->validationAnomaly(anna::functions::asString("Unknown operation %s. Unable to validate", STRING_WITH_QUOTATION_MARKS__C_STR(me)));
592 // Parent information:
594 me.setMessage(a_id, stackCommand->getName().c_str());
596 //////////////////////////////
597 // Flags coherence checking //
598 //////////////////////////////
600 bool result = flagsOK(rc);
603 // OAM & Depth management
604 oamModule.activateAlarm(OamModule::Alarm::MessageValidation__Operation__s__HaveIncoherentFlags__d__, STRING_WITH_QUOTATION_MARKS__C_STR(me.asString()), (int)a_flags);
605 oamModule.count(OamModule::Counter::MessageValidation__OperationHaveIncoherentFlags);
607 if(answer) answer->setResultCode(rc);
609 getEngine()->validationAnomaly(anna::functions::asString("Operation %s have incoherent flags (%d)", STRING_WITH_QUOTATION_MARKS__C_STR(me.asString()), (int)a_flags));
615 result = Avp::validLevel(a_avps, stackCommand->avprule_begin(), stackCommand->avprule_end(), getEngine(), me, answer) && result;
617 ////////////////////////
618 // Childrens checking //
619 ////////////////////////
620 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++)
621 result = ((*it).second->valid(me, answer)) && result;
627 //------------------------------------------------------------------------------
628 //-------------------------------------------------------------- Message::code()
629 //------------------------------------------------------------------------------
630 const anna::DataBlock & Message::code() throw(anna::RuntimeException) {
632 Engine::ValidationMode::_v vmode = getEngine()->getValidationMode();
634 if((vmode == Engine::ValidationMode::BeforeEncoding) || (vmode == Engine::ValidationMode::Always)) {
636 throw anna::RuntimeException("Try to encode an invalid message. See previous report on warning-level traces", ANNA_FILE_LOCATION);
640 Engine::FixMode::_v fmode = getEngine()->getFixMode();
642 if((fmode == Engine::FixMode::BeforeEncoding) || (fmode == Engine::FixMode::Always)) fix();
646 std::string trace = "Message to code:\n";
647 trace += asXMLString();
648 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
651 U24 length = getLength();
653 a_forCode.allocate(length);
654 char* buffer = (char*)a_forCode.getData();
655 // Version and length
656 buffer[0] = (S8) a_version;
657 buffer[1] = (S8)(length >> 16);
658 buffer[2] = (S8)(length >> 8);
659 buffer[3] = (S8) length;
661 buffer[4] = (S8) a_flags;
662 buffer[5] = (S8)(a_id.first >> 16);
663 buffer[6] = (S8)(a_id.first >> 8);
664 buffer[7] = (S8) a_id.first;
666 buffer[8] = (S8)(a_applicationId >> 24);
667 buffer[9] = (S8)(a_applicationId >> 16);
668 buffer[10] = (S8)(a_applicationId >> 8);
669 buffer[11] = (S8) a_applicationId;
671 buffer[12] = (S8)(a_hopByHop >> 24);
672 buffer[13] = (S8)(a_hopByHop >> 16);
673 buffer[14] = (S8)(a_hopByHop >> 8);
674 buffer[15] = (S8) a_hopByHop;
676 buffer[16] = (S8)(a_endToEnd >> 24);
677 buffer[17] = (S8)(a_endToEnd >> 16);
678 buffer[18] = (S8)(a_endToEnd >> 8);
679 buffer[19] = (S8) a_endToEnd;
680 // Data start position:
681 int startDataPos = HeaderLength;
683 if(startDataPos == length) {
684 LOGDEBUG(anna::Logger::debug("There is no Avps to encode (only-header message)", ANNA_FILE_LOCATION));
687 S8 * dataPart = buffer + startDataPos;
688 int dataBytes; // not used but could be useful for checking (length - startDataPos)
689 // Each avp encoding will remain padding octets depending on format. In order to
690 // code avps colection (each avp will be multiple of 4) we clean the entire buffer
691 // to ensure padding (easier than custom-made for each format):
692 memset(dataPart, 0, length - startDataPos); // no estoy seguro de que el clear del DataBlock haga esto...
694 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) {
695 Avp::avp(it)->code(dataPart, dataBytes);
696 dataPart = dataPart + 4 * REQUIRED_WORDS(dataBytes);
702 std::string trace = "DataBlock encoded:\n";
703 trace += a_forCode.asString();
704 // trace += "\nAs continuous hexadecimal string:\n";
705 // trace += anna::functions::asHexString(a_forCode);
706 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
712 //------------------------------------------------------------------------------
713 //----------------------------------------------------- Message::fromXMLString()
714 //------------------------------------------------------------------------------
715 void Message::fromXMLString(const std::string &xmlString) throw(anna::RuntimeException) {
716 LOGDEBUG(anna::Logger::debug("Reading diameter message from xml string representation", ANNA_FILE_LOCATION));
717 anna::xml::DocumentMemory xmlDocument; // has private copy constructor defined but not implemented to avoid inhenrit/copy (is very heavy)
718 const anna::xml::Node *rootNode;
719 xmlDocument.initialize(xmlString.c_str());
720 rootNode = xmlDocument.parse(getEngine()->getDTD()); // Parsing: fail here if xml violates dtd
721 LOGDEBUG(anna::Logger::debug("Read OK from XML string representation", ANNA_FILE_LOCATION));
726 //------------------------------------------------------------------------------
727 //----------------------------------------------------------- Message::fromXML()
728 //------------------------------------------------------------------------------
729 void Message::fromXML(const anna::xml::Node* messageNode) throw(anna::RuntimeException) {
730 // <!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>
731 const anna::xml::Attribute *version, *name, *code, *flags, *pbit, *ebit, *tbit, *appid, *hbh, *ete;
732 version = messageNode->getAttribute("version", false /* no exception */);
733 name = messageNode->getAttribute("name", false /* no exception */);
734 code = messageNode->getAttribute("code", false /* no exception */);
735 flags = messageNode->getAttribute("flags", false /* no exception */);
736 pbit = messageNode->getAttribute("p-bit", false /* no exception */);
737 ebit = messageNode->getAttribute("e-bit", false /* no exception */);
738 tbit = messageNode->getAttribute("t-bit", false /* no exception */);
739 appid = messageNode->getAttribute("application-id"); // required
740 hbh = messageNode->getAttribute("hop-by-hop-id", false /* no exception */);
741 ete = messageNode->getAttribute("end-by-end-id", false /* no exception */);
749 i_aux = version->getIntegerValue();
751 if(i_aux < 0 || i_aux > 256) {
752 std::string msg = "Error processing avp <version '"; msg += version->getValue();
753 msg += "': out of range [0,256]";
754 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
761 // This is called before any operation which needs to know about the stack elements (this could set the dictionary)
762 setApplicationId(appid->getIntegerValue());
765 const stack::Dictionary * dictionary = getEngine()->getDictionary();
766 const stack::Command *stackCommand = NULL;
771 std::string msg = "Error processing command <name '"; msg += name->getValue();
772 msg += "'>: no dictionary available. Load one or use <'code' + 'flags'> instead of <'name'>";
773 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
776 stackCommand = dictionary->getCommand(name->getValue());
779 std::string msg = "Error processing command <name '"; msg += name->getValue();
780 msg += "'>: no command found for this identifier at available dictionary";
781 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
785 // Check attributes exclusiveness
786 if(name) { // compact mode
788 std::string msg = "Error processing command <name '"; msg += name->getValue();
789 msg += "'>: message attributes <'code' + 'flags'> are not allowed if <'name'> is provided";
790 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
793 setId(stackCommand->getId(), false /* don't clear */);
794 // 'P', 'E' and 'T' flags:
795 bool activateP = pbit ? (pbit->getValue() == "yes") : false;
796 bool activateE = ebit ? (ebit->getValue() == "yes") : false;
797 bool activateT = tbit ? (tbit->getValue() == "yes") : false;
799 if(activateP) a_flags |= PBitMask;
801 if(activateE) a_flags |= EBitMask;
803 if(activateT) a_flags |= TBitMask;
805 std::string s_code = code ? code->getValue() : "?";
806 std::string s_flags = flags ? flags->getValue() : "?";
808 if(!code || !flags) {
809 std::string msg = "Error processing command <code '"; msg += s_code;
810 msg += "' + flags '"; msg += s_flags;
811 msg += "'>: both must be provided if <'name'> don't";
812 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
815 if(pbit || ebit || tbit) {
816 std::string msg = "Error processing command <code '"; msg += s_code;
817 msg += "' + flags '"; msg += s_flags;
818 msg += "'>: neither of 'p-bit', 'e-bit' or 't-bit' fields are allowed if those are present";
819 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
823 i_aux = code->getIntegerValue();
826 std::string msg = "Error processing command <code '"; msg += s_code;
827 msg += "': negative values are not allowed";
828 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
833 i_aux = flags->getIntegerValue();
835 if(i_aux < 0 || i_aux > 256) {
836 std::string msg = "Error processing command <flags '"; msg += s_flags;
837 msg += "': out of range [0,256]";
838 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
842 int flagsBCK = a_flags;
844 a_id = CommandId(u_code, requestBit() /* based on a_flags */);
845 // Flags could have been updated regarding dictionary, but during parsing we must respect xml file:
851 u_aux = hbh->getIntegerValue();
855 std::string msg = "Error processing command <hop-by-hop-id '"; msg += hbh->getValue();
856 msg += "': negative values are not allowed";
857 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
866 u_aux = ete->getIntegerValue();
870 std::string msg = "Error processing command <end-to-end-id '"; msg += ete->getValue();
871 msg += "': negative values are not allowed";
872 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
881 for(anna::xml::Node::const_child_iterator it = messageNode->child_begin(); it != messageNode->child_end(); it++) {
882 std::string nodeName = (*it)->getName();
884 if(nodeName != "avp") {
885 std::string msg = "Unsupported message child node name '"; msg += nodeName;
886 msg += "': use 'avp'";
887 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
891 avp = getEngine()->allocateAvp();
893 } catch(anna::RuntimeException &ex) {
894 getEngine()->releaseAvp(avp);
903 //------------------------------------------------------------------------------
904 //----------------------------------------------------------- Message::loadXML()
905 //------------------------------------------------------------------------------
906 void Message::loadXML(const std::string & xmlPathFile) throw(anna::RuntimeException) {
908 std::string trace = "Loading diameter message from file '";
909 trace += xmlPathFile;
911 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
913 anna::xml::DocumentFile xmlDocument; // has private copy constructor defined but not implemented to avoid inhenrit/copy (is very heavy)
914 const anna::xml::Node *rootNode;
915 xmlDocument.initialize(xmlPathFile.c_str()); // fail here is i/o error
916 rootNode = xmlDocument.parse(getEngine()->getDTD()); // Parsing: fail here if xml violates dtd
918 std::string trace = "Loaded XML file (";
919 trace += xmlPathFile;
921 trace += anna::xml::Compiler().apply(rootNode);
922 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
928 //------------------------------------------------------------------------------
929 //------------------------------------------------------------- Message::asXML()
930 //------------------------------------------------------------------------------
931 anna::xml::Node* Message::asXML(anna::xml::Node* parent) const throw() {
932 // <!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>
933 anna::xml::Node* result = parent->createChild("message");
934 // Dictionary stack command:
935 const stack::Command *stackCommand = getStackCommand();
936 bool compactMode = stackCommand /*&& flagsOK()*/;
937 result->createAttribute("version", anna::functions::asString((int)a_version));
940 result->createAttribute("name", stackCommand->getName());
942 if(proxiableBit()) result->createAttribute("p-bit", "yes");
944 if(errorBit()) result->createAttribute("e-bit", "yes");
946 if(potentiallyReTransmittedMessageBit()) result->createAttribute("t-bit", "yes");
948 result->createAttribute("code", a_id.first);
949 result->createAttribute("flags", (int)a_flags);
952 result->createAttribute("application-id", anna::functions::asString(a_applicationId));
953 result->createAttribute("hop-by-hop-id", anna::functions::asString(a_hopByHop));
954 result->createAttribute("end-by-end-id", anna::functions::asString(a_endToEnd));
957 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) {
958 Avp::avp(it)->asXML(result);
965 //------------------------------------------------------------------------------
966 //------------------------------------------------------- Message::asXMLString()
967 //------------------------------------------------------------------------------
968 std::string Message::asXMLString() const throw() {
969 anna::xml::Node root("root");
970 return anna::xml::Compiler().apply(asXML(&root));
974 //------------------------------------------------------------------------------
975 //------------------------------------------------------------ Message::isLike()
976 //------------------------------------------------------------------------------
977 bool Message::isLike(const std::string &pattern) const throw() {
978 anna::RegularExpression re(pattern);
979 return re.isLike(asXMLString());