1 // ANNA - Anna is Not Nothingness Anymore
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
5 // http://redmine.teslayout.com/projects/anna-suite
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
11 // * Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
13 // * Redistributions in binary form must reproduce the above
14 // copyright notice, this list of conditions and the following disclaimer
15 // in the documentation and/or other materials provided with the
17 // * Neither the name of the copyright holder nor the names of its
18 // contributors may be used to endorse or promote products derived from
19 // this software without specific prior written permission.
21 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 // Authors: eduardo.ramos.testillano@gmail.com
34 // cisco.tierra@gmail.com
38 #include <anna/diameter/codec/Avp.hpp>
39 #include <anna/diameter/codec/Format.hpp>
41 #include <anna/config/defines.hpp> // general types, decoding helpers (DECODE[2/3/4]BYTES_INDX_VALUETYPE), etc.
42 #include <anna/diameter/functions.hpp>
43 #include <anna/diameter/helpers/defines.hpp>
44 #include <anna/diameter/codec/basetypes/basetypes.hpp>
45 #include <anna/diameter/codec/functions.hpp> // REQUIRED_WORDS
46 #include <anna/diameter/codec/OamModule.hpp>
47 #include <anna/diameter/stack/Avp.hpp>
48 #include <anna/diameter/stack/Format.hpp>
49 #include <anna/diameter/stack/Dictionary.hpp>
50 #include <anna/diameter/stack/Engine.hpp>
51 #include <anna/diameter/codec/Engine.hpp>
52 #include <anna/core/functions.hpp>
53 #include <anna/core/util/RegularExpression.hpp>
55 #include <anna/core/tracing/Logger.hpp>
56 #include <anna/core/functions.hpp>
57 #include <anna/core/tracing/TraceMethod.hpp>
58 #include <anna/xml/xml.hpp>
65 using namespace anna::diameter::codec;
74 const int Avp::HeaderLengthVactive(12);
75 const int Avp::HeaderLengthVinactive(8);
76 const U8 Avp::VBitMask(0x80);
77 const U8 Avp::MBitMask(0x40);
78 const U8 Avp::PBitMask(0x20);
83 //------------------------------------------------------------------------------
84 //------------------------------------------------------------------- Avp::Avp()
85 //------------------------------------------------------------------------------
91 //------------------------------------------------------------------------------
92 //------------------------------------------------------------------- Avp::Avp()
93 //------------------------------------------------------------------------------
100 //------------------------------------------------------------------------------
101 //------------------------------------------------------------------ Avp::~Avp()
102 //------------------------------------------------------------------------------
108 //------------------------------------------------------------------------------
109 //------------------------------------------------------------- Avp::getEngine()
110 //------------------------------------------------------------------------------
111 Engine * Avp::getEngine() const throw(anna::RuntimeException) {
112 return a_engine ? a_engine : (a_engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION));
116 //------------------------------------------------------------------------------
117 //------------------------------------------------------------ Avp::initialize()
118 //------------------------------------------------------------------------------
119 void Avp::initialize() throw() {
121 a_id = helpers::AVPID__AVP; // (0,0)
123 a_insertionPositionForChilds = 0;
124 a_OctetString = NULL;
135 a_DiameterIdentity = NULL;
136 a_DiameterURI = NULL;
138 a_IPFilterRule = NULL;
139 a_QoSFilterRule = NULL;
142 /////////////////////
143 // Format specific //
144 /////////////////////
145 initializeByFormat();
149 //------------------------------------------------------------------------------
150 //----------------------------------------------------------------- Avp::clear()
151 //------------------------------------------------------------------------------
152 void Avp::clear() throw(anna::RuntimeException) {
153 delete a_OctetString;
161 for(avp_iterator it = avp_begin(); it != avp_end(); it++) { /*avp(it)->clear(); */getEngine()->releaseAvp(avp(it)); }
167 delete a_DiameterIdentity;
168 delete a_DiameterURI;
170 delete a_IPFilterRule;
171 delete a_QoSFilterRule;
175 /////////////////////
176 // Format specific //
177 /////////////////////
184 //------------------------------------------------------------------------------
185 //-------------------------------------------------------------- Avp::avp_find()
186 //------------------------------------------------------------------------------
187 avp_iterator Avp::avp_find(avp_container &avps, AvpId id, unsigned int position) throw() {
191 for(avp_iterator it = avps.begin(); it != avps.end(); it++) {
194 if(aux && (aux->getId() == id)) {
197 if(match == position) return it;
205 //------------------------------------------------------------------------------
206 //---------------------------------------------------------------- Avp::addAvp()
207 //------------------------------------------------------------------------------
208 Avp * Avp::addAvp(avp_container &avps, int &insertionPositionForChilds, AvpId id, Engine *engine) throw() {
209 Avp * result = engine->allocateAvp();
211 addChild(avps, insertionPositionForChilds, result);
216 //------------------------------------------------------------------------------
217 //------------------------------------------------------------- Avp::removeAvp()
218 //------------------------------------------------------------------------------
219 bool Avp::removeAvp(avp_container &avps, find_container &finds, AvpId id, int ocurrence, Engine *engine) throw() {
220 bool removed = false;
221 bool do_remove = true;
222 int position = ocurrence;
224 if(position < 0) { /* reversed access */
225 position = countAvp(avps, id) + 1 + position;
227 // Special cases -> 0 and negative results:
228 // (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)
229 // (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)
230 // (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 ...)
231 if(position <= 0) do_remove = false;
235 int n = position ? position : 1 /* will search always the first and remove, the first and remove, the first and remove ... */;
238 while((it = avp_find(avps, id, n)) != avps.end()) {
239 engine->releaseAvp((*it).second);
248 // Cache system reset (remove will invalidate cached findings):
251 const stack::Avp *stackAvp = getStackAvp(id, engine);
252 std::string msg = "Removed Avp "; msg += stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id));
253 msg += anna::functions::asString(" with provided ocurrence (%d)", ocurrence);
254 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
258 const stack::Avp *stackAvp = getStackAvp(id, engine);
259 std::string msg = "Can't found Avp "; msg += stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id));
260 msg += anna::functions::asString(" with provided ocurrence (%d), in order to be removed", ocurrence);
261 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
269 //------------------------------------------------------------------------------
270 //-------------------------------------------------------------- Avp::countAvp()
271 //------------------------------------------------------------------------------
272 int Avp::countAvp(const avp_container &avps, AvpId id) throw() {
274 const_avp_iterator it;
276 while((it = avp_find(avps, id, result + 1)) != avps.end()) result++;
282 //------------------------------------------------------------------------------
283 //-------------------------------------------------------------- Avp::firstAvp()
284 //------------------------------------------------------------------------------
285 const Avp* Avp::firstAvp(const avp_container &avps, AvpId id) throw() {
286 const_avp_iterator it = avp_find(avps, id, 1);
295 //------------------------------------------------------------------------------
296 //----------------------------------------------------------- Avp::countChilds()
297 //------------------------------------------------------------------------------
298 int Avp::countChilds(const avp_container &avps) throw() {
303 //------------------------------------------------------------------------------
304 //---------------------------------------------------------------- Avp::getAvp()
305 //------------------------------------------------------------------------------
306 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) {
308 LOGDEBUG(anna::Logger::debug("Ocurrence number zero has no sense. NULL returned.", ANNA_FILE_LOCATION));
312 bool do_search = true;
314 int position = ocurrence;
316 if(position < 0) { /* reversed access */
317 position = countAvp(avps, id) + 1 + position;
319 // Special cases -> 0 and negative results:
320 // (1) User wants to get the last, but no avp is found: position = 0 + 1 - 1 = 0 (can't find 0-position ...)
321 // (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 ...)
322 // (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 ...)
323 if(position <= 0) do_search = false;
326 const Avp * result = NULL;
329 // Search at cache finds:
330 find_key key(id, position);
331 find_iterator fit = finds.find(key);
332 cached = (fit != finds.end());
335 result = (*fit).second;
337 const_avp_iterator it = avp_find(avps, id, position);
339 if(it != avps.end()) {
340 result = (*it).second;
341 finds[key] = const_cast<Avp*>(result); // store in cache
349 const stack::Avp *stackAvp = getStackAvp(id, engine);
350 std::string msg = "Found Avp "; msg += stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id));
351 msg += anna::functions::asString(" with provided ocurrence (%d) which was ", ocurrence);
352 msg += cached ? "already cached:\n" : "the first search, now cached:\n";
353 msg += result->asXMLString();
354 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
361 case anna::Exception::Mode::Throw: {
362 const stack::Avp *stackAvp = getStackAvp(id, engine);
363 std::string msg = "Can't found Avp "; msg += stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id));
364 msg += anna::functions::asString(" with provided ocurrence (%d)", ocurrence);
365 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
368 case anna::Exception::Mode::Trace: {
370 const stack::Avp *stackAvp = getStackAvp(id, engine);
371 std::string msg = "Can't found Avp "; msg += stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id));
372 msg += anna::functions::asString(" with provided ocurrence (%d)", ocurrence);
373 anna::Logger::warning(msg, ANNA_FILE_LOCATION);
377 case anna::Exception::Mode::Ignore: {
379 const stack::Avp *stackAvp = getStackAvp(id, engine);
380 std::string msg = "Can't found Avp "; msg += stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id));
381 msg += anna::functions::asString(" with provided ocurrence (%d)", ocurrence);
382 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
392 //------------------------------------------------------------------------------
393 //--------------------------------------------------------------- Avp::_getAvp()
394 //------------------------------------------------------------------------------
395 const Avp *Avp::_getAvp(AvpId id, int ocurrence, anna::Exception::Mode::_v emode) const throw(anna::RuntimeException) {
396 // Dictionary stack avp and format (this):
397 const stack::Avp *stackAvp = getStackAvp();
398 const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
400 if(!stackFormat || !stackFormat->isGrouped())
401 throw anna::RuntimeException("This method only applies over grouped avps.", ANNA_FILE_LOCATION);
403 return getAvp(a_avps, (find_container&)a_finds, id, ocurrence, getEngine(), emode);
407 //------------------------------------------------------------------------------
408 //---------------------------------------------------------- Avp::assertFormat()
409 //------------------------------------------------------------------------------
410 void Avp::assertFormat(const std::string &name) const throw(anna::RuntimeException) {
411 // Dictionary stack avp and format:
412 const stack::Avp *stackAvp = getStackAvp();
413 const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
414 std::string format = stackFormat ? stackFormat->getName() : "Unknown";
417 std::string msg = "The Avp ";
418 msg += anna::diameter::functions::avpIdAsPairString(a_id);
419 msg += " with format '";
421 msg += "' is not compatible with the API method used (";
424 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
429 //------------------------------------------------------------------------------
430 //--------------------------------------------------------------- Avp::flagsOK()
431 //------------------------------------------------------------------------------
432 bool Avp::flagsOK() const throw() {
433 // Dictionary stack avp:
434 const stack::Avp *stackAvp = getStackAvp();
437 anna::Logger::error("Impossible to decide if flags are correct because stack avp is not identified. Assume flags ok", ANNA_FILE_LOCATION);
442 bool Vnone = (stackAvp->getVbit() == stack::Avp::FlagRule::None);
444 bool Vmust = (stackAvp->getVbit() == stack::Avp::FlagRule::must);
446 bool Vmustnot = (stackAvp->getVbit() == stack::Avp::FlagRule::mustnot);
448 bool Mnone = (stackAvp->getMbit() == stack::Avp::FlagRule::None);
450 bool Mmust = (stackAvp->getMbit() == stack::Avp::FlagRule::must);
452 bool Mmustnot = (stackAvp->getMbit() == stack::Avp::FlagRule::mustnot);
454 bool Pnone = (stackAvp->getPbit() == stack::Avp::FlagRule::None);
456 bool Pmust = (stackAvp->getPbit() == stack::Avp::FlagRule::must);
458 bool Pmustnot = (stackAvp->getPbit() == stack::Avp::FlagRule::mustnot);
461 if((Vnone && Mnone && Pnone && vendorBit()) || (Vmust && !vendorBit()) || (Vmustnot && vendorBit())) {
462 anna::Logger::error("Vendor Bit (V) incoherence found", ANNA_FILE_LOCATION);
466 // Exit on permissive mode:
467 if(getEngine()->ignoreFlagsOnValidation()) return true; // Ignore checking for AVP 'M' & 'P' bits
470 if((Mmust && !mandatoryBit()) || (Mmustnot && mandatoryBit())) {
471 anna::Logger::error("Mandatory Bit (M) incoherence found", ANNA_FILE_LOCATION);
476 if((Pmust && !encryptionBit()) || (Pmustnot && encryptionBit())) {
477 anna::Logger::error("Encryption Bit (P) incoherence found", ANNA_FILE_LOCATION);
482 if((a_flags & 0x1f) != 0x00) {
483 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);
491 //------------------------------------------------------------------------------
492 //----------------------------------------------------------------- Avp::setId()
493 //------------------------------------------------------------------------------
494 void Avp::setId(AvpId id) throw(anna::RuntimeException) {
495 // Generic AVP assignment has no sense
496 if(id == helpers::AVPID__AVP) return;
498 // Clear class content:
502 // Dictionary stack avp and format:
503 const stack::Avp *stackAvp = getStackAvp(); // based on dictionary and a_id
504 const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
506 // Dictionary flags for known types:
508 if(stackAvp->getVbit() == stack::Avp::FlagRule::must) a_flags |= VBitMask;
510 if(stackAvp->getMbit() == stack::Avp::FlagRule::must) a_flags |= MBitMask;
512 if(stackAvp->getPbit() == stack::Avp::FlagRule::must) a_flags |= PBitMask;
514 if(a_id.second != 0) a_flags |= VBitMask; else a_flags &= (~VBitMask);
517 if(!stackFormat) { // Unknown Avp
519 std::string msg = "Unknown format for AVP identifier ";
520 msg += anna::diameter::functions::avpIdAsPairString(id);
521 msg += ". Raw data without specific format will be managed";
522 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
524 a_Unknown = new Unknown();
528 // Avp class formats (Avp child classes should implement this source code block for application-specific formats):
529 if(stackFormat->isOctetString()) a_OctetString = new OctetString();
530 else if(stackFormat->isInteger32()) a_Integer32 = new Integer32();
531 else if(stackFormat->isInteger64()) a_Integer64 = new Integer64();
532 else if(stackFormat->isUnsigned32()) a_Unsigned32 = new Unsigned32();
533 else if(stackFormat->isUnsigned64()) a_Unsigned64 = new Unsigned64();
534 else if(stackFormat->isFloat32()) a_Float32 = new Float32();
535 else if(stackFormat->isFloat64()) a_Float64 = new Float64();
536 //else if (stackFormat->isGrouped())
537 else if(stackFormat->isAddress()) a_Address = new Address();
538 else if(stackFormat->isTime()) a_Time = new Time();
539 else if(stackFormat->isUTF8String()) a_UTF8String = new UTF8String();
540 else if(stackFormat->isDiameterIdentity()) a_DiameterIdentity = new DiameterIdentity();
541 else if(stackFormat->isDiameterURI()) a_DiameterURI = new DiameterURI();
542 else if(stackFormat->isEnumerated()) a_Enumerated = new Enumerated();
543 else if(stackFormat->isIPFilterRule()) a_IPFilterRule = new IPFilterRule();
544 else if(stackFormat->isQoSFilterRule()) a_QoSFilterRule = new QoSFilterRule();
546 /////////////////////
547 // Format specific //
548 /////////////////////
549 allocationByFormat(stackFormat);
553 //------------------------------------------------------------------------------
554 //----------------------------------------------------------------- Avp::setId()
555 //------------------------------------------------------------------------------
556 void Avp::setId(const char *name) throw(anna::RuntimeException) {
557 setId(getEngine()->avpIdForName(name));
561 //------------------------------------------------------------------------------
562 //---------------------------------------------------------------- Avp::addAvp()
563 //------------------------------------------------------------------------------
564 Avp * Avp::addAvp(const char *name) throw(anna::RuntimeException) {
565 return addAvp(getEngine()->avpIdForName(name));
569 //------------------------------------------------------------------------------
570 //------------------------------------------------------------- Avp::removeAvp()
571 //------------------------------------------------------------------------------
572 bool Avp::removeAvp(const char *name, int ocurrence) throw(anna::RuntimeException) {
573 return removeAvp(getEngine()->avpIdForName(name), ocurrence);
577 //------------------------------------------------------------------------------
578 //--------------------------------------------------------------- Avp::_getAvp()
579 //------------------------------------------------------------------------------
580 const Avp *Avp::_getAvp(const char *name, int ocurrence, anna::Exception::Mode::_v emode) const throw(anna::RuntimeException) {
581 return getAvp(getEngine()->avpIdForName(name), ocurrence, emode);
585 //------------------------------------------------------------------------------
586 //-------------------------------------------------------------- Avp::countAvp()
587 //------------------------------------------------------------------------------
588 int Avp::countAvp(const char *name) const throw(anna::RuntimeException) {
589 return countAvp(getEngine()->avpIdForName(name));
592 //------------------------------------------------------------------------------
593 //------------------------------------------------------------- Avp::getLength()
594 //------------------------------------------------------------------------------
595 U24 Avp::getLength() const throw() {
598 const stack::Avp *stackAvp = getStackAvp();
599 const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
601 result = vendorBit() ? HeaderLengthVactive : HeaderLengthVinactive;
604 result += a_Unknown->getSize();
608 if(stackFormat->isOctetString()) result += a_OctetString->getSize();
609 else if(stackFormat->isInteger32()) result += a_Integer32->getSize();
610 else if(stackFormat->isInteger64()) result += a_Integer64->getSize();
611 else if(stackFormat->isUnsigned32()) result += a_Unsigned32->getSize();
612 else if(stackFormat->isUnsigned64()) result += a_Unsigned64->getSize();
613 else if(stackFormat->isFloat32()) result += a_Float32->getSize();
614 else if(stackFormat->isFloat64()) result += a_Float64->getSize();
615 else if(stackFormat->isGrouped()) for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) result += 4 * REQUIRED_WORDS(avp(it)->getLength());
616 else if(stackFormat->isAddress()) result += a_Address->getSize();
617 else if(stackFormat->isTime()) result += a_Time->getSize();
618 else if(stackFormat->isUTF8String()) result += a_UTF8String->getSize();
619 else if(stackFormat->isDiameterIdentity()) result += a_DiameterIdentity->getSize();
620 else if(stackFormat->isDiameterURI()) result += a_DiameterURI->getSize();
621 else if(stackFormat->isEnumerated()) result += a_Enumerated->getSize();
622 else if(stackFormat->isIPFilterRule()) result += a_IPFilterRule->getSize();
623 else if(stackFormat->isQoSFilterRule()) result += a_QoSFilterRule->getSize();
625 /////////////////////
626 // Format specific //
627 /////////////////////
628 result += getLengthByFormat(stackFormat);
633 //------------------------------------------------------------------------------
634 //-------------------------------------------- Avp::unknownAvpWithMandatoryBit()
635 //------------------------------------------------------------------------------
636 void Avp::unknownAvpWithMandatoryBit() const throw(anna::RuntimeException) {
637 OamModule &oamModule = OamModule::instantiate();
638 const char *c_aid = STRING_WITH_QUOTATION_MARKS__C_STR(anna::diameter::functions::avpIdAsPairString(a_id));
639 oamModule.activateAlarm(OamModule::Alarm::AvpDecode__UnknownAvp__s__WithMandatoryBit, c_aid);
640 oamModule.count(OamModule::Counter::AvpDecode__UnknownAvpWithMandatoryBit);
642 std::string msg = anna::functions::asString("Detected unknown Avp %s with mandatory bit activated", c_aid);
643 anna::Logger::warning(msg, ANNA_FILE_LOCATION);
647 //------------------------------------------------------------------------------
648 //-------------------------------------------------------- Avp::decodeDataPart()
649 //------------------------------------------------------------------------------
650 void Avp::decodeDataPart(const char * buffer, int size, const parent_t & parent, Message *answer) throw(anna::RuntimeException) {
652 OamModule &oamModule = OamModule::instantiate();
653 // Dictionary stack avp and format:
654 const stack::Avp *stackAvp = getStackAvp();
655 const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
658 a_Unknown->decode(buffer, size);
662 if(stackFormat->isOctetString()) a_OctetString->decode(buffer, size);
663 else if(stackFormat->isInteger32()) a_Integer32->decode(buffer, size);
664 else if(stackFormat->isInteger64()) a_Integer64->decode(buffer, size);
665 else if(stackFormat->isUnsigned32()) a_Unsigned32->decode(buffer, size);
666 else if(stackFormat->isUnsigned64()) a_Unsigned64->decode(buffer, size);
667 else if(stackFormat->isFloat32()) a_Float32->decode(buffer, size);
668 else if(stackFormat->isFloat64()) a_Float64->decode(buffer, size);
669 else if(stackFormat->isGrouped()) {
671 LOGDEBUG(anna::Logger::debug("Grouped Avp has empty data part", ANNA_FILE_LOCATION));
675 if((size % 4) != 0) {
676 oamModule.activateAlarm(OamModule::Alarm::AvpDecode__IncorrectLength);
677 oamModule.count(OamModule::Counter::AvpDecode__IncorrectLength);
680 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_AVP_LENGTH);
681 answer->setFailedAvp(parent, a_id);
684 throw anna::RuntimeException("Avp format error, the avp length is incorrect (must be multiple of 4 on grouped type)", ANNA_FILE_LOCATION);
691 parent_t me = parent;
694 while(avpPos < size) {
696 avp = getEngine()->allocateAvp();
697 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) */);
698 avp -> decode(db, me, answer);
699 } catch(anna::RuntimeException &ex) {
700 getEngine()->releaseAvp(avp);
705 avpPos += 4 * REQUIRED_WORDS(avp->getLength());
707 } else if(stackFormat->isAddress()) a_Address->decode(buffer, size);
708 else if(stackFormat->isTime()) a_Time->decode(buffer, size);
709 else if(stackFormat->isUTF8String()) a_UTF8String->decode(buffer, size);
710 else if(stackFormat->isDiameterIdentity()) a_DiameterIdentity->decode(buffer, size);
711 else if(stackFormat->isDiameterURI()) a_DiameterURI->decode(buffer, size);
712 else if(stackFormat->isEnumerated()) a_Enumerated->decode(buffer, size);
713 else if(stackFormat->isIPFilterRule()) a_IPFilterRule->decode(buffer, size);
714 else if(stackFormat->isQoSFilterRule()) a_QoSFilterRule->decode(buffer, size);
716 /////////////////////
717 // Format specific //
718 /////////////////////
719 decodeDataPartByFormat(buffer, size, stackFormat);
722 //------------------------------------------------------------------------------
723 //---------------------------------------------------------------- Avp::decode()
724 //------------------------------------------------------------------------------
725 void Avp::decode(const anna::DataBlock &db, const parent_t & parent, Message *answer) throw(anna::RuntimeException) {
727 OamModule &oamModule = OamModule::instantiate();
729 if(db.getSize() < HeaderLengthVinactive) {
730 oamModule.activateAlarm(OamModule::Alarm::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength);
731 oamModule.count(OamModule::Counter::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength);
732 // DIAMETER_INVALID_AVP_LENGTH; // no podr� construir un avp fiable, as� que no registro el result-code
733 throw anna::RuntimeException("Not enough bytes to cover avp header length", ANNA_FILE_LOCATION);
736 const char * buffer = db.getData();
739 // 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
740 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
742 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
743 // | AVP Flags | AVP Length |
744 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
745 // | Vendor-ID (opt) |
746 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
749 // Code flags and vendor-id
750 U32 code = DECODE4BYTES_INDX_VALUETYPE(buffer, 0, U32);
752 a_flags = (S8)buffer[4];
754 U32 vendorID = helpers::VENDORID__base;
757 if(db.getSize() < HeaderLengthVactive) {
758 oamModule.activateAlarm(OamModule::Alarm::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength);
759 oamModule.count(OamModule::Counter::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength);
760 // DIAMETER_INVALID_AVP_LENGTH; // no podr� construir un avp fiable, as� que no registro el result-code
761 throw anna::RuntimeException(anna::functions::asString("Not enough bytes to cover avp header length (avp code = %u)", code), ANNA_FILE_LOCATION);
764 vendorID = DECODE4BYTES_INDX_VALUETYPE(buffer, 8, U32);
766 if(vendorID == helpers::VENDORID__base) {
767 // A vendor ID value of zero (0) corresponds to the IETF adopted AVP
768 // values, as managed by the IANA. Since the absence of the vendor
769 // ID field implies that the AVP in question is not vendor specific,
771 // implementations MUST NOT use the zero (0) vendor ID.
772 oamModule.activateAlarm(OamModule::Alarm::AvpDecode__IncoherenceBetweenActivatedVBitAndZeroedVendorIDValueReceived);
773 oamModule.count(OamModule::Counter::AvpDecode__IncoherenceBetweenActivatedVBitAndZeroedVendorIDValueReceived);
774 throw anna::RuntimeException(anna::functions::asString("Incoherence between activated V bit and zeroed vendor-id value received (avp code = %u)", code), ANNA_FILE_LOCATION);
779 setId(AvpId(code, vendorID));
780 // Flags could have been updated regarding dictionary, but during decoding we must respect buffer received:
781 a_flags = (S8)buffer[4];
783 // Here i know id and flags:
784 // 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
785 // a Diameter client, server, proxy, or translation agent and either the AVP or its value is unrecognized, the message MUST be rejected.
786 // Diameter Relay and redirect agents MUST NOT reject messages with unrecognized AVPs.
787 if(!getStackAvp() && mandatoryBit()) {
789 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_AVP_UNSUPPORTED);
790 answer->setFailedAvp(parent, a_id);
793 unknownAvpWithMandatoryBit();
797 U24 length = DECODE3BYTES_INDX_VALUETYPE(buffer, 5, U24);
798 // Data start position:
799 int startDataPos = vendorBit() ? HeaderLengthVactive : HeaderLengthVinactive;
801 int dataBytes = length - startDataPos;
804 oamModule.activateAlarm(OamModule::Alarm::AvpDecode__IncorrectLength);
805 oamModule.count(OamModule::Counter::AvpDecode__IncorrectLength);
808 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_AVP_LENGTH);
809 answer->setFailedAvp(parent, a_id);
812 throw anna::RuntimeException(anna::functions::asString("Avp format error, the avp length is incorrect (avp code = %u)", code), ANNA_FILE_LOCATION);
816 decodeDataPart(buffer + startDataPos, dataBytes, parent, answer);
817 } catch(anna::RuntimeException &ex) {
818 oamModule.activateAlarm(OamModule::Alarm::AvpDecode__DataPartInconsistence);
819 oamModule.count(OamModule::Counter::AvpDecode__DataPartInconsistence);
822 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_AVP_VALUE);
823 answer->setFailedAvp(parent, a_id);
826 throw anna::RuntimeException(anna::functions::asString("Internal Avp decoding error (avp code = %u): %s", code, ex.getText().c_str()), ANNA_FILE_LOCATION);
831 //------------------------------------------------------------------------------
832 //----------------------------------------------------------- Avp::getStackAvp()
833 //------------------------------------------------------------------------------
834 const anna::diameter::stack::Avp *Avp::getStackAvp(AvpId id, Engine *engine) throw() {
835 const stack::Dictionary * dictionary = engine->getDictionary();
836 return (dictionary ? (dictionary->getAvp(id)) : NULL);
840 //------------------------------------------------------------------------------
841 //------------------------------------------------------------------- Avp::fix()
842 //------------------------------------------------------------------------------
843 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() {
845 if(avps.size() == 0) return; // empty content, nothing to fix
847 if(ruleBegin == ruleEnd) return; // no reference. Cannot fix
849 // Copy reference container and clear internal map in order to build a fixed version:
850 avp_container unfixedAvps;
852 for(const_avp_iterator it = avps.begin(); it != avps.end(); it++)
853 unfixedAvps[(*it).first] = (*it).second;
856 // Cache system reset (fix probably will invalidate cached findings):
858 insertionPositionForChilds = 0;
862 for(anna::diameter::stack::const_avprule_iterator rule_it = ruleBegin; rule_it != ruleEnd; rule_it++) {
863 while((avp_it = Avp::avp_find(unfixedAvps, (*rule_it).second.getId(), 1)) != unfixedAvps.end()) {
864 avp = (*avp_it).second;
865 addChild(avps, insertionPositionForChilds, avp);
866 unfixedAvps.erase(avp_it); // processed
870 // Add remaining avps:
871 for(avp_it = unfixedAvps.begin(); avp_it != unfixedAvps.end(); avp_it++) {
872 avp = (*avp_it).second;
874 if(avp) addChild(avps, insertionPositionForChilds, avp);
878 for(avp_iterator it = avps.begin(); it != avps.end(); it++) {
881 if(avp->hasChildren()) avp->fix();
886 //------------------------------------------------------------------------------
887 //------------------------------------------------------------------- Avp::fix()
888 //------------------------------------------------------------------------------
889 void Avp::fix() throw() {
890 // Dictionary stack avp:
891 const stack::Avp *stackAvp = getStackAvp();
892 const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
895 //LOGDEBUG(anna::Logger::debug("No dictionary avp reference found. Cannot fix.", ANNA_FILE_LOCATION));
899 if(!stackFormat || !stackFormat->isGrouped()) {
900 //LOGDEBUG(anna::Logger::debug("Avp is not grouped. Nothing to fix.", ANNA_FILE_LOCATION));
904 fix(a_avps, (find_container&)a_finds, a_insertionPositionForChilds, stackAvp->avprule_begin(), stackAvp->avprule_end());
908 //------------------------------------------------------------------------------
909 //------------------------------------------------------------ Avp::validLevel()
910 //------------------------------------------------------------------------------
911 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) {
914 OamModule &oamModule = OamModule::instantiate();
920 const_avp_iterator avp_it = avps.begin();
921 anna::diameter::stack::const_avprule_iterator rule_it;
924 for(rule_it = ruleBegin; rule_it != ruleEnd; rule_it++) {
927 if((*rule_it).second.isFixed()) {
928 if(avps.size() == 0) break; // cardinality checking will show this anomaly
930 if(avp_it != avps.end()) {
931 id = Avp::avp(avp_it)->getId();
933 if(id != (*rule_it).second.getId()) {
935 // Missing fixed rule: %s
936 } else if(Avp::avp_find(avps, id, 2) != avps.end()) {
938 // More than one fixed ocurrency for rule %s (*)
942 // (*) for (int k = 0; k < (*rule_it).second.getQualMax(); k++) avp_it++
948 // OAM & Depth management
949 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()));
950 oamModule.count(OamModule::Counter::LevelValidation__MissingFixedRule);
953 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_MISSING_AVP);
954 answer->setFailedAvp(parent, (*rule_it).second.getId());
957 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())));
959 } else break; // finish fixed
963 // Cardinality // Mandatory control is implicit here
965 anna::diameter::stack::const_avprule_iterator generic_rule_it = ruleEnd;
966 int min, max, amount;
968 for(rule_it = ruleBegin; rule_it != ruleEnd; rule_it++) {
969 if((*rule_it).second.isAny()) { generic_rule_it = rule_it; continue; } // generic Avp will be managed after
971 id = (*rule_it).second.getId();
972 min = (*rule_it).second.getQualMin();
973 max = (*rule_it).second.getQualMax(); // -1 means infinite
974 amount = Avp::countAvp(avps, id);
976 if((amount < min) || ((max != -1) && (amount > max))) {
977 // Failed rule %s for cardinality (found %d items)
979 // OAM & Depth management
980 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()));
981 oamModule.count(OamModule::Counter::LevelValidation__FailedRuleForCardinality);
984 oamModule.count(OamModule::Counter::LevelValidation__FailedRuleForCardinalityLessThanNeeded);
987 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_MISSING_AVP);
988 answer->setFailedAvp(parent, id);
991 oamModule.count(OamModule::Counter::LevelValidation__FailedRuleForCardinalityMoreThanNeeded);
994 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_AVP_OCCURS_TOO_MANY_TIMES);
995 answer->setFailedAvp(parent, id);
999 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())));
1003 bool haveGeneric = (generic_rule_it != ruleEnd);
1008 std::map < AvpId, int /* dummy */ > disregarded; // 'Disregardeds' are Avps not in rules list
1009 std::map < AvpId, int /* dummy */ >::const_iterator disregarded_it;
1011 for(avp_it = avps.begin(); avp_it != avps.end(); avp_it++) {
1012 id = Avp::avp(avp_it)->getId();
1013 // Find rule for the child:
1014 foundInRules = false;
1016 for(rule_it = ruleBegin; rule_it != ruleEnd; rule_it++) {
1017 if((*rule_it).second.getId() == id) {
1018 foundInRules = true;
1024 disregarded[id] = 0;
1028 // Generic AVP cardinality checkings
1029 int disregardeds = disregarded.size();
1032 min = (*generic_rule_it).second.getQualMin();
1033 max = (*generic_rule_it).second.getQualMax(); // -1 means infinite
1034 amount = disregardeds;
1036 if((amount < min) || ((max != -1) && (amount > max))) {
1037 // Failed Generic AVP rule %s for cardinality (found %d disregarded items inside %s)
1039 // OAM & Depth management
1040 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()));
1041 oamModule.count(OamModule::Counter::LevelValidation__FailedGenericAvpRuleForCardinalityFoundDisregardedItem);
1044 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_AVP_NOT_ALLOWED);
1045 answer->setFailedAvp(parent, id); // NO SENSE... what to put ?
1048 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())));
1050 } else if(disregardeds) { // When Generic AVP missing, no disregarded Avps are allowed
1051 // Found %d disregarded items inside %s and Generic AVP was not specified
1053 // Build disregarded list as string (unknown as avp id pair):
1054 std::string s_disregardeds = "";
1055 const stack::Avp *stackAvp;
1057 for(disregarded_it = disregarded.begin(); disregarded_it != disregarded.end(); disregarded_it++) {
1058 id = (*disregarded_it).first;
1059 stackAvp = getStackAvp(id, engine);
1060 s_disregardeds += (stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id)));
1061 s_disregardeds += ", ";
1063 // We wouldn't know where are these disregarded, but...
1065 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_AVP_NOT_ALLOWED);
1066 answer->setFailedAvp(parent, id);
1070 s_disregardeds.erase(s_disregardeds.size() - 2, 2); // remove last ', '
1071 // OAM & Depth management
1072 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));
1073 oamModule.count(OamModule::Counter::LevelValidation__FoundDisregardedItemsAndGenericAVPWasNotSpecified);
1074 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)));
1081 //------------------------------------------------------------------------------
1082 //----------------------------------------------------------------- Avp::valid()
1083 //------------------------------------------------------------------------------
1084 bool Avp::valid(const parent_t & parent, Message *answer) const throw(anna::RuntimeException) {
1086 OamModule &oamModule = OamModule::instantiate();
1087 // Dictionary stack avp:
1088 const stack::Avp *stackAvp = getStackAvp();
1089 const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
1092 // No dictionary avp reference found. Cannot validate
1093 return true; // perhaps a unknown Avp
1097 parent_t me = parent;
1098 me.addAvp(a_id, stackAvp->getName().c_str());
1101 // No format avp reference found. Cannot validate
1102 return true; // perhaps a unknown Avp
1105 //////////////////////////////
1106 // Flags coherence checking //
1107 //////////////////////////////
1108 bool result = flagsOK();
1111 // OAM & Depth management
1112 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()));
1113 oamModule.count(OamModule::Counter::AvpValidation__AvpFlagsDoesNotFulfillTheDefinedFlagRules);
1116 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_AVP_BITS);
1117 answer->setFailedAvp(parent, a_id, stackAvp->getName().c_str()); // RFC 6733 says nothing about Failed-AVP in this case...
1120 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())));
1123 //////////////////////
1124 // Enumerated range //
1125 //////////////////////
1126 if(stackFormat->isEnumerated()) {
1127 if(!stackAvp->allowEnum(a_Enumerated->getValue())) {
1129 // OAM & Depth management
1130 oamModule.activateAlarm(OamModule::Alarm::AvpValidation__EnumeratedAvp__s__WithValue__d__DoesNotComplyRestriction__s__, STRING_WITH_QUOTATION_MARKS__C_STR(me.asString()), a_Enumerated->getValue(), stackAvp->getEnums());
1131 oamModule.count(OamModule::Counter::AvpValidation__EnumeratedAvpWithValueDoesNotComplyRestriction);
1134 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_AVP_VALUE);
1135 answer->setFailedAvp(parent, a_id, stackAvp->getName().c_str());
1138 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()));
1142 ////////////////////
1143 // Level checking //
1144 ////////////////////
1145 result = Avp::validLevel(a_avps, stackAvp->avprule_begin(), stackAvp->avprule_end(), getEngine(), me, answer) && result;
1147 ////////////////////////
1148 // Childrens checking //
1149 ////////////////////////
1150 if(a_id == helpers::base::AVPID__Failed_AVP) return result; // DON'T VALIDATE CONTENT FOR Failed-AVP, because it won't be valid...
1152 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++)
1153 result = ((*it).second->valid(me, answer)) && result;
1159 //------------------------------------------------------------------------------
1160 //------------------------------------------------------------------ Avp::code()
1161 //------------------------------------------------------------------------------
1162 void Avp::code(char* buffer, int &size) const throw(anna::RuntimeException) {
1164 buffer[0] = (S8)(a_id.first >> 24);
1165 buffer[1] = (S8)(a_id.first >> 16);
1166 buffer[2] = (S8)(a_id.first >> 8);
1167 buffer[3] = (S8) a_id.first;
1170 buffer[4] = (S8) a_flags;
1171 buffer[5] = (S8)(size >> 16);
1172 buffer[6] = (S8)(size >> 8);
1173 buffer[7] = (S8) size;
1177 buffer[8] = (S8)(a_id.second >> 24);
1178 buffer[9] = (S8)(a_id.second >> 16);
1179 buffer[10] = (S8)(a_id.second >> 8);
1180 buffer[11] = (S8) a_id.second;
1183 // Data start position:
1184 int startDataPos = vendorBit() ? HeaderLengthVactive : HeaderLengthVinactive;
1186 S8 * dataPart = buffer + startDataPos;
1187 int dataBytes; // not used but could be useful for checking (size - startDataPos)
1189 if(startDataPos == size) {
1190 LOGDEBUG(anna::Logger::debug("There is no data part to encode", ANNA_FILE_LOCATION));
1195 const stack::Avp *stackAvp = getStackAvp();
1196 const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
1199 a_Unknown->code(dataPart, dataBytes);
1203 if(stackFormat->isOctetString()) a_OctetString->code(dataPart, dataBytes);
1204 else if(stackFormat->isInteger32()) a_Integer32->code(dataPart, dataBytes);
1205 else if(stackFormat->isInteger64()) a_Integer64->code(dataPart, dataBytes);
1206 else if(stackFormat->isUnsigned32()) a_Unsigned32->code(dataPart, dataBytes);
1207 else if(stackFormat->isUnsigned64()) a_Unsigned64->code(dataPart, dataBytes);
1208 else if(stackFormat->isFloat32()) a_Float32->code(dataPart, dataBytes);
1209 else if(stackFormat->isFloat64()) a_Float64->code(dataPart, dataBytes);
1210 else if(stackFormat->isGrouped()) {
1211 // // Each avp encoding will remain padding octets depending on format. In order to
1212 // // code grouped content (each avp will be multiple of 4) we clean the entire buffer
1213 // // to ensure padding (easier than custom-made for each format):
1214 // memset(dataPart, 0, size - startDataPos);
1215 char *dataPartGrouped = dataPart;
1216 int dataBytesGrouped;
1218 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) {
1219 avp(it)->code(dataPartGrouped, dataBytesGrouped);
1220 dataPartGrouped = dataPartGrouped + 4 * REQUIRED_WORDS(dataBytesGrouped);
1222 } else if(stackFormat->isAddress()) a_Address->code(dataPart, dataBytes);
1223 else if(stackFormat->isTime()) a_Time->code(dataPart, dataBytes);
1224 else if(stackFormat->isUTF8String()) a_UTF8String->code(dataPart, dataBytes);
1225 else if(stackFormat->isDiameterIdentity()) a_DiameterIdentity->code(dataPart, dataBytes);
1226 else if(stackFormat->isDiameterURI()) a_DiameterURI->code(dataPart, dataBytes);
1227 else if(stackFormat->isEnumerated()) a_Enumerated->code(dataPart, dataBytes);
1228 else if(stackFormat->isIPFilterRule()) a_IPFilterRule->code(dataPart, dataBytes);
1229 else if(stackFormat->isQoSFilterRule()) a_QoSFilterRule->code(dataPart, dataBytes);
1231 /////////////////////
1232 // Format specific //
1233 /////////////////////
1234 codeByFormat(dataPart, stackFormat);
1238 //------------------------------------------------------------------------------
1239 //------------------------------------------------------------ Avp::getXMLdata()
1240 //------------------------------------------------------------------------------
1241 std::string Avp::getXMLdata(bool & isHex, const stack::Format *stackFormat) const throw() {
1242 std::string result = "";
1246 // if (!stackFormat) {
1248 // return a_Unknown->asHexString();
1250 // } catch (anna::RuntimeException &ex) {
1256 return a_Unknown->asHexString(); // el asHexString del OctetString no puede lanzar una excepcion en realidad
1259 // Special case for Address: could launch exception if not printable
1261 if(stackFormat->isAddress()) return a_Address->asPrintableString();
1262 } catch(anna::RuntimeException&) {
1265 return a_Address->asHexString();
1269 if(stackFormat->isOctetString()) {
1271 return a_OctetString->asHexString();
1275 if(stackFormat->isInteger32()) return a_Integer32->asPrintableString();
1277 if(stackFormat->isInteger64()) return a_Integer64->asPrintableString();
1279 if(stackFormat->isUnsigned32()) return a_Unsigned32->asPrintableString();
1281 if(stackFormat->isUnsigned64()) return a_Unsigned64->asPrintableString();
1283 if(stackFormat->isFloat32()) return a_Float32->asPrintableString();
1285 if(stackFormat->isFloat64()) return a_Float64->asPrintableString();
1287 //if (stackFormat->isAddress()) return a_Address->asPrintableString();
1289 if(stackFormat->isTime()) return a_Time->asPrintableString();
1291 if(stackFormat->isUTF8String()) return a_UTF8String->asPrintableString();
1293 if(stackFormat->isDiameterIdentity()) return a_DiameterIdentity->asPrintableString();
1295 if(stackFormat->isDiameterURI()) return a_DiameterURI->asPrintableString();
1297 if(stackFormat->isEnumerated()) return a_Enumerated->asPrintableString();
1299 if(stackFormat->isIPFilterRule()) return a_IPFilterRule->asPrintableString();
1301 if(stackFormat->isQoSFilterRule()) return a_QoSFilterRule->asPrintableString();
1303 /////////////////////
1304 // Format specific //
1305 /////////////////////
1306 return getXMLdataByFormat(isHex, stackFormat);
1307 } catch(anna::RuntimeException &ex) {
1315 //------------------------------------------------------------------------------
1316 //---------------------------------------------------------------- Avp::decode()
1317 //------------------------------------------------------------------------------
1318 void Avp::decode(const anna::DataBlock &db) throw(anna::RuntimeException) {
1320 parent.setMessage(CommandId(0, false), "No-Parent");
1321 decode(db, parent, NULL);
1325 //------------------------------------------------------------------------------
1326 //--------------------------------------------------------------- Avp::fromXML()
1327 //------------------------------------------------------------------------------
1328 void Avp::fromXML(const anna::xml::Node* avpNode) throw(anna::RuntimeException) {
1329 // <!ATTLIST avp id CDATA #IMPLIED code CDATA #IMPLIED vendor-code CDATA #IMPLIED flags CDATA #IMPLIED data CDATA #IMPLIED hex-data CDATA #IMPLIED>
1330 const anna::xml::Attribute *name, *code, *vendorCode, *flags, *data, *hexData;
1331 name = avpNode->getAttribute("name", false /* no exception */);
1332 code = avpNode->getAttribute("code", false /* no exception */);
1333 vendorCode = avpNode->getAttribute("vendor-code", false /* no exception */);
1334 flags = avpNode->getAttribute("flags", false /* no exception */);
1335 data = avpNode->getAttribute("data", false /* no exception */);
1336 hexData = avpNode->getAttribute("hex-data", false /* no exception */);
1338 const stack::Dictionary * dictionary = getEngine()->getDictionary();
1339 const stack::Avp *stackAvp = NULL;
1340 const stack::Format *stackFormat = NULL;
1345 std::string msg = "Error processing avp <name '"; msg += name->getValue();
1346 msg += "'>: no dictionary available. Load one or use <'code' + 'flags' + 'vendorCode'> instead of <'name'>";
1347 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1350 stackAvp = dictionary->getAvp(name->getValue());
1353 std::string msg = "Error processing avp <name '"; msg += name->getValue();
1354 msg += "'>: no avp found for this identifier at available dictionary";
1355 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1358 stackFormat = stackAvp->getFormat();
1361 // Check attributes exclusiveness
1362 if(name) { // compact mode
1363 if(code || flags || vendorCode) {
1364 std::string msg = "Error processing avp <name '"; msg += name->getValue();
1365 msg += "'>: avp attributes <'code' + 'flags' + 'vendorCode'> are not allowed if <'name'> is provided";
1366 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1369 setId(stackAvp->getId());
1371 if(!code || !flags || !vendorCode) {
1372 std::string s_code = code ? code->getValue() : "?";
1373 std::string s_flags = flags ? flags->getValue() : "?";
1374 std::string s_vendorCode = vendorCode ? vendorCode->getValue() : "?";
1375 std::string msg = "Error processing avp <code '"; msg += s_code;
1376 msg += "' + flags '"; msg += s_flags;
1377 msg += "' + vendorCode '"; msg += s_vendorCode;
1378 msg += "'>: all must be provided if <'name'> don't";
1379 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1383 int i_aux = code->getIntegerValue();
1386 std::string msg = "Error processing avp <code '"; msg += code->getValue();
1387 msg += "': negative values are not allowed";
1388 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1393 i_aux = flags->getIntegerValue();
1395 if(i_aux < 0 || i_aux > 256) {
1396 std::string msg = "Error processing avp <flags '"; msg += flags->getValue();
1397 msg += "': out of range [0,256]";
1398 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1402 int flagsBCK = a_flags;
1403 // VendorCode checks
1404 i_aux = vendorCode->getIntegerValue();
1407 std::string msg = "Error processing avp <vendorCode '"; msg += vendorCode->getValue();
1408 msg += "': negative values are not allowed";
1409 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1412 U32 u_vendorCode = i_aux;
1413 bool vendorSpecific1 = (u_vendorCode != 0);
1414 bool vendorSpecific2 = (((a_flags) & VBitMask) != 0x00);
1416 if(vendorSpecific1 != vendorSpecific2) {
1417 std::string msg = "Error processing avp <vendorCode '"; msg += vendorCode->getValue();
1418 msg += "' and avp <flags '"; msg += flags->getValue();
1419 msg += "': incompatible vendor-specific properties";
1420 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1423 // Final assignments
1424 setId(AvpId(u_code, u_vendorCode));
1425 // Flags could have been updated regarding dictionary, but during parsing we must respect xml file:
1427 stackAvp = getStackAvp();
1428 stackFormat = stackAvp ? stackAvp->getFormat() : NULL;
1432 // Check if grouped not confirmed
1433 anna::xml::Node::const_child_iterator it;
1434 anna::xml::Node::const_child_iterator minii = avpNode->child_begin();
1435 anna::xml::Node::const_child_iterator maxii = avpNode->child_end();
1436 const bool hasChildren(minii != maxii);
1439 // We need to confirm is grouped
1441 throw anna::RuntimeException("An xml avp node with children nodes could not confirmed as Grouped", ANNA_FILE_LOCATION);
1443 if(!stackFormat->isGrouped())
1444 throw anna::RuntimeException("An xml avp node with children nodes is not grouped type", ANNA_FILE_LOCATION);
1447 throw anna::RuntimeException("An xml avp node with children nodes has 'data' or 'hex-data' field", ANNA_FILE_LOCATION);
1451 std::string s_avp = name ? (name->getValue()) : (anna::diameter::functions::avpIdAsPairString(a_id));
1453 if(data && hexData) {
1454 std::string msg = "Not allowed both 'data' and 'hex-data' definitions. Avp ";
1456 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1460 bool unknown = !stackFormat;
1461 bool octetString = stackFormat && (stackFormat->isOctetString());
1463 if(data && (unknown || octetString)) {
1464 std::string msg = "Not recommended 'data' field at ";
1465 msg += unknown ? "Unknown" : "OctetString";
1466 msg += "-format Avp "; msg += s_avp;
1467 msg += ". Use better 'hex-data' or omit content fields if empty";
1468 anna::Logger::warning(msg, ANNA_FILE_LOCATION);
1473 if(data) a_Unknown->fromPrintableString(data->getValue().c_str());
1474 else if(hexData) a_Unknown->fromHexString(hexData->getValue());
1479 if(stackFormat->isOctetString()) {
1480 if(data) a_OctetString->fromPrintableString(data->getValue().c_str());
1481 else if(hexData) a_OctetString->fromHexString(hexData->getValue());
1482 } else if(stackFormat->isInteger32()) {
1483 if(data) a_Integer32->fromPrintableString(data->getValue().c_str());
1484 else if(hexData) a_Integer32->fromHexString(hexData->getValue());
1485 } else if(stackFormat->isInteger64()) {
1486 if(data) a_Integer64->fromPrintableString(data->getValue().c_str());
1487 else if(hexData) a_Integer64->fromHexString(hexData->getValue());
1488 } else if(stackFormat->isUnsigned32()) {
1489 if(data) a_Unsigned32->fromPrintableString(data->getValue().c_str());
1490 else if(hexData) a_Unsigned32->fromHexString(hexData->getValue());
1491 } else if(stackFormat->isUnsigned64()) {
1492 if(data) a_Unsigned64->fromPrintableString(data->getValue().c_str());
1493 else if(hexData) a_Unsigned64->fromHexString(hexData->getValue());
1494 } else if(stackFormat->isFloat32()) {
1495 if(data) a_Float32->fromPrintableString(data->getValue().c_str());
1496 else if(hexData) a_Float32->fromHexString(hexData->getValue());
1497 } else if(stackFormat->isFloat64()) {
1498 if(data) a_Float64->fromPrintableString(data->getValue().c_str());
1499 else if(hexData) a_Float64->fromHexString(hexData->getValue());
1500 } else if(stackFormat->isGrouped()) {
1504 for(it = minii; it != maxii; it++) {
1505 std::string nodeName = (*it)->getName();
1507 if(nodeName != "avp") {
1508 std::string msg = "Unsupported grouped avp child node name '"; msg += nodeName;
1509 msg += "': use 'avp'";
1510 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1514 avp = getEngine()->allocateAvp();
1515 avp -> fromXML(*it);
1516 } catch(anna::RuntimeException &ex) {
1517 getEngine()->releaseAvp(avp);
1523 } else if(stackFormat->isAddress()) {
1524 if(data) a_Address->fromPrintableString(data->getValue().c_str());
1525 else if(hexData) a_Address->fromHexString(hexData->getValue());
1526 } else if(stackFormat->isTime()) {
1527 if(data) a_Time->fromPrintableString(data->getValue().c_str());
1528 else if(hexData) a_Time->fromHexString(hexData->getValue());
1529 } else if(stackFormat->isUTF8String()) {
1530 if(data) a_UTF8String->fromPrintableString(data->getValue().c_str());
1531 else if(hexData) a_UTF8String->fromHexString(hexData->getValue());
1532 } else if(stackFormat->isDiameterIdentity()) {
1533 if(data) a_DiameterIdentity->fromPrintableString(data->getValue().c_str());
1534 else if(hexData) a_DiameterIdentity->fromHexString(hexData->getValue());
1535 } else if(stackFormat->isDiameterURI()) {
1536 if(data) a_DiameterURI->fromPrintableString(data->getValue().c_str());
1537 else if(hexData) a_DiameterURI->fromHexString(hexData->getValue());
1538 } else if(stackFormat->isEnumerated()) {
1539 if(data) a_Enumerated->fromPrintableString(data->getValue().c_str());
1540 else if(hexData) a_Enumerated->fromHexString(hexData->getValue());
1541 } else if(stackFormat->isIPFilterRule()) {
1542 if(data) a_IPFilterRule->fromPrintableString(data->getValue().c_str());
1543 else if(hexData) a_IPFilterRule->fromHexString(hexData->getValue());
1544 } else if(stackFormat->isQoSFilterRule()) {
1545 if(data) a_QoSFilterRule->fromPrintableString(data->getValue().c_str());
1546 else if(hexData) a_QoSFilterRule->fromHexString(hexData->getValue());
1549 /////////////////////
1550 // Format specific //
1551 /////////////////////
1552 fromXMLByFormat(data, hexData, stackFormat);
1555 //------------------------------------------------------------------------------
1556 //----------------------------------------------------------------- Avp::asXML()
1557 //------------------------------------------------------------------------------
1558 anna::xml::Node* Avp::asXML(anna::xml::Node* parent) const throw() {
1559 // <!ATTLIST avp id CDATA #IMPLIED code CDATA #IMPLIED vendor-code CDATA #IMPLIED flags CDATA #IMPLIED data CDATA #IMPLIED hex-data CDATA #IMPLIED>
1560 anna::xml::Node* result = parent->createChild("avp");
1561 // Dictionary stack avp and format:
1562 const stack::Avp *stackAvp = getStackAvp();
1563 const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
1564 bool compactMode = (stackAvp && flagsOK());
1567 result->createAttribute("name", stackAvp->getName());
1569 result->createAttribute("code", a_id.first);
1570 result->createAttribute("vendor-code", a_id.second);
1571 result->createAttribute("flags", (int)a_flags);
1574 // Grouped special case:
1575 if(stackFormat && stackFormat->isGrouped()) {
1576 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) avp(it)->asXML(result);
1581 // Data part literals:
1583 std::string value = getXMLdata(isHex, stackFormat);
1586 result->createAttribute("hex-data", value);
1588 result->createAttribute("data", value);
1589 const char *alias = stackAvp->getAlias(value);
1591 if(alias) result->createAttribute("alias", alias); // additional information
1598 //------------------------------------------------------------------------------
1599 //----------------------------------------------------------- Avp::asXMLString()
1600 //------------------------------------------------------------------------------
1601 std::string Avp::asXMLString() const throw() {
1602 anna::xml::Node root("root");
1603 return anna::xml::Compiler().apply(asXML(&root));
1607 //------------------------------------------------------------------------------
1608 //---------------------------------------------------------------- Avp::isLike()
1609 //------------------------------------------------------------------------------
1610 bool Avp::isLike(const std::string &pattern) const throw() {
1611 anna::RegularExpression re(pattern);
1612 return re.isLike(asXMLString());