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(Engine *engine) : a_engine(engine), a_forCode(true) {
64 //------------------------------------------------------------------------------
65 //----------------------------------------------------------- Message::Message()
66 //------------------------------------------------------------------------------
67 Message::Message(CommandId id, Engine *engine) : a_engine(engine), a_forCode(true) {
73 //------------------------------------------------------------------------------
74 //---------------------------------------------------------- Message::~Message()
75 //------------------------------------------------------------------------------
81 //------------------------------------------------------------------------------
82 //--------------------------------------------------------- Message::getEngine()
83 //------------------------------------------------------------------------------
84 Engine * Message::getEngine() const throw(anna::RuntimeException) {
86 throw anna::RuntimeException("Invalid codec engine reference (NULL)", ANNA_FILE_LOCATION);
93 //------------------------------------------------------------------------------
94 //-------------------------------------------------------- Message::initialize()
95 //------------------------------------------------------------------------------
96 void Message::initialize() throw() {
98 a_id = CommandId(0, false);
104 a_insertionPositionForChilds = 0;
109 //------------------------------------------------------------------------------
110 //------------------------------------------------------------- Message::clear()
111 //------------------------------------------------------------------------------
112 void Message::clear() throw(anna::RuntimeException) {
113 for(avp_iterator it = avp_begin(); it != avp_end(); it++) { /*avp(it)->clear(); */getEngine()->releaseAvp(Avp::avp(it)); }
124 //------------------------------------------------------------------------------
125 //----------------------------------------------------------- Message::flagsOK()
126 //------------------------------------------------------------------------------
127 bool Message::flagsOK(int &rc) const throw() {
128 // Dictionary stack command:
129 const stack::Command *stackCommand = getStackCommand();
132 anna::Logger::error("Impossible to decide if flags are correct because stack command is not identified. Assume flags ok", ANNA_FILE_LOCATION);
133 //rc = helpers::base::AVPVALUES__Result_Code::?????;
137 // DIAMETER_INVALID_HDR_BITS 3008
139 // A request was received whose bits in the Diameter header were set
140 // either to an invalid combination or to a value that is
141 // inconsistent with the Command Code's definition.
144 if(stackCommand->isRequest() != isRequest()) ok = false; // en teoria es imposible salir por aqui: blindado en la dtd
146 if(isRequest() && errorBit()) {
147 anna::Logger::error("E(rror) bit is not allowed at diameter requests", ANNA_FILE_LOCATION);
151 if(isAnswer() && potentiallyReTransmittedMessageBit()) {
152 anna::Logger::error("T(Potentially re-transmitted message) bit is not allowed at diameter answers", ANNA_FILE_LOCATION);
157 rc = helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_HDR_BITS;
161 // DIAMETER_INVALID_BIT_IN_HEADER 5013
163 // This error is returned when a reserved bit in the Diameter header
164 // is set to one (1) or the bits in the Diameter header are set
166 if((a_flags & 0x0f) != 0x00) {
167 anna::Logger::error("Any (or more than one) of the reserved message flags bit has been activated. Reserved bits must be null", ANNA_FILE_LOCATION);
168 rc = helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_BIT_IN_HEADER;
176 //------------------------------------------------------------------------------
177 //------------------------------------------------------------- Message::setId()
178 //------------------------------------------------------------------------------
179 void Message::setId(CommandId id, bool _clear) throw(anna::RuntimeException) {
180 // Clear class content:
185 // Dictionary stack command:
186 const stack::Command *stackCommand = getStackCommand(); // based on dictionary and a_id
188 // Dictionary flags for known types:
190 if(stackCommand->isRequest()) a_flags |= RBitMask;
192 if(a_id.second) a_flags |= RBitMask; else a_flags &= (~RBitMask);
197 //------------------------------------------------------------------------------
198 //------------------------------------------------------------- Message::setId()
199 //------------------------------------------------------------------------------
200 void Message::setId(const char *name) throw(anna::RuntimeException) {
201 setId(getEngine()->commandIdForName(name));
205 //------------------------------------------------------------------------------
206 //-------------------------------------------------- Message::setApplicationId()
207 //------------------------------------------------------------------------------
208 void Message::setApplicationId(U32 aid) throw(anna::RuntimeException) {
209 a_applicationId = aid;
211 // Default behaviour:
212 if (!getEngine()->hasSelectStackWithApplicationId()) return;
214 // Adapts for Application-ID stack identifier:
215 getEngine()->setDictionary(aid);
219 //------------------------------------------------------------------------------
220 //------------------------------------------------------------ Message::addAvp()
221 //------------------------------------------------------------------------------
222 Avp * Message::addAvp(const char *name) throw(anna::RuntimeException) {
223 return addAvp(getEngine()->avpIdForName(name));
227 //------------------------------------------------------------------------------
228 //--------------------------------------------------------- Message::removeAvp()
229 //------------------------------------------------------------------------------
230 bool Message::removeAvp(const char *name, int ocurrence) throw(anna::RuntimeException) {
231 return removeAvp(getEngine()->avpIdForName(name), ocurrence);
235 //------------------------------------------------------------------------------
236 //----------------------------------------------------------- Message::_getAvp()
237 //------------------------------------------------------------------------------
238 const Avp * Message::_getAvp(const char *name, int ocurrence, anna::Exception::Mode::_v emode) const throw(anna::RuntimeException) {
239 return getAvp(getEngine()->avpIdForName(name), ocurrence, emode);
243 //------------------------------------------------------------------------------
244 //---------------------------------------------------------- Message::countAvp()
245 //------------------------------------------------------------------------------
246 int Message::countAvp(const char *name) const throw(anna::RuntimeException) {
247 return countAvp(getEngine()->avpIdForName(name));
251 //------------------------------------------------------------------------------
252 //--------------------------------------------------------- Message::getLength()
253 //------------------------------------------------------------------------------
254 U24 Message::getLength() const throw() {
257 result = HeaderLength;
259 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) result += 4 * REQUIRED_WORDS(Avp::avp(it)->getLength());
265 //------------------------------------------------------------------------------
266 //------------------------------------------------------------ Message::decode()
267 //------------------------------------------------------------------------------
268 void Message::decode(const anna::DataBlock &db, Message *ptrAnswer) throw(anna::RuntimeException) {
271 anna::xml::Node root("Message::decode");
272 std::string trace = "DataBlock to decode:\n";
273 trace += db.asString();
274 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
277 // EXCEPTION MANAGEMENT IN THIS METHOD
278 // ===================================
280 // If an error ocurred, decoding will stop launching exception but we will catch it and go on with validation because perhaps
281 // the achieved message could be valid against all odds. Only fatal errors cause direct decoding exception (length problems
285 // Launch exception on first validation error (validateAll == false), or log warning reporting all validation errors when
286 // complete validation is desired (validateAll == true, engine default) launching a final exception like "the decoded message is invalid".
288 OamModule &oamModule = OamModule::instantiate();
290 if(db.getSize() < HeaderLength) {
291 oamModule.activateAlarm(OamModule::Alarm::MessageDecode__NotEnoughBytesToCoverMessageHeaderLength);
292 oamModule.count(OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageHeaderLength);
293 // DIAMETER_INVALID_MESSAGE_LENGTH; // no podr� construir un answer fiable, as� que no registro el result-code
294 throw anna::RuntimeException("Not enough bytes to cover message header length (20 bytes)", ANNA_FILE_LOCATION);
297 const char * buffer = db.getData();
300 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
301 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
302 // | Version | Message Length |
303 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
304 // | command flags | Command-Code |
305 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
306 // | Application-ID |
307 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
308 // | Hop-by-Hop Identifier |
309 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
310 // | End-to-End Identifier |
311 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
313 // +-+-+-+-+-+-+-+-+-+-+-+-+-
315 a_version = (S8)buffer[0];
317 U24 length = DECODE3BYTES_INDX_VALUETYPE(buffer, 1, U24); // total length including header fields
319 a_flags = (S8)buffer[4];
321 U24 code = DECODE3BYTES_INDX_VALUETYPE(buffer, 5, U24);
323 a_id = CommandId(code, requestBit() /* based on a_flags */);
325 setApplicationId(DECODE4BYTES_INDX_VALUETYPE(buffer, 8, U32)); // centralize set, because it could be used for stack selection.
327 a_hopByHop = DECODE4BYTES_INDX_VALUETYPE(buffer, 12, U32);
329 a_endToEnd = DECODE4BYTES_INDX_VALUETYPE(buffer, 16, U32);
331 // Only build answer for a request:
332 Message *answer = isRequest() ? ptrAnswer : NULL;
334 if(answer) answer->setHeaderToAnswer(*this);
337 if(db.getSize() < length) {
338 oamModule.activateAlarm(OamModule::Alarm::MessageDecode__NotEnoughBytesToCoverMessageLength);
339 oamModule.count(OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageLength);
341 if(answer) answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_MESSAGE_LENGTH);
343 throw anna::RuntimeException("Not enough bytes to cover message length", ANNA_FILE_LOCATION);
346 // Message identifier
347 // Flags could have been updated regarding dictionary, but during decoding we must respect buffer received:
348 a_flags = (S8)buffer[4];
349 // Avps start position:
350 const S8 * startData = buffer + HeaderLength;
351 U24 dataBytes = length - HeaderLength;
353 if(dataBytes < 8 /* minimum avp */) {
354 LOGDEBUG(anna::Logger::debug("Message empty (without avps)", ANNA_FILE_LOCATION));
360 anna::DataBlock db_aux;
362 // Parent information:
364 parent.setMessage(a_id);
367 while(avpPos < dataBytes) {
369 avp = getEngine()->createAvp(NULL);
370 db_aux.assign(startData + avpPos, dataBytes - avpPos /* is valid to pass total length (indeed i don't know the real avp length) because it will be limited and this has deep copy disabled (no memory is reserved) */);
371 avp -> decode(db_aux, parent, answer);
372 } catch(anna::RuntimeException &ex) {
373 getEngine()->releaseAvp(avp);
375 anna::Logger::warning(ex.getText(), ANNA_FILE_LOCATION);
376 anna::Logger::warning("Although a decoding error was found, validation could be checked because message could be enough for the application", ANNA_FILE_LOCATION);
382 avpPos += 4 * REQUIRED_WORDS(avp->getLength());
386 Engine::FixMode::_v fmode = getEngine()->getFixMode();
388 if((fmode == Engine::FixMode::AfterDecoding) || (fmode == Engine::FixMode::Always)) fix();
392 std::string trace = "Message decoded:\n";
393 trace += asXMLString();
394 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
397 Engine::ValidationMode::_v vmode = getEngine()->getValidationMode();
399 if((vmode == Engine::ValidationMode::AfterDecoding) || (vmode == Engine::ValidationMode::Always))
401 throw anna::RuntimeException("The decoded message is invalid. See previous report on warning-level traces", ANNA_FILE_LOCATION);
405 //------------------------------------------------------------------------------
406 //--------------------------------------------------- Message::getStackCommand()
407 //------------------------------------------------------------------------------
408 const anna::diameter::stack::Command *Message::getStackCommand(CommandId id) const throw(anna::RuntimeException) {
409 const stack::Dictionary * dictionary = getEngine()->getDictionary();
410 return (dictionary ? (dictionary->getCommand(id)) : NULL);
414 //------------------------------------------------------------------------------
415 //----------------------------------------------------- Message::setResultCode()
416 //------------------------------------------------------------------------------
417 void Message::setResultCode(int rc) throw(anna::RuntimeException) {
418 if(isRequest()) return;
420 // Add Result-Code if not yet added. Even if validation depth is set to 'Complete',
421 // the Result-Code value will be the first found during the message analysis:
422 Avp *resultCodeAvp = getAvp(helpers::base::AVPID__Result_Code, 1, anna::Exception::Mode::Ignore);
425 addAvp(helpers::base::AVPID__Result_Code)->getUnsigned32()->setValue(rc);
426 else if(resultCodeAvp->getUnsigned32()->getValue() == helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS) // Only success could be replaced
427 resultCodeAvp->getUnsigned32()->setValue(rc);
430 setErrorBit(rc >= 3001 && rc <= 3010 /* protocol errors */);
434 //------------------------------------------------------------------------------
435 //----------------------------------------------------- Message::getResultCode()
436 //------------------------------------------------------------------------------
437 int Message::getResultCode() const throw() {
439 const Avp *resultCodeAvp = getAvp(helpers::base::AVPID__Result_Code, 1, anna::Exception::Mode::Ignore);
442 return resultCodeAvp->getUnsigned32()->getValue();
449 //------------------------------------------------------------------------------
450 //------------------------------------------------------ Message::setFailedAvp()
451 //------------------------------------------------------------------------------
452 void Message::setFailedAvp(const parent_t &parent, AvpId wrong, const char *wrongName) throw(anna::RuntimeException) {
454 if(isRequest()) return;
458 // 7.5. Failed-AVP AVP
460 // The Failed-AVP AVP (AVP Code 279) is of type Grouped and provides
461 // debugging information in cases where a request is rejected or not
462 // fully processed due to erroneous information in a specific AVP. The
463 // value of the Result-Code AVP will provide information on the reason
464 // for the Failed-AVP AVP. A Diameter answer message SHOULD contain an
465 // instance of the Failed-AVP AVP that corresponds to the error
466 // indicated by the Result-Code AVP. For practical purposes, this
467 // Failed-AVP would typically refer to the first AVP processing error
468 // that a Diameter node encounters.
470 // Although the Failed-AVP definition has cardinality 1* and Failed-AVP itself is defined in
471 // most of the command codes as *[Failed-AVP], i think this is not a deliberate ambiguity.
472 // Probably the RFC wants to give freedom to the application layer, but it is recommended to
473 // have only one child (wrong avp) inside a unique message Failed-AVP to ease the Result-Code
474 // correspondence. Anyway, this behaviour could be easily opened commenting condition block (*).
475 Avp *theFailedAvp = getAvp(helpers::base::AVPID__Failed_AVP, 1, anna::Exception::Mode::Ignore);
477 LOGDEBUG(anna::Logger::debug("Failed-AVP has already been added. RFC 6733 Section 7.5 recommends to store only the first error found", ANNA_FILE_LOCATION));
481 // Section 7.5 RFC 6733: A Diameter message SHOULD contain one Failed-AVP AVP
482 theFailedAvp = addAvp(helpers::base::AVPID__Failed_AVP);
483 Avp *leaf = theFailedAvp;
486 std::string msg = "Adding to Failed-AVP, the wrong avp ";
487 msg += wrongName ? wrongName : (anna::diameter::functions::avpIdAsPairString(wrong));
488 msg += " found inside ";
489 msg += parent.asString();
491 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
494 std::vector<AvpId>::const_iterator it;
495 for(it = parent.AvpsId.begin(); it != parent.AvpsId.end(); it++)
496 leaf = leaf->addAvp(*it);
502 //------------------------------------------------------------------------------
503 //----------------------------------------------- Message::setStandardToAnswer()
504 //------------------------------------------------------------------------------
505 void Message::setStandardToAnswer(const Message &request, const std::string &originHost, const std::string &originRealm, int resultCode) throw() {
506 if(!request.getId().second) return;
509 setHeaderToAnswer(request);
510 // Session-Id if exists:
511 const Avp *reqSessionId = request.getAvp(helpers::base::AVPID__Session_Id, 1, anna::Exception::Mode::Ignore);
514 if(!getAvp(helpers::base::AVPID__Session_Id, 1, anna::Exception::Mode::Ignore))
515 addAvp(helpers::base::AVPID__Session_Id)->getUTF8String()->setValue(reqSessionId->getUTF8String()->getValue());
517 // Origin-Host & Realm
518 if(!getAvp(helpers::base::AVPID__Origin_Host, 1, anna::Exception::Mode::Ignore))
519 addAvp(helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(originHost);
521 if(!getAvp(helpers::base::AVPID__Origin_Realm, 1, anna::Exception::Mode::Ignore))
522 addAvp(helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(originRealm);
524 // Proxy-Info AVPs if exist, in the same order:
525 for(const_avp_iterator it = request.avp_begin(); it != request.avp_end(); it++)
526 if((*it).second->getId() == helpers::base::AVPID__Proxy_Info)
527 addAvp((*it).second);
529 // If no Result-Code was added is because all was ok, then application could detect another problem:
530 setResultCode(resultCode);
534 std::string msg = "Completed answer:\n";
535 msg += asXMLString();
536 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
541 //------------------------------------------------------------------------------
542 //--------------------------------------------------------------- Message::fix()
543 //------------------------------------------------------------------------------
544 void Message::fix() throw() {
545 // Dictionary stack command:
546 const stack::Command *stackCommand = getStackCommand();
549 LOGDEBUG(anna::Logger::debug("No dictionary command reference found. Cannot fix.", ANNA_FILE_LOCATION));
550 // Try to get to the first place the Session-ID (if exists) because...
551 // RFC 6733: All messages pertaining to a specific session MUST include only one Session-Id AVP ...
552 // ... When present, the Session-Id SHOULD appear immediately following the Diameter header
553 avp_iterator it = Avp::avp_find(a_avps, helpers::base::AVPID__Session_Id, 1 /* one and only */);
555 if(it != avp_end()) {
556 int sessionPos = (*it).first;
557 Avp *first = (*avp_begin()).second;
558 a_avps[0] = (*it).second; // Session-Id
559 a_avps[sessionPos] = first;
560 LOGDEBUG(anna::Logger::debug("Session-Id has been manually fixed to the first place", ANNA_FILE_LOCATION));
566 Avp::fix(a_avps, (find_container&)a_finds, a_insertionPositionForChilds, stackCommand->avprule_begin(), stackCommand->avprule_end());
570 //------------------------------------------------------------------------------
571 //------------------------------------------------------------- Message::valid()
572 //------------------------------------------------------------------------------
573 bool Message::valid(Message *ptrAnswer) const throw(anna::RuntimeException) {
575 OamModule &oamModule = OamModule::instantiate();
576 // Dictionary stack command:
577 const stack::Command *stackCommand = getStackCommand();
578 // Only build answer for a request:
579 Message *answer = isRequest() ? ptrAnswer : NULL;
581 if(answer) answer->setHeaderToAnswer(*this);
585 std::string me = anna::diameter::functions::commandIdAsPairString(a_id);
586 oamModule.activateAlarm(OamModule::Alarm::MessageValidation__UnknownOperation__s__UnableToValidate, STRING_WITH_QUOTATION_MARKS__C_STR(me));
587 oamModule.count(OamModule::Counter::MessageValidation__UnknownOperationUnableToValidate);
589 if(answer) answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_COMMAND_UNSUPPORTED);
591 getEngine()->validationAnomaly(anna::functions::asString("Unknown operation %s. Unable to validate", STRING_WITH_QUOTATION_MARKS__C_STR(me)));
595 // Parent information:
597 me.setMessage(a_id, stackCommand->getName().c_str());
599 //////////////////////////////
600 // Flags coherence checking //
601 //////////////////////////////
603 bool result = flagsOK(rc);
606 // OAM & Depth management
607 oamModule.activateAlarm(OamModule::Alarm::MessageValidation__Operation__s__HaveIncoherentFlags__d__, STRING_WITH_QUOTATION_MARKS__C_STR(me.asString()), (int)a_flags);
608 oamModule.count(OamModule::Counter::MessageValidation__OperationHaveIncoherentFlags);
610 if(answer) answer->setResultCode(rc);
612 getEngine()->validationAnomaly(anna::functions::asString("Operation %s have incoherent flags (%d)", STRING_WITH_QUOTATION_MARKS__C_STR(me.asString()), (int)a_flags));
618 result = Avp::validLevel(a_avps, stackCommand->avprule_begin(), stackCommand->avprule_end(), getEngine(), me, answer) && result;
620 ////////////////////////
621 // Childrens checking //
622 ////////////////////////
623 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++)
624 result = ((*it).second->valid(me, answer)) && result;
630 //------------------------------------------------------------------------------
631 //-------------------------------------------------------------- Message::code()
632 //------------------------------------------------------------------------------
633 const anna::DataBlock & Message::code() throw(anna::RuntimeException) {
635 Engine::ValidationMode::_v vmode = getEngine()->getValidationMode();
637 if((vmode == Engine::ValidationMode::BeforeEncoding) || (vmode == Engine::ValidationMode::Always)) {
639 throw anna::RuntimeException("Try to encode an invalid message. See previous report on warning-level traces", ANNA_FILE_LOCATION);
643 Engine::FixMode::_v fmode = getEngine()->getFixMode();
645 if((fmode == Engine::FixMode::BeforeEncoding) || (fmode == Engine::FixMode::Always)) fix();
649 std::string trace = "Message to code:\n";
650 trace += asXMLString();
651 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
654 U24 length = getLength();
656 a_forCode.allocate(length);
657 char* buffer = (char*)a_forCode.getData();
658 // Version and length
659 buffer[0] = (S8) a_version;
660 buffer[1] = (S8)(length >> 16);
661 buffer[2] = (S8)(length >> 8);
662 buffer[3] = (S8) length;
664 buffer[4] = (S8) a_flags;
665 buffer[5] = (S8)(a_id.first >> 16);
666 buffer[6] = (S8)(a_id.first >> 8);
667 buffer[7] = (S8) a_id.first;
669 buffer[8] = (S8)(a_applicationId >> 24);
670 buffer[9] = (S8)(a_applicationId >> 16);
671 buffer[10] = (S8)(a_applicationId >> 8);
672 buffer[11] = (S8) a_applicationId;
674 buffer[12] = (S8)(a_hopByHop >> 24);
675 buffer[13] = (S8)(a_hopByHop >> 16);
676 buffer[14] = (S8)(a_hopByHop >> 8);
677 buffer[15] = (S8) a_hopByHop;
679 buffer[16] = (S8)(a_endToEnd >> 24);
680 buffer[17] = (S8)(a_endToEnd >> 16);
681 buffer[18] = (S8)(a_endToEnd >> 8);
682 buffer[19] = (S8) a_endToEnd;
683 // Data start position:
684 int startDataPos = HeaderLength;
686 if(startDataPos == length) {
687 LOGDEBUG(anna::Logger::debug("There is no Avps to encode (only-header message)", ANNA_FILE_LOCATION));
690 S8 * dataPart = buffer + startDataPos;
691 int dataBytes; // not used but could be useful for checking (length - startDataPos)
692 // Each avp encoding will remain padding octets depending on format. In order to
693 // code avps colection (each avp will be multiple of 4) we clean the entire buffer
694 // to ensure padding (easier than custom-made for each format):
695 memset(dataPart, 0, length - startDataPos); // no estoy seguro de que el clear del DataBlock haga esto...
697 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) {
698 Avp::avp(it)->code(dataPart, dataBytes);
699 dataPart = dataPart + 4 * REQUIRED_WORDS(dataBytes);
705 std::string trace = "DataBlock encoded:\n";
706 trace += a_forCode.asString();
707 // trace += "\nAs continuous hexadecimal string:\n";
708 // trace += anna::functions::asHexString(a_forCode);
709 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
715 //------------------------------------------------------------------------------
716 //----------------------------------------------------- Message::fromXMLString()
717 //------------------------------------------------------------------------------
718 void Message::fromXMLString(const std::string &xmlString) throw(anna::RuntimeException) {
719 LOGDEBUG(anna::Logger::debug("Reading diameter message from xml string representation", ANNA_FILE_LOCATION));
720 anna::xml::DocumentMemory xmlDocument; // has private copy constructor defined but not implemented to avoid inhenrit/copy (is very heavy)
721 const anna::xml::Node *rootNode;
722 xmlDocument.initialize(xmlString.c_str());
723 rootNode = xmlDocument.parse(getEngine()->getDTD()); // Parsing: fail here if xml violates dtd
724 LOGDEBUG(anna::Logger::debug("Read OK from XML string representation", ANNA_FILE_LOCATION));
729 //------------------------------------------------------------------------------
730 //----------------------------------------------------------- Message::fromXML()
731 //------------------------------------------------------------------------------
732 void Message::fromXML(const anna::xml::Node* messageNode) throw(anna::RuntimeException) {
733 // <!ATTLIST message version CDATA #IMPLIED name CDATA #IMPLIED code CDATA #IMPLIED flags CDATA #IMPLIED p-bit (yes | no) #IMPLIED e-bit (yes | no) #IMPLIED t-bit (yes | no) #IMPLIED application-id CDATA #REQUIRED hop-by-hop-id CDATA #IMPLIED end-by-end-id CDATA #IMPLIED>
734 const anna::xml::Attribute *version, *name, *code, *flags, *pbit, *ebit, *tbit, *appid, *hbh, *ete;
735 version = messageNode->getAttribute("version", false /* no exception */);
736 name = messageNode->getAttribute("name", false /* no exception */);
737 code = messageNode->getAttribute("code", false /* no exception */);
738 flags = messageNode->getAttribute("flags", false /* no exception */);
739 pbit = messageNode->getAttribute("p-bit", false /* no exception */);
740 ebit = messageNode->getAttribute("e-bit", false /* no exception */);
741 tbit = messageNode->getAttribute("t-bit", false /* no exception */);
742 appid = messageNode->getAttribute("application-id"); // required
743 hbh = messageNode->getAttribute("hop-by-hop-id", false /* no exception */);
744 ete = messageNode->getAttribute("end-by-end-id", false /* no exception */);
752 i_aux = version->getIntegerValue();
754 if(i_aux < 0 || i_aux > 256) {
755 std::string msg = "Error processing avp <version '"; msg += version->getValue();
756 msg += "': out of range [0,256]";
757 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
764 // This is called before any operation which needs to know about the stack elements (this could set the dictionary)
765 setApplicationId(appid->getIntegerValue());
768 const stack::Dictionary * dictionary = getEngine()->getDictionary();
769 const stack::Command *stackCommand = NULL;
774 std::string msg = "Error processing command <name '"; msg += name->getValue();
775 msg += "'>: no dictionary available. Load one or use <'code' + 'flags'> instead of <'name'>";
776 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
779 stackCommand = dictionary->getCommand(name->getValue());
782 std::string msg = "Error processing command <name '"; msg += name->getValue();
783 msg += "'>: no command found for this identifier at available dictionary";
784 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
788 // Check attributes exclusiveness
789 if(name) { // compact mode
791 std::string msg = "Error processing command <name '"; msg += name->getValue();
792 msg += "'>: message attributes <'code' + 'flags'> are not allowed if <'name'> is provided";
793 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
796 setId(stackCommand->getId(), false /* don't clear */);
797 // 'P', 'E' and 'T' flags:
798 bool activateP = pbit ? (pbit->getValue() == "yes") : false;
799 bool activateE = ebit ? (ebit->getValue() == "yes") : false;
800 bool activateT = tbit ? (tbit->getValue() == "yes") : false;
802 if(activateP) a_flags |= PBitMask;
804 if(activateE) a_flags |= EBitMask;
806 if(activateT) a_flags |= TBitMask;
808 std::string s_code = code ? code->getValue() : "?";
809 std::string s_flags = flags ? flags->getValue() : "?";
811 if(!code || !flags) {
812 std::string msg = "Error processing command <code '"; msg += s_code;
813 msg += "' + flags '"; msg += s_flags;
814 msg += "'>: both must be provided if <'name'> don't";
815 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
818 if(pbit || ebit || tbit) {
819 std::string msg = "Error processing command <code '"; msg += s_code;
820 msg += "' + flags '"; msg += s_flags;
821 msg += "'>: neither of 'p-bit', 'e-bit' or 't-bit' fields are allowed if those are present";
822 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
826 i_aux = code->getIntegerValue();
829 std::string msg = "Error processing command <code '"; msg += s_code;
830 msg += "': negative values are not allowed";
831 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
836 i_aux = flags->getIntegerValue();
838 if(i_aux < 0 || i_aux > 256) {
839 std::string msg = "Error processing command <flags '"; msg += s_flags;
840 msg += "': out of range [0,256]";
841 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
845 int flagsBCK = a_flags;
847 a_id = CommandId(u_code, requestBit() /* based on a_flags */);
848 // Flags could have been updated regarding dictionary, but during parsing we must respect xml file:
854 u_aux = hbh->getIntegerValue();
858 std::string msg = "Error processing command <hop-by-hop-id '"; msg += hbh->getValue();
859 msg += "': negative values are not allowed";
860 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
869 u_aux = ete->getIntegerValue();
873 std::string msg = "Error processing command <end-to-end-id '"; msg += ete->getValue();
874 msg += "': negative values are not allowed";
875 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
884 for(anna::xml::Node::const_child_iterator it = messageNode->child_begin(); it != messageNode->child_end(); it++) {
885 std::string nodeName = (*it)->getName();
887 if(nodeName != "avp") {
888 std::string msg = "Unsupported message child node name '"; msg += nodeName;
889 msg += "': use 'avp'";
890 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
894 avp = getEngine()->createAvp(NULL);
896 } catch(anna::RuntimeException &ex) {
897 getEngine()->releaseAvp(avp);
906 //------------------------------------------------------------------------------
907 //----------------------------------------------------------- Message::loadXML()
908 //------------------------------------------------------------------------------
909 void Message::loadXML(const std::string & xmlPathFile) throw(anna::RuntimeException) {
911 std::string trace = "Loading diameter message from file '";
912 trace += xmlPathFile;
914 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
916 anna::xml::DocumentFile xmlDocument; // has private copy constructor defined but not implemented to avoid inhenrit/copy (is very heavy)
917 const anna::xml::Node *rootNode;
918 xmlDocument.initialize(xmlPathFile.c_str()); // fail here is i/o error
919 rootNode = xmlDocument.parse(getEngine()->getDTD()); // Parsing: fail here if xml violates dtd
921 std::string trace = "Loaded XML file (";
922 trace += xmlPathFile;
924 trace += anna::xml::Compiler().apply(rootNode);
925 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
931 //------------------------------------------------------------------------------
932 //------------------------------------------------------------- Message::asXML()
933 //------------------------------------------------------------------------------
934 anna::xml::Node* Message::asXML(anna::xml::Node* parent) const throw() {
935 // <!ATTLIST message version CDATA #IMPLIED name CDATA #IMPLIED code CDATA #IMPLIED flags CDATA #IMPLIED application-id CDATA #REQUIRED hop-by-hop-id CDATA #IMPLIED end-by-end-id CDATA #IMPLIED>
936 anna::xml::Node* result = parent->createChild("message");
937 // Dictionary stack command:
938 const stack::Command *stackCommand = getStackCommand();
939 bool compactMode = stackCommand /*&& flagsOK()*/;
940 result->createAttribute("version", anna::functions::asString((int)a_version));
943 result->createAttribute("name", stackCommand->getName());
945 if(proxiableBit()) result->createAttribute("p-bit", "yes");
947 if(errorBit()) result->createAttribute("e-bit", "yes");
949 if(potentiallyReTransmittedMessageBit()) result->createAttribute("t-bit", "yes");
951 result->createAttribute("code", a_id.first);
952 result->createAttribute("flags", (int)a_flags);
955 result->createAttribute("application-id", anna::functions::asString(a_applicationId));
956 result->createAttribute("hop-by-hop-id", anna::functions::asString(a_hopByHop));
957 result->createAttribute("end-by-end-id", anna::functions::asString(a_endToEnd));
960 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) {
961 Avp::avp(it)->asXML(result);
968 //------------------------------------------------------------------------------
969 //------------------------------------------------------- Message::asXMLString()
970 //------------------------------------------------------------------------------
971 std::string Message::asXMLString() const throw() {
972 anna::xml::Node root("root");
973 return anna::xml::Compiler().apply(asXML(&root));
977 //------------------------------------------------------------------------------
978 //------------------------------------------------------------ Message::isLike()
979 //------------------------------------------------------------------------------
980 bool Message::isLike(const std::string &pattern) const throw() {
981 anna::RegularExpression re(pattern);
982 return re.isLike(asXMLString());