Hard refactoring. CodecEngine is associated to a unique stack.
[anna.git] / source / diameter / codec / Avp.cpp
1 // ANNA - Anna is Not Nothingness Anymore                                                         //
2 //                                                                                                //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo                         //
4 //                                                                                                //
5 // See project site at http://redmine.teslayout.com/projects/anna-suite                           //
6 // See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE //
7
8
9 // Local
10 #include <anna/diameter/codec/Avp.hpp>
11 #include <anna/diameter/codec/Format.hpp>
12
13 #include <anna/config/defines.hpp> // general types, decoding helpers (DECODE[2/3/4]BYTES_INDX_VALUETYPE), etc.
14 #include <anna/diameter/functions.hpp>
15 #include <anna/diameter/helpers/defines.hpp>
16 #include <anna/diameter/codec/basetypes/basetypes.hpp>
17 #include <anna/diameter/codec/functions.hpp> // REQUIRED_WORDS
18 #include <anna/diameter/codec/OamModule.hpp>
19 #include <anna/diameter/stack/Avp.hpp>
20 #include <anna/diameter/stack/Format.hpp>
21 #include <anna/diameter/stack/Dictionary.hpp>
22 #include <anna/diameter/stack/Engine.hpp>
23 #include <anna/diameter/codec/Engine.hpp>
24 #include <anna/core/functions.hpp>
25 #include <anna/core/util/RegularExpression.hpp>
26
27 #include <anna/core/tracing/Logger.hpp>
28 #include <anna/core/functions.hpp>
29 #include <anna/core/tracing/TraceMethod.hpp>
30 #include <anna/xml/xml.hpp>
31
32 // STL
33 #include <map>
34
35
36 using namespace anna;
37 using namespace anna::diameter::codec;
38
39
40 //static
41 namespace anna {
42
43 namespace diameter {
44
45 namespace codec {
46 const int Avp::HeaderLengthVactive(12);
47 const int Avp::HeaderLengthVinactive(8);
48 const U8 Avp::VBitMask(0x80);
49 const U8 Avp::MBitMask(0x40);
50 const U8 Avp::PBitMask(0x20);
51 }
52 }
53 }
54
55 //------------------------------------------------------------------------------
56 //------------------------------------------------------------------- Avp::Avp()
57 //------------------------------------------------------------------------------
58 Avp::Avp(Engine *engine) : a_engine(engine) {
59   initialize();
60 }
61
62 //------------------------------------------------------------------------------
63 //------------------------------------------------------------------- Avp::Avp()
64 //------------------------------------------------------------------------------
65 Avp::Avp(AvpId id, Engine *engine) : a_engine(engine) {
66   initialize();
67   setId(id);
68 }
69
70 //------------------------------------------------------------------------------
71 //------------------------------------------------------------------ Avp::~Avp()
72 //------------------------------------------------------------------------------
73 Avp::~Avp() {
74   clear();
75 }
76
77 //------------------------------------------------------------------------------
78 //------------------------------------------------------------- Avp::setEngine()
79 //------------------------------------------------------------------------------
80 void Avp::setEngine(Engine *engine) throw() {
81   if (a_engine && engine != a_engine) {
82     LOGWARNING(anna::Logger::warning("Ignored: it is not a good practice to change the codec engine once assigned. Clear the avp first to set the engine again.", ANNA_FILE_LOCATION));
83     return;
84   }
85
86   a_engine = engine;
87 }
88
89 //------------------------------------------------------------------------------
90 //------------------------------------------------------------- Avp::getEngine()
91 //------------------------------------------------------------------------------
92 Engine * Avp::getEngine() const throw(anna::RuntimeException) {
93   if(!a_engine)
94     throw anna::RuntimeException("Invalid codec engine reference (NULL). Use setEngine() to set the corresponding codec engine", ANNA_FILE_LOCATION);
95
96   return a_engine;
97 }
98
99
100 //------------------------------------------------------------------------------
101 //------------------------------------------------------------ Avp::initialize()
102 //------------------------------------------------------------------------------
103 void Avp::initialize() throw() {
104   a_id = helpers::AVPID__AVP; // (0,0)
105   a_flags = 0x00;
106   a_insertionPositionForChilds = 0;
107   a_OctetString = NULL;
108   a_Integer32 = NULL;
109   a_Integer64 = NULL;
110   a_Unsigned32 = NULL;
111   a_Unsigned64 = NULL;
112   a_Float32 = NULL;
113   a_Float64 = NULL;
114   //a_avps.clear();
115   a_Address = NULL;
116   a_Time = NULL;
117   a_UTF8String = NULL;
118   a_DiameterIdentity = NULL;
119   a_DiameterURI = NULL;
120   a_Enumerated = NULL;
121   a_IPFilterRule = NULL;
122   a_QoSFilterRule = NULL;
123   a_Unknown = NULL;
124   //a_finds.clear();
125   /////////////////////
126   // Format specific //
127   /////////////////////
128   initializeByFormat();
129 }
130
131
132 //------------------------------------------------------------------------------
133 //----------------------------------------------------------------- Avp::clear()
134 //------------------------------------------------------------------------------
135 void Avp::clear() throw(anna::RuntimeException) {
136   delete a_OctetString;
137   delete a_Integer32;
138   delete a_Integer64;
139   delete a_Unsigned32;
140   delete a_Unsigned64;
141   delete a_Float32;
142   delete a_Float64;
143
144   for(avp_iterator it = avp_begin(); it != avp_end(); it++) { /*avp(it)->clear(); */getEngine()->releaseAvp(avp(it)); }
145
146   a_avps.clear();
147   delete a_Address;
148   delete a_Time;
149   delete a_UTF8String;
150   delete a_DiameterIdentity;
151   delete a_DiameterURI;
152   delete a_Enumerated;
153   delete a_IPFilterRule;
154   delete a_QoSFilterRule;
155   delete a_Unknown;
156   // Cache system:
157   a_finds.clear();
158   /////////////////////
159   // Format specific //
160   /////////////////////
161   clearByFormat();
162   // Initialize:
163   initialize();
164 }
165
166
167 //------------------------------------------------------------------------------
168 //-------------------------------------------------------------- Avp::avp_find()
169 //------------------------------------------------------------------------------
170 avp_iterator Avp::avp_find(avp_container &avps, AvpId id, unsigned int position) throw() {
171   int match = 0;
172   Avp *aux;
173
174   for(avp_iterator it = avps.begin(); it != avps.end(); it++) {
175     aux = (*it).second;
176
177     if(aux && (aux->getId() == id)) {
178       match++;
179
180       if(match == position) return it;
181     }
182   }
183
184   return avps.end();
185 }
186
187
188 //------------------------------------------------------------------------------
189 //---------------------------------------------------------------- Avp::addAvp()
190 //------------------------------------------------------------------------------
191 Avp * Avp::addAvp(avp_container &avps, int &insertionPositionForChilds, AvpId id, Engine *engine) throw() {
192   Avp * result = engine->createAvp(NULL);
193   result->setId(id);
194   addChild(avps, insertionPositionForChilds, result);
195   return result;
196 }
197
198
199 //------------------------------------------------------------------------------
200 //---------------------------------------------------------------- Avp::addAvp()
201 //------------------------------------------------------------------------------
202 Avp * Avp::addAvp(Avp * avp) throw(anna::RuntimeException) {
203   if(!avp) return NULL;
204   if (avp->getEngine() != getEngine()) return NULL;
205   addChild(avp);
206   return avp;
207 }
208
209
210 //------------------------------------------------------------------------------
211 //------------------------------------------------------------- Avp::removeAvp()
212 //------------------------------------------------------------------------------
213 bool Avp::removeAvp(avp_container &avps, find_container &finds, AvpId id, int ocurrence, Engine *engine) throw() {
214   bool removed = false;
215   bool do_remove = true;
216   int position = ocurrence;
217
218   if(position < 0) {  /* reversed access */
219     position = countAvp(avps, id) + 1 + position;
220
221     // Special cases -> 0 and negative results:
222     // (1) User wants to remove the last, but no avp is found: position = 0 + 1 - 1 = 0 (would removes all but, no avp will be found: return now)
223     // (2) User wants to remove some intermediate avp, i.e. '-5', but only 4 avps are found: 4 + 1 - 5 = 0 (would removes all !!!: return to avoid unexpected behaviour)
224     // (2) User wants to remove some intermediate avp, i.e. '-5', but only 3 avps are found: 3 + 1 - 5 = -1 (can't find negative positions ...)
225     if(position <= 0) do_remove = false;
226   }
227
228   if(do_remove) {
229     int n = position ? position : 1 /* will search always the first and remove, the first and remove, the first and remove ... */;
230     avp_iterator it;
231
232     while((it = avp_find(avps, id, n)) != avps.end()) {
233       engine->releaseAvp((*it).second);
234       avps.erase(it);
235       removed = true;
236
237       if(position) break;
238     }
239   }
240
241   if(removed) {
242     // Cache system reset (remove will invalidate cached findings):
243     finds.clear();
244     LOGDEBUG(
245       const stack::Avp *stackAvp = getStackAvp(id, engine);
246       std::string msg = "Removed Avp "; msg += stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id));
247       msg += anna::functions::asString(" with provided ocurrence (%d)", ocurrence);
248       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
249     );
250   } else {
251     LOGDEBUG(
252       const stack::Avp *stackAvp = getStackAvp(id, engine);
253       std::string msg = "Can't found Avp "; msg += stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id));
254       msg += anna::functions::asString(" with provided ocurrence (%d), in order to be removed", ocurrence);
255       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
256     );
257   }
258
259   return removed;
260 }
261
262
263 //------------------------------------------------------------------------------
264 //-------------------------------------------------------------- Avp::countAvp()
265 //------------------------------------------------------------------------------
266 int Avp::countAvp(const avp_container &avps, AvpId id) throw() {
267   int result = 0;
268   const_avp_iterator it;
269
270   while((it = avp_find(avps, id, result + 1)) != avps.end()) result++;
271
272   return result;
273 }
274
275
276 //------------------------------------------------------------------------------
277 //-------------------------------------------------------------- Avp::firstAvp()
278 //------------------------------------------------------------------------------
279 const Avp* Avp::firstAvp(const avp_container &avps, AvpId id) throw() {
280   const_avp_iterator it = avp_find(avps, id, 1);
281
282   if(it != avps.end())
283     return (*it).second;
284
285   return NULL;
286 }
287
288
289 //------------------------------------------------------------------------------
290 //----------------------------------------------------------- Avp::countChilds()
291 //------------------------------------------------------------------------------
292 int Avp::countChilds(const avp_container &avps) throw() {
293   return avps.size();
294 }
295
296
297 //------------------------------------------------------------------------------
298 //---------------------------------------------------------------- Avp::getAvp()
299 //------------------------------------------------------------------------------
300 const Avp *Avp::getAvp(const avp_container &avps, find_container &finds, AvpId id, int ocurrence, Engine *engine, anna::Exception::Mode::_v emode) throw(anna::RuntimeException) {
301   if(ocurrence == 0) {
302     LOGDEBUG(anna::Logger::debug("Ocurrence number zero has no sense. NULL returned.", ANNA_FILE_LOCATION));
303     return NULL;
304   }
305
306   bool do_search = true;
307   bool cached;
308   int position = ocurrence;
309
310   if(position < 0) {  /* reversed access */
311     position = countAvp(avps, id) + 1 + position;
312
313     // Special cases -> 0 and negative results:
314     // (1) User wants to get the last, but no avp is found: position = 0 + 1 - 1 = 0 (can't find 0-position ...)
315     // (2) User wants to get some intermediate avp, i.e. '-5', but only 4 avps are found: 4 + 1 - 5 = 0 (can't find 0-position ...)
316     // (2) User wants to get some intermediate avp, i.e. '-5', but only 3 avps are found: 3 + 1 - 5 = -1 (can't find negative positions ...)
317     if(position <= 0) do_search = false;
318   }
319
320   const Avp * result = NULL;
321
322   if(do_search) {
323     // Search at cache finds:
324     find_key key(id, position);
325     find_iterator fit = finds.find(key);
326     cached = (fit != finds.end());
327
328     if(cached) {
329       result = (*fit).second;
330     } else {
331       const_avp_iterator it = avp_find(avps, id, position);
332
333       if(it != avps.end()) {
334         result = (*it).second;
335         finds[key] = const_cast<Avp*>(result); // store in cache
336       }
337     }
338   }
339
340   // Avp found:
341   if(result) {
342     LOGDEBUG(
343       const stack::Avp *stackAvp = getStackAvp(id, engine);
344       std::string msg = "Found Avp "; msg += stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id));
345       msg += anna::functions::asString(" with provided ocurrence (%d) which was ", ocurrence);
346       msg += cached ? "already cached:\n" : "the first search, now cached:\n";
347       msg += result->asXMLString();
348       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
349     );
350     return result;
351   }
352
353   // Avp not found:
354   switch(emode) {
355   case anna::Exception::Mode::Throw: {
356     const stack::Avp *stackAvp = getStackAvp(id, engine);
357     std::string msg = "Can't found Avp "; msg += stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id));
358     msg += anna::functions::asString(" with provided ocurrence (%d)", ocurrence);
359     throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
360     break;
361   }
362   case anna::Exception::Mode::Trace: {
363     LOGWARNING(
364       const stack::Avp *stackAvp = getStackAvp(id, engine);
365       std::string msg = "Can't found Avp "; msg += stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id));
366       msg += anna::functions::asString(" with provided ocurrence (%d)", ocurrence);
367       anna::Logger::warning(msg, ANNA_FILE_LOCATION);
368     );
369     break;
370   }
371   case anna::Exception::Mode::Ignore: {
372     LOGDEBUG(
373       const stack::Avp *stackAvp = getStackAvp(id, engine);
374       std::string msg = "Can't found Avp "; msg += stackAvp ? (stackAvp->getName()) : (anna::diameter::functions::avpIdAsPairString(id));
375       msg += anna::functions::asString(" with provided ocurrence (%d)", ocurrence);
376       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
377     );
378     break;
379   }
380   }
381
382   return NULL;
383 }
384
385
386 //------------------------------------------------------------------------------
387 //--------------------------------------------------------------- Avp::_getAvp()
388 //------------------------------------------------------------------------------
389 const Avp *Avp::_getAvp(AvpId id, int ocurrence, anna::Exception::Mode::_v emode) const throw(anna::RuntimeException) {
390   // Dictionary stack avp and format (this):
391   const stack::Avp *stackAvp = getStackAvp();
392   const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
393
394   if(!stackFormat || !stackFormat->isGrouped())
395     throw anna::RuntimeException("This method only applies over grouped avps.", ANNA_FILE_LOCATION);
396
397   return getAvp(a_avps, (find_container&)a_finds, id, ocurrence, getEngine(), emode);
398 }
399
400
401 //------------------------------------------------------------------------------
402 //---------------------------------------------------------- Avp::assertFormat()
403 //------------------------------------------------------------------------------
404 void Avp::assertFormat(const std::string &name) const throw(anna::RuntimeException) {
405   // Dictionary stack avp and format:
406   const stack::Avp *stackAvp = getStackAvp();
407   const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
408   std::string format = stackFormat ? stackFormat->getName() : "Unknown";
409
410   if(format != name) {
411     std::string msg = "The Avp ";
412     msg += anna::diameter::functions::avpIdAsPairString(a_id);
413     msg += " with format '";
414     msg += format;
415     msg += "' is not compatible with the API method used (";
416     msg += name;
417     msg += ")";
418     throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
419   }
420 }
421
422
423 //------------------------------------------------------------------------------
424 //--------------------------------------------------------------- Avp::flagsOK()
425 //------------------------------------------------------------------------------
426 bool Avp::flagsOK() const throw() {
427   // Dictionary stack avp:
428   const stack::Avp *stackAvp = getStackAvp();
429
430   if(!stackAvp) {
431     anna::Logger::error("Impossible to decide if flags are correct because stack avp is not identified. Assume flags ok", ANNA_FILE_LOCATION);
432     return true;
433   };
434
435   // Assignments
436   bool Vnone = (stackAvp->getVbit() == stack::Avp::FlagRule::None);
437
438   bool Vmust = (stackAvp->getVbit() == stack::Avp::FlagRule::must);
439
440   bool Vmustnot = (stackAvp->getVbit() == stack::Avp::FlagRule::mustnot);
441
442   bool Mnone = (stackAvp->getMbit() == stack::Avp::FlagRule::None);
443
444   bool Mmust = (stackAvp->getMbit() == stack::Avp::FlagRule::must);
445
446   bool Mmustnot = (stackAvp->getMbit() == stack::Avp::FlagRule::mustnot);
447
448   bool Pnone = (stackAvp->getPbit() == stack::Avp::FlagRule::None);
449
450   bool Pmust = (stackAvp->getPbit() == stack::Avp::FlagRule::must);
451
452   bool Pmustnot = (stackAvp->getPbit() == stack::Avp::FlagRule::mustnot);
453
454   // V-bit
455   if((Vnone && Mnone && Pnone && vendorBit()) || (Vmust && !vendorBit()) || (Vmustnot && vendorBit())) {
456     anna::Logger::error("Vendor Bit (V) incoherence found", ANNA_FILE_LOCATION);
457     return false;
458   }
459
460   // Exit on permissive mode:
461   if(getEngine()->ignoreFlagsOnValidation()) return true;  // Ignore checking for AVP 'M' & 'P' bits
462
463   // M-bit
464   if((Mmust && !mandatoryBit()) || (Mmustnot && mandatoryBit())) {
465     anna::Logger::error("Mandatory Bit (M) incoherence found", ANNA_FILE_LOCATION);
466     return false;
467   }
468
469   // P-bit
470   if((Pmust && !encryptionBit()) || (Pmustnot && encryptionBit())) {
471     anna::Logger::error("Encryption Bit (P) incoherence found", ANNA_FILE_LOCATION);
472     return false;
473   }
474
475   // Reserved bits
476   if((a_flags & 0x1f) != 0x00) {
477     anna::Logger::error("Any (or more than one) of the reserved avp flags bit has been activated. Reserved bits must be null", ANNA_FILE_LOCATION);
478     return false;
479   }
480
481   return true;
482 }
483
484
485 //------------------------------------------------------------------------------
486 //----------------------------------------------------------------- Avp::setId()
487 //------------------------------------------------------------------------------
488 void Avp::setId(AvpId id) throw(anna::RuntimeException) {
489   // Generic AVP assignment has no sense
490   if(id == helpers::AVPID__AVP) return;
491
492   // Clear class content:
493   clear();
494   // Id assignment:
495   a_id = id;
496   // Dictionary stack avp and format:
497   const stack::Avp *stackAvp = getStackAvp(); // based on dictionary and a_id
498   const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
499
500   // Dictionary flags for known types:
501   if(stackAvp) {
502     if(stackAvp->getVbit() == stack::Avp::FlagRule::must) a_flags |= VBitMask;
503
504     if(stackAvp->getMbit() == stack::Avp::FlagRule::must) a_flags |= MBitMask;
505
506     if(stackAvp->getPbit() == stack::Avp::FlagRule::must) a_flags |= PBitMask;
507   } else {
508     if(a_id.second != 0) a_flags |= VBitMask; else a_flags &= (~VBitMask);
509   }
510
511   if(!stackFormat) {  // Unknown Avp
512     LOGDEBUG(
513       std::string msg = "Unknown format for AVP identifier ";
514       msg += anna::diameter::functions::avpIdAsPairString(id);
515       msg += ". Raw data without specific format will be managed";
516       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
517     );
518     a_Unknown = new Unknown();
519     return;
520   }
521
522   // Avp class formats (Avp child classes should implement this source code block for application-specific formats):
523   if(stackFormat->isOctetString()) a_OctetString = new OctetString();
524   else if(stackFormat->isInteger32()) a_Integer32 = new Integer32();
525   else if(stackFormat->isInteger64()) a_Integer64 = new Integer64();
526   else if(stackFormat->isUnsigned32()) a_Unsigned32 = new Unsigned32();
527   else if(stackFormat->isUnsigned64()) a_Unsigned64 = new Unsigned64();
528   else if(stackFormat->isFloat32()) a_Float32 = new Float32();
529   else if(stackFormat->isFloat64()) a_Float64 = new Float64();
530   //else if (stackFormat->isGrouped())
531   else if(stackFormat->isAddress()) a_Address = new Address();
532   else if(stackFormat->isTime()) a_Time = new Time();
533   else if(stackFormat->isUTF8String()) a_UTF8String = new UTF8String();
534   else if(stackFormat->isDiameterIdentity()) a_DiameterIdentity = new DiameterIdentity();
535   else if(stackFormat->isDiameterURI()) a_DiameterURI = new DiameterURI();
536   else if(stackFormat->isEnumerated()) a_Enumerated = new Enumerated();
537   else if(stackFormat->isIPFilterRule()) a_IPFilterRule = new IPFilterRule();
538   else if(stackFormat->isQoSFilterRule()) a_QoSFilterRule = new QoSFilterRule();
539
540   /////////////////////
541   // Format specific //
542   /////////////////////
543   allocationByFormat(stackFormat);
544 }
545
546
547 //------------------------------------------------------------------------------
548 //----------------------------------------------------------------- Avp::setId()
549 //------------------------------------------------------------------------------
550 void Avp::setId(const char *name) throw(anna::RuntimeException) {
551   setId(getEngine()->avpIdForName(name));
552 }
553
554
555 //------------------------------------------------------------------------------
556 //---------------------------------------------------------------- Avp::addAvp()
557 //------------------------------------------------------------------------------
558 Avp * Avp::addAvp(const char *name) throw(anna::RuntimeException) {
559   return addAvp(getEngine()->avpIdForName(name));
560 }
561
562
563 //------------------------------------------------------------------------------
564 //------------------------------------------------------------- Avp::removeAvp()
565 //------------------------------------------------------------------------------
566 bool Avp::removeAvp(const char *name, int ocurrence) throw(anna::RuntimeException) {
567   return removeAvp(getEngine()->avpIdForName(name), ocurrence);
568 }
569
570
571 //------------------------------------------------------------------------------
572 //--------------------------------------------------------------- Avp::_getAvp()
573 //------------------------------------------------------------------------------
574 const Avp *Avp::_getAvp(const char *name, int ocurrence, anna::Exception::Mode::_v emode) const throw(anna::RuntimeException) {
575   return getAvp(getEngine()->avpIdForName(name), ocurrence, emode);
576 }
577
578
579 //------------------------------------------------------------------------------
580 //-------------------------------------------------------------- Avp::countAvp()
581 //------------------------------------------------------------------------------
582 int Avp::countAvp(const char *name) const throw(anna::RuntimeException) {
583   return countAvp(getEngine()->avpIdForName(name));
584 }
585
586 //------------------------------------------------------------------------------
587 //------------------------------------------------------------- Avp::getLength()
588 //------------------------------------------------------------------------------
589 U24 Avp::getLength() const throw() {
590   U24 result;
591   // Avp format:
592   const stack::Avp *stackAvp = getStackAvp();
593   const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
594   // Header length:
595   result = vendorBit() ? HeaderLengthVactive : HeaderLengthVinactive;
596
597   if(!stackFormat) {
598     result += a_Unknown->getSize();
599     return result;
600   }
601
602   if(stackFormat->isOctetString()) result += a_OctetString->getSize();
603   else if(stackFormat->isInteger32()) result += a_Integer32->getSize();
604   else if(stackFormat->isInteger64()) result += a_Integer64->getSize();
605   else if(stackFormat->isUnsigned32()) result += a_Unsigned32->getSize();
606   else if(stackFormat->isUnsigned64()) result += a_Unsigned64->getSize();
607   else if(stackFormat->isFloat32()) result += a_Float32->getSize();
608   else if(stackFormat->isFloat64()) result += a_Float64->getSize();
609   else if(stackFormat->isGrouped()) for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) result += 4 * REQUIRED_WORDS(avp(it)->getLength());
610   else if(stackFormat->isAddress()) result += a_Address->getSize();
611   else if(stackFormat->isTime()) result += a_Time->getSize();
612   else if(stackFormat->isUTF8String()) result += a_UTF8String->getSize();
613   else if(stackFormat->isDiameterIdentity()) result += a_DiameterIdentity->getSize();
614   else if(stackFormat->isDiameterURI()) result += a_DiameterURI->getSize();
615   else if(stackFormat->isEnumerated()) result += a_Enumerated->getSize();
616   else if(stackFormat->isIPFilterRule()) result += a_IPFilterRule->getSize();
617   else if(stackFormat->isQoSFilterRule()) result += a_QoSFilterRule->getSize();
618
619   /////////////////////
620   // Format specific //
621   /////////////////////
622   result += getLengthByFormat(stackFormat);
623   return result;
624 }
625
626
627 //------------------------------------------------------------------------------
628 //-------------------------------------------- Avp::unknownAvpWithMandatoryBit()
629 //------------------------------------------------------------------------------
630 void Avp::unknownAvpWithMandatoryBit() const throw(anna::RuntimeException) {
631   OamModule &oamModule = OamModule::instantiate();
632   const char *c_aid = STRING_WITH_QUOTATION_MARKS__C_STR(anna::diameter::functions::avpIdAsPairString(a_id));
633   oamModule.activateAlarm(OamModule::Alarm::AvpDecode__UnknownAvp__s__WithMandatoryBit, c_aid);
634   oamModule.count(OamModule::Counter::AvpDecode__UnknownAvpWithMandatoryBit);
635   LOGWARNING(
636     std::string msg = anna::functions::asString("Detected unknown Avp %s with mandatory bit activated", c_aid);
637     anna::Logger::warning(msg, ANNA_FILE_LOCATION);
638   );
639 }
640
641 //------------------------------------------------------------------------------
642 //-------------------------------------------------------- Avp::decodeDataPart()
643 //------------------------------------------------------------------------------
644 void Avp::decodeDataPart(const char * buffer, int size, const parent_t & parent, Message *answer) throw(anna::RuntimeException) {
645   // OAM
646   OamModule &oamModule = OamModule::instantiate();
647   // Dictionary stack avp and format:
648   const stack::Avp *stackAvp = getStackAvp();
649   const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
650
651   if(!stackFormat) {
652     a_Unknown->decode(buffer, size);
653     return;
654   }
655
656   if(stackFormat->isOctetString()) a_OctetString->decode(buffer, size);
657   else if(stackFormat->isInteger32()) a_Integer32->decode(buffer, size);
658   else if(stackFormat->isInteger64()) a_Integer64->decode(buffer, size);
659   else if(stackFormat->isUnsigned32()) a_Unsigned32->decode(buffer, size);
660   else if(stackFormat->isUnsigned64()) a_Unsigned64->decode(buffer, size);
661   else if(stackFormat->isFloat32()) a_Float32->decode(buffer, size);
662   else if(stackFormat->isFloat64()) a_Float64->decode(buffer, size);
663   else if(stackFormat->isGrouped()) {
664     if(size == 0) {
665       LOGDEBUG(anna::Logger::debug("Grouped Avp has empty data part", ANNA_FILE_LOCATION));
666       return;
667     }
668
669     if((size % 4) != 0) {
670       oamModule.activateAlarm(OamModule::Alarm::AvpDecode__IncorrectLength);
671       oamModule.count(OamModule::Counter::AvpDecode__IncorrectLength);
672
673       if(answer) {
674         answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_AVP_LENGTH);
675         answer->setFailedAvp(parent, a_id);
676       }
677
678       throw anna::RuntimeException("Avp format error, the avp length is incorrect (must be multiple of 4 on grouped type)", ANNA_FILE_LOCATION);
679     }
680
681     int avpPos = 0;
682     Avp* avp;
683     anna::DataBlock db;
684     // Me as parent:
685     parent_t me = parent;
686     me.addAvp(a_id);
687
688     while(avpPos < size) {
689       try {
690         avp = getEngine()->createAvp(NULL);
691         db.assign(buffer + avpPos, size - avpPos /* is valid to pass total size (indeed i don't know the real avp size) because it will be limited and this has deep copy disabled (no memory is reserved) */);
692         avp -> decode(db, me, answer);
693       } catch(anna::RuntimeException &ex) {
694         getEngine()->releaseAvp(avp);
695         throw;
696       }
697
698       addChild(avp);
699       avpPos += 4 * REQUIRED_WORDS(avp->getLength());
700     }
701   } else if(stackFormat->isAddress()) a_Address->decode(buffer, size);
702   else if(stackFormat->isTime()) a_Time->decode(buffer, size);
703   else if(stackFormat->isUTF8String()) a_UTF8String->decode(buffer, size);
704   else if(stackFormat->isDiameterIdentity()) a_DiameterIdentity->decode(buffer, size);
705   else if(stackFormat->isDiameterURI()) a_DiameterURI->decode(buffer, size);
706   else if(stackFormat->isEnumerated()) a_Enumerated->decode(buffer, size);
707   else if(stackFormat->isIPFilterRule()) a_IPFilterRule->decode(buffer, size);
708   else if(stackFormat->isQoSFilterRule()) a_QoSFilterRule->decode(buffer, size);
709
710   /////////////////////
711   // Format specific //
712   /////////////////////
713   decodeDataPartByFormat(buffer, size, stackFormat);
714 }
715
716 //------------------------------------------------------------------------------
717 //---------------------------------------------------------------- Avp::decode()
718 //------------------------------------------------------------------------------
719 void Avp::decode(const anna::DataBlock &db, const parent_t & parent, Message *answer) throw(anna::RuntimeException) {
720   // OAM
721   OamModule &oamModule = OamModule::instantiate();
722
723   if(db.getSize() < HeaderLengthVinactive) {
724     oamModule.activateAlarm(OamModule::Alarm::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength);
725     oamModule.count(OamModule::Counter::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength);
726     // DIAMETER_INVALID_AVP_LENGTH; // no podr� construir un avp fiable, as� que no registro el result-code
727     throw anna::RuntimeException("Not enough bytes to cover avp header length", ANNA_FILE_LOCATION);
728   }
729
730   const char * buffer = db.getData();
731
732   //       0                   1                   2                   3
733   //       0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
734   //      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
735   //      |                           AVP Code                            |
736   //      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
737   //      |   AVP Flags   |                  AVP Length                   |
738   //      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
739   //      |                        Vendor-ID (opt)                        |
740   //      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
741   //      |    Data ...
742   //      +-+-+-+-+-+-+-+-+
743   // Code flags and vendor-id
744   U32 code = DECODE4BYTES_INDX_VALUETYPE(buffer, 0, U32);
745
746   a_flags = (S8)buffer[4];
747
748   U32 vendorID = helpers::VENDORID__base;
749
750   if(vendorBit()) {
751     if(db.getSize() < HeaderLengthVactive) {
752       oamModule.activateAlarm(OamModule::Alarm::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength);
753       oamModule.count(OamModule::Counter::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength);
754       // DIAMETER_INVALID_AVP_LENGTH; // no podr� construir un avp fiable, as� que no registro el result-code
755       throw anna::RuntimeException(anna::functions::asString("Not enough bytes to cover avp header length (avp code = %u)", code), ANNA_FILE_LOCATION);
756     }
757
758     vendorID = DECODE4BYTES_INDX_VALUETYPE(buffer, 8, U32);
759
760     if(vendorID == helpers::VENDORID__base) {
761       //      A vendor ID value of zero (0) corresponds to the IETF adopted AVP
762       //      values, as managed by the IANA. Since the absence of the vendor
763       //      ID field implies that the AVP in question is not vendor specific,
764       //      ...
765       //      implementations MUST NOT use the zero (0) vendor ID.
766       oamModule.activateAlarm(OamModule::Alarm::AvpDecode__IncoherenceBetweenActivatedVBitAndZeroedVendorIDValueReceived);
767       oamModule.count(OamModule::Counter::AvpDecode__IncoherenceBetweenActivatedVBitAndZeroedVendorIDValueReceived);
768       throw anna::RuntimeException(anna::functions::asString("Incoherence between activated V bit and zeroed vendor-id value received (avp code = %u)", code), ANNA_FILE_LOCATION);
769     }
770   }
771
772   // Avp identifier
773   setId(AvpId(code, vendorID));
774   // Flags could have been updated regarding dictionary, but during decoding we must respect buffer received:
775   a_flags = (S8)buffer[4];
776
777   // Here i know id and flags:
778   //   The 'M' Bit, known as the Mandatory bit, indicates whether support of the AVP is required. If an AVP with the 'M' bit set is received by
779   //   a Diameter client, server, proxy, or translation agent and either the AVP or its value is unrecognized, the message MUST be rejected.
780   //   Diameter Relay and redirect agents MUST NOT reject messages with unrecognized AVPs.
781   if(!getStackAvp() && mandatoryBit()) {
782     if(answer) {
783       answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_AVP_UNSUPPORTED);
784       answer->setFailedAvp(parent, a_id);
785     }
786
787     unknownAvpWithMandatoryBit();
788   }
789
790   // Avp Length
791   U24 length = DECODE3BYTES_INDX_VALUETYPE(buffer, 5, U24);
792   // Data start position:
793   int startDataPos = vendorBit() ? HeaderLengthVactive : HeaderLengthVinactive;
794   // Data part:
795   int dataBytes = length - startDataPos;
796
797   if(dataBytes < 0) {
798     oamModule.activateAlarm(OamModule::Alarm::AvpDecode__IncorrectLength);
799     oamModule.count(OamModule::Counter::AvpDecode__IncorrectLength);
800
801     if(answer) {
802       answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_AVP_LENGTH);
803       answer->setFailedAvp(parent, a_id);
804     }
805
806     throw anna::RuntimeException(anna::functions::asString("Avp format error, the avp length is incorrect (avp code = %u)", code), ANNA_FILE_LOCATION);
807   }
808
809   try {
810     decodeDataPart(buffer + startDataPos, dataBytes, parent, answer);
811   } catch(anna::RuntimeException &ex) {
812     oamModule.activateAlarm(OamModule::Alarm::AvpDecode__DataPartInconsistence);
813     oamModule.count(OamModule::Counter::AvpDecode__DataPartInconsistence);
814
815     if(answer) {
816       answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_AVP_VALUE);
817       answer->setFailedAvp(parent, a_id);
818     }
819
820     throw anna::RuntimeException(anna::functions::asString("Internal Avp decoding error (avp code = %u): %s", code, ex.getText().c_str()), ANNA_FILE_LOCATION);
821   }
822 }
823
824
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);
831 }
832
833
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() {
838   // Exit cases
839   if(avps.size() == 0) return;  // empty content, nothing to fix
840
841   if(ruleBegin == ruleEnd) return;  // no reference. Cannot fix
842
843   // Copy reference container and clear internal map in order to build a fixed version:
844   avp_container unfixedAvps;
845
846   for(const_avp_iterator it = avps.begin(); it != avps.end(); it++)
847     unfixedAvps[(*it).first] = (*it).second;
848
849   avps.clear();
850   // Cache system reset (fix probably will invalidate cached findings):
851   finds.clear();
852   insertionPositionForChilds = 0;
853   avp_iterator avp_it;
854   Avp * avp;
855
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
861     }
862   }
863
864   // Add remaining avps:
865   for(avp_it = unfixedAvps.begin(); avp_it != unfixedAvps.end(); avp_it++) {
866     avp = (*avp_it).second;
867
868     if(avp) addChild(avps, insertionPositionForChilds, avp);
869   }
870
871   // Fix grouped Avps:
872   for(avp_iterator it = avps.begin(); it != avps.end(); it++) {
873     avp = (*it).second;
874
875     if(avp->hasChildren()) avp->fix();
876   }
877 }
878
879
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*/;
887
888   if(!stackAvp) {
889     //LOGDEBUG(anna::Logger::debug("No dictionary avp reference found. Cannot fix.", ANNA_FILE_LOCATION));
890     return;
891   }
892
893   if(!stackFormat || !stackFormat->isGrouped()) {
894     //LOGDEBUG(anna::Logger::debug("Avp is not grouped. Nothing to fix.", ANNA_FILE_LOCATION));
895     return;
896   }
897
898   fix(a_avps, (find_container&)a_finds, a_insertionPositionForChilds, stackAvp->avprule_begin(), stackAvp->avprule_end());
899 }
900
901
902 //------------------------------------------------------------------------------
903 //------------------------------------------------------------ Avp::validLevel()
904 //------------------------------------------------------------------------------
905 bool Avp::validLevel(const avp_container &avps, anna::diameter::stack::const_avprule_iterator ruleBegin, anna::diameter::stack::const_avprule_iterator ruleEnd, Engine * engine, const parent_t & parent, Message *answer) throw(anna::RuntimeException) {
906   bool result = true;
907   // OAM
908   OamModule &oamModule = OamModule::instantiate();
909   ///////////
910   // Fixed //
911   ///////////
912   // auxiliary
913   AvpId id;
914   const_avp_iterator avp_it = avps.begin();
915   anna::diameter::stack::const_avprule_iterator rule_it;
916   bool okFixed;
917
918   for(rule_it = ruleBegin; rule_it != ruleEnd; rule_it++) {
919     okFixed = true;
920
921     if((*rule_it).second.isFixed()) {
922       if(avps.size() == 0) break;  // cardinality checking will show this anomaly
923
924       if(avp_it != avps.end()) {
925         id = Avp::avp(avp_it)->getId();
926
927         if(id != (*rule_it).second.getId()) {
928           okFixed = false;
929           // Missing fixed rule: %s
930         } else if(Avp::avp_find(avps, id, 2) != avps.end()) {
931           okFixed = false;
932           // More than one fixed ocurrency for rule %s (*)
933         }
934
935         avp_it++;
936         // (*) for (int k = 0; k < (*rule_it).second.getQualMax(); k++) avp_it++
937       } else
938         okFixed = false;
939
940       if(!okFixed) {
941         result = false;
942         // OAM & Depth management
943         oamModule.activateAlarm(OamModule::Alarm::LevelValidation__MissingFixedRule__s__Inside__s__, STRING_WITH_QUOTATION_MARKS__C_STR((*rule_it).second.asString(false /*ommit dots & pair*/)), STRING_WITH_QUOTATION_MARKS__C_STR(parent.asString()));
944         oamModule.count(OamModule::Counter::LevelValidation__MissingFixedRule);
945
946         if(answer) {
947           answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_MISSING_AVP);
948           answer->setFailedAvp(parent, (*rule_it).second.getId());
949         }
950
951         engine->validationAnomaly(anna::functions::asString("Missing fixed rule %s inside %s", STRING_WITH_QUOTATION_MARKS__C_STR((*rule_it).second.asString(false /*ommit dots & pair*/)), STRING_WITH_QUOTATION_MARKS__C_STR(parent.asString())));
952       }
953     } else break; // finish fixed
954   }
955
956   /////////////////
957   // Cardinality // Mandatory control is implicit here
958   /////////////////
959   anna::diameter::stack::const_avprule_iterator generic_rule_it = ruleEnd;
960   int min, max, amount;
961
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
964
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);
969
970     if((amount < min) || ((max != -1) && (amount > max))) {
971       // Failed rule %s for cardinality (found %d items)
972       result = false;
973       // OAM & Depth management
974       oamModule.activateAlarm(OamModule::Alarm::LevelValidation__FailedRule__s__ForCardinality_Found__d__ItemsInside__s__, STRING_WITH_QUOTATION_MARKS__C_STR((*rule_it).second.asString(false /*ommit dots & pair*/)), amount, STRING_WITH_QUOTATION_MARKS__C_STR(parent.asString()));
975       oamModule.count(OamModule::Counter::LevelValidation__FailedRuleForCardinality);
976
977       if(amount < min) {
978         oamModule.count(OamModule::Counter::LevelValidation__FailedRuleForCardinalityLessThanNeeded);
979
980         if(answer) {
981           answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_MISSING_AVP);
982           answer->setFailedAvp(parent, id);
983         }
984       } else {
985         oamModule.count(OamModule::Counter::LevelValidation__FailedRuleForCardinalityMoreThanNeeded);
986
987         if(answer) {
988           answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_AVP_OCCURS_TOO_MANY_TIMES);
989           answer->setFailedAvp(parent, id);
990         }
991       }
992
993       engine->validationAnomaly(anna::functions::asString("Failed rule %s for cardinality (found %d items inside %s)", STRING_WITH_QUOTATION_MARKS__C_STR((*rule_it).second.asString(false /*ommit dots & pair*/)), amount, STRING_WITH_QUOTATION_MARKS__C_STR(parent.asString())));
994     }
995   }
996
997   bool haveGeneric = (generic_rule_it != ruleEnd);
998   /////////////////
999   // Generic AVP //
1000   /////////////////
1001   bool foundInRules;
1002   std::map < AvpId, int /* dummy */ > disregarded; // 'Disregardeds' are Avps not in rules list
1003   std::map < AvpId, int /* dummy */ >::const_iterator disregarded_it;
1004
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;
1009
1010     for(rule_it = ruleBegin; rule_it != ruleEnd; rule_it++) {
1011       if((*rule_it).second.getId() == id) {
1012         foundInRules = true;
1013         break;
1014       }
1015     }
1016
1017     if(!foundInRules) {
1018       disregarded[id] = 0;
1019     }
1020   }
1021
1022   // Generic AVP cardinality checkings
1023   int disregardeds = disregarded.size();
1024
1025   if(haveGeneric) {
1026     min = (*generic_rule_it).second.getQualMin();
1027     max = (*generic_rule_it).second.getQualMax(); // -1 means infinite
1028     amount = disregardeds;
1029
1030     if((amount < min) || ((max != -1) && (amount > max))) {
1031       // Failed Generic AVP rule %s for cardinality (found %d disregarded items inside %s)
1032       result = false;
1033       // OAM & Depth management
1034       oamModule.activateAlarm(OamModule::Alarm::LevelValidation__FailedGenericAvpRule__s__ForCardinality_Found__d__DisregardedItemsInside__s__, STRING_WITH_QUOTATION_MARKS__C_STR((*generic_rule_it).second.asString(false /*ommit dots & pair*/)), amount, STRING_WITH_QUOTATION_MARKS__C_STR(parent.asString()));
1035       oamModule.count(OamModule::Counter::LevelValidation__FailedGenericAvpRuleForCardinalityFoundDisregardedItem);
1036
1037       if(answer) {
1038         answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_AVP_NOT_ALLOWED);
1039         answer->setFailedAvp(parent, id); // NO SENSE... what to put ?
1040       }
1041
1042       engine->validationAnomaly(anna::functions::asString("Failed Generic AVP rule %s for cardinality (found %d disregarded items inside %s)", STRING_WITH_QUOTATION_MARKS__C_STR((*generic_rule_it).second.asString(false /*ommit dots & pair*/)), amount, STRING_WITH_QUOTATION_MARKS__C_STR(parent.asString())));
1043     }
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
1046     result = false;
1047     // Build disregarded list as string (unknown as avp id pair):
1048     std::string s_disregardeds = "";
1049     const stack::Avp *stackAvp;
1050
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 += ", ";
1056
1057       // We wouldn't know where are these disregarded, but...
1058       if(answer) {
1059         answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_AVP_NOT_ALLOWED);
1060         answer->setFailedAvp(parent, id);
1061       }
1062     }
1063
1064     s_disregardeds.erase(s_disregardeds.size() - 2, 2); // remove last ', '
1065     // OAM & Depth management
1066     oamModule.activateAlarm(OamModule::Alarm::LevelValidation__FoundDisregardedItemsInside__s__AndGenericAVPWasNotSpecified__s__, STRING_WITH_QUOTATION_MARKS__C_STR(parent.asString()), STRING_WITH_QUOTATION_MARKS__C_STR(s_disregardeds));
1067     oamModule.count(OamModule::Counter::LevelValidation__FoundDisregardedItemsAndGenericAVPWasNotSpecified);
1068     engine->validationAnomaly(anna::functions::asString("Found disregarded items inside %s and Generic AVP was not specified: %s", STRING_WITH_QUOTATION_MARKS__C_STR(parent.asString()), STRING_WITH_QUOTATION_MARKS__C_STR(s_disregardeds)));
1069   }
1070
1071   return result;
1072 }
1073
1074
1075 //------------------------------------------------------------------------------
1076 //----------------------------------------------------------------- Avp::valid()
1077 //------------------------------------------------------------------------------
1078 bool Avp::valid(const parent_t & parent, Message *answer) const throw(anna::RuntimeException) {
1079   // OAM
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*/;
1084
1085   if(!stackAvp) {
1086     // No dictionary avp reference found. Cannot validate
1087     return true; // perhaps a unknown Avp
1088   }
1089
1090   // Me as parent:
1091   parent_t me = parent;
1092   me.addAvp(a_id, stackAvp->getName().c_str());
1093
1094   if(!stackFormat) {
1095     // No format avp reference found. Cannot validate
1096     return true; // perhaps a unknown Avp
1097   }
1098
1099   //////////////////////////////
1100   // Flags coherence checking //
1101   //////////////////////////////
1102   bool result = flagsOK();
1103
1104   if(!result) {
1105     // OAM & Depth management
1106     oamModule.activateAlarm(OamModule::Alarm::AvpValidation__Avp__s__Flags__d__DoesNotFulfillTheDefinedFlagRules__s__, STRING_WITH_QUOTATION_MARKS__C_STR(me.asString()), (int)a_flags, STRING_WITH_QUOTATION_MARKS__C_STR(stackAvp->getFlagRulesDescription()));
1107     oamModule.count(OamModule::Counter::AvpValidation__AvpFlagsDoesNotFulfillTheDefinedFlagRules);
1108
1109     if(answer) {
1110       answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_AVP_BITS);
1111       answer->setFailedAvp(parent, a_id, stackAvp->getName().c_str()); // RFC 6733 says nothing about Failed-AVP in this case...
1112     }
1113
1114     getEngine()->validationAnomaly(anna::functions::asString("The AVP %s flags (%d) does not fulfill the defined flag rules: %s", STRING_WITH_QUOTATION_MARKS__C_STR(me.asString()), (int)a_flags, STRING_WITH_QUOTATION_MARKS__C_STR(stackAvp->getFlagRulesDescription())));
1115   }
1116
1117   //////////////////////
1118   // Enumerated range //
1119   //////////////////////
1120   if(stackFormat->isEnumerated()) {
1121     if(!stackAvp->allowEnum(a_Enumerated->getValue())) {
1122       result = false;
1123       // OAM & Depth management
1124       oamModule.activateAlarm(OamModule::Alarm::AvpValidation__EnumeratedAvp__s__WithValue__d__DoesNotComplyRestriction__s__, STRING_WITH_QUOTATION_MARKS__C_STR(me.asString()), a_Enumerated->getValue(), stackAvp->getEnums());
1125       oamModule.count(OamModule::Counter::AvpValidation__EnumeratedAvpWithValueDoesNotComplyRestriction);
1126
1127       if(answer) {
1128         answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_INVALID_AVP_VALUE);
1129         answer->setFailedAvp(parent, a_id, stackAvp->getName().c_str());
1130       }
1131
1132       getEngine()->validationAnomaly(anna::functions::asString("Enumerated AVP %s with value %d does not comply to restriction: %s", STRING_WITH_QUOTATION_MARKS__C_STR(me.asString()), a_Enumerated->getValue(), stackAvp->getEnums()));
1133     }
1134   }
1135
1136   ////////////////////
1137   // Level checking //
1138   ////////////////////
1139   result = Avp::validLevel(a_avps, stackAvp->avprule_begin(), stackAvp->avprule_end(), getEngine(), me, answer) && result;
1140
1141   ////////////////////////
1142   // Childrens checking //
1143   ////////////////////////
1144   if(a_id == helpers::base::AVPID__Failed_AVP) return result;  // DON'T VALIDATE CONTENT FOR Failed-AVP, because it won't be valid...
1145
1146   for(const_avp_iterator it = avp_begin(); it != avp_end(); it++)
1147     result = ((*it).second->valid(me, answer)) && result;
1148
1149   return result;
1150 }
1151
1152
1153 //------------------------------------------------------------------------------
1154 //------------------------------------------------------------------ Avp::code()
1155 //------------------------------------------------------------------------------
1156 void Avp::code(char* buffer, int &size) const throw(anna::RuntimeException) {
1157   // Code
1158   buffer[0] = (S8)(a_id.first >> 24);
1159   buffer[1] = (S8)(a_id.first >> 16);
1160   buffer[2] = (S8)(a_id.first >> 8);
1161   buffer[3] = (S8) a_id.first;
1162   // Flags and length
1163   size = getLength();
1164   buffer[4] = (S8) a_flags;
1165   buffer[5] = (S8)(size >> 16);
1166   buffer[6] = (S8)(size >> 8);
1167   buffer[7] = (S8) size;
1168
1169   // Vendor-id
1170   if(vendorBit()) {
1171     buffer[8] = (S8)(a_id.second >> 24);
1172     buffer[9] = (S8)(a_id.second >> 16);
1173     buffer[10] = (S8)(a_id.second >> 8);
1174     buffer[11] = (S8) a_id.second;
1175   }
1176
1177   // Data start position:
1178   int startDataPos = vendorBit() ? HeaderLengthVactive : HeaderLengthVinactive;
1179   // Data part:
1180   S8 * dataPart = buffer + startDataPos;
1181   int dataBytes; // not used but could be useful for checking (size - startDataPos)
1182
1183   if(startDataPos == size) {
1184     LOGDEBUG(anna::Logger::debug("There is no data part to encode", ANNA_FILE_LOCATION));
1185     return;
1186   }
1187
1188   // Avp format:
1189   const stack::Avp *stackAvp = getStackAvp();
1190   const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
1191
1192   if(!stackFormat) {
1193     a_Unknown->code(dataPart, dataBytes);
1194     return;
1195   }
1196
1197   if(stackFormat->isOctetString()) a_OctetString->code(dataPart, dataBytes);
1198   else if(stackFormat->isInteger32()) a_Integer32->code(dataPart, dataBytes);
1199   else if(stackFormat->isInteger64()) a_Integer64->code(dataPart, dataBytes);
1200   else if(stackFormat->isUnsigned32()) a_Unsigned32->code(dataPart, dataBytes);
1201   else if(stackFormat->isUnsigned64()) a_Unsigned64->code(dataPart, dataBytes);
1202   else if(stackFormat->isFloat32()) a_Float32->code(dataPart, dataBytes);
1203   else if(stackFormat->isFloat64()) a_Float64->code(dataPart, dataBytes);
1204   else if(stackFormat->isGrouped()) {
1205 //      // Each avp encoding will remain padding octets depending on format. In order to
1206 //      //  code grouped content (each avp will be multiple of 4) we clean the entire buffer
1207 //      //  to ensure padding (easier than custom-made for each format):
1208 //      memset(dataPart, 0, size - startDataPos);
1209     char *dataPartGrouped = dataPart;
1210     int dataBytesGrouped;
1211
1212     for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) {
1213       avp(it)->code(dataPartGrouped, dataBytesGrouped);
1214       dataPartGrouped = dataPartGrouped + 4 * REQUIRED_WORDS(dataBytesGrouped);
1215     }
1216   } else if(stackFormat->isAddress()) a_Address->code(dataPart, dataBytes);
1217   else if(stackFormat->isTime()) a_Time->code(dataPart, dataBytes);
1218   else if(stackFormat->isUTF8String()) a_UTF8String->code(dataPart, dataBytes);
1219   else if(stackFormat->isDiameterIdentity()) a_DiameterIdentity->code(dataPart, dataBytes);
1220   else if(stackFormat->isDiameterURI()) a_DiameterURI->code(dataPart, dataBytes);
1221   else if(stackFormat->isEnumerated()) a_Enumerated->code(dataPart, dataBytes);
1222   else if(stackFormat->isIPFilterRule()) a_IPFilterRule->code(dataPart, dataBytes);
1223   else if(stackFormat->isQoSFilterRule()) a_QoSFilterRule->code(dataPart, dataBytes);
1224
1225   /////////////////////
1226   // Format specific //
1227   /////////////////////
1228   codeByFormat(dataPart, stackFormat);
1229 }
1230
1231
1232 //------------------------------------------------------------------------------
1233 //------------------------------------------------------------ Avp::getXMLdata()
1234 //------------------------------------------------------------------------------
1235 std::string Avp::getXMLdata(bool & isHex, const stack::Format *stackFormat) const throw() {
1236   std::string result = "";
1237   isHex = false;
1238   // Unknown
1239 //   try {
1240 //      if (!stackFormat) {
1241 //         isHex = true;
1242 //         return a_Unknown->asHexString();
1243 //      }
1244 //   } catch (anna::RuntimeException &ex) {
1245 //      ex.trace();
1246 //   }
1247
1248   if(!stackFormat) {
1249     isHex = true;
1250     // Tricky situation: if you change the dictionary dynamically, and a previous formatted avp
1251     //  becomes unknown (the change consists in remove Avps basically), then this would get a core
1252     //  dump: a_Unknown = NULL. We are not going to protect that situation because it represents a
1253     //  implementation fault, and there are many points which could have similar bad behaviour
1254     //  (those where we access directly the a_Unknown pointer).
1255     // The best way to afford this is ... TODO:
1256     // Freeze dictionary after use from any resource (avp, message), setting a flag which deny
1257     //  any modification in such dictionary. The best way to do this is on engine configuration
1258     //  for Avp o Message, where we could  invoke something like getEngine()->getDictionary()->freeze()
1259
1260     return a_Unknown->asHexString(); // asHexString for OctetString cannot launch exception
1261   }
1262
1263   // Special case for Address: could launch exception if not printable
1264   try {
1265     if(stackFormat->isAddress()) return a_Address->asPrintableString();
1266   } catch(anna::RuntimeException&) {
1267     //ex.trace();
1268     isHex = true;
1269     return a_Address->asHexString();
1270   }
1271
1272   try {
1273     if(stackFormat->isOctetString()) {
1274       isHex = true;
1275       return a_OctetString->asHexString();
1276     }
1277
1278     // Non-hexadecimal
1279     if(stackFormat->isInteger32()) return a_Integer32->asPrintableString();
1280
1281     if(stackFormat->isInteger64()) return a_Integer64->asPrintableString();
1282
1283     if(stackFormat->isUnsigned32()) return a_Unsigned32->asPrintableString();
1284
1285     if(stackFormat->isUnsigned64()) return a_Unsigned64->asPrintableString();
1286
1287     if(stackFormat->isFloat32()) return a_Float32->asPrintableString();
1288
1289     if(stackFormat->isFloat64()) return a_Float64->asPrintableString();
1290
1291     //if (stackFormat->isAddress()) return a_Address->asPrintableString();
1292
1293     if(stackFormat->isTime()) return a_Time->asPrintableString();
1294
1295     if(stackFormat->isUTF8String()) return a_UTF8String->asPrintableString();
1296
1297     if(stackFormat->isDiameterIdentity()) return a_DiameterIdentity->asPrintableString();
1298
1299     if(stackFormat->isDiameterURI()) return a_DiameterURI->asPrintableString();
1300
1301     if(stackFormat->isEnumerated()) return a_Enumerated->asPrintableString();
1302
1303     if(stackFormat->isIPFilterRule()) return a_IPFilterRule->asPrintableString();
1304
1305     if(stackFormat->isQoSFilterRule()) return a_QoSFilterRule->asPrintableString();
1306
1307     /////////////////////
1308     // Format specific //
1309     /////////////////////
1310     return getXMLdataByFormat(isHex, stackFormat);
1311   } catch(anna::RuntimeException &ex) {
1312     ex.trace();
1313   }
1314
1315   return result;
1316 }
1317
1318
1319 //------------------------------------------------------------------------------
1320 //---------------------------------------------------------------- Avp::decode()
1321 //------------------------------------------------------------------------------
1322 void Avp::decode(const anna::DataBlock &db) throw(anna::RuntimeException) {
1323   parent_t parent;
1324   parent.setMessage(CommandId(0, false), "No-Parent");
1325   decode(db, parent, NULL);
1326 }
1327
1328
1329 //------------------------------------------------------------------------------
1330 //--------------------------------------------------------------- Avp::fromXML()
1331 //------------------------------------------------------------------------------
1332 void Avp::fromXML(const anna::xml::Node* avpNode) throw(anna::RuntimeException) {
1333   // <!ATTLIST avp id CDATA #IMPLIED code CDATA #IMPLIED vendor-code CDATA #IMPLIED flags CDATA #IMPLIED data CDATA #IMPLIED hex-data CDATA #IMPLIED>
1334   const anna::xml::Attribute *name, *code, *vendorCode, *flags, *data, *hexData;
1335   name = avpNode->getAttribute("name", false /* no exception */);
1336   code = avpNode->getAttribute("code", false /* no exception */);
1337   vendorCode = avpNode->getAttribute("vendor-code", false /* no exception */);
1338   flags = avpNode->getAttribute("flags", false /* no exception */);
1339   data = avpNode->getAttribute("data", false /* no exception */);
1340   hexData = avpNode->getAttribute("hex-data", false /* no exception */);
1341   // Dictionary
1342   const stack::Dictionary * dictionary = getEngine()->getDictionary();
1343   const stack::Avp *stackAvp = NULL;
1344   const stack::Format *stackFormat = NULL;
1345
1346   // Compact mode
1347   if(name) {
1348     if(!dictionary) {
1349       std::string msg = "Error processing avp <name '"; msg += name->getValue();
1350       msg += "'>: no dictionary available. Load one or use <'code' + 'flags' + 'vendorCode'> instead of <'name'>";
1351       throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1352     }
1353
1354     stackAvp = dictionary->getAvp(name->getValue());
1355
1356     if(!stackAvp) {
1357       std::string msg = "Error processing avp <name '"; msg += name->getValue();
1358       msg += "'>: no avp found for this identifier at available dictionary";
1359       throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1360     }
1361
1362     stackFormat = stackAvp->getFormat();
1363   }
1364
1365   // Check attributes exclusiveness
1366   if(name) {  // compact mode
1367     bool allowFlagsField = ( stackAvp->getVbit() == anna::diameter::stack::Avp::FlagRule::may || stackAvp->getVbit() == anna::diameter::stack::Avp::FlagRule::shouldnot
1368                              || stackAvp->getMbit() == anna::diameter::stack::Avp::FlagRule::may || stackAvp->getMbit() == anna::diameter::stack::Avp::FlagRule::shouldnot
1369                              /* umm, perhaps we could omit for bit P, whic is deprecated ... */
1370                              /* || stackAvp->getPbit() == anna::diameter::stack::Avp::FlagRule::may || stackAvp->getPbit() == anna::diameter::stack::Avp::FlagRule::shouldnot*/ );
1371     if(code || (flags && !allowFlagsField) || vendorCode) {
1372       std::string msg = "Error processing avp <name '"; msg += name->getValue();
1373       if (flags) msg += "'>: avp attributes <'code' + 'flags' + 'vendorCode'> are not allowed if <'name'> is provided (also flags is not permitted: no may, no shouldnot)";
1374       else msg += "'>: avp attributes <'code' + 'vendorCode'> are not allowed if <'name'> is provided";
1375       throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1376     }
1377
1378     setId(stackAvp->getId());
1379
1380     if (flags && allowFlagsField) {
1381       // Flags check
1382       int i_aux = flags->getIntegerValue();
1383
1384       if(i_aux < 0 || i_aux > 256) {
1385         std::string msg = "Error processing avp <flags '"; msg += flags->getValue();
1386         msg += "': out of range [0,256]";
1387         throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1388       }
1389
1390       a_flags = i_aux;
1391     }
1392
1393
1394   } else {
1395     if(!code || !flags || !vendorCode) {
1396       std::string s_code = code ? code->getValue() : "?";
1397       std::string s_flags = flags ? flags->getValue() : "?";
1398       std::string s_vendorCode = vendorCode ? vendorCode->getValue() : "?";
1399       std::string msg = "Error processing avp <code '"; msg += s_code;
1400       msg += "' + flags '"; msg += s_flags;
1401       msg += "' + vendorCode '"; msg += s_vendorCode;
1402       msg += "'>: all must be provided if <'name'> don't";
1403       throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1404     }
1405
1406     // Code check
1407     int i_aux = code->getIntegerValue();
1408
1409     if(i_aux < 0) {
1410       std::string msg = "Error processing avp <code '"; msg += code->getValue();
1411       msg += "': negative values are not allowed";
1412       throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1413     }
1414
1415     U24 u_code = i_aux;
1416     // Flags check
1417     i_aux = flags->getIntegerValue();
1418
1419     if(i_aux < 0 || i_aux > 256) {
1420       std::string msg = "Error processing avp <flags '"; msg += flags->getValue();
1421       msg += "': out of range [0,256]";
1422       throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1423     }
1424
1425     a_flags = i_aux;
1426     int flagsBCK = a_flags;
1427     // VendorCode checks
1428     i_aux = vendorCode->getIntegerValue();
1429
1430     if(i_aux < 0) {
1431       std::string msg = "Error processing avp <vendorCode '"; msg += vendorCode->getValue();
1432       msg += "': negative values are not allowed";
1433       throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1434     }
1435
1436     U32 u_vendorCode = i_aux;
1437     bool vendorSpecific1 = (u_vendorCode != 0);
1438     bool vendorSpecific2 = (((a_flags) & VBitMask) != 0x00);
1439
1440     if(vendorSpecific1 != vendorSpecific2) {
1441       std::string msg = "Error processing avp <vendorCode '"; msg += vendorCode->getValue();
1442       msg += "' and avp <flags '"; msg += flags->getValue();
1443       msg += "': incompatible vendor-specific properties";
1444       throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1445     }
1446
1447     // Final assignments
1448     setId(AvpId(u_code, u_vendorCode));
1449     // Flags could have been updated regarding dictionary, but during parsing we must respect xml file:
1450     a_flags = flagsBCK;
1451     stackAvp = getStackAvp();
1452     stackFormat = stackAvp ? stackAvp->getFormat() : NULL;
1453   }
1454
1455   // Childrens
1456   // Check if grouped not confirmed
1457   anna::xml::Node::const_child_iterator it;
1458   anna::xml::Node::const_child_iterator minii = avpNode->child_begin();
1459   anna::xml::Node::const_child_iterator maxii = avpNode->child_end();
1460   const bool hasChildren(minii != maxii);
1461
1462   if(hasChildren) {
1463     // We need to confirm is grouped
1464     if(!stackFormat)
1465       throw anna::RuntimeException("An xml avp node with children nodes could not confirmed as Grouped", ANNA_FILE_LOCATION);
1466
1467     if(!stackFormat->isGrouped())
1468       throw anna::RuntimeException("An xml avp node with children nodes is not grouped type", ANNA_FILE_LOCATION);
1469
1470     if(data || hexData)
1471       throw anna::RuntimeException("An xml avp node with children nodes has 'data' or 'hex-data' field", ANNA_FILE_LOCATION);
1472   }
1473
1474   // Presentation
1475   std::string s_avp = name ? (name->getValue()) : (anna::diameter::functions::avpIdAsPairString(a_id));
1476
1477   if(data && hexData) {
1478     std::string msg = "Not allowed both 'data' and 'hex-data' definitions. Avp ";
1479     msg += s_avp;
1480     throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1481   }
1482
1483   LOGWARNING(
1484     bool unknown = !stackFormat;
1485     bool octetString = stackFormat && (stackFormat->isOctetString());
1486
1487   if(data && (unknown || octetString)) {
1488   std::string msg = "Not recommended 'data' field at ";
1489   msg += unknown ? "Unknown" : "OctetString";
1490   msg += "-format Avp "; msg += s_avp;
1491   msg += ". Use better 'hex-data' or omit content fields if empty";
1492   anna::Logger::warning(msg, ANNA_FILE_LOCATION);
1493   }
1494   );
1495
1496   if(!stackFormat) {
1497     if(data) a_Unknown->fromPrintableString(data->getValue().c_str());
1498     else if(hexData) a_Unknown->fromHexString(hexData->getValue());
1499
1500     return;
1501   }
1502
1503   if(stackFormat->isOctetString()) {
1504     if(data) a_OctetString->fromPrintableString(data->getValue().c_str());
1505     else if(hexData) a_OctetString->fromHexString(hexData->getValue());
1506   } else if(stackFormat->isInteger32()) {
1507     if(data) a_Integer32->fromPrintableString(data->getValue().c_str());
1508     else if(hexData) a_Integer32->fromHexString(hexData->getValue());
1509   } else if(stackFormat->isInteger64()) {
1510     if(data) a_Integer64->fromPrintableString(data->getValue().c_str());
1511     else if(hexData) a_Integer64->fromHexString(hexData->getValue());
1512   } else if(stackFormat->isUnsigned32()) {
1513     if(data) a_Unsigned32->fromPrintableString(data->getValue().c_str());
1514     else if(hexData) a_Unsigned32->fromHexString(hexData->getValue());
1515   } else if(stackFormat->isUnsigned64()) {
1516     if(data) a_Unsigned64->fromPrintableString(data->getValue().c_str());
1517     else if(hexData) a_Unsigned64->fromHexString(hexData->getValue());
1518   } else if(stackFormat->isFloat32()) {
1519     if(data) a_Float32->fromPrintableString(data->getValue().c_str());
1520     else if(hexData) a_Float32->fromHexString(hexData->getValue());
1521   } else if(stackFormat->isFloat64()) {
1522     if(data) a_Float64->fromPrintableString(data->getValue().c_str());
1523     else if(hexData) a_Float64->fromHexString(hexData->getValue());
1524   } else if(stackFormat->isGrouped()) {
1525     // Childrens
1526     Avp *avp;
1527
1528     for(it = minii; it != maxii; it++) {
1529       std::string nodeName = (*it)->getName();
1530
1531       if(nodeName != "avp") {
1532         std::string msg = "Unsupported grouped avp child node name '"; msg += nodeName;
1533         msg += "': use 'avp'";
1534         throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1535       }
1536
1537       try {
1538         avp =  getEngine()->createAvp(NULL);
1539         avp -> fromXML(*it);
1540       } catch(anna::RuntimeException &ex) {
1541         getEngine()->releaseAvp(avp);
1542         throw;
1543       }
1544
1545       addAvp(avp);
1546     }
1547   } else if(stackFormat->isAddress()) {
1548     if(data) a_Address->fromPrintableString(data->getValue().c_str());
1549     else if(hexData) a_Address->fromHexString(hexData->getValue());
1550   } else if(stackFormat->isTime()) {
1551     if(data) a_Time->fromPrintableString(data->getValue().c_str());
1552     else if(hexData) a_Time->fromHexString(hexData->getValue());
1553   } else if(stackFormat->isUTF8String()) {
1554     if(data) a_UTF8String->fromPrintableString(data->getValue().c_str());
1555     else if(hexData) a_UTF8String->fromHexString(hexData->getValue());
1556   } else if(stackFormat->isDiameterIdentity()) {
1557     if(data) a_DiameterIdentity->fromPrintableString(data->getValue().c_str());
1558     else if(hexData) a_DiameterIdentity->fromHexString(hexData->getValue());
1559   } else if(stackFormat->isDiameterURI()) {
1560     if(data) a_DiameterURI->fromPrintableString(data->getValue().c_str());
1561     else if(hexData) a_DiameterURI->fromHexString(hexData->getValue());
1562   } else if(stackFormat->isEnumerated()) {
1563     if(data) a_Enumerated->fromPrintableString(data->getValue().c_str());
1564     else if(hexData) a_Enumerated->fromHexString(hexData->getValue());
1565   } else if(stackFormat->isIPFilterRule()) {
1566     if(data) a_IPFilterRule->fromPrintableString(data->getValue().c_str());
1567     else if(hexData) a_IPFilterRule->fromHexString(hexData->getValue());
1568   } else if(stackFormat->isQoSFilterRule()) {
1569     if(data) a_QoSFilterRule->fromPrintableString(data->getValue().c_str());
1570     else if(hexData) a_QoSFilterRule->fromHexString(hexData->getValue());
1571   }
1572
1573   /////////////////////
1574   // Format specific //
1575   /////////////////////
1576   fromXMLByFormat(data, hexData, stackFormat);
1577 }
1578
1579 //------------------------------------------------------------------------------
1580 //----------------------------------------------------------------- Avp::asXML()
1581 //------------------------------------------------------------------------------
1582 anna::xml::Node* Avp::asXML(anna::xml::Node* parent) const throw() {
1583   // <!ATTLIST avp id CDATA #IMPLIED code CDATA #IMPLIED vendor-code CDATA #IMPLIED flags CDATA #IMPLIED data CDATA #IMPLIED hex-data CDATA #IMPLIED>
1584   anna::xml::Node* result = parent->createChild("avp");
1585   // Dictionary stack avp and format:
1586   const stack::Avp *stackAvp = getStackAvp();
1587   const stack::Format *stackFormat = stackAvp ? (stackAvp->getFormat()) : NULL /*Unknown*/;
1588   bool compactMode = (stackAvp && flagsOK());
1589
1590   if(compactMode) {
1591     result->createAttribute("name", stackAvp->getName());
1592     // If may or shouldnot is present in AVP definition, we have to show flags to avoid uncertainty
1593     if ( stackAvp->getVbit() == anna::diameter::stack::Avp::FlagRule::may || stackAvp->getVbit() == anna::diameter::stack::Avp::FlagRule::shouldnot
1594          || stackAvp->getMbit() == anna::diameter::stack::Avp::FlagRule::may || stackAvp->getMbit() == anna::diameter::stack::Avp::FlagRule::shouldnot
1595          /* umm, perhaps we could omit for bit P, whic is deprecated ... */
1596          /* || stackAvp->getPbit() == anna::diameter::stack::Avp::FlagRule::may || stackAvp->getPbit() == anna::diameter::stack::Avp::FlagRule::shouldnot*/ )
1597       result->createAttribute("flags", (int)a_flags);
1598   } else {
1599     result->createAttribute("code", a_id.first);
1600     result->createAttribute("vendor-code", a_id.second);
1601     result->createAttribute("flags", (int)a_flags);
1602   }
1603
1604   // Grouped special case:
1605   if(stackFormat && stackFormat->isGrouped()) {
1606     for(const_avp_iterator it = avp_begin(); it != avp_end(); it++) avp(it)->asXML(result);
1607
1608     return result;
1609   }
1610
1611   // Data part literals:
1612   bool isHex;
1613   std::string value = getXMLdata(isHex, stackFormat);
1614
1615   if(isHex) {
1616     result->createAttribute("hex-data", value);
1617   } else {
1618     result->createAttribute("data", value);
1619     const char *alias = stackAvp->getAlias(value);
1620
1621     if(alias) result->createAttribute("alias", alias);  // additional information
1622   }
1623
1624   return result;
1625 }
1626
1627
1628 //------------------------------------------------------------------------------
1629 //----------------------------------------------------------- Avp::asXMLString()
1630 //------------------------------------------------------------------------------
1631 std::string Avp::asXMLString() const throw() {
1632   anna::xml::Node root("root");
1633   return anna::xml::Compiler().apply(asXML(&root));
1634 }
1635
1636
1637 //------------------------------------------------------------------------------
1638 //---------------------------------------------------------------- Avp::isLike()
1639 //------------------------------------------------------------------------------
1640 bool Avp::isLike(const std::string &pattern) const throw() {
1641   anna::RegularExpression re(pattern);
1642   return re.isLike(asXMLString());
1643 }