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>
54 #include <anna/core/tracing/Logger.hpp>
55 #include <anna/core/functions.hpp>
56 #include <anna/core/tracing/TraceMethod.hpp>
57 #include <anna/xml/xml.hpp>
64 using namespace anna::diameter::codec;
73 const int Avp::HeaderLengthVactive(12);
74 const int Avp::HeaderLengthVinactive(8);
75 const U8 Avp::VBitMask(0x80);
76 const U8 Avp::MBitMask(0x40);
77 const U8 Avp::PBitMask(0x20);
82 //------------------------------------------------------------------------------
83 //------------------------------------------------------------------- Avp::Avp()
84 //------------------------------------------------------------------------------
90 //------------------------------------------------------------------------------
91 //------------------------------------------------------------------- Avp::Avp()
92 //------------------------------------------------------------------------------
99 //------------------------------------------------------------------------------
100 //------------------------------------------------------------------ Avp::~Avp()
101 //------------------------------------------------------------------------------
107 //------------------------------------------------------------------------------
108 //------------------------------------------------------------- Avp::getEngine()
109 //------------------------------------------------------------------------------
110 Engine * Avp::getEngine() const throw(anna::RuntimeException) {
111 return a_engine ? a_engine : (a_engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION));
115 //------------------------------------------------------------------------------
116 //------------------------------------------------------------ Avp::initialize()
117 //------------------------------------------------------------------------------
118 void Avp::initialize() throw() {
120 a_id = helpers::AVPID__AVP; // (0,0)
122 a_insertionPositionForChilds = 0;
123 a_OctetString = NULL;
134 a_DiameterIdentity = NULL;
135 a_DiameterURI = NULL;
137 a_IPFilterRule = NULL;
138 a_QoSFilterRule = NULL;
141 /////////////////////
142 // Format specific //
143 /////////////////////
144 initializeByFormat();
148 //------------------------------------------------------------------------------
149 //----------------------------------------------------------------- Avp::clear()
150 //------------------------------------------------------------------------------
151 void Avp::clear() throw(anna::RuntimeException) {
152 delete a_OctetString;
160 for(avp_iterator it = avp_begin(); it != avp_end(); it++) { /*avp(it)->clear(); */getEngine()->releaseAvp(avp(it)); }
166 delete a_DiameterIdentity;
167 delete a_DiameterURI;
169 delete a_IPFilterRule;
170 delete a_QoSFilterRule;
174 /////////////////////
175 // Format specific //
176 /////////////////////
183 //------------------------------------------------------------------------------
184 //-------------------------------------------------------------- Avp::avp_find()
185 //------------------------------------------------------------------------------
186 avp_iterator Avp::avp_find(avp_container &avps, AvpId id, unsigned int position) throw() {
190 for(avp_iterator it = avps.begin(); it != avps.end(); it++) {
193 if(aux && (aux->getId() == id)) {
196 if(match == position) return it;
204 //------------------------------------------------------------------------------
205 //---------------------------------------------------------------- Avp::addAvp()
206 //------------------------------------------------------------------------------
207 Avp * Avp::addAvp(avp_container &avps, int &insertionPositionForChilds, AvpId id, Engine *engine) throw() {
208 Avp * result = engine->allocateAvp();
210 addChild(avps, insertionPositionForChilds, result);
215 //------------------------------------------------------------------------------
216 //------------------------------------------------------------- Avp::removeAvp()
217 //------------------------------------------------------------------------------
218 bool Avp::removeAvp(avp_container &avps, find_container &finds, AvpId id, int ocurrence, Engine *engine) throw() {
219 bool removed = false;
220 bool do_remove = true;
221 int position = ocurrence;
223 if(position < 0) { /* reversed access */
224 position = countAvp(avps, id) + 1 + position;
226 // Special cases -> 0 and negative results:
227 // (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)
228 // (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)
229 // (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 ...)
230 if(position <= 0) do_remove = false;
234 int n = position ? position : 1 /* will search always the first and remove, the first and remove, the first and remove ... */;
237 while((it = avp_find(avps, id, n)) != avps.end()) {
238 engine->releaseAvp((*it).second);
247 // Cache system reset (remove will invalidate cached findings):
250 const stack::Avp *stackAvp = getStackAvp(id, engine);
251 std::string msg = "Removed Avp "; msg += stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id));
252 msg += anna::functions::asString(" with provided ocurrence (%d)", ocurrence);
253 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
257 const stack::Avp *stackAvp = getStackAvp(id, engine);
258 std::string msg = "Can't found Avp "; msg += stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id));
259 msg += anna::functions::asString(" with provided ocurrence (%d), in order to be removed", ocurrence);
260 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
268 //------------------------------------------------------------------------------
269 //-------------------------------------------------------------- Avp::countAvp()
270 //------------------------------------------------------------------------------
271 int Avp::countAvp(const avp_container &avps, AvpId id) throw() {
273 const_avp_iterator it;
275 while((it = avp_find(avps, id, result + 1)) != avps.end()) result++;
281 //------------------------------------------------------------------------------
282 //-------------------------------------------------------------- Avp::firstAvp()
283 //------------------------------------------------------------------------------
284 const Avp* Avp::firstAvp(const avp_container &avps, AvpId id) throw() {
285 const_avp_iterator it = avp_find(avps, id, 1);
294 //------------------------------------------------------------------------------
295 //----------------------------------------------------------- Avp::countChilds()
296 //------------------------------------------------------------------------------
297 int Avp::countChilds(const avp_container &avps) throw() {
302 //------------------------------------------------------------------------------
303 //---------------------------------------------------------------- Avp::getAvp()
304 //------------------------------------------------------------------------------
305 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) {
307 LOGDEBUG(anna::Logger::debug("Ocurrence number zero has no sense. NULL returned.", ANNA_FILE_LOCATION));
311 bool do_search = true;
313 int position = ocurrence;
315 if(position < 0) { /* reversed access */
316 position = countAvp(avps, id) + 1 + position;
318 // Special cases -> 0 and negative results:
319 // (1) User wants to get the last, but no avp is found: position = 0 + 1 - 1 = 0 (can't find 0-position ...)
320 // (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 ...)
321 // (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 ...)
322 if(position <= 0) do_search = false;
325 const Avp * result = NULL;
328 // Search at cache finds:
329 find_key key(id, position);
330 find_iterator fit = finds.find(key);
331 cached = (fit != finds.end());
334 result = (*fit).second;
336 const_avp_iterator it = avp_find(avps, id, position);
338 if(it != avps.end()) {
339 result = (*it).second;
340 finds[key] = const_cast<Avp*>(result); // store in cache
348 const stack::Avp *stackAvp = getStackAvp(id, engine);
349 std::string msg = "Found Avp "; msg += stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id));
350 msg += anna::functions::asString(" with provided ocurrence (%d) which was ", ocurrence);
351 msg += cached ? "already cached:\n" : "the first search, now cached:\n";
352 msg += result->asXMLString();
353 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
360 case anna::Exception::Mode::Throw: {
361 const stack::Avp *stackAvp = getStackAvp(id, engine);
362 std::string msg = "Can't found Avp "; msg += stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id));
363 msg += anna::functions::asString(" with provided ocurrence (%d)", ocurrence);
364 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
367 case anna::Exception::Mode::Trace: {
369 const stack::Avp *stackAvp = getStackAvp(id, engine);
370 std::string msg = "Can't found Avp "; msg += stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id));
371 msg += anna::functions::asString(" with provided ocurrence (%d)", ocurrence);
372 anna::Logger::warning(msg, ANNA_FILE_LOCATION);
376 case anna::Exception::Mode::Ignore: {
378 const stack::Avp *stackAvp = getStackAvp(id, engine);
379 std::string msg = "Can't found Avp "; msg += stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id));
380 msg += anna::functions::asString(" with provided ocurrence (%d)", ocurrence);
381 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
391 //------------------------------------------------------------------------------
392 //--------------------------------------------------------------- Avp::_getAvp()
393 //------------------------------------------------------------------------------
394 const Avp *Avp::_getAvp(AvpId id, int ocurrence, anna::Exception::Mode::_v emode) const throw(anna::RuntimeException) {
395 // Dictionary stack avp and format (this):
396 const stack::Avp *stackAvp = getStackAvp();
397 const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
399 if(!stackFormat || !stackFormat->isGrouped())
400 throw anna::RuntimeException("This method only applies over grouped avps.", ANNA_FILE_LOCATION);
402 return getAvp(a_avps, (find_container&)a_finds, id, ocurrence, getEngine(), emode);
406 //------------------------------------------------------------------------------
407 //---------------------------------------------------------- Avp::assertFormat()
408 //------------------------------------------------------------------------------
409 void Avp::assertFormat(const std::string &name) const throw(anna::RuntimeException) {
410 // Dictionary stack avp and format:
411 const stack::Avp *stackAvp = getStackAvp();
412 const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
413 std::string format = stackFormat ? stackFormat->getName() : "Unknown";
416 std::string msg = "The Avp ";
417 msg += anna::diameter::functions::avpIdAsPairString(a_id);
418 msg += " with format '";
420 msg += "' is not compatible with the API method used (";
423 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
428 //------------------------------------------------------------------------------
429 //--------------------------------------------------------------- Avp::flagsOK()
430 //------------------------------------------------------------------------------
431 bool Avp::flagsOK() const throw() {
432 // Dictionary stack avp:
433 const stack::Avp *stackAvp = getStackAvp();
436 anna::Logger::error("Impossible to decide if flags are correct because stack avp is not identified. Assume flags ok", ANNA_FILE_LOCATION);
441 bool Vnone = (stackAvp->getVbit() == stack::Avp::FlagRule::None);
443 bool Vmust = (stackAvp->getVbit() == stack::Avp::FlagRule::must);
445 bool Vmustnot = (stackAvp->getVbit() == stack::Avp::FlagRule::mustnot);
447 bool Mnone = (stackAvp->getMbit() == stack::Avp::FlagRule::None);
449 bool Mmust = (stackAvp->getMbit() == stack::Avp::FlagRule::must);
451 bool Mmustnot = (stackAvp->getMbit() == stack::Avp::FlagRule::mustnot);
453 bool Pnone = (stackAvp->getPbit() == stack::Avp::FlagRule::None);
455 bool Pmust = (stackAvp->getPbit() == stack::Avp::FlagRule::must);
457 bool Pmustnot = (stackAvp->getPbit() == stack::Avp::FlagRule::mustnot);
460 if((Vnone && Mnone && Pnone && vendorBit()) || (Vmust && !vendorBit()) || (Vmustnot && vendorBit())) {
461 anna::Logger::error("Vendor Bit (V) incoherence found", ANNA_FILE_LOCATION);
465 // Exit on permissive mode:
466 if(getEngine()->ignoreFlagsOnValidation()) return true; // Ignore checking for AVP 'M' & 'P' bits
469 if((Mmust && !mandatoryBit()) || (Mmustnot && mandatoryBit())) {
470 anna::Logger::error("Mandatory Bit (M) incoherence found", ANNA_FILE_LOCATION);
475 if((Pmust && !encryptionBit()) || (Pmustnot && encryptionBit())) {
476 anna::Logger::error("Encryption Bit (P) incoherence found", ANNA_FILE_LOCATION);
481 if((a_flags & 0x1f) != 0x00) {
482 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);
490 //------------------------------------------------------------------------------
491 //----------------------------------------------------------------- Avp::setId()
492 //------------------------------------------------------------------------------
493 void Avp::setId(AvpId id) throw(anna::RuntimeException) {
494 // Generic AVP assignment has no sense
495 if(id == helpers::AVPID__AVP) return;
497 // Clear class content:
501 // Dictionary stack avp and format:
502 const stack::Avp *stackAvp = getStackAvp(); // based on dictionary and a_id
503 const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
505 // Dictionary flags for known types:
507 if(stackAvp->getVbit() == stack::Avp::FlagRule::must) a_flags |= VBitMask;
509 if(stackAvp->getMbit() == stack::Avp::FlagRule::must) a_flags |= MBitMask;
511 if(stackAvp->getPbit() == stack::Avp::FlagRule::must) a_flags |= PBitMask;
513 if(a_id.second != 0) a_flags |= VBitMask; else a_flags &= (~VBitMask);
516 if(!stackFormat) { // Unknown Avp
518 std::string msg = "Unknown format for AVP identifier ";
519 msg += anna::diameter::functions::avpIdAsPairString(id);
520 msg += ". Raw data without specific format will be managed";
521 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
523 a_Unknown = new Unknown();
527 // Avp class formats (Avp child classes should implement this source code block for application-specific formats):
528 if(stackFormat->isOctetString()) a_OctetString = new OctetString();
529 else if(stackFormat->isInteger32()) a_Integer32 = new Integer32();
530 else if(stackFormat->isInteger64()) a_Integer64 = new Integer64();
531 else if(stackFormat->isUnsigned32()) a_Unsigned32 = new Unsigned32();
532 else if(stackFormat->isUnsigned64()) a_Unsigned64 = new Unsigned64();
533 else if(stackFormat->isFloat32()) a_Float32 = new Float32();
534 else if(stackFormat->isFloat64()) a_Float64 = new Float64();
535 //else if (stackFormat->isGrouped())
536 else if(stackFormat->isAddress()) a_Address = new Address();
537 else if(stackFormat->isTime()) a_Time = new Time();
538 else if(stackFormat->isUTF8String()) a_UTF8String = new UTF8String();
539 else if(stackFormat->isDiameterIdentity()) a_DiameterIdentity = new DiameterIdentity();
540 else if(stackFormat->isDiameterURI()) a_DiameterURI = new DiameterURI();
541 else if(stackFormat->isEnumerated()) a_Enumerated = new Enumerated();
542 else if(stackFormat->isIPFilterRule()) a_IPFilterRule = new IPFilterRule();
543 else if(stackFormat->isQoSFilterRule()) a_QoSFilterRule = new QoSFilterRule();
545 /////////////////////
546 // Format specific //
547 /////////////////////
548 allocationByFormat(stackFormat);
552 //------------------------------------------------------------------------------
553 //----------------------------------------------------------------- Avp::setId()
554 //------------------------------------------------------------------------------
555 void Avp::setId(const char *name) throw(anna::RuntimeException) {
556 setId(getEngine()->avpIdForName(name));
560 //------------------------------------------------------------------------------
561 //---------------------------------------------------------------- Avp::addAvp()
562 //------------------------------------------------------------------------------
563 Avp * Avp::addAvp(const char *name) throw(anna::RuntimeException) {
564 return addAvp(getEngine()->avpIdForName(name));
568 //------------------------------------------------------------------------------
569 //------------------------------------------------------------- Avp::removeAvp()
570 //------------------------------------------------------------------------------
571 bool Avp::removeAvp(const char *name, int ocurrence) throw(anna::RuntimeException) {
572 return removeAvp(getEngine()->avpIdForName(name), ocurrence);
576 //------------------------------------------------------------------------------
577 //--------------------------------------------------------------- Avp::_getAvp()
578 //------------------------------------------------------------------------------
579 const Avp *Avp::_getAvp(const char *name, int ocurrence, anna::Exception::Mode::_v emode) const throw(anna::RuntimeException) {
580 return getAvp(getEngine()->avpIdForName(name), ocurrence, emode);
584 //------------------------------------------------------------------------------
585 //-------------------------------------------------------------- Avp::countAvp()
586 //------------------------------------------------------------------------------
587 int Avp::countAvp(const char *name) const throw(anna::RuntimeException) {
588 return countAvp(getEngine()->avpIdForName(name));
591 //------------------------------------------------------------------------------
592 //------------------------------------------------------------- Avp::getLength()
593 //------------------------------------------------------------------------------
594 U24 Avp::getLength() const throw() {
597 const stack::Avp *stackAvp = getStackAvp();
598 const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
600 result = vendorBit() ? HeaderLengthVactive : HeaderLengthVinactive;
603 result += a_Unknown->getSize();
607 if(stackFormat->isOctetString()) result += a_OctetString->getSize();
608 else if(stackFormat->isInteger32()) result += a_Integer32->getSize();
609 else if(stackFormat->isInteger64()) result += a_Integer64->getSize();
610 else if(stackFormat->isUnsigned32()) result += a_Unsigned32->getSize();
611 else if(stackFormat->isUnsigned64()) result += a_Unsigned64->getSize();
612 else if(stackFormat->isFloat32()) result += a_Float32->getSize();
613 else if(stackFormat->isFloat64()) result += a_Float64->getSize();
614 else if(stackFormat->isGrouped()) for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) result += 4 * REQUIRED_WORDS(avp(it)->getLength());
615 else if(stackFormat->isAddress()) result += a_Address->getSize();
616 else if(stackFormat->isTime()) result += a_Time->getSize();
617 else if(stackFormat->isUTF8String()) result += a_UTF8String->getSize();
618 else if(stackFormat->isDiameterIdentity()) result += a_DiameterIdentity->getSize();
619 else if(stackFormat->isDiameterURI()) result += a_DiameterURI->getSize();
620 else if(stackFormat->isEnumerated()) result += a_Enumerated->getSize();
621 else if(stackFormat->isIPFilterRule()) result += a_IPFilterRule->getSize();
622 else if(stackFormat->isQoSFilterRule()) result += a_QoSFilterRule->getSize();
624 /////////////////////
625 // Format specific //
626 /////////////////////
627 result += getLengthByFormat(stackFormat);
632 //------------------------------------------------------------------------------
633 //-------------------------------------------- Avp::unknownAvpWithMandatoryBit()
634 //------------------------------------------------------------------------------
635 void Avp::unknownAvpWithMandatoryBit(Message *answer) const throw(anna::RuntimeException) {
636 OamModule &oamModule = OamModule::instantiate();
637 const char *c_aid = STRING_WITH_QUOTATION_MARKS__C_STR(anna::diameter::functions::avpIdAsPairString(a_id));
638 oamModule.activateAlarm(OamModule::Alarm::AvpDecode__UnknownAvp__s__WithMandatoryBit, c_aid);
639 oamModule.count(OamModule::Counter::AvpDecode__UnknownAvpWithMandatoryBit);
641 std::string msg = anna::functions::asString("Detected unknown Avp %s with mandatory bit activated", c_aid);
642 anna::Logger::warning(msg, ANNA_FILE_LOCATION);
646 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_AVP_UNSUPPORTED);
647 answer->setFailedAvp((Avp*)this);
651 //------------------------------------------------------------------------------
652 //-------------------------------------------------------- Avp::decodeDataPart()
653 //------------------------------------------------------------------------------
654 void Avp::decodeDataPart(const char * buffer, int size, Message *answer) throw(anna::RuntimeException) {
656 OamModule &oamModule = OamModule::instantiate();
657 // Dictionary stack avp and format:
658 const stack::Avp *stackAvp = getStackAvp();
659 const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
662 a_Unknown->decode(buffer, size);
666 if(stackFormat->isOctetString()) a_OctetString->decode(buffer, size);
667 else if(stackFormat->isInteger32()) a_Integer32->decode(buffer, size);
668 else if(stackFormat->isInteger64()) a_Integer64->decode(buffer, size);
669 else if(stackFormat->isUnsigned32()) a_Unsigned32->decode(buffer, size);
670 else if(stackFormat->isUnsigned64()) a_Unsigned64->decode(buffer, size);
671 else if(stackFormat->isFloat32()) a_Float32->decode(buffer, size);
672 else if(stackFormat->isFloat64()) a_Float64->decode(buffer, size);
673 else if(stackFormat->isGrouped()) {
675 LOGDEBUG(anna::Logger::debug("Grouped Avp has empty data part", ANNA_FILE_LOCATION));
679 if((size % 4) != 0) {
680 oamModule.activateAlarm(OamModule::Alarm::AvpDecode__IncorrectLength);
681 oamModule.count(OamModule::Counter::AvpDecode__IncorrectLength);
684 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_AVP_LENGTH);
685 //answer->setFailedAvp(a_id);
688 throw anna::RuntimeException("Avp format error, the avp length is incorrect (must be multiple of 4 on grouped type)", ANNA_FILE_LOCATION);
695 while(avpPos < size) {
697 avp = getEngine()->allocateAvp();
698 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) */);
699 avp -> decode(db, answer);
700 } catch(anna::RuntimeException &ex) {
701 getEngine()->releaseAvp(avp);
706 avpPos += 4 * REQUIRED_WORDS(avp->getLength());
708 } else if(stackFormat->isAddress()) a_Address->decode(buffer, size);
709 else if(stackFormat->isTime()) a_Time->decode(buffer, size);
710 else if(stackFormat->isUTF8String()) a_UTF8String->decode(buffer, size);
711 else if(stackFormat->isDiameterIdentity()) a_DiameterIdentity->decode(buffer, size);
712 else if(stackFormat->isDiameterURI()) a_DiameterURI->decode(buffer, size);
713 else if(stackFormat->isEnumerated()) a_Enumerated->decode(buffer, size);
714 else if(stackFormat->isIPFilterRule()) a_IPFilterRule->decode(buffer, size);
715 else if(stackFormat->isQoSFilterRule()) a_QoSFilterRule->decode(buffer, size);
717 /////////////////////
718 // Format specific //
719 /////////////////////
720 decodeDataPartByFormat(buffer, size, stackFormat);
723 //------------------------------------------------------------------------------
724 //---------------------------------------------------------------- Avp::decode()
725 //------------------------------------------------------------------------------
726 void Avp::decode(const anna::DataBlock &db, Message *answer) throw(anna::RuntimeException) {
728 OamModule &oamModule = OamModule::instantiate();
730 if(db.getSize() < HeaderLengthVinactive) {
731 oamModule.activateAlarm(OamModule::Alarm::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength);
732 oamModule.count(OamModule::Counter::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength);
733 // DIAMETER_INVALID_AVP_LENGTH; // no podr� construir un avp fiable, as� que no registro el result-code
734 throw anna::RuntimeException("Not enough bytes to cover avp header length", ANNA_FILE_LOCATION);
737 const char * buffer = db.getData();
740 // 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
741 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
743 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
744 // | AVP Flags | AVP Length |
745 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
746 // | Vendor-ID (opt) |
747 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
750 // Code flags and vendor-id
751 U32 code = DECODE4BYTES_INDX_VALUETYPE(buffer, 0, U32);
753 a_flags = (S8)buffer[4];
755 U32 vendorID = helpers::VENDORID__base;
758 if(db.getSize() < HeaderLengthVactive) {
759 oamModule.activateAlarm(OamModule::Alarm::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength);
760 oamModule.count(OamModule::Counter::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength);
761 // DIAMETER_INVALID_AVP_LENGTH; // no podr� construir un avp fiable, as� que no registro el result-code
762 throw anna::RuntimeException(anna::functions::asString("Not enough bytes to cover avp header length (avp code = %u)", code), ANNA_FILE_LOCATION);
765 vendorID = DECODE4BYTES_INDX_VALUETYPE(buffer, 8, U32);
767 if(vendorID == helpers::VENDORID__base) {
768 // A vendor ID value of zero (0) corresponds to the IETF adopted AVP
769 // values, as managed by the IANA. Since the absence of the vendor
770 // ID field implies that the AVP in question is not vendor specific,
772 // implementations MUST NOT use the zero (0) vendor ID.
773 oamModule.activateAlarm(OamModule::Alarm::AvpDecode__IncoherenceBetweenActivatedVBitAndZeroedVendorIDValueReceived);
774 oamModule.count(OamModule::Counter::AvpDecode__IncoherenceBetweenActivatedVBitAndZeroedVendorIDValueReceived);
775 throw anna::RuntimeException(anna::functions::asString("Incoherence between activated V bit and zeroed vendor-id value received (avp code = %u)", code), ANNA_FILE_LOCATION);
780 setId(AvpId(code, vendorID));
781 // Flags could have been updated regarding dictionary, but during decoding we must respect buffer received:
782 a_flags = (S8)buffer[4];
784 // Here i know id and flags:
785 // 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
786 // a Diameter client, server, proxy, or translation agent and either the AVP or its value is unrecognized, the message MUST be rejected.
787 // Diameter Relay and redirect agents MUST NOT reject messages with unrecognized AVPs.
788 if(!getStackAvp() && mandatoryBit()) unknownAvpWithMandatoryBit(answer);
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(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, 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); // unspecified error ...
817 //answer->setFailedAvp((Avp*)this);
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 std::string & parentDescription, 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*/)));
944 oamModule.count(OamModule::Counter::LevelValidation__MissingFixedRule);
947 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_MISSING_AVP);
948 answer->setFailedAvp((*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(parentDescription)));
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(parentDescription));
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(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((Avp*)firstAvp(avps, id) /* first instance */);
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(parentDescription)));
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(parentDescription));
1035 oamModule.count(OamModule::Counter::LevelValidation__FailedGenericAvpRuleForCardinalityFoundDisregardedItem);
1038 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_AVP_NOT_ALLOWED);
1039 //answer->setFailedAvp((Avp*)firstAvp(avps, id) /* first instance */); // 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(parentDescription)));
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((Avp*)firstAvp(avps, id) /* first instance */);
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(parentDescription), 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(parentDescription), STRING_WITH_QUOTATION_MARKS__C_STR(s_disregardeds)));
1075 //------------------------------------------------------------------------------
1076 //----------------------------------------------------------------- Avp::valid()
1077 //------------------------------------------------------------------------------
1078 bool Avp::valid(const std::string & parentDescription, 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*/;
1087 // No dictionary avp reference found. Cannot validate
1088 return true; // perhaps a unknown Avp
1091 me = parentDescription + "->" + stackAvp->getName();
1094 // No format avp reference found. Cannot validate
1095 return true; // perhaps a unknown Avp
1098 //////////////////////////////
1099 // Flags coherence checking //
1100 //////////////////////////////
1101 bool result = flagsOK();
1104 // OAM & Depth management
1105 oamModule.activateAlarm(OamModule::Alarm::AvpValidation__Avp__s__Flags__d__DoesNotFulfillTheDefinedFlagRules__s__, STRING_WITH_QUOTATION_MARKS__C_STR(me), (int)a_flags, STRING_WITH_QUOTATION_MARKS__C_STR(stackAvp->getFlagRulesDescription()));
1106 oamModule.count(OamModule::Counter::AvpValidation__AvpFlagsDoesNotFulfillTheDefinedFlagRules);
1109 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_AVP_BITS);
1110 answer->setFailedAvp((Avp*)this); // RFC 6733 says nothing about Failed-AVP in this case...
1113 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), (int)a_flags, STRING_WITH_QUOTATION_MARKS__C_STR(stackAvp->getFlagRulesDescription())));
1116 //////////////////////
1117 // Enumerated range //
1118 //////////////////////
1119 if(stackFormat->isEnumerated()) {
1120 if(!stackAvp->allowEnum(a_Enumerated->getValue())) {
1122 // OAM & Depth management
1123 oamModule.activateAlarm(OamModule::Alarm::AvpValidation__EnumeratedAvp__s__WithValue__d__DoesNotComplyRestriction__s__, STRING_WITH_QUOTATION_MARKS__C_STR(me), a_Enumerated->getValue(), stackAvp->getEnums());
1124 oamModule.count(OamModule::Counter::AvpValidation__EnumeratedAvpWithValueDoesNotComplyRestriction);
1127 answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_AVP_VALUE);
1128 answer->setFailedAvp((Avp*)this);
1131 getEngine()->validationAnomaly(anna::functions::asString("Enumerated AVP %s with value %d does not comply to restriction: %s", STRING_WITH_QUOTATION_MARKS__C_STR(me), a_Enumerated->getValue(), stackAvp->getEnums()));
1135 ////////////////////
1136 // Level checking //
1137 ////////////////////
1138 result = Avp::validLevel(a_avps, stackAvp->avprule_begin(), stackAvp->avprule_end(), getEngine(), me, answer) && result;
1140 ////////////////////////
1141 // Childrens checking //
1142 ////////////////////////
1143 if(a_id == helpers::base::AVPID__Failed_AVP) return result; // DON'T VALIDATE CONTENT FOR Failed-AVP, because it won't be valid...
1145 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++)
1146 result = ((*it).second->valid(me, answer)) && result;
1152 //------------------------------------------------------------------------------
1153 //------------------------------------------------------------------ Avp::code()
1154 //------------------------------------------------------------------------------
1155 void Avp::code(char* buffer, int &size) const throw(anna::RuntimeException) {
1157 buffer[0] = (S8)(a_id.first >> 24);
1158 buffer[1] = (S8)(a_id.first >> 16);
1159 buffer[2] = (S8)(a_id.first >> 8);
1160 buffer[3] = (S8) a_id.first;
1163 buffer[4] = (S8) a_flags;
1164 buffer[5] = (S8)(size >> 16);
1165 buffer[6] = (S8)(size >> 8);
1166 buffer[7] = (S8) size;
1170 buffer[8] = (S8)(a_id.second >> 24);
1171 buffer[9] = (S8)(a_id.second >> 16);
1172 buffer[10] = (S8)(a_id.second >> 8);
1173 buffer[11] = (S8) a_id.second;
1176 // Data start position:
1177 int startDataPos = vendorBit() ? HeaderLengthVactive : HeaderLengthVinactive;
1179 S8 * dataPart = buffer + startDataPos;
1180 int dataBytes; // not used but could be useful for checking (size - startDataPos)
1182 if(startDataPos == size) {
1183 LOGDEBUG(anna::Logger::debug("There is no data part to encode", ANNA_FILE_LOCATION));
1188 const stack::Avp *stackAvp = getStackAvp();
1189 const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
1192 a_Unknown->code(dataPart, dataBytes);
1196 if(stackFormat->isOctetString()) a_OctetString->code(dataPart, dataBytes);
1197 else if(stackFormat->isInteger32()) a_Integer32->code(dataPart, dataBytes);
1198 else if(stackFormat->isInteger64()) a_Integer64->code(dataPart, dataBytes);
1199 else if(stackFormat->isUnsigned32()) a_Unsigned32->code(dataPart, dataBytes);
1200 else if(stackFormat->isUnsigned64()) a_Unsigned64->code(dataPart, dataBytes);
1201 else if(stackFormat->isFloat32()) a_Float32->code(dataPart, dataBytes);
1202 else if(stackFormat->isFloat64()) a_Float64->code(dataPart, dataBytes);
1203 else if(stackFormat->isGrouped()) {
1204 // // Each avp encoding will remain padding octets depending on format. In order to
1205 // // code grouped content (each avp will be multiple of 4) we clean the entire buffer
1206 // // to ensure padding (easier than custom-made for each format):
1207 // memset(dataPart, 0, size - startDataPos);
1208 char *dataPartGrouped = dataPart;
1209 int dataBytesGrouped;
1211 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) {
1212 avp(it)->code(dataPartGrouped, dataBytesGrouped);
1213 dataPartGrouped = dataPartGrouped + 4 * REQUIRED_WORDS(dataBytesGrouped);
1215 } else if(stackFormat->isAddress()) a_Address->code(dataPart, dataBytes);
1216 else if(stackFormat->isTime()) a_Time->code(dataPart, dataBytes);
1217 else if(stackFormat->isUTF8String()) a_UTF8String->code(dataPart, dataBytes);
1218 else if(stackFormat->isDiameterIdentity()) a_DiameterIdentity->code(dataPart, dataBytes);
1219 else if(stackFormat->isDiameterURI()) a_DiameterURI->code(dataPart, dataBytes);
1220 else if(stackFormat->isEnumerated()) a_Enumerated->code(dataPart, dataBytes);
1221 else if(stackFormat->isIPFilterRule()) a_IPFilterRule->code(dataPart, dataBytes);
1222 else if(stackFormat->isQoSFilterRule()) a_QoSFilterRule->code(dataPart, dataBytes);
1224 /////////////////////
1225 // Format specific //
1226 /////////////////////
1227 codeByFormat(dataPart, stackFormat);
1231 //------------------------------------------------------------------------------
1232 //------------------------------------------------------------ Avp::getXMLdata()
1233 //------------------------------------------------------------------------------
1234 std::string Avp::getXMLdata(bool & isHex, const stack::Format *stackFormat) const throw() {
1235 std::string result = "";
1239 // if (!stackFormat) {
1241 // return a_Unknown->asHexString();
1243 // } catch (anna::RuntimeException &ex) {
1249 return a_Unknown->asHexString(); // el asHexString del OctetString no puede lanzar una excepcion en realidad
1252 // Special case for Address: could launch exception if not printable
1254 if(stackFormat->isAddress()) return a_Address->asPrintableString();
1255 } catch(anna::RuntimeException&) {
1258 return a_Address->asHexString();
1262 if(stackFormat->isOctetString()) {
1264 return a_OctetString->asHexString();
1268 if(stackFormat->isInteger32()) return a_Integer32->asPrintableString();
1270 if(stackFormat->isInteger64()) return a_Integer64->asPrintableString();
1272 if(stackFormat->isUnsigned32()) return a_Unsigned32->asPrintableString();
1274 if(stackFormat->isUnsigned64()) return a_Unsigned64->asPrintableString();
1276 if(stackFormat->isFloat32()) return a_Float32->asPrintableString();
1278 if(stackFormat->isFloat64()) return a_Float64->asPrintableString();
1280 //if (stackFormat->isAddress()) return a_Address->asPrintableString();
1282 if(stackFormat->isTime()) return a_Time->asPrintableString();
1284 if(stackFormat->isUTF8String()) return a_UTF8String->asPrintableString();
1286 if(stackFormat->isDiameterIdentity()) return a_DiameterIdentity->asPrintableString();
1288 if(stackFormat->isDiameterURI()) return a_DiameterURI->asPrintableString();
1290 if(stackFormat->isEnumerated()) return a_Enumerated->asPrintableString();
1292 if(stackFormat->isIPFilterRule()) return a_IPFilterRule->asPrintableString();
1294 if(stackFormat->isQoSFilterRule()) return a_QoSFilterRule->asPrintableString();
1296 /////////////////////
1297 // Format specific //
1298 /////////////////////
1299 return getXMLdataByFormat(isHex, stackFormat);
1300 } catch(anna::RuntimeException &ex) {
1308 //------------------------------------------------------------------------------
1309 //--------------------------------------------------------------- Avp::fromXML()
1310 //------------------------------------------------------------------------------
1311 void Avp::fromXML(const anna::xml::Node* avpNode) throw(anna::RuntimeException) {
1312 // <!ATTLIST avp id CDATA #IMPLIED code CDATA #IMPLIED vendor-code CDATA #IMPLIED flags CDATA #IMPLIED data CDATA #IMPLIED hex-data CDATA #IMPLIED>
1313 const anna::xml::Attribute *name, *code, *vendorCode, *flags, *data, *hexData;
1314 name = avpNode->getAttribute("name", false /* no exception */);
1315 code = avpNode->getAttribute("code", false /* no exception */);
1316 vendorCode = avpNode->getAttribute("vendor-code", false /* no exception */);
1317 flags = avpNode->getAttribute("flags", false /* no exception */);
1318 data = avpNode->getAttribute("data", false /* no exception */);
1319 hexData = avpNode->getAttribute("hex-data", false /* no exception */);
1321 const stack::Dictionary * dictionary = getEngine()->getDictionary();
1322 const stack::Avp *stackAvp = NULL;
1323 const stack::Format *stackFormat = NULL;
1328 std::string msg = "Error processing avp <name '"; msg += name->getValue();
1329 msg += "'>: no dictionary available. Load one or use <'code' + 'flags' + 'vendorCode'> instead of <'name'>";
1330 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1333 stackAvp = dictionary->getAvp(name->getValue());
1336 std::string msg = "Error processing avp <name '"; msg += name->getValue();
1337 msg += "'>: no avp found for this identifier at available dictionary";
1338 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1341 stackFormat = stackAvp->getFormat();
1344 // Check attributes exclusiveness
1345 if(name) { // compact mode
1346 if(code || flags || vendorCode) {
1347 std::string msg = "Error processing avp <name '"; msg += name->getValue();
1348 msg += "'>: avp attributes <'code' + 'flags' + 'vendorCode'> are not allowed if <'name'> is provided";
1349 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1352 setId(stackAvp->getId());
1354 if(!code || !flags || !vendorCode) {
1355 std::string s_code = code ? code->getValue() : "?";
1356 std::string s_flags = flags ? flags->getValue() : "?";
1357 std::string s_vendorCode = vendorCode ? vendorCode->getValue() : "?";
1358 std::string msg = "Error processing avp <code '"; msg += s_code;
1359 msg += "' + flags '"; msg += s_flags;
1360 msg += "' + vendorCode '"; msg += s_vendorCode;
1361 msg += "'>: all must be provided if <'name'> don't";
1362 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1366 int i_aux = code->getIntegerValue();
1369 std::string msg = "Error processing avp <code '"; msg += code->getValue();
1370 msg += "': negative values are not allowed";
1371 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1376 i_aux = flags->getIntegerValue();
1378 if(i_aux < 0 || i_aux > 256) {
1379 std::string msg = "Error processing avp <flags '"; msg += flags->getValue();
1380 msg += "': out of range [0,256]";
1381 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1385 int flagsBCK = a_flags;
1386 // VendorCode checks
1387 i_aux = vendorCode->getIntegerValue();
1390 std::string msg = "Error processing avp <vendorCode '"; msg += vendorCode->getValue();
1391 msg += "': negative values are not allowed";
1392 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1395 U32 u_vendorCode = i_aux;
1396 bool vendorSpecific1 = (u_vendorCode != 0);
1397 bool vendorSpecific2 = (((a_flags) & VBitMask) != 0x00);
1399 if(vendorSpecific1 != vendorSpecific2) {
1400 std::string msg = "Error processing avp <vendorCode '"; msg += vendorCode->getValue();
1401 msg += "' and avp <flags '"; msg += flags->getValue();
1402 msg += "': incompatible vendor-specific properties";
1403 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1406 // Final assignments
1407 setId(AvpId(u_code, u_vendorCode));
1408 // Flags could have been updated regarding dictionary, but during parsing we must respect xml file:
1410 stackAvp = getStackAvp();
1411 stackFormat = stackAvp ? stackAvp->getFormat() : NULL;
1415 // Check if grouped not confirmed
1416 anna::xml::Node::const_child_iterator it;
1417 anna::xml::Node::const_child_iterator minii = avpNode->child_begin();
1418 anna::xml::Node::const_child_iterator maxii = avpNode->child_end();
1419 const bool hasChildren(minii != maxii);
1422 // We need to confirm is grouped
1424 throw anna::RuntimeException("An xml avp node with children nodes could not confirmed as Grouped", ANNA_FILE_LOCATION);
1426 if(!stackFormat->isGrouped())
1427 throw anna::RuntimeException("An xml avp node with children nodes is not grouped type", ANNA_FILE_LOCATION);
1430 throw anna::RuntimeException("An xml avp node with children nodes has 'data' or 'hex-data' field", ANNA_FILE_LOCATION);
1434 std::string s_avp = name ? (name->getValue()) : (anna::diameter::functions::avpIdAsPairString(a_id));
1436 if(data && hexData) {
1437 std::string msg = "Not allowed both 'data' and 'hex-data' definitions. Avp ";
1439 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1443 bool unknown = !stackFormat;
1444 bool octetString = stackFormat && (stackFormat->isOctetString());
1446 if(data && (unknown || octetString)) {
1447 std::string msg = "Not recommended 'data' field at ";
1448 msg += unknown ? "Unknown" : "OctetString";
1449 msg += "-format Avp "; msg += s_avp;
1450 msg += ". Use better 'hex-data' or omit content fields if empty";
1451 anna::Logger::warning(msg, ANNA_FILE_LOCATION);
1456 if(data) a_Unknown->fromPrintableString(data->getValue().c_str());
1457 else if(hexData) a_Unknown->fromHexString(hexData->getValue());
1462 if(stackFormat->isOctetString()) {
1463 if(data) a_OctetString->fromPrintableString(data->getValue().c_str());
1464 else if(hexData) a_OctetString->fromHexString(hexData->getValue());
1465 } else if(stackFormat->isInteger32()) {
1466 if(data) a_Integer32->fromPrintableString(data->getValue().c_str());
1467 else if(hexData) a_Integer32->fromHexString(hexData->getValue());
1468 } else if(stackFormat->isInteger64()) {
1469 if(data) a_Integer64->fromPrintableString(data->getValue().c_str());
1470 else if(hexData) a_Integer64->fromHexString(hexData->getValue());
1471 } else if(stackFormat->isUnsigned32()) {
1472 if(data) a_Unsigned32->fromPrintableString(data->getValue().c_str());
1473 else if(hexData) a_Unsigned32->fromHexString(hexData->getValue());
1474 } else if(stackFormat->isUnsigned64()) {
1475 if(data) a_Unsigned64->fromPrintableString(data->getValue().c_str());
1476 else if(hexData) a_Unsigned64->fromHexString(hexData->getValue());
1477 } else if(stackFormat->isFloat32()) {
1478 if(data) a_Float32->fromPrintableString(data->getValue().c_str());
1479 else if(hexData) a_Float32->fromHexString(hexData->getValue());
1480 } else if(stackFormat->isFloat64()) {
1481 if(data) a_Float64->fromPrintableString(data->getValue().c_str());
1482 else if(hexData) a_Float64->fromHexString(hexData->getValue());
1483 } else if(stackFormat->isGrouped()) {
1487 for(it = minii; it != maxii; it++) {
1488 std::string nodeName = (*it)->getName();
1490 if(nodeName != "avp") {
1491 std::string msg = "Unsupported grouped avp child node name '"; msg += nodeName;
1492 msg += "': use 'avp'";
1493 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1497 avp = getEngine()->allocateAvp();
1498 avp -> fromXML(*it);
1499 } catch(anna::RuntimeException &ex) {
1500 getEngine()->releaseAvp(avp);
1506 } else if(stackFormat->isAddress()) {
1507 if(data) a_Address->fromPrintableString(data->getValue().c_str());
1508 else if(hexData) a_Address->fromHexString(hexData->getValue());
1509 } else if(stackFormat->isTime()) {
1510 if(data) a_Time->fromPrintableString(data->getValue().c_str());
1511 else if(hexData) a_Time->fromHexString(hexData->getValue());
1512 } else if(stackFormat->isUTF8String()) {
1513 if(data) a_UTF8String->fromPrintableString(data->getValue().c_str());
1514 else if(hexData) a_UTF8String->fromHexString(hexData->getValue());
1515 } else if(stackFormat->isDiameterIdentity()) {
1516 if(data) a_DiameterIdentity->fromPrintableString(data->getValue().c_str());
1517 else if(hexData) a_DiameterIdentity->fromHexString(hexData->getValue());
1518 } else if(stackFormat->isDiameterURI()) {
1519 if(data) a_DiameterURI->fromPrintableString(data->getValue().c_str());
1520 else if(hexData) a_DiameterURI->fromHexString(hexData->getValue());
1521 } else if(stackFormat->isEnumerated()) {
1522 if(data) a_Enumerated->fromPrintableString(data->getValue().c_str());
1523 else if(hexData) a_Enumerated->fromHexString(hexData->getValue());
1524 } else if(stackFormat->isIPFilterRule()) {
1525 if(data) a_IPFilterRule->fromPrintableString(data->getValue().c_str());
1526 else if(hexData) a_IPFilterRule->fromHexString(hexData->getValue());
1527 } else if(stackFormat->isQoSFilterRule()) {
1528 if(data) a_QoSFilterRule->fromPrintableString(data->getValue().c_str());
1529 else if(hexData) a_QoSFilterRule->fromHexString(hexData->getValue());
1532 /////////////////////
1533 // Format specific //
1534 /////////////////////
1535 fromXMLByFormat(data, hexData, stackFormat);
1538 //------------------------------------------------------------------------------
1539 //----------------------------------------------------------------- Avp::asXML()
1540 //------------------------------------------------------------------------------
1541 anna::xml::Node* Avp::asXML(anna::xml::Node* parent) const throw() {
1542 // <!ATTLIST avp id CDATA #IMPLIED code CDATA #IMPLIED vendor-code CDATA #IMPLIED flags CDATA #IMPLIED data CDATA #IMPLIED hex-data CDATA #IMPLIED>
1543 anna::xml::Node* result = parent->createChild("avp");
1544 // Dictionary stack avp and format:
1545 const stack::Avp *stackAvp = getStackAvp();
1546 const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
1547 bool compactMode = (stackAvp && flagsOK());
1550 result->createAttribute("name", stackAvp->getName());
1552 result->createAttribute("code", a_id.first);
1553 result->createAttribute("vendor-code", a_id.second);
1554 result->createAttribute("flags", (int)a_flags);
1557 // Grouped special case:
1558 if(stackFormat && stackFormat->isGrouped()) {
1559 for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) avp(it)->asXML(result);
1564 // Data part literals:
1566 std::string value = getXMLdata(isHex, stackFormat);
1569 result->createAttribute("hex-data", value);
1571 result->createAttribute("data", value);
1572 const char *alias = stackAvp->getAlias(value);
1574 if(alias) result->createAttribute("alias", alias); // additional information
1580 //------------------------------------------------------------------------------
1581 //----------------------------------------------------------- Avp::asXMLString()
1582 //------------------------------------------------------------------------------
1583 std::string Avp::asXMLString() const throw() {
1584 anna::xml::Node root("root");
1585 return anna::xml::Compiler().apply(asXML(&root));