Suuports clang compiler
[anna.git] / source / comm / CompatCodec.cpp
1 // ANNA - Anna is Not Nothingness Anymore
2 //
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
4 //
5 // http://redmine.teslayout.com/projects/anna-suite
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
9 // are met:
10 //
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
16 // distribution.
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.
20 //
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.
32 //
33 // Authors: eduardo.ramos.testillano@gmail.com
34 //          cisco.tierra@gmail.com
35
36
37 #include <stdlib.h>
38 #include <time.h>
39 #include <netinet/in.h>
40
41 #include <anna/core/RuntimeException.hpp>
42 #include <anna/config/defines.hpp>
43 #include <anna/core/tracing/Logger.hpp>
44 #include <anna/core/functions.hpp>
45 #include <anna/core/util/Second.hpp>
46 #include <anna/core/util/Millisecond.hpp>
47 #include <anna/core/util/Microsecond.hpp>
48
49 #include <anna/comm/CompatCodec.hpp>
50 #include <anna/comm/functions.hpp>
51 #include <anna/comm/Variable.hpp>
52
53 using namespace std;
54 using namespace anna;
55
56 bool comm::CompatCodec::st_initScramble(false);
57
58 // static
59 template <class T, class M> comm::Variable* insert(const char* name, const short int id, M& theVector, T& value)
60 throw(RuntimeException) {
61   comm::Variable* result = theVector.find(id);
62
63   if(result != NULL)
64     throw RuntimeException(functions::asString("Variable Id %d alreay used", id), ANNA_FILE_LOCATION);
65
66   theVector.add(result = new comm::Variable(id, name, value));
67   LOGDEBUG(
68     String msg("insert <T, M> | ");
69     msg <<  result->asString();
70     Logger::debug(msg, ANNA_FILE_LOCATION);
71   );
72   return result;
73 }
74
75 // static
76 template <class T, class M> comm::Variable* insertRef(const char* name, const short int id, M& theVector, T& value)
77 throw(RuntimeException) {
78   comm::Variable* result = theVector.find(id);
79
80   if(result != NULL)
81     throw RuntimeException(functions::asString("Variable Id %d alreay used", id), ANNA_FILE_LOCATION);
82
83   theVector.add(result = new comm::Variable(id, name, value.refValue()));
84   LOGDEBUG(
85     String msg("insert <T, M> | ");
86     msg <<  result->asString();
87     Logger::debug(msg, ANNA_FILE_LOCATION);
88   );
89   return result;
90 }
91
92 comm::CompatCodec::CompatCodec(const comm::CompatCodec::Type type, const bool scramble)  :
93   comm::Message(comm::Message::StatusCodeBuffer::None),
94   a_type(type),
95   a_scramble(scramble),
96   a_nullCounter(0) {
97   if(a_scramble == true && st_initScramble == false) {
98     st_initScramble = true;
99     srand(time(NULL));
100   }
101 }
102
103 comm::CompatCodec::~CompatCodec() {
104   for(iterator ii = begin(), maxii = end(); ii != maxii; ii ++)
105     delete variable(ii);
106
107   a_variables.clear();
108 }
109
110 const comm::Variable* comm::CompatCodec::attach(const char* name, const short int id, std::string& value)
111 throw(RuntimeException) {
112   return insert(name, id, a_variables, value);
113 }
114
115 const comm::Variable* comm::CompatCodec::attach(const char* name, const short int id, int& value)
116 throw(RuntimeException) {
117   const int backup(value);
118   const Variable* result = insert(name, id, a_variables, value);
119   value = backup;
120   return result;
121 }
122
123 const comm::Variable* comm::CompatCodec::attach(const char* name, const short int id, S64& value)
124 throw(RuntimeException) {
125   const S64 backup(value);
126   const Variable* result = insert(name, id, a_variables, value);
127   value = backup;
128   return result;
129 }
130
131 const comm::Variable* comm::CompatCodec::attach(const char* name, const short int id, bool& value)
132 throw(RuntimeException) {
133   const bool backup(value);
134   const Variable* result = insert(name, id, a_variables, value);
135   value = backup;
136   return result;
137 }
138
139 const comm::Variable* comm::CompatCodec::attach(const char* name, const short int id, DataBlock& value)
140 throw(RuntimeException) {
141   return insert(name, id, a_variables, value);
142 }
143
144 const comm::Variable* comm::CompatCodec::attach(const char* name, const short int id, float& value)
145 throw(RuntimeException) {
146   const float backup(value);
147   const Variable* result = insert(name, id, a_variables, value);
148   value = backup;
149   return result;
150 }
151
152 const comm::Variable* comm::CompatCodec::attach(const char* name, const short int id, double& value)
153 throw(RuntimeException) {
154   const double backup(value);
155   const Variable* result = insert(name, id, a_variables, value);
156   value = backup;
157   return result;
158 }
159
160 const comm::Variable* comm::CompatCodec::attach(const char* name, const short int id, Second& value)
161 throw(RuntimeException) {
162   const Second backup(value);
163   const Variable* result = insertRef(name, id, a_variables, value);
164   value = backup;
165   return result;
166 }
167
168 const comm::Variable* comm::CompatCodec::attach(const char* name, const short int id, Millisecond& value)
169 throw(RuntimeException) {
170   const Millisecond backup(value);
171   const Variable* result = insertRef(name, id, a_variables, value);
172   value = backup;
173   return result;
174 }
175
176 const comm::Variable* comm::CompatCodec::attach(const char* name, const short int id, Microsecond& value)
177 throw(RuntimeException) {
178   const Microsecond backup(value);
179   const Variable* result = insertRef(name, id, a_variables, value);
180   value = backup;
181   return result;
182 }
183
184 const comm::Variable* comm::CompatCodec::attach(const char* name, const short int id, comm::CompatCodec& value)
185 throw(RuntimeException) {
186   if(&value == this) {
187     String msg("comm::CompatCodec::attach | Variable: ");
188     msg << name << " | Can not link with itself";
189     throw RuntimeException(msg, ANNA_FILE_LOCATION);
190   }
191
192   return insert(name, id, a_variables, value);
193 }
194
195 void comm::CompatCodec::setNull(const short int id, const bool isNull)
196 throw(RuntimeException) {
197   Variable* variable = a_variables.find(id);
198
199   if(variable == NULL)
200     throw RuntimeException(functions::asString("Id %d is not defined", id), ANNA_FILE_LOCATION);
201
202   if(variable->isNull()) {
203     if(isNull == false) a_nullCounter --;
204   }
205   else {
206     if(isNull == true) a_nullCounter ++;
207   }
208
209   variable->setNull(isNull);
210 }
211
212 void comm::CompatCodec::setNull(const comm::Variable* variable, const bool isNull)
213 throw() {
214   if(variable->isNull()) {
215     if(isNull == false) a_nullCounter --;
216   }
217   else {
218     if(isNull == true) a_nullCounter ++;
219   }
220
221   const_cast <comm::Variable*>(variable)->setNull(isNull);
222 }
223
224 bool comm::CompatCodec::isNull(const short int id) const
225 throw(RuntimeException) {
226   const Variable* variable = a_variables.find(id);
227
228   if(variable == NULL)
229     throw RuntimeException(functions::asString("Id %d is not defined", id), ANNA_FILE_LOCATION);
230
231   return variable->isNull();
232 }
233
234 const comm::Variable& comm::CompatCodec::find(const short int id) const
235 throw(RuntimeException) {
236   const Variable* variable = a_variables.find(id);
237
238   if(variable == NULL)
239     throw RuntimeException(functions::asString("Id %d is not defined", id), ANNA_FILE_LOCATION);
240
241   return *variable;
242 }
243
244 //-----------------------------------------------------------------------
245 // Codificacin de los datos en un bloque de memoria.
246 //
247 // mensaje ::= <byte0><byte1><byte2> <dato> ... <dato>
248 //
249 // dato ::= <byteA><byteB><byteC> [<cadena | int | long | bloque>]
250 // cadena ::= <byteLSB><byteMSB> < contenido > </0>
251 // int ::= <byteLSB> <byte> <byte> <byteMSB>
252 // long ::= <byteLSB> <byte> <byte> <byteMSB>
253 // bloque ::= <int> < contenido >
254 //
255 // (0) byte0 = Si es distinto de cero => contiene la clave usada para codificar
256 //     el mensaje.
257 // (2) byte1 = Nmero de datos que contiene el mensaje.
258 //     Recordar que slo se transfieren a este bloque de memoria los datos que
259 //     tengan asignado algn value.
260 // (1) byte2 = Typeentificador del mensaje interno.
261 // (3) Los bytes A y B contienen del identificador del dato.
262 // (4) Los cuatro primeros bits del byteC indican el tipo de dato. En los
263 //     tipos de datos boolean su contenido se guarda en el bit mas significativo
264 //     de este byte.
265 // (5) En las cadenas los dos primeros byres indican la longitud de la cadena
266 //     incluyendo el indicador de fin de cadena, luego aparece el contenido
267 //     de la cadena y finalmente el 0. El cero se incluye para optimizar
268 //     la recogida de datos.
269 //-----------------------------------------------------------------------
270 const DataBlock& comm::CompatCodec::code()
271 throw(RuntimeException) {
272   unsigned char c(0);
273   iterator ii;
274   iterator maxii(a_variables.end());
275   Variable* variable;
276   int stringLen;
277   const char* string;
278   char aux [sizeof(S64)];
279
280   if(a_scramble == true)     // (1)
281     while(c == 0) c = rand() % 0xff;
282
283   DataBlock& self = *this;
284   self.clear();
285   self += c;
286   self += (char)(a_variables.size() - a_nullCounter);          // (2)
287   self += comm::CompatCodec::getType();                              // (1)
288
289   for(ii = begin(); ii != maxii; ii ++) {
290     variable = CompatCodec::variable(ii);
291
292     if(a_nullCounter > 0 && variable->isNull() == true)
293       continue;
294
295     switch(variable->getType()) {
296     case Variable::Type::String:
297       self += variable->codec();
298       stringLen = anna_strlen(string = variable->getStringValue()) + 1;
299       self.append(comm::functions::codeShort(aux, stringLen), sizeof(short int));
300       self.append(string, stringLen);
301       break;
302     case Variable::Type::Integer:
303       self += variable->codec();
304       self.append(comm::functions::codeInteger(aux, variable->getInteger()), sizeof(int));
305       break;
306     case Variable::Type::Integer64:
307       self += variable->codec();
308       self.append(comm::functions::codeInteger64(aux, variable->getInteger64()), sizeof(S64));
309       break;
310     case Variable::Type::Boolean:
311       self.append(comm::functions::codeShort(aux, variable->getId()), sizeof(short int));      // (3)
312       c = Variable::Type::Boolean;
313
314       if(variable->getBoolean() == true)    // (4)
315         c |= 0x80;
316
317       self += c;
318       break;
319     case Variable::Type::Block:
320       self += variable->codec();
321       self.append(comm::functions::codeInteger(aux, variable->getDataBlock().getSize()), sizeof(int));
322       self += variable->getDataBlock();
323       break;
324     case Variable::Type::Float:
325       self += variable->codec();
326       self.append(comm::functions::codeFloat(aux, variable->getFloat()), sizeof(float));
327       break;
328     case Variable::Type::Double:
329       self += variable->codec();
330       self.append(comm::functions::codeDouble(aux, variable->getDouble()), sizeof(float));
331       break;
332     case Variable::Type::Custom:
333       self += variable->codec();
334       {
335         const DataBlock& codec = reinterpret_cast <CompatCodec*>(variable->getCustom())->code();
336         self.append(comm::functions::codeInteger(aux, codec.getSize()), sizeof(int));
337         self += codec;
338       }
339       break;
340     default: break;
341     }
342   }
343
344   LOGDEBUG(
345
346     // Se sacan aqui para evitar qtene que comprobar el estado de las trazas en cada paso
347     for(ii = begin(); ii != maxii; ii ++)
348     Logger::debug(CompatCodec::variable(ii)->asString(), ANNA_FILE_LOCATION);
349     Logger::write(Logger::Debug, "comm::CompatCodec::code", self, ANNA_FILE_LOCATION)
350   );
351
352   if(a_scramble == true) {
353     char* data = const_cast <char*>(self.getData());
354     int size = self.getSize();
355
356     for(int i = 1, key = data [0]; i < size; i ++)
357       data [i] ^= key ++;
358   }
359
360   return self;
361 }
362
363 //-------------------------------------------------------------------------------------------
364 void comm::CompatCodec::decode(const DataBlock& dataBlock)
365 throw(RuntimeException) {
366   const char* data = dataBlock.getData();
367   const int size = dataBlock.getSize();
368
369   if(size < 1)
370     throw RuntimeException("Can not decode an empty DataBlock", ANNA_FILE_LOCATION);
371
372   if(data [0] != 0)
373     for(int i = 1, key(data [0]); i < size; i ++)
374       const_cast <char*>(data)[i] ^= key ++;
375
376   LOGDEBUG(Logger::write(Logger::Debug, "comm::CompatCodec::decode", dataBlock, ANNA_FILE_LOCATION));
377   const int maxdata = data [1];
378
379   if(maxdata != a_variables.size())
380     normalDecode(data, size, maxdata);
381   else if(optimizedDecode(data, size) == false)
382     normalDecode(data, size, maxdata);
383
384   LOGDEBUG(
385
386     for(const_iterator ii = begin(), maxii = end(); ii != maxii; ii ++)
387     Logger::debug(CompatCodec::variable(ii)->asString(), ANNA_FILE_LOCATION);
388   );
389 }
390
391 //-------------------------------------------------------------------------------------------
392 // Decodifica los buffers que pueden contener variables nulas.
393 //-------------------------------------------------------------------------------------------
394 void comm::CompatCodec::normalDecode(const char* data, const int size, const int maxdata)
395 throw(RuntimeException) {
396   // Mientras no se demuestre lo contrario todas las variables son nulas
397   a_nullCounter = a_variables.size();
398
399   for(iterator ii = begin(), maxii = end(); ii != maxii; ii ++)
400     CompatCodec::variable(ii)->setNull(true);
401
402   short int id;
403   int nbytes;
404   Variable* variable;
405   bool hasError = false;
406   const char* top = data + size;
407   data += 3;
408
409   for(int ndata = 0; ndata < maxdata && data < top; ndata ++) {
410     id = comm::functions::decodeShort(data);
411     data += sizeof(short int);
412
413     if((variable = a_variables.find(id)) == NULL) {
414       hasError = true;
415       break;
416     }
417
418     a_nullCounter --;
419
420     switch(*data  & 0x7f) {
421     case Variable::Type::String:
422       nbytes = comm::functions::decodeShort(++ data);
423       variable->setValue(data += sizeof(short int));
424       data += nbytes;
425       break;
426     case Variable::Type::Integer:
427       variable->setInteger(comm::functions::decodeInteger(++ data));
428       data += sizeof(int);
429       break;
430     case Variable::Type::Integer64:
431       variable->setValue(comm::functions::decodeInteger64(++ data));
432       data += sizeof(S64);
433       break;
434     case  Variable::Type::Boolean:
435       variable->setBoolean((*data & 0x80) ? true : false);
436       data ++;
437       break;
438     case Variable::Type::Block:
439       nbytes = comm::functions::decodeInteger(++ data);
440       variable->setDataBlock(DataBlock(data += sizeof(int), nbytes, false));
441       data += nbytes;
442       break;
443     case Variable::Type::Float:
444       variable->setFloat(comm::functions::decodeFloat(++ data));
445       data += sizeof(float);
446       break;
447     case Variable::Type::Double:
448       variable->setDouble(comm::functions::decodeDouble(++ data));
449       data += sizeof(double);
450       break;
451     case Variable::Type::Custom:
452       nbytes = comm::functions::decodeInteger(++ data);
453       {
454         DataBlock dataBlock(data += sizeof(int), nbytes, false);
455         reinterpret_cast <CompatCodec*>(variable->getCustom())->decode(dataBlock);
456       }
457       data += nbytes;
458       break;
459     }
460   }
461
462   if(hasError == true) {
463     string msg("comm::CompatCodec::normalDecode | Buffer: ");
464     msg += functions::asString(DataBlock(data, size, false));
465     msg += functions::asText(" | Id is not defined: ", id);
466     Logger::error(msg, ANNA_FILE_LOCATION);
467   }
468
469   if(a_nullCounter < 0) {
470     a_nullCounter = 0;
471     LOGWARNING(
472       string msg("comm::CompatCodec::normalDecode | Buffer: ");
473       msg += functions::asString(DataBlock(data, size, false));
474       msg += " | NullCounter is less than zero";
475       Logger::warning(msg, ANNA_FILE_LOCATION);
476     );
477   }
478 }
479
480 //-------------------------------------------------------------------------------------------
481 // Decodifica optimizadamente buffers que no tengan variables nulas.
482 // (1) El codigo de la variable
483 //-------------------------------------------------------------------------------------------
484 bool comm::CompatCodec::optimizedDecode(const char* data, const int size)
485 throw(RuntimeException) {
486   int nbytes;
487   Variable* variable;
488   const char* top = data + size;
489   data += 3;
490
491   for(iterator ii = begin(), maxii = end(); ii != maxii && data < top; ii ++) {
492     data += sizeof(short int);
493     variable = CompatCodec::variable(ii);
494
495     switch(*data & 0x7f) {
496     case Variable::Type::String:
497       nbytes = comm::functions::decodeShort(++ data);
498       variable->setValue(data += sizeof(short int));
499       data += nbytes;
500       break;
501     case Variable::Type::Integer:
502       variable->setInteger(comm::functions::decodeInteger(++ data));
503       data += sizeof(int);
504       break;
505     case Variable::Type::Integer64:
506       variable->setValue(comm::functions::decodeInteger64(++ data));
507       data += sizeof(S64);
508       break;
509     case  Variable::Type::Boolean:
510       variable->setBoolean((*data & 0x80) ? true : false);
511       data ++;
512       break;
513     case Variable::Type::Block:
514       nbytes = comm::functions::decodeInteger(++ data);
515       variable->setDataBlock(DataBlock(data += sizeof(int), nbytes, false));
516       data += nbytes;
517       break;
518     case Variable::Type::Float:
519       variable->setFloat(comm::functions::decodeFloat(++ data));
520       data += sizeof(float);
521       break;
522     case Variable::Type::Double:
523       variable->setDouble(comm::functions::decodeDouble(++ data));
524       data += sizeof(double);
525       break;
526     case Variable::Type::Custom:
527       nbytes = comm::functions::decodeInteger(++ data);
528       {
529         DataBlock dataBlock(data += sizeof(int), nbytes, false);
530         reinterpret_cast <CompatCodec*>(variable->getCustom())->decode(dataBlock);
531       }
532       data += nbytes;
533       break;
534     }
535   }
536
537   return (data == top);
538 }
539
540 comm::CompatCodec::Type comm::CompatCodec::getType(const DataBlock& dataBlock)
541 throw(RuntimeException) {
542   const int size(dataBlock.getSize());
543
544   if(size <= 1)
545     throw RuntimeException("DataBlock is not valid", ANNA_FILE_LOCATION);
546
547   const char* data(dataBlock.getData());
548   comm::CompatCodec::Type result;
549   result = (data [0] != 0) ? ((data [0] + 1) ^ data [2]) : data [2];
550   LOGDEBUG(Logger::write(Logger::Debug, "comm::CompatCodec::getType", result, ANNA_FILE_LOCATION));
551   return result;
552 }
553
554 comm::CompatCodec::VariableContainer::VariableContainer() {
555   a_maxSize = 16;
556   a_size = 0;
557   a_variables = new Variable* [a_maxSize];
558   anna_memset(a_variables, 0, sizeof(Variable*) * a_maxSize);
559 }
560
561 void comm::CompatCodec::VariableContainer::add(comm::Variable* variable)
562 throw() {
563   if(a_size == a_maxSize) {
564     int maxSize = (a_maxSize << 1) - (a_maxSize >> 1);
565     Variable** variables = new Variable* [maxSize];
566     anna_memset(variables, 0, sizeof(Variable*) * maxSize);
567     anna_memcpy(variables, a_variables, sizeof(Variable*) * a_size);
568     delete a_variables;
569     a_variables = variables;
570     a_maxSize = maxSize;
571   }
572
573   a_variables [a_size ++] = variable;
574 }
575
576 comm::Variable* comm::CompatCodec::VariableContainer::find(const int id)
577 throw() {
578   for(int ii = 0; ii < a_size; ii ++) {
579     if(a_variables [ii]->getId() == id)
580       return a_variables [ii];
581   }
582
583   return NULL;
584 }
585
586 const comm::Variable* comm::CompatCodec::VariableContainer::find(const int id) const
587 throw() {
588   for(int ii = 0; ii < a_size; ii ++) {
589     if(a_variables [ii]->getId() == id)
590       return a_variables [ii];
591   }
592
593   return NULL;
594 }
595
596 void comm::CompatCodec::VariableContainer::clear()
597 throw() {
598   delete [] a_variables;
599   a_maxSize = a_size = 0;
600 }
601