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/Avp.hpp>
11 #include <anna/diameter/codec/Format.hpp>
13 #include <anna/config/defines.hpp> // general types, decoding helpers (DECODE[2/3/4]BYTES_INDX_VALUETYPE), etc.
14 #include <anna/diameter/functions.hpp>
15 #include <anna/diameter/helpers/defines.hpp>
16 #include <anna/diameter/codec/basetypes/basetypes.hpp>
17 #include <anna/diameter/codec/functions.hpp> // REQUIRED_WORDS
18 #include <anna/diameter/codec/OamModule.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/diameter/codec/Engine.hpp>
24 #include <anna/core/functions.hpp>
25 #include <anna/core/util/RegularExpression.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>
37 using namespace anna::diameter::codec;
46 const int Avp::HeaderLengthVactive(12);
47 const int Avp::HeaderLengthVinactive(8);
48 const U8 Avp::VBitMask(0x80);
49 const U8 Avp::MBitMask(0x40);
50 const U8 Avp::PBitMask(0x20);
55 //------------------------------------------------------------------------------
56 //------------------------------------------------------------------- Avp::Avp()
57 //------------------------------------------------------------------------------
58 Avp::Avp(Engine *engine) : a_engine(engine) {
62 //------------------------------------------------------------------------------
63 //------------------------------------------------------------------- Avp::Avp()
64 //------------------------------------------------------------------------------
65 Avp::Avp(AvpId id, Engine *engine) : a_engine(engine) {
70 //------------------------------------------------------------------------------
71 //------------------------------------------------------------------ Avp::~Avp()
72 //------------------------------------------------------------------------------
77 //------------------------------------------------------------------------------
78 //------------------------------------------------------------- Avp::setEngine()
79 //------------------------------------------------------------------------------
80 void Avp::setEngine(Engine *engine) throw() {
81 if (a_engine && engine != a_engine) {
82 LOGWARNING(anna::Logger::warning("Ignored: it is not a good practice to change the codec engine once assigned. Clear the avp first to set the engine again.", ANNA_FILE_LOCATION));
89 //------------------------------------------------------------------------------
90 //------------------------------------------------------------- Avp::getEngine()
91 //------------------------------------------------------------------------------
92 Engine * Avp::getEngine() const throw(anna::RuntimeException) {
94 throw anna::RuntimeException("Invalid codec engine reference (NULL). Use setEngine() to set the corresponding codec engine", ANNA_FILE_LOCATION);
100 //------------------------------------------------------------------------------
101 //------------------------------------------------------------ Avp::initialize()
102 //------------------------------------------------------------------------------
103 void Avp::initialize() throw() {
104 a_id = helpers::AVPID__AVP; // (0,0)
106 a_insertionPositionForChilds = 0;
107 a_OctetString = NULL;
118 a_DiameterIdentity = NULL;
119 a_DiameterURI = NULL;
121 a_IPFilterRule = NULL;
122 a_QoSFilterRule = NULL;
125 /////////////////////
126 // Format specific //
127 /////////////////////
128 initializeByFormat();
132 //------------------------------------------------------------------------------
133 //----------------------------------------------------------------- Avp::clear()
134 //------------------------------------------------------------------------------
135 void Avp::clear() throw(anna::RuntimeException) {
136 delete a_OctetString;
144 for(avp_iterator it = avp_begin(); it != avp_end(); it++) { /*avp(it)->clear(); */getEngine()->releaseAvp(avp(it)); }
150 delete a_DiameterIdentity;
151 delete a_DiameterURI;
153 delete a_IPFilterRule;
154 delete a_QoSFilterRule;
158 /////////////////////
159 // Format specific //
160 /////////////////////
167 //------------------------------------------------------------------------------
168 //-------------------------------------------------------------- Avp::avp_find()
169 //------------------------------------------------------------------------------
170 avp_iterator Avp::avp_find(avp_container &avps, AvpId id, unsigned int position) throw() {
174 for(avp_iterator it = avps.begin(); it != avps.end(); it++) {
177 if(aux && (aux->getId() == id)) {
180 if(match == position) return it;
188 //------------------------------------------------------------------------------
189 //---------------------------------------------------------------- Avp::addAvp()
190 //------------------------------------------------------------------------------
191 Avp * Avp::addAvp(avp_container &avps, int &insertionPositionForChilds, AvpId id, Engine *engine) throw() {
192 Avp * result = engine->createAvp(NULL);
194 addChild(avps, insertionPositionForChilds, result);
199 //------------------------------------------------------------------------------
200 //---------------------------------------------------------------- Avp::addAvp()
201 //------------------------------------------------------------------------------
202 Avp * Avp::addAvp(Avp * avp) throw(anna::RuntimeException) {
203 if(!avp) return NULL;
204 if (avp->getEngine() != getEngine()) return NULL;
210 //------------------------------------------------------------------------------
211 //------------------------------------------------------------- Avp::removeAvp()
212 //------------------------------------------------------------------------------
213 bool Avp::removeAvp(avp_container &avps, find_container &finds, AvpId id, int ocurrence, Engine *engine) throw() {
214 bool removed = false;
215 bool do_remove = true;
216 int position = ocurrence;
218 if(position < 0) { /* reversed access */
219 position = countAvp(avps, id) + 1 + position;
221 // Special cases -> 0 and negative results:
222 // (1) User wants to remove the last, but no avp is found: position = 0 + 1 - 1 = 0 (would removes all but, no avp will be found: return now)
223 // (2) User wants to remove some intermediate avp, i.e. '-5', but only 4 avps are found: 4 + 1 - 5 = 0 (would removes all !!!: return to avoid unexpected behaviour)
224 // (2) User wants to remove some intermediate avp, i.e. '-5', but only 3 avps are found: 3 + 1 - 5 = -1 (can't find negative positions ...)
225 if(position <= 0) do_remove = false;
229 int n = position ? position : 1 /* will search always the first and remove, the first and remove, the first and remove ... */;
232 while((it = avp_find(avps, id, n)) != avps.end()) {
233 engine->releaseAvp((*it).second);
242 // Cache system reset (remove will invalidate cached findings):
245 const stack::Avp *stackAvp = getStackAvp(id, engine);
246 std::string msg = "Removed Avp "; msg += stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id));
247 msg += anna::functions::asString(" with provided ocurrence (%d)", ocurrence);
248 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
252 const stack::Avp *stackAvp = getStackAvp(id, engine);
253 std::string msg = "Can't found Avp "; msg += stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id));
254 msg += anna::functions::asString(" with provided ocurrence (%d), in order to be removed", ocurrence);
255 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
263 //------------------------------------------------------------------------------
264 //-------------------------------------------------------------- Avp::countAvp()
265 //------------------------------------------------------------------------------
266 int Avp::countAvp(const avp_container &avps, AvpId id) throw() {
268 const_avp_iterator it;
270 while((it = avp_find(avps, id, result + 1)) != avps.end()) result++;
276 //------------------------------------------------------------------------------
277 //-------------------------------------------------------------- Avp::firstAvp()
278 //------------------------------------------------------------------------------
279 const Avp* Avp::firstAvp(const avp_container &avps, AvpId id) throw() {
280 const_avp_iterator it = avp_find(avps, id, 1);
289 //------------------------------------------------------------------------------
290 //----------------------------------------------------------- Avp::countChilds()
291 //------------------------------------------------------------------------------
292 int Avp::countChilds(const avp_container &avps) throw() {
297 //------------------------------------------------------------------------------
298 //---------------------------------------------------------------- Avp::getAvp()
299 //------------------------------------------------------------------------------
300 const Avp *Avp::getAvp(const avp_container &avps, find_container &finds, AvpId id, int ocurrence, Engine *engine, anna::Exception::Mode::_v emode) throw(anna::RuntimeException) {
302 LOGDEBUG(anna::Logger::debug("Ocurrence number zero has no sense. NULL returned.", ANNA_FILE_LOCATION));
306 bool do_search = true;
308 int position = ocurrence;
310 if(position < 0) { /* reversed access */
311 position = countAvp(avps, id) + 1 + position;
313 // Special cases -> 0 and negative results:
314 // (1) User wants to get the last, but no avp is found: position = 0 + 1 - 1 = 0 (can't find 0-position ...)
315 // (2) User wants to get some intermediate avp, i.e. '-5', but only 4 avps are found: 4 + 1 - 5 = 0 (can't find 0-position ...)
316 // (2) User wants to get some intermediate avp, i.e. '-5', but only 3 avps are found: 3 + 1 - 5 = -1 (can't find negative positions ...)
317 if(position <= 0) do_search = false;
320 const Avp * result = NULL;
323 // Search at cache finds:
324 find_key key(id, position);
325 find_iterator fit = finds.find(key);
326 cached = (fit != finds.end());
329 result = (*fit).second;
331 const_avp_iterator it = avp_find(avps, id, position);
333 if(it != avps.end()) {
334 result = (*it).second;
335 finds[key] = const_cast<Avp*>(result); // store in cache
343 const stack::Avp *stackAvp = getStackAvp(id, engine);
344 std::string msg = "Found Avp "; msg += stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id));
345 msg += anna::functions::asString(" with provided ocurrence (%d) which was ", ocurrence);
346 msg += cached ? "already cached:\n" : "the first search, now cached:\n";
347 msg += result->asXMLString();
348 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
355 case anna::Exception::Mode::Throw: {
356 const stack::Avp *stackAvp = getStackAvp(id, engine);
357 std::string msg = "Can't found Avp "; msg += stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id));
358 msg += anna::functions::asString(" with provided ocurrence (%d)", ocurrence);
359 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
362 case anna::Exception::Mode::Trace: {
364 const stack::Avp *stackAvp = getStackAvp(id, engine);
365 std::string msg = "Can't found Avp "; msg += stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id));
366 msg += anna::functions::asString(" with provided ocurrence (%d)", ocurrence);
367 anna::Logger::warning(msg, ANNA_FILE_LOCATION);
371 case anna::Exception::Mode::Ignore: {
373 const stack::Avp *stackAvp = getStackAvp(id, engine);
374 std::string msg = "Can't found Avp "; msg += stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id));
375 msg += anna::functions::asString(" with provided ocurrence (%d)", ocurrence);
376 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
386 //------------------------------------------------------------------------------
387 //--------------------------------------------------------------- Avp::_getAvp()
388 //------------------------------------------------------------------------------
389 const Avp *Avp::_getAvp(AvpId id, int ocurrence, anna::Exception::Mode::_v emode) const throw(anna::RuntimeException) {
390 // Dictionary stack avp and format (this):
391 const stack::Avp *stackAvp = getStackAvp();
392 const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
394 if(!stackFormat || !stackFormat->isGrouped())
395 throw anna::RuntimeException("This method only applies over grouped avps.", ANNA_FILE_LOCATION);
397 return getAvp(a_avps, (find_container&)a_finds, id, ocurrence, getEngine(), emode);
401 //------------------------------------------------------------------------------
402 //---------------------------------------------------------- Avp::assertFormat()
403 //------------------------------------------------------------------------------
404 void Avp::assertFormat(const std::string &name) const throw(anna::RuntimeException) {
405 // Dictionary stack avp and format:
406 const stack::Avp *stackAvp = getStackAvp();
407 const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
408 std::string format = stackFormat ? stackFormat->getName() : "Unknown";
411 std::string msg = "The Avp ";
412 msg += anna::diameter::functions::avpIdAsPairString(a_id);
413 msg += " with format '";
415 msg += "' is not compatible with the API method used (";
418 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
423 //------------------------------------------------------------------------------
424 //--------------------------------------------------------------- Avp::flagsOK()
425 //------------------------------------------------------------------------------
426 bool Avp::flagsOK() const throw() {
427 // Dictionary stack avp:
428 const stack::Avp *stackAvp = getStackAvp();
431 anna::Logger::error("Impossible to decide if flags are correct because stack avp is not identified. Assume flags ok", ANNA_FILE_LOCATION);
436 bool Vnone = (stackAvp->getVbit() == stack::Avp::FlagRule::None);
438 bool Vmust = (stackAvp->getVbit() == stack::Avp::FlagRule::must);
440 bool Vmustnot = (stackAvp->getVbit() == stack::Avp::FlagRule::mustnot);
442 bool Mnone = (stackAvp->getMbit() == stack::Avp::FlagRule::None);
444 bool Mmust = (stackAvp->getMbit() == stack::Avp::FlagRule::must);
446 bool Mmustnot = (stackAvp->getMbit() == stack::Avp::FlagRule::mustnot);
448 bool Pnone = (stackAvp->getPbit() == stack::Avp::FlagRule::None);
450 bool Pmust = (stackAvp->getPbit() == stack::Avp::FlagRule::must);
452 bool Pmustnot = (stackAvp->getPbit() == stack::Avp::FlagRule::mustnot);
455 if((Vnone && Mnone && Pnone && vendorBit()) || (Vmust && !vendorBit()) || (Vmustnot && vendorBit())) {
456 anna::Logger::error("Vendor Bit (V) incoherence found", ANNA_FILE_LOCATION);
460 // Exit on permissive mode:
461 if(getEngine()->ignoreFlagsOnValidation()) return true; // Ignore checking for AVP 'M' & 'P' bits
464 if((Mmust && !mandatoryBit()) || (Mmustnot && mandatoryBit())) {
465 anna::Logger::error("Mandatory Bit (M) incoherence found", ANNA_FILE_LOCATION);
470 if((Pmust && !encryptionBit()) || (Pmustnot && encryptionBit())) {
471 anna::Logger::error("Encryption Bit (P) incoherence found", ANNA_FILE_LOCATION);
476 if((a_flags & 0x1f) != 0x00) {
477 anna::Logger::error("Any (or more than one) of the reserved avp flags bit has been activated. Reserved bits must be null", ANNA_FILE_LOCATION);
485 //------------------------------------------------------------------------------
486 //----------------------------------------------------------------- Avp::setId()
487 //------------------------------------------------------------------------------
488 void Avp::setId(AvpId id) throw(anna::RuntimeException) {
489 // Generic AVP assignment has no sense
490 if(id == helpers::AVPID__AVP) return;
492 // Clear class content:
496 // Dictionary stack avp and format:
497 const stack::Avp *stackAvp = getStackAvp(); // based on dictionary and a_id
498 const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
500 // Dictionary flags for known types:
502 if(stackAvp->getVbit() == stack::Avp::FlagRule::must) a_flags |= VBitMask;
504 if(stackAvp->getMbit() == stack::Avp::FlagRule::must) a_flags |= MBitMask;
506 if(stackAvp->getPbit() == stack::Avp::FlagRule::must) a_flags |= PBitMask;
508 if(a_id.second != 0) a_flags |= VBitMask; else a_flags &= (~VBitMask);
511 if(!stackFormat) { // Unknown Avp
513 std::string msg = "Unknown format for AVP identifier ";
514 msg += anna::diameter::functions::avpIdAsPairString(id);
515 msg += ". Raw data without specific format will be managed";
516 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
518 a_Unknown = new Unknown();
522 // Avp class formats (Avp child classes should implement this source code block for application-specific formats):
523 if(stackFormat->isOctetString()) a_OctetString = new OctetString();
524 else if(stackFormat->isInteger32()) a_Integer32 = new Integer32();
525 else if(stackFormat->isInteger64()) a_Integer64 = new Integer64();
526 else if(stackFormat->isUnsigned32()) a_Unsigned32 = new Unsigned32();
527 else if(stackFormat->isUnsigned64()) a_Unsigned64 = new Unsigned64();
528 else if(stackFormat->isFloat32()) a_Float32 = new Float32();
529 else if(stackFormat->isFloat64()) a_Float64 = new Float64();
530 //else if (stackFormat->isGrouped())
531 else if(stackFormat->isAddress()) a_Address = new Address();
532 else if(stackFormat->isTime()) a_Time = new Time();
533 else if(stackFormat->isUTF8String()) a_UTF8String = new UTF8String();
534 else if(stackFormat->isDiameterIdentity()) a_DiameterIdentity = new DiameterIdentity();
535 else if(stackFormat->isDiameterURI()) a_DiameterURI = new DiameterURI();
536 else if(stackFormat->isEnumerated()) a_Enumerated = new Enumerated();
537 else if(stackFormat->isIPFilterRule()) a_IPFilterRule = new IPFilterRule();
538 else if(stackFormat->isQoSFilterRule()) a_QoSFilterRule = new QoSFilterRule();
540 /////////////////////
541 // Format specific //
542 /////////////////////
543 allocationByFormat(stackFormat);
547 //------------------------------------------------------------------------------
548 //----------------------------------------------------------------- Avp::setId()
549 //------------------------------------------------------------------------------
550 void Avp::setId(const char *name) throw(anna::RuntimeException) {
551 setId(getEngine()->avpIdForName(name));
555 //------------------------------------------------------------------------------
556 //---------------------------------------------------------------- Avp::addAvp()
557 //------------------------------------------------------------------------------
558 Avp * Avp::addAvp(const char *name) throw(anna::RuntimeException) {
559 return addAvp(getEngine()->avpIdForName(name));
563 //------------------------------------------------------------------------------
564 //------------------------------------------------------------- Avp::removeAvp()
565 //------------------------------------------------------------------------------
566 bool Avp::removeAvp(const char *name, int ocurrence) throw(anna::RuntimeException) {
567 return removeAvp(getEngine()->avpIdForName(name), ocurrence);
571 //------------------------------------------------------------------------------
572 //--------------------------------------------------------------- Avp::_getAvp()
573 //------------------------------------------------------------------------------
574 const Avp *Avp::_getAvp(const char *name, int ocurrence, anna::Exception::Mode::_v emode) const throw(anna::RuntimeException) {
575 return getAvp(getEngine()->avpIdForName(name), ocurrence, emode);
579 //------------------------------------------------------------------------------
580 //-------------------------------------------------------------- Avp::countAvp()
581 //------------------------------------------------------------------------------
582 int Avp::countAvp(const char *name) const throw(anna::RuntimeException) {
583 return countAvp(getEngine()->avpIdForName(name));
586 //------------------------------------------------------------------------------
587 //------------------------------------------------------------- Avp::getLength()
588 //------------------------------------------------------------------------------
589 U24 Avp::getLength() const throw() {
592 const stack::Avp *stackAvp = getStackAvp();
593 const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
595 result = vendorBit() ? HeaderLengthVactive : HeaderLengthVinactive;
598 result += a_Unknown->getSize();
602 if(stackFormat->isOctetString()) result += a_OctetString->getSize();
603 else if(stackFormat->isInteger32()) result += a_Integer32->getSize();
604 else if(stackFormat->isInteger64()) result += a_Integer64->getSize();
605 else if(stackFormat->isUnsigned32()) result += a_Unsigned32->getSize();
606 else if(stackFormat->isUnsigned64()) result += a_Unsigned64->getSize();
607 else if(stackFormat->isFloat32()) result += a_Float32->getSize();
608 else if(stackFormat->isFloat64()) result += a_Float64->getSize();
609 else if(stackFormat->isGrouped()) for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) result += 4 * REQUIRED_WORDS(avp(it)->getLength());
610 else if(stackFormat->isAddress()) result += a_Address->getSize();
611 else if(stackFormat->isTime()) result += a_Time->getSize();
612 else if(stackFormat->isUTF8String()) result += a_UTF8String->getSize();
613 else if(stackFormat->isDiameterIdentity()) result += a_DiameterIdentity->getSize();
614 else if(stackFormat->isDiameterURI()) result += a_DiameterURI->getSize();
615 else if(stackFormat->isEnumerated()) result += a_Enumerated->getSize();
616 else if(stackFormat->isIPFilterRule()) result += a_IPFilterRule->getSize();
617 else if(stackFormat->isQoSFilterRule()) result += a_QoSFilterRule->getSize();
619 /////////////////////
620 // Format specific //
621 /////////////////////
622 result += getLengthByFormat(stackFormat);
627 //------------------------------------------------------------------------------
628 //-------------------------------------------- Avp::unknownAvpWithMandatoryBit()
629 //------------------------------------------------------------------------------
630 void Avp::unknownAvpWithMandatoryBit() const throw(anna::RuntimeException) {
631 OamModule &oamModule = OamModule::instantiate();
632 const char *c_aid = STRING_WITH_QUOTATION_MARKS__C_STR(anna::diameter::functions::avpIdAsPairString(a_id));
633 oamModule.activateAlarm(OamModule::Alarm::AvpDecode__UnknownAvp__s__WithMandatoryBit, c_aid);
634 oamModule.count(OamModule::Counter::AvpDecode__UnknownAvpWithMandatoryBit);
636 std::string msg = anna::functions::asString("Detected unknown Avp %s with mandatory bit activated", c_aid);
637 anna::Logger::warning(msg, ANNA_FILE_LOCATION);
641 //------------------------------------------------------------------------------
642 //-------------------------------------------------------- Avp::decodeDataPart()
643 //------------------------------------------------------------------------------
644 void Avp::decodeDataPart(const char * buffer, int size, const parent_t & parent, Message *answer) throw(anna::RuntimeException) {
646 OamModule &oamModule = OamModule::instantiate();
647 // Dictionary stack avp and format:
648 const stack::Avp *stackAvp = getStackAvp();
649 const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
652 a_Unknown->decode(buffer, size);
656 if(stackFormat->isOctetString()) a_OctetString->decode(buffer, size);
657 else if(stackFormat->isInteger32()) a_Integer32->decode(buffer, size);
658 else if(stackFormat->isInteger64()) a_Integer64->decode(buffer, size);
659 else if(stackFormat->isUnsigned32()) a_Unsigned32->decode(buffer, size);
660 else if(stackFormat->isUnsigned64()) a_Unsigned64->decode(buffer, size);
661 else if(stackFormat->isFloat32()) a_Float32->decode(buffer, size);
662 else if(stackFormat->isFloat64()) a_Float64->decode(buffer, size);
663 else if(stackFormat->isGrouped()) {
665 LOGDEBUG(anna::Logger::debug("Grouped Avp has empty data part", ANNA_FILE_LOCATION));
669 if((size % 4) != 0) {
670 oamModule.activateAlarm(OamModule::Alarm::AvpDecode__IncorrectLength);
671 oamModule.count(OamModule::Counter::AvpDecode__IncorrectLength);
674 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_AVP_LENGTH);
675 answer->setFailedAvp(parent, a_id);
678 throw anna::RuntimeException("Avp format error, the avp length is incorrect (must be multiple of 4 on grouped type)", ANNA_FILE_LOCATION);
685 parent_t me = parent;
688 while(avpPos < size) {
690 avp = getEngine()->createAvp(NULL);
691 db.assign(buffer + avpPos, size - avpPos /* is valid to pass total size (indeed i don't know the real avp size) because it will be limited and this has deep copy disabled (no memory is reserved) */);
692 avp -> decode(db, me, answer);
693 } catch(anna::RuntimeException &ex) {
694 getEngine()->releaseAvp(avp);
699 avpPos += 4 * REQUIRED_WORDS(avp->getLength());
701 } else if(stackFormat->isAddress()) a_Address->decode(buffer, size);
702 else if(stackFormat->isTime()) a_Time->decode(buffer, size);
703 else if(stackFormat->isUTF8String()) a_UTF8String->decode(buffer, size);
704 else if(stackFormat->isDiameterIdentity()) a_DiameterIdentity->decode(buffer, size);
705 else if(stackFormat->isDiameterURI()) a_DiameterURI->decode(buffer, size);
706 else if(stackFormat->isEnumerated()) a_Enumerated->decode(buffer, size);
707 else if(stackFormat->isIPFilterRule()) a_IPFilterRule->decode(buffer, size);
708 else if(stackFormat->isQoSFilterRule()) a_QoSFilterRule->decode(buffer, size);
710 /////////////////////
711 // Format specific //
712 /////////////////////
713 decodeDataPartByFormat(buffer, size, stackFormat);
716 //------------------------------------------------------------------------------
717 //---------------------------------------------------------------- Avp::decode()
718 //------------------------------------------------------------------------------
719 void Avp::decode(const anna::DataBlock &db, const parent_t & parent, Message *answer) throw(anna::RuntimeException) {
721 OamModule &oamModule = OamModule::instantiate();
723 if(db.getSize() < HeaderLengthVinactive) {
724 oamModule.activateAlarm(OamModule::Alarm::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength);
725 oamModule.count(OamModule::Counter::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength);
726 // DIAMETER_INVALID_AVP_LENGTH; // no podr� construir un avp fiable, as� que no registro el result-code
727 throw anna::RuntimeException("Not enough bytes to cover avp header length", ANNA_FILE_LOCATION);
730 const char * buffer = db.getData();
733 // 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
734 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
736 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
737 // | AVP Flags | AVP Length |
738 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
739 // | Vendor-ID (opt) |
740 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
743 // Code flags and vendor-id
744 U32 code = DECODE4BYTES_INDX_VALUETYPE(buffer, 0, U32);
746 a_flags = (S8)buffer[4];
748 U32 vendorID = helpers::VENDORID__base;
751 if(db.getSize() < HeaderLengthVactive) {
752 oamModule.activateAlarm(OamModule::Alarm::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength);
753 oamModule.count(OamModule::Counter::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength);
754 // DIAMETER_INVALID_AVP_LENGTH; // no podr� construir un avp fiable, as� que no registro el result-code
755 throw anna::RuntimeException(anna::functions::asString("Not enough bytes to cover avp header length (avp code = %u)", code), ANNA_FILE_LOCATION);
758 vendorID = DECODE4BYTES_INDX_VALUETYPE(buffer, 8, U32);
760 if(vendorID == helpers::VENDORID__base) {
761 // A vendor ID value of zero (0) corresponds to the IETF adopted AVP
762 // values, as managed by the IANA. Since the absence of the vendor
763 // ID field implies that the AVP in question is not vendor specific,
765 // implementations MUST NOT use the zero (0) vendor ID.
766 oamModule.activateAlarm(OamModule::Alarm::AvpDecode__IncoherenceBetweenActivatedVBitAndZeroedVendorIDValueReceived);
767 oamModule.count(OamModule::Counter::AvpDecode__IncoherenceBetweenActivatedVBitAndZeroedVendorIDValueReceived);
768 throw anna::RuntimeException(anna::functions::asString("Incoherence between activated V bit and zeroed vendor-id value received (avp code = %u)", code), ANNA_FILE_LOCATION);
773 setId(AvpId(code, vendorID));
774 // Flags could have been updated regarding dictionary, but during decoding we must respect buffer received:
775 a_flags = (S8)buffer[4];
777 // Here i know id and flags:
778 // The 'M' Bit, known as the Mandatory bit, indicates whether support of the AVP is required. If an AVP with the 'M' bit set is received by
779 // a Diameter client, server, proxy, or translation agent and either the AVP or its value is unrecognized, the message MUST be rejected.
780 // Diameter Relay and redirect agents MUST NOT reject messages with unrecognized AVPs.
781 if(!getStackAvp() && mandatoryBit()) {
783 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_AVP_UNSUPPORTED);
784 answer->setFailedAvp(parent, a_id);
787 unknownAvpWithMandatoryBit();
791 U24 length = DECODE3BYTES_INDX_VALUETYPE(buffer, 5, U24);
792 // Data start position:
793 int startDataPos = vendorBit() ? HeaderLengthVactive : HeaderLengthVinactive;
795 int dataBytes = length - startDataPos;
798 oamModule.activateAlarm(OamModule::Alarm::AvpDecode__IncorrectLength);
799 oamModule.count(OamModule::Counter::AvpDecode__IncorrectLength);
802 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_AVP_LENGTH);
803 answer->setFailedAvp(parent, a_id);
806 throw anna::RuntimeException(anna::functions::asString("Avp format error, the avp length is incorrect (avp code = %u)", code), ANNA_FILE_LOCATION);
810 decodeDataPart(buffer + startDataPos, dataBytes, parent, answer);
811 } catch(anna::RuntimeException &ex) {
812 oamModule.activateAlarm(OamModule::Alarm::AvpDecode__DataPartInconsistence);
813 oamModule.count(OamModule::Counter::AvpDecode__DataPartInconsistence);
816 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_AVP_VALUE);
817 answer->setFailedAvp(parent, a_id);
820 throw anna::RuntimeException(anna::functions::asString("Internal Avp decoding error (avp code = %u): %s", code, ex.getText().c_str()), ANNA_FILE_LOCATION);
825 //------------------------------------------------------------------------------
826 //----------------------------------------------------------- Avp::getStackAvp()
827 //------------------------------------------------------------------------------
828 const anna::diameter::stack::Avp *Avp::getStackAvp(AvpId id, Engine *engine) throw() {
829 const stack::Dictionary * dictionary = engine->getDictionary();
830 return (dictionary ? (dictionary->getAvp(id)) : NULL);
834 //------------------------------------------------------------------------------
835 //------------------------------------------------------------------- Avp::fix()
836 //------------------------------------------------------------------------------
837 void Avp::fix(avp_container &avps, find_container &finds, int &insertionPositionForChilds, anna::diameter::stack::const_avprule_iterator ruleBegin, anna::diameter::stack::const_avprule_iterator ruleEnd) throw() {
839 if(avps.size() == 0) return; // empty content, nothing to fix
841 if(ruleBegin == ruleEnd) return; // no reference. Cannot fix
843 // Copy reference container and clear internal map in order to build a fixed version:
844 avp_container unfixedAvps;
846 for(const_avp_iterator it = avps.begin(); it != avps.end(); it++)
847 unfixedAvps[(*it).first] = (*it).second;
850 // Cache system reset (fix probably will invalidate cached findings):
852 insertionPositionForChilds = 0;
856 for(anna::diameter::stack::const_avprule_iterator rule_it = ruleBegin; rule_it != ruleEnd; rule_it++) {
857 while((avp_it = Avp::avp_find(unfixedAvps, (*rule_it).second.getId(), 1)) != unfixedAvps.end()) {
858 avp = (*avp_it).second;
859 addChild(avps, insertionPositionForChilds, avp);
860 unfixedAvps.erase(avp_it); // processed
864 // Add remaining avps:
865 for(avp_it = unfixedAvps.begin(); avp_it != unfixedAvps.end(); avp_it++) {
866 avp = (*avp_it).second;
868 if(avp) addChild(avps, insertionPositionForChilds, avp);
872 for(avp_iterator it = avps.begin(); it != avps.end(); it++) {
875 if(avp->hasChildren()) avp->fix();
880 //------------------------------------------------------------------------------
881 //------------------------------------------------------------------- Avp::fix()
882 //------------------------------------------------------------------------------
883 void Avp::fix() throw() {
884 // Dictionary stack avp:
885 const stack::Avp *stackAvp = getStackAvp();
886 const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
889 //LOGDEBUG(anna::Logger::debug("No dictionary avp reference found. Cannot fix.", ANNA_FILE_LOCATION));
893 if(!stackFormat || !stackFormat->isGrouped()) {
894 //LOGDEBUG(anna::Logger::debug("Avp is not grouped. Nothing to fix.", ANNA_FILE_LOCATION));
898 fix(a_avps, (find_container&)a_finds, a_insertionPositionForChilds, stackAvp->avprule_begin(), stackAvp->avprule_end());
902 //------------------------------------------------------------------------------
903 //------------------------------------------------------------ Avp::validLevel()
904 //------------------------------------------------------------------------------
905 bool Avp::validLevel(const avp_container &avps, anna::diameter::stack::const_avprule_iterator ruleBegin, anna::diameter::stack::const_avprule_iterator ruleEnd, Engine * engine, const parent_t & parent, Message *answer) throw(anna::RuntimeException) {
908 OamModule &oamModule = OamModule::instantiate();
914 const_avp_iterator avp_it = avps.begin();
915 anna::diameter::stack::const_avprule_iterator rule_it;
918 for(rule_it = ruleBegin; rule_it != ruleEnd; rule_it++) {
921 if((*rule_it).second.isFixed()) {
922 if(avps.size() == 0) break; // cardinality checking will show this anomaly
924 if(avp_it != avps.end()) {
925 id = Avp::avp(avp_it)->getId();
927 if(id != (*rule_it).second.getId()) {
929 // Missing fixed rule: %s
930 } else if(Avp::avp_find(avps, id, 2) != avps.end()) {
932 // More than one fixed ocurrency for rule %s (*)
936 // (*) for (int k = 0; k < (*rule_it).second.getQualMax(); k++) avp_it++
942 // OAM & Depth management
943 oamModule.activateAlarm(OamModule::Alarm::LevelValidation__MissingFixedRule__s__Inside__s__, STRING_WITH_QUOTATION_MARKS__C_STR((*rule_it).second.asString(false /*ommit dots & pair*/)), STRING_WITH_QUOTATION_MARKS__C_STR(parent.asString()));
944 oamModule.count(OamModule::Counter::LevelValidation__MissingFixedRule);
947 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_MISSING_AVP);
948 answer->setFailedAvp(parent, (*rule_it).second.getId());
951 engine->validationAnomaly(anna::functions::asString("Missing fixed rule %s inside %s", STRING_WITH_QUOTATION_MARKS__C_STR((*rule_it).second.asString(false /*ommit dots & pair*/)), STRING_WITH_QUOTATION_MARKS__C_STR(parent.asString())));
953 } else break; // finish fixed
957 // Cardinality // Mandatory control is implicit here
959 anna::diameter::stack::const_avprule_iterator generic_rule_it = ruleEnd;
960 int min, max, amount;
962 for(rule_it = ruleBegin; rule_it != ruleEnd; rule_it++) {
963 if((*rule_it).second.isAny()) { generic_rule_it = rule_it; continue; } // generic Avp will be managed after
965 id = (*rule_it).second.getId();
966 min = (*rule_it).second.getQualMin();
967 max = (*rule_it).second.getQualMax(); // -1 means infinite
968 amount = Avp::countAvp(avps, id);
970 if((amount < min) || ((max != -1) && (amount > max))) {
971 // Failed rule %s for cardinality (found %d items)
973 // OAM & Depth management
974 oamModule.activateAlarm(OamModule::Alarm::LevelValidation__FailedRule__s__ForCardinality_Found__d__ItemsInside__s__, STRING_WITH_QUOTATION_MARKS__C_STR((*rule_it).second.asString(false /*ommit dots & pair*/)), amount, STRING_WITH_QUOTATION_MARKS__C_STR(parent.asString()));
975 oamModule.count(OamModule::Counter::LevelValidation__FailedRuleForCardinality);
978 oamModule.count(OamModule::Counter::LevelValidation__FailedRuleForCardinalityLessThanNeeded);
981 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_MISSING_AVP);
982 answer->setFailedAvp(parent, id);
985 oamModule.count(OamModule::Counter::LevelValidation__FailedRuleForCardinalityMoreThanNeeded);
988 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_AVP_OCCURS_TOO_MANY_TIMES);
989 answer->setFailedAvp(parent, id);
993 engine->validationAnomaly(anna::functions::asString("Failed rule %s for cardinality (found %d items inside %s)", STRING_WITH_QUOTATION_MARKS__C_STR((*rule_it).second.asString(false /*ommit dots & pair*/)), amount, STRING_WITH_QUOTATION_MARKS__C_STR(parent.asString())));
997 bool haveGeneric = (generic_rule_it != ruleEnd);
1002 std::map < AvpId, int /* dummy */ > disregarded; // 'Disregardeds' are Avps not in rules list
1003 std::map < AvpId, int /* dummy */ >::const_iterator disregarded_it;
1005 for(avp_it = avps.begin(); avp_it != avps.end(); avp_it++) {
1006 id = Avp::avp(avp_it)->getId();
1007 // Find rule for the child:
1008 foundInRules = false;
1010 for(rule_it = ruleBegin; rule_it != ruleEnd; rule_it++) {
1011 if((*rule_it).second.getId() == id) {
1012 foundInRules = true;
1018 disregarded[id] = 0;
1022 // Generic AVP cardinality checkings
1023 int disregardeds = disregarded.size();
1026 min = (*generic_rule_it).second.getQualMin();
1027 max = (*generic_rule_it).second.getQualMax(); // -1 means infinite
1028 amount = disregardeds;
1030 if((amount < min) || ((max != -1) && (amount > max))) {
1031 // Failed Generic AVP rule %s for cardinality (found %d disregarded items inside %s)
1033 // OAM & Depth management
1034 oamModule.activateAlarm(OamModule::Alarm::LevelValidation__FailedGenericAvpRule__s__ForCardinality_Found__d__DisregardedItemsInside__s__, STRING_WITH_QUOTATION_MARKS__C_STR((*generic_rule_it).second.asString(false /*ommit dots & pair*/)), amount, STRING_WITH_QUOTATION_MARKS__C_STR(parent.asString()));
1035 oamModule.count(OamModule::Counter::LevelValidation__FailedGenericAvpRuleForCardinalityFoundDisregardedItem);
1038 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_AVP_NOT_ALLOWED);
1039 answer->setFailedAvp(parent, id); // NO SENSE... what to put ?
1042 engine->validationAnomaly(anna::functions::asString("Failed Generic AVP rule %s for cardinality (found %d disregarded items inside %s)", STRING_WITH_QUOTATION_MARKS__C_STR((*generic_rule_it).second.asString(false /*ommit dots & pair*/)), amount, STRING_WITH_QUOTATION_MARKS__C_STR(parent.asString())));
1044 } else if(disregardeds) { // When Generic AVP missing, no disregarded Avps are allowed
1045 // Found %d disregarded items inside %s and Generic AVP was not specified
1047 // Build disregarded list as string (unknown as avp id pair):
1048 std::string s_disregardeds = "";
1049 const stack::Avp *stackAvp;
1051 for(disregarded_it = disregarded.begin(); disregarded_it != disregarded.end(); disregarded_it++) {
1052 id = (*disregarded_it).first;
1053 stackAvp = getStackAvp(id, engine);
1054 s_disregardeds += (stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id)));
1055 s_disregardeds += ", ";
1057 // We wouldn't know where are these disregarded, but...
1059 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_AVP_NOT_ALLOWED);
1060 answer->setFailedAvp(parent, id);
1064 s_disregardeds.erase(s_disregardeds.size() - 2, 2); // remove last ', '
1065 // OAM & Depth management
1066 oamModule.activateAlarm(OamModule::Alarm::LevelValidation__FoundDisregardedItemsInside__s__AndGenericAVPWasNotSpecified__s__, STRING_WITH_QUOTATION_MARKS__C_STR(parent.asString()), STRING_WITH_QUOTATION_MARKS__C_STR(s_disregardeds));
1067 oamModule.count(OamModule::Counter::LevelValidation__FoundDisregardedItemsAndGenericAVPWasNotSpecified);
1068 engine->validationAnomaly(anna::functions::asString("Found disregarded items inside %s and Generic AVP was not specified: %s", STRING_WITH_QUOTATION_MARKS__C_STR(parent.asString()), STRING_WITH_QUOTATION_MARKS__C_STR(s_disregardeds)));
1075 //------------------------------------------------------------------------------
1076 //----------------------------------------------------------------- Avp::valid()
1077 //------------------------------------------------------------------------------
1078 bool Avp::valid(const parent_t & parent, Message *answer) const throw(anna::RuntimeException) {
1080 OamModule &oamModule = OamModule::instantiate();
1081 // Dictionary stack avp:
1082 const stack::Avp *stackAvp = getStackAvp();
1083 const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
1086 // No dictionary avp reference found. Cannot validate
1087 return true; // perhaps a unknown Avp
1091 parent_t me = parent;
1092 me.addAvp(a_id, stackAvp->getName().c_str());
1095 // No format avp reference found. Cannot validate
1096 return true; // perhaps a unknown Avp
1099 //////////////////////////////
1100 // Flags coherence checking //
1101 //////////////////////////////
1102 bool result = flagsOK();
1105 // OAM & Depth management
1106 oamModule.activateAlarm(OamModule::Alarm::AvpValidation__Avp__s__Flags__d__DoesNotFulfillTheDefinedFlagRules__s__, STRING_WITH_QUOTATION_MARKS__C_STR(me.asString()), (int)a_flags, STRING_WITH_QUOTATION_MARKS__C_STR(stackAvp->getFlagRulesDescription()));
1107 oamModule.count(OamModule::Counter::AvpValidation__AvpFlagsDoesNotFulfillTheDefinedFlagRules);
1110 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_AVP_BITS);
1111 answer->setFailedAvp(parent, a_id, stackAvp->getName().c_str()); // RFC 6733 says nothing about Failed-AVP in this case...
1114 getEngine()->validationAnomaly(anna::functions::asString("The AVP %s flags (%d) does not fulfill the defined flag rules: %s", STRING_WITH_QUOTATION_MARKS__C_STR(me.asString()), (int)a_flags, STRING_WITH_QUOTATION_MARKS__C_STR(stackAvp->getFlagRulesDescription())));
1117 //////////////////////
1118 // Enumerated range //
1119 //////////////////////
1120 if(stackFormat->isEnumerated()) {
1121 if(!stackAvp->allowEnum(a_Enumerated->getValue())) {
1123 // OAM & Depth management
1124 oamModule.activateAlarm(OamModule::Alarm::AvpValidation__EnumeratedAvp__s__WithValue__d__DoesNotComplyRestriction__s__, STRING_WITH_QUOTATION_MARKS__C_STR(me.asString()), a_Enumerated->getValue(), stackAvp->getEnums());
1125 oamModule.count(OamModule::Counter::AvpValidation__EnumeratedAvpWithValueDoesNotComplyRestriction);
1128 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_AVP_VALUE);
1129 answer->setFailedAvp(parent, a_id, stackAvp->getName().c_str());
1132 getEngine()->validationAnomaly(anna::functions::asString("Enumerated AVP %s with value %d does not comply to restriction: %s", STRING_WITH_QUOTATION_MARKS__C_STR(me.asString()), a_Enumerated->getValue(), stackAvp->getEnums()));
1136 ////////////////////
1137 // Level checking //
1138 ////////////////////
1139 result = Avp::validLevel(a_avps, stackAvp->avprule_begin(), stackAvp->avprule_end(), getEngine(), me, answer) && result;
1141 ////////////////////////
1142 // Childrens checking //
1143 ////////////////////////
1144 if(a_id == helpers::base::AVPID__Failed_AVP) return result; // DON'T VALIDATE CONTENT FOR Failed-AVP, because it won't be valid...
1146 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++)
1147 result = ((*it).second->valid(me, answer)) && result;
1153 //------------------------------------------------------------------------------
1154 //------------------------------------------------------------------ Avp::code()
1155 //------------------------------------------------------------------------------
1156 void Avp::code(char* buffer, int &size) const throw(anna::RuntimeException) {
1158 buffer[0] = (S8)(a_id.first >> 24);
1159 buffer[1] = (S8)(a_id.first >> 16);
1160 buffer[2] = (S8)(a_id.first >> 8);
1161 buffer[3] = (S8) a_id.first;
1164 buffer[4] = (S8) a_flags;
1165 buffer[5] = (S8)(size >> 16);
1166 buffer[6] = (S8)(size >> 8);
1167 buffer[7] = (S8) size;
1171 buffer[8] = (S8)(a_id.second >> 24);
1172 buffer[9] = (S8)(a_id.second >> 16);
1173 buffer[10] = (S8)(a_id.second >> 8);
1174 buffer[11] = (S8) a_id.second;
1177 // Data start position:
1178 int startDataPos = vendorBit() ? HeaderLengthVactive : HeaderLengthVinactive;
1180 S8 * dataPart = buffer + startDataPos;
1181 int dataBytes; // not used but could be useful for checking (size - startDataPos)
1183 if(startDataPos == size) {
1184 LOGDEBUG(anna::Logger::debug("There is no data part to encode", ANNA_FILE_LOCATION));
1189 const stack::Avp *stackAvp = getStackAvp();
1190 const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
1193 a_Unknown->code(dataPart, dataBytes);
1197 if(stackFormat->isOctetString()) a_OctetString->code(dataPart, dataBytes);
1198 else if(stackFormat->isInteger32()) a_Integer32->code(dataPart, dataBytes);
1199 else if(stackFormat->isInteger64()) a_Integer64->code(dataPart, dataBytes);
1200 else if(stackFormat->isUnsigned32()) a_Unsigned32->code(dataPart, dataBytes);
1201 else if(stackFormat->isUnsigned64()) a_Unsigned64->code(dataPart, dataBytes);
1202 else if(stackFormat->isFloat32()) a_Float32->code(dataPart, dataBytes);
1203 else if(stackFormat->isFloat64()) a_Float64->code(dataPart, dataBytes);
1204 else if(stackFormat->isGrouped()) {
1205 // // Each avp encoding will remain padding octets depending on format. In order to
1206 // // code grouped content (each avp will be multiple of 4) we clean the entire buffer
1207 // // to ensure padding (easier than custom-made for each format):
1208 // memset(dataPart, 0, size - startDataPos);
1209 char *dataPartGrouped = dataPart;
1210 int dataBytesGrouped;
1212 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) {
1213 avp(it)->code(dataPartGrouped, dataBytesGrouped);
1214 dataPartGrouped = dataPartGrouped + 4 * REQUIRED_WORDS(dataBytesGrouped);
1216 } else if(stackFormat->isAddress()) a_Address->code(dataPart, dataBytes);
1217 else if(stackFormat->isTime()) a_Time->code(dataPart, dataBytes);
1218 else if(stackFormat->isUTF8String()) a_UTF8String->code(dataPart, dataBytes);
1219 else if(stackFormat->isDiameterIdentity()) a_DiameterIdentity->code(dataPart, dataBytes);
1220 else if(stackFormat->isDiameterURI()) a_DiameterURI->code(dataPart, dataBytes);
1221 else if(stackFormat->isEnumerated()) a_Enumerated->code(dataPart, dataBytes);
1222 else if(stackFormat->isIPFilterRule()) a_IPFilterRule->code(dataPart, dataBytes);
1223 else if(stackFormat->isQoSFilterRule()) a_QoSFilterRule->code(dataPart, dataBytes);
1225 /////////////////////
1226 // Format specific //
1227 /////////////////////
1228 codeByFormat(dataPart, stackFormat);
1232 //------------------------------------------------------------------------------
1233 //------------------------------------------------------------ Avp::getXMLdata()
1234 //------------------------------------------------------------------------------
1235 std::string Avp::getXMLdata(bool & isHex, const stack::Format *stackFormat) const throw() {
1236 std::string result = "";
1240 // if (!stackFormat) {
1242 // return a_Unknown->asHexString();
1244 // } catch (anna::RuntimeException &ex) {
1250 // Tricky situation: if you change the dictionary dynamically, and a previous formatted avp
1251 // becomes unknown (the change consists in remove Avps basically), then this would get a core
1252 // dump: a_Unknown = NULL. We are not going to protect that situation because it represents a
1253 // implementation fault, and there are many points which could have similar bad behaviour
1254 // (those where we access directly the a_Unknown pointer).
1255 // The best way to afford this is ... TODO:
1256 // Freeze dictionary after use from any resource (avp, message), setting a flag which deny
1257 // any modification in such dictionary. The best way to do this is on engine configuration
1258 // for Avp o Message, where we could invoke something like getEngine()->getDictionary()->freeze()
1260 return a_Unknown->asHexString(); // asHexString for OctetString cannot launch exception
1263 // Special case for Address: could launch exception if not printable
1265 if(stackFormat->isAddress()) return a_Address->asPrintableString();
1266 } catch(anna::RuntimeException&) {
1269 return a_Address->asHexString();
1273 if(stackFormat->isOctetString()) {
1275 return a_OctetString->asHexString();
1279 if(stackFormat->isInteger32()) return a_Integer32->asPrintableString();
1281 if(stackFormat->isInteger64()) return a_Integer64->asPrintableString();
1283 if(stackFormat->isUnsigned32()) return a_Unsigned32->asPrintableString();
1285 if(stackFormat->isUnsigned64()) return a_Unsigned64->asPrintableString();
1287 if(stackFormat->isFloat32()) return a_Float32->asPrintableString();
1289 if(stackFormat->isFloat64()) return a_Float64->asPrintableString();
1291 //if (stackFormat->isAddress()) return a_Address->asPrintableString();
1293 if(stackFormat->isTime()) return a_Time->asPrintableString();
1295 if(stackFormat->isUTF8String()) return a_UTF8String->asPrintableString();
1297 if(stackFormat->isDiameterIdentity()) return a_DiameterIdentity->asPrintableString();
1299 if(stackFormat->isDiameterURI()) return a_DiameterURI->asPrintableString();
1301 if(stackFormat->isEnumerated()) return a_Enumerated->asPrintableString();
1303 if(stackFormat->isIPFilterRule()) return a_IPFilterRule->asPrintableString();
1305 if(stackFormat->isQoSFilterRule()) return a_QoSFilterRule->asPrintableString();
1307 /////////////////////
1308 // Format specific //
1309 /////////////////////
1310 return getXMLdataByFormat(isHex, stackFormat);
1311 } catch(anna::RuntimeException &ex) {
1319 //------------------------------------------------------------------------------
1320 //---------------------------------------------------------------- Avp::decode()
1321 //------------------------------------------------------------------------------
1322 void Avp::decode(const anna::DataBlock &db) throw(anna::RuntimeException) {
1324 parent.setMessage(CommandId(0, false), "No-Parent");
1325 decode(db, parent, NULL);
1329 //------------------------------------------------------------------------------
1330 //--------------------------------------------------------------- Avp::fromXML()
1331 //------------------------------------------------------------------------------
1332 void Avp::fromXML(const anna::xml::Node* avpNode) throw(anna::RuntimeException) {
1333 // <!ATTLIST avp id CDATA #IMPLIED code CDATA #IMPLIED vendor-code CDATA #IMPLIED flags CDATA #IMPLIED data CDATA #IMPLIED hex-data CDATA #IMPLIED>
1334 const anna::xml::Attribute *name, *code, *vendorCode, *flags, *data, *hexData;
1335 name = avpNode->getAttribute("name", false /* no exception */);
1336 code = avpNode->getAttribute("code", false /* no exception */);
1337 vendorCode = avpNode->getAttribute("vendor-code", false /* no exception */);
1338 flags = avpNode->getAttribute("flags", false /* no exception */);
1339 data = avpNode->getAttribute("data", false /* no exception */);
1340 hexData = avpNode->getAttribute("hex-data", false /* no exception */);
1342 const stack::Dictionary * dictionary = getEngine()->getDictionary();
1343 const stack::Avp *stackAvp = NULL;
1344 const stack::Format *stackFormat = NULL;
1349 std::string msg = "Error processing avp <name '"; msg += name->getValue();
1350 msg += "'>: no dictionary available. Load one or use <'code' + 'flags' + 'vendorCode'> instead of <'name'>";
1351 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1354 stackAvp = dictionary->getAvp(name->getValue());
1357 std::string msg = "Error processing avp <name '"; msg += name->getValue();
1358 msg += "'>: no avp found for this identifier at available dictionary";
1359 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1362 stackFormat = stackAvp->getFormat();
1365 // Check attributes exclusiveness
1366 if(name) { // compact mode
1367 bool allowFlagsField = ( stackAvp->getVbit() == anna::diameter::stack::Avp::FlagRule::may || stackAvp->getVbit() == anna::diameter::stack::Avp::FlagRule::shouldnot
1368 || stackAvp->getMbit() == anna::diameter::stack::Avp::FlagRule::may || stackAvp->getMbit() == anna::diameter::stack::Avp::FlagRule::shouldnot
1369 /* umm, perhaps we could omit for bit P, whic is deprecated ... */
1370 /* || stackAvp->getPbit() == anna::diameter::stack::Avp::FlagRule::may || stackAvp->getPbit() == anna::diameter::stack::Avp::FlagRule::shouldnot*/ );
1371 if(code || (flags && !allowFlagsField) || vendorCode) {
1372 std::string msg = "Error processing avp <name '"; msg += name->getValue();
1373 if (flags) msg += "'>: avp attributes <'code' + 'flags' + 'vendorCode'> are not allowed if <'name'> is provided (also flags is not permitted: no may, no shouldnot)";
1374 else msg += "'>: avp attributes <'code' + 'vendorCode'> are not allowed if <'name'> is provided";
1375 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1378 setId(stackAvp->getId());
1380 if (flags && allowFlagsField) {
1382 int i_aux = flags->getIntegerValue();
1384 if(i_aux < 0 || i_aux > 256) {
1385 std::string msg = "Error processing avp <flags '"; msg += flags->getValue();
1386 msg += "': out of range [0,256]";
1387 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1395 if(!code || !flags || !vendorCode) {
1396 std::string s_code = code ? code->getValue() : "?";
1397 std::string s_flags = flags ? flags->getValue() : "?";
1398 std::string s_vendorCode = vendorCode ? vendorCode->getValue() : "?";
1399 std::string msg = "Error processing avp <code '"; msg += s_code;
1400 msg += "' + flags '"; msg += s_flags;
1401 msg += "' + vendorCode '"; msg += s_vendorCode;
1402 msg += "'>: all must be provided if <'name'> don't";
1403 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1407 int i_aux = code->getIntegerValue();
1410 std::string msg = "Error processing avp <code '"; msg += code->getValue();
1411 msg += "': negative values are not allowed";
1412 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1417 i_aux = flags->getIntegerValue();
1419 if(i_aux < 0 || i_aux > 256) {
1420 std::string msg = "Error processing avp <flags '"; msg += flags->getValue();
1421 msg += "': out of range [0,256]";
1422 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1426 int flagsBCK = a_flags;
1427 // VendorCode checks
1428 i_aux = vendorCode->getIntegerValue();
1431 std::string msg = "Error processing avp <vendorCode '"; msg += vendorCode->getValue();
1432 msg += "': negative values are not allowed";
1433 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1436 U32 u_vendorCode = i_aux;
1437 bool vendorSpecific1 = (u_vendorCode != 0);
1438 bool vendorSpecific2 = (((a_flags) & VBitMask) != 0x00);
1440 if(vendorSpecific1 != vendorSpecific2) {
1441 std::string msg = "Error processing avp <vendorCode '"; msg += vendorCode->getValue();
1442 msg += "' and avp <flags '"; msg += flags->getValue();
1443 msg += "': incompatible vendor-specific properties";
1444 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1447 // Final assignments
1448 setId(AvpId(u_code, u_vendorCode));
1449 // Flags could have been updated regarding dictionary, but during parsing we must respect xml file:
1451 stackAvp = getStackAvp();
1452 stackFormat = stackAvp ? stackAvp->getFormat() : NULL;
1456 // Check if grouped not confirmed
1457 anna::xml::Node::const_child_iterator it;
1458 anna::xml::Node::const_child_iterator minii = avpNode->child_begin();
1459 anna::xml::Node::const_child_iterator maxii = avpNode->child_end();
1460 const bool hasChildren(minii != maxii);
1463 // We need to confirm is grouped
1465 throw anna::RuntimeException("An xml avp node with children nodes could not confirmed as Grouped", ANNA_FILE_LOCATION);
1467 if(!stackFormat->isGrouped())
1468 throw anna::RuntimeException("An xml avp node with children nodes is not grouped type", ANNA_FILE_LOCATION);
1471 throw anna::RuntimeException("An xml avp node with children nodes has 'data' or 'hex-data' field", ANNA_FILE_LOCATION);
1475 std::string s_avp = name ? (name->getValue()) : (anna::diameter::functions::avpIdAsPairString(a_id));
1477 if(data && hexData) {
1478 std::string msg = "Not allowed both 'data' and 'hex-data' definitions. Avp ";
1480 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1484 bool unknown = !stackFormat;
1485 bool octetString = stackFormat && (stackFormat->isOctetString());
1487 if(data && (unknown || octetString)) {
1488 std::string msg = "Not recommended 'data' field at ";
1489 msg += unknown ? "Unknown" : "OctetString";
1490 msg += "-format Avp "; msg += s_avp;
1491 msg += ". Use better 'hex-data' or omit content fields if empty";
1492 anna::Logger::warning(msg, ANNA_FILE_LOCATION);
1497 if(data) a_Unknown->fromPrintableString(data->getValue().c_str());
1498 else if(hexData) a_Unknown->fromHexString(hexData->getValue());
1503 if(stackFormat->isOctetString()) {
1504 if(data) a_OctetString->fromPrintableString(data->getValue().c_str());
1505 else if(hexData) a_OctetString->fromHexString(hexData->getValue());
1506 } else if(stackFormat->isInteger32()) {
1507 if(data) a_Integer32->fromPrintableString(data->getValue().c_str());
1508 else if(hexData) a_Integer32->fromHexString(hexData->getValue());
1509 } else if(stackFormat->isInteger64()) {
1510 if(data) a_Integer64->fromPrintableString(data->getValue().c_str());
1511 else if(hexData) a_Integer64->fromHexString(hexData->getValue());
1512 } else if(stackFormat->isUnsigned32()) {
1513 if(data) a_Unsigned32->fromPrintableString(data->getValue().c_str());
1514 else if(hexData) a_Unsigned32->fromHexString(hexData->getValue());
1515 } else if(stackFormat->isUnsigned64()) {
1516 if(data) a_Unsigned64->fromPrintableString(data->getValue().c_str());
1517 else if(hexData) a_Unsigned64->fromHexString(hexData->getValue());
1518 } else if(stackFormat->isFloat32()) {
1519 if(data) a_Float32->fromPrintableString(data->getValue().c_str());
1520 else if(hexData) a_Float32->fromHexString(hexData->getValue());
1521 } else if(stackFormat->isFloat64()) {
1522 if(data) a_Float64->fromPrintableString(data->getValue().c_str());
1523 else if(hexData) a_Float64->fromHexString(hexData->getValue());
1524 } else if(stackFormat->isGrouped()) {
1528 for(it = minii; it != maxii; it++) {
1529 std::string nodeName = (*it)->getName();
1531 if(nodeName != "avp") {
1532 std::string msg = "Unsupported grouped avp child node name '"; msg += nodeName;
1533 msg += "': use 'avp'";
1534 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1538 avp = getEngine()->createAvp(NULL);
1539 avp -> fromXML(*it);
1540 } catch(anna::RuntimeException &ex) {
1541 getEngine()->releaseAvp(avp);
1547 } else if(stackFormat->isAddress()) {
1548 if(data) a_Address->fromPrintableString(data->getValue().c_str());
1549 else if(hexData) a_Address->fromHexString(hexData->getValue());
1550 } else if(stackFormat->isTime()) {
1551 if(data) a_Time->fromPrintableString(data->getValue().c_str());
1552 else if(hexData) a_Time->fromHexString(hexData->getValue());
1553 } else if(stackFormat->isUTF8String()) {
1554 if(data) a_UTF8String->fromPrintableString(data->getValue().c_str());
1555 else if(hexData) a_UTF8String->fromHexString(hexData->getValue());
1556 } else if(stackFormat->isDiameterIdentity()) {
1557 if(data) a_DiameterIdentity->fromPrintableString(data->getValue().c_str());
1558 else if(hexData) a_DiameterIdentity->fromHexString(hexData->getValue());
1559 } else if(stackFormat->isDiameterURI()) {
1560 if(data) a_DiameterURI->fromPrintableString(data->getValue().c_str());
1561 else if(hexData) a_DiameterURI->fromHexString(hexData->getValue());
1562 } else if(stackFormat->isEnumerated()) {
1563 if(data) a_Enumerated->fromPrintableString(data->getValue().c_str());
1564 else if(hexData) a_Enumerated->fromHexString(hexData->getValue());
1565 } else if(stackFormat->isIPFilterRule()) {
1566 if(data) a_IPFilterRule->fromPrintableString(data->getValue().c_str());
1567 else if(hexData) a_IPFilterRule->fromHexString(hexData->getValue());
1568 } else if(stackFormat->isQoSFilterRule()) {
1569 if(data) a_QoSFilterRule->fromPrintableString(data->getValue().c_str());
1570 else if(hexData) a_QoSFilterRule->fromHexString(hexData->getValue());
1573 /////////////////////
1574 // Format specific //
1575 /////////////////////
1576 fromXMLByFormat(data, hexData, stackFormat);
1579 //------------------------------------------------------------------------------
1580 //----------------------------------------------------------------- Avp::asXML()
1581 //------------------------------------------------------------------------------
1582 anna::xml::Node* Avp::asXML(anna::xml::Node* parent) const throw() {
1583 // <!ATTLIST avp id CDATA #IMPLIED code CDATA #IMPLIED vendor-code CDATA #IMPLIED flags CDATA #IMPLIED data CDATA #IMPLIED hex-data CDATA #IMPLIED>
1584 anna::xml::Node* result = parent->createChild("avp");
1585 // Dictionary stack avp and format:
1586 const stack::Avp *stackAvp = getStackAvp();
1587 const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
1588 bool compactMode = (stackAvp && flagsOK());
1591 result->createAttribute("name", stackAvp->getName());
1592 // If may or shouldnot is present in AVP definition, we have to show flags to avoid uncertainty
1593 if ( stackAvp->getVbit() == anna::diameter::stack::Avp::FlagRule::may || stackAvp->getVbit() == anna::diameter::stack::Avp::FlagRule::shouldnot
1594 || stackAvp->getMbit() == anna::diameter::stack::Avp::FlagRule::may || stackAvp->getMbit() == anna::diameter::stack::Avp::FlagRule::shouldnot
1595 /* umm, perhaps we could omit for bit P, whic is deprecated ... */
1596 /* || stackAvp->getPbit() == anna::diameter::stack::Avp::FlagRule::may || stackAvp->getPbit() == anna::diameter::stack::Avp::FlagRule::shouldnot*/ )
1597 result->createAttribute("flags", (int)a_flags);
1599 result->createAttribute("code", a_id.first);
1600 result->createAttribute("vendor-code", a_id.second);
1601 result->createAttribute("flags", (int)a_flags);
1604 // Grouped special case:
1605 if(stackFormat && stackFormat->isGrouped()) {
1606 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) avp(it)->asXML(result);
1611 // Data part literals:
1613 std::string value = getXMLdata(isHex, stackFormat);
1616 result->createAttribute("hex-data", value);
1618 result->createAttribute("data", value);
1619 const char *alias = stackAvp->getAlias(value);
1621 if(alias) result->createAttribute("alias", alias); // additional information
1628 //------------------------------------------------------------------------------
1629 //----------------------------------------------------------- Avp::asXMLString()
1630 //------------------------------------------------------------------------------
1631 std::string Avp::asXMLString() const throw() {
1632 anna::xml::Node root("root");
1633 return anna::xml::Compiler().apply(asXML(&root));
1637 //------------------------------------------------------------------------------
1638 //---------------------------------------------------------------- Avp::isLike()
1639 //------------------------------------------------------------------------------
1640 bool Avp::isLike(const std::string &pattern) const throw() {
1641 anna::RegularExpression re(pattern);
1642 return re.isLike(asXMLString());