Improve help and programmed answers output.
[anna.git] / example / diameter / launcher / main.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 <fstream>
38 #include <iostream>
39 #include <time.h>
40 #include <sys/stat.h> // chmod
41 #include <fcntl.h> // open / write
42
43 #include <string>
44 #include <map>
45 #include <deque>
46
47
48 #include <anna/config/defines.hpp>
49 #include <anna/comm/comm.hpp>
50 #include <anna/core/core.hpp>
51 #include <anna/xml/xml.hpp>
52 #include <anna/app/functions.hpp>
53 #include <anna/http/Request.hpp>
54 #include <anna/http/Response.hpp>
55 #include <anna/http/Handler.hpp>
56 #include <anna/http/Transport.hpp>
57 #include <anna/http/functions.hpp>
58 #include <anna/comm/functions.hpp>
59 #include <anna/timex/Engine.hpp>
60 #include <anna/timex/Clock.hpp>
61 #include <anna/diameter/stack/Engine.hpp>
62 #include <anna/diameter/codec/Engine.hpp>
63 #include <anna/diameter.comm/OamModule.hpp>
64 #include <anna/diameter.comm/ClientSession.hpp>
65 #include <anna/diameter.comm/LocalServer.hpp>
66 #include <anna/diameter.comm/Engine.hpp>
67 #include <anna/diameter.comm/Entity.hpp>
68 #include <anna/diameter.comm/Response.hpp>
69 #include <anna/diameter/functions.hpp>
70 #include <anna/diameter/codec/OamModule.hpp>
71 #include <anna/diameter/codec/functions.hpp>
72 #include <anna/time/functions.hpp>
73 #include <anna/time/Date.hpp>
74 #include <anna/diameter/helpers/base/defines.hpp>
75 #include <anna/diameter/helpers/base/functions.hpp>
76 #include <anna/diameter/helpers/dcca/defines.hpp>
77 #include <anna/diameter/helpers/dcca/functions.hpp>
78 #include <anna/statistics/Engine.hpp>
79 #include <anna/core/functions.hpp>
80
81 namespace anna {
82 class DataBlock;
83 }
84
85 namespace anna {
86 namespace diameter {
87 namespace comm {
88 class Entity;
89 class Response;
90 class LocalServer;
91 }
92 }
93 }
94
95 #define SIGUSR2_TASKS_INPUT_FILENAME "./sigusr2.tasks.input"
96 #define SIGUSR2_TASKS_OUTPUT_FILENAME "./sigusr2.tasks.output"
97
98
99 // Auxiliary message for sendings
100 anna::diameter::comm::Message G_commMsgSent2c, G_commMsgSent2e, G_commMsgFwd2c, G_commMsgFwd2e;
101 anna::diameter::comm::Message G_commMsg;
102 anna::diameter::codec::Message G_codecMsg, G_codecAnsMsg;
103 anna::Recycler<anna::diameter::comm::Message> G_commMessages; // create on requests forwards without programmed answer / release in answers forward
104
105 // Auxiliary resources for answers programming
106 class ProgrammedAnswers {
107
108 typedef std::deque<anna::diameter::codec::Message*> codec_messages_deque;
109 typedef std::deque<anna::diameter::codec::Message*>::iterator codec_messages_deque_iterator;
110 typedef std::deque<anna::diameter::codec::Message*>::const_iterator codec_messages_deque_const_iterator;
111 typedef std::map < int /* message code */, codec_messages_deque* > reacting_answers_container;
112 typedef std::map < int /* message code */, codec_messages_deque* >::iterator  reacting_answers_iterator;
113 typedef std::map < int /* message code */, codec_messages_deque* >::const_iterator  reacting_answers_const_iterator;
114
115   reacting_answers_container a_deques;
116
117   public:
118     ProgrammedAnswers() {};
119     ~ProgrammedAnswers() { clear(); }
120
121     void clear () throw() {
122       for (reacting_answers_const_iterator it = a_deques.begin(); it != a_deques.end(); it++) {
123         anna::diameter::codec::Engine *engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION);
124         engine->releaseMessage(*(it->second->begin()));
125         delete(it->second);
126       }
127       a_deques.clear();
128     }
129
130     void dump () throw() {
131       std::string outfilename, xmlString;
132       for(reacting_answers_const_iterator it = a_deques.begin(); it != a_deques.end(); it++) {
133         int sequence = 1;
134         for(codec_messages_deque_const_iterator itm = it->second->begin(); itm != it->second->end(); itm++) {
135           // programmed_answer.<code>.<sequence>
136           outfilename = "programmed_answer.";
137           outfilename += anna::functions::asString(it->first);
138           outfilename += ".";
139           outfilename += anna::functions::asString(sequence++);
140           outfilename += ".xml";
141           std::ofstream outfile(outfilename.c_str(), std::ifstream::out);
142           xmlString =  (*itm)->asXMLString();
143           outfile.write(xmlString.c_str(), xmlString.size());
144           outfile.close();
145         }
146       }
147     }
148
149     void addMessage(int code, anna::diameter::codec::Message *message) throw() {
150       reacting_answers_const_iterator it = a_deques.find(code);
151       if (it != a_deques.end()) {
152         it->second->push_back(message);
153       }
154       else {
155         codec_messages_deque *deque = new codec_messages_deque;
156         a_deques[code] = deque;
157         deque->push_back(message);
158       }
159     }
160
161     anna::diameter::codec::Message* getMessage(int code) const throw() { //get the front message (begin()), returns NULL if deque is empty
162       anna::diameter::codec::Message *result = NULL;
163       reacting_answers_const_iterator it = a_deques.find(code);
164       if (it != a_deques.end()) {
165         if (!it->second->empty()) result = *(it->second->begin());
166       }
167       return result;
168     }
169
170     void nextMessage(int code) throw() { //pops the deque and release the message (when deque is not empty: deque::empty)
171       reacting_answers_const_iterator it = a_deques.find(code);
172       if (it != a_deques.end()) {
173         if (!it->second->empty()) {
174           anna::diameter::codec::Engine *engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION);
175           engine->releaseMessage(*(it->second->begin()));
176           it->second->pop_front();
177         }
178       }
179     }
180
181     std::string asString() const throw() {
182       std::string result = "No ocurrences found\n\n";
183       std::string s_code;
184       if(a_deques.size() != 0) {
185         result = "";
186         for(reacting_answers_const_iterator it = a_deques.begin(); it != a_deques.end(); it++) {
187           
188           s_code = "Answer code ";
189           s_code += anna::functions::asString(it->first);
190           result += anna::functions::highlightJustify(s_code);
191           for(codec_messages_deque_const_iterator itm = it->second->begin(); itm != it->second->end(); itm++) {
192             result += (*itm)->asXMLString();
193             result += "\n";
194           }
195           result += "\n";
196         }
197       }
198       return result;
199     }
200 };
201
202 ProgrammedAnswers G_reactingAnswers2C, G_reactingAnswers2E;
203
204
205
206 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
207 // COUNTERS RECORD PROCEDURE //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
208 class MyCounterRecorderClock : public anna::timex::Clock {
209 public:
210   MyCounterRecorderClock(const char *clockName, const anna::Millisecond & timeout) :
211     anna::timex::Clock(clockName, timeout) {;}
212   //virtual ~MyCounterRecorderClock();
213
214   virtual bool tick() throw(RuntimeException) {
215     anna::diameter::comm::OamModule::instantiate().recordCounters();
216     anna::diameter::codec::OamModule::instantiate().recordCounters();
217     return true;
218   }
219 };
220
221 class MyCounterRecorder : public anna::oam::CounterRecorder {
222
223   // attributes
224   int a_stream;
225   std::string a_fileNamePrefix;
226   std::string a_fileName;
227   time_t a_previousTime;
228   std::string a_fixedLine;
229
230   // pure virtual definitions:
231   void open() throw(anna::RuntimeException) {
232     static char str [256];
233     const time_t now = ::time(NULL);
234     struct tm tmNow;
235     struct tm tmPrevious;
236     anna_memcpy(&tmNow, localtime(&now), sizeof(tmNow));
237     anna_memcpy(&tmPrevious, localtime(&a_previousTime), sizeof(tmPrevious));
238     sprintf(
239       str, ".Date%04d%02d%02d.Time%02d%02d%02d",
240       1900 + (tmNow.tm_year), (tmNow.tm_mon) + 1,
241       tmNow.tm_mday, tmNow.tm_hour, tmNow.tm_min, tmNow.tm_sec);
242     a_fileName = a_fileNamePrefix;
243     a_fileName += str;
244     LOGDEBUG(
245       std::string msg("Flush counters | ");
246       msg += a_fileName;
247       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
248     );
249
250     if((a_stream = ::open(a_fileName.c_str(), O_WRONLY | O_CREAT, S_IWUSR)) == -1)
251       throw RuntimeException(anna::functions::asString("Error opening file '%s'; errno = %d", a_fileName.c_str(), errno), ANNA_FILE_LOCATION);
252
253     sprintf(str, "%04d-%02d-%02d %02d:%02d|%04d-%02d-%02d %02d:%02d",
254             1900 + (tmPrevious.tm_year), (tmPrevious.tm_mon) + 1,
255             tmPrevious.tm_mday, tmPrevious.tm_hour, tmPrevious.tm_min,
256             1900 + (tmNow.tm_year), (tmNow.tm_mon) + 1,
257             tmNow.tm_mday, tmNow.tm_hour, tmNow.tm_min
258            );
259     a_fixedLine = str;
260   }
261
262
263   void apply(const anna::oam::Counter& counter) throw(anna::RuntimeException) {
264     static char line [356];
265     anna::oam::Counter::type_t value = counter;
266     sprintf(line, "%s|%06d|%07u|%s\n", a_fixedLine.c_str(), counter.getReference(), value, counter.getName().c_str());
267
268     if(write(a_stream, line, anna_strlen(line)) == -1)
269       throw RuntimeException(anna::functions::asString("Error writting to file '%s'; errno = %d", a_fileName.c_str(), errno), ANNA_FILE_LOCATION);
270   }
271
272   void close() throw() {
273     if(a_stream != -1) {
274       ::close(a_stream);
275       a_stream = -1;
276     }
277
278     chmod(a_fileName.c_str(), S_IWUSR | S_IRUSR);
279     a_previousTime = ::time(NULL);
280   }
281
282   std::string asString() const throw() {
283     std::string result = "Physical counters dump at file '";
284     result += a_fileName;
285     result += "'. Another way to see counters: context dump (kill -10 <pid>";
286     return result;
287   }
288
289 public:
290   MyCounterRecorder(const std::string &fnp) : a_stream(-1), a_fileNamePrefix(fnp) {
291     a_previousTime = ::time(NULL);
292   }
293 };
294
295 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
296
297
298 class MyDiameterEntity : public anna::diameter::comm::Entity {
299
300   void eventResponse(const anna::diameter::comm::Response&) throw(anna::RuntimeException);
301   void eventRequest(anna::diameter::comm::ClientSession *, const anna::DataBlock&) throw(anna::RuntimeException);
302   void eventUnknownResponse(anna::diameter::comm::ClientSession *, const anna::DataBlock&) throw(anna::RuntimeException);
303
304   // Reimplementation
305   int readSocketId(const anna::diameter::comm::Message* message, int maxClientSessions) const throw();
306 };
307
308 class MyLocalServer : public anna::diameter::comm::LocalServer {
309
310   void eventResponse(const anna::diameter::comm::Response&) throw(anna::RuntimeException);
311   void eventRequest(anna::diameter::comm::ServerSession *, const anna::DataBlock&) throw(anna::RuntimeException);
312   void eventUnknownResponse(anna::diameter::comm::ServerSession *, const anna::DataBlock&) throw(anna::RuntimeException);
313 };
314
315 class MyDiameterEngine : public anna::diameter::comm::Engine {
316 public:
317
318   static const char* getClassName() throw() { return "launcher::MyDiameterEngine"; }
319   MyDiameterEngine() {;}
320
321 // Default implementation is enough
322 //   void readDPA(anna::DataBlock &dpa, const anna::DataBlock & dpr) throw() {;} // DPA is not replied
323 //   void readCEA(anna::DataBlock &cea, const anna::DataBlock & cer) throw() {;} // CEA is not replied
324 //   void readDWA(anna::DataBlock &dwa, const anna::DataBlock & dwr) throw() {;} // DWA is not replied
325
326 private:
327   anna::Recycler<MyDiameterEntity> a_entitiesRecycler;
328
329   anna::diameter::comm::Entity* allocateEntity() throw() { return a_entitiesRecycler.create(); }
330
331   void releaseEntity(anna::diameter::comm::Entity* entity) throw() {
332     MyDiameterEntity* aux = static_cast <MyDiameterEntity*>(entity);
333     a_entitiesRecycler.release(aux);
334   }
335
336   anna::Recycler<MyLocalServer> a_localServersRecycler;
337
338   anna::diameter::comm::LocalServer* allocateLocalServer() throw() { return a_localServersRecycler.create(); }
339
340   void releaseLocalServer(anna::diameter::comm::LocalServer* localServer) throw() {
341     MyLocalServer* aux = static_cast <MyLocalServer*>(localServer);
342     a_localServersRecycler.release(aux);
343   }
344 };
345
346
347 class MyHandler : public anna::http::Handler {
348 public:
349   MyHandler() :  anna::http::Handler("http_converter::MyHandler") {
350     allocateResponse()->createHeader(anna::http::Header::Type::Date);
351   }
352
353 private:
354
355   void evRequest(anna::comm::ClientSocket&, const anna::http::Request& request) throw(anna::RuntimeException);
356   void evResponse(anna::comm::ClientSocket&, const anna::http::Response&) throw(anna::RuntimeException) {;}
357 };
358
359 class MyCommunicator : public anna::comm::Communicator {
360 public:
361   MyCommunicator(const anna::comm::Communicator::WorkMode::_v acceptMode = anna::comm::Communicator::WorkMode::Single) : anna::comm::Communicator(acceptMode),
362     a_contexts("Contexts")
363   {;}
364
365   void prepareAnswer(anna::diameter::codec::Message *answer, const anna::DataBlock &request) const throw();
366   void terminate() throw();
367
368 private:
369   anna::ThreadData <MyHandler> a_contexts;
370   void eventReceiveMessage(anna::comm::ClientSocket&, const anna::comm::Message&) throw(anna::RuntimeException);
371   void eventBreakConnection(Server* server) throw();
372 };
373
374 class Launcher : public anna::comm::Application {
375
376   MyCommunicator *a_communicator;
377   MyDiameterEngine *a_myDiameterEngine;
378   anna::diameter::comm::Entity *a_entity;
379   std::string a_logFile, a_burstLogFile;
380   std::ofstream a_burstLogStream;
381   bool a_splitLog, a_detailedLog;
382   anna::time::Date a_start_time;
383   anna::timex::Engine* a_timeEngine;
384   MyCounterRecorder *a_counterRecorder;
385   MyCounterRecorderClock *a_counterRecorderClock;
386   std::string a_cerPathfile;
387   std::string a_dwrPathfile;
388
389   // Burst feature
390   int a_burstCycle;
391   bool a_burstRepeat;
392   bool a_burstActive;
393   std::map < int /* dummy, p.e. used for order number */, anna::diameter::comm::Message* > a_burstMessages;
394   int a_burstLoadIndx;
395   std::map<int, anna::diameter::comm::Message*>::const_iterator a_burstDeliveryIt;
396   int a_otaRequest;
397   int a_burstPopCounter;
398
399   anna::comm::ServerSocket* a_httpServerSocket; // HTTP
400   anna::diameter::comm::LocalServer* a_diameterLocalServer; // DIAMETER
401   void checkTimeMeasure(const char * commandLineParameter, bool optional = true) throw(anna::RuntimeException);
402   void initialize() throw(anna::RuntimeException); // HTTP
403   void run() throw(anna::RuntimeException);
404
405 public:
406   Launcher();
407
408   MyCommunicator *getCommunicator() throw() { return a_communicator; }
409   MyDiameterEngine* getMyDiameterEngine() const throw() { return (a_myDiameterEngine); }
410   void baseProtocolSetupAsClient(void) throw(anna::RuntimeException);
411   anna::diameter::comm::Entity *getEntity() throw() { return a_entity; }
412   anna::diameter::comm::LocalServer* getDiameterLocalServer() throw() { return a_diameterLocalServer; }
413   void eventOperation(const std::string &, std::string &) throw(anna::RuntimeException);
414   bool logEnabled() const throw() { return (((a_logFile == "") || (a_logFile == "null")) ? false : true); }
415   void writeLogFile(const anna::DataBlock & db, const std::string &logExtension, const std::string &detail) const throw();
416   void writeLogFile(const anna::diameter::codec::Message & decodedMessage, const std::string &logExtension, const std::string &detail) const throw();
417   void writeBurstLogFile(const std::string &buffer) throw();
418   bool burstLogEnabled() const throw() { return (((a_burstLogFile == "") || (a_burstLogFile == "null")) ? false : true); }
419   void startDiameterServer(int) throw(anna::RuntimeException);
420
421   anna::xml::Node* asXML(anna::xml::Node* parent) const throw();
422   void resetStatistics() throw() { a_myDiameterEngine->resetStatistics(); }
423   void resetCounters() throw();
424   void signalUSR2() throw(anna::RuntimeException);
425   std::string help() const throw();
426
427   // helpers
428   bool getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) const throw();
429
430   // Burst feature
431   int clearBurst() throw(); // returns removed
432   int loadBurstMessage(const anna::DataBlock & db) throw(anna::RuntimeException);
433   void repeatBurst(bool repeat) throw() { a_burstRepeat = repeat; }
434   int startBurst(int initialLoad) throw();  // return processed on start, or -1 if burst list is empty, -2 if invalid initial load (0 or negative)
435   int pushBurst(int loadAmount) throw(); // returns pushed (perhaps is less than provided because of no repeat mode and burst list exhausted), or -1 if burst list is empty, -2 if invalid load (0 or negative)
436   int sendBurst(int loadAmount) throw(); // returns sent (burst always cycled using send), returns -1 if burst list is empty, -2 if invalid load (0 or negative)
437   int popBurst(int releaseAmount) throw(); // returns popped (perhaps is less than provided because of OTA request), or -1 if burst stopped
438   int stopBurst() throw(); // returns remaining on cycle, or -1 if burst already stopped
439   bool burstActive() const throw() { return a_burstActive; }
440   bool sendBurstMessage(bool anyway = false) throw();
441   std::string lookBurst(int order) const throw();
442   std::string gotoBurst(int order) throw();
443 };
444
445 bool Launcher::getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) const throw() {
446   // Get hex string
447   static char buffer[8192];
448   std::ifstream infile(pathfile.c_str(), std::ifstream::in);
449
450   if(infile.is_open()) {
451     infile >> buffer;
452     std::string hexString(buffer, strlen(buffer));
453     // Allow colon separator in hex string: we have to remove them before processing with 'fromHexString':
454     hexString.erase(std::remove(hexString.begin(), hexString.end(), ':'), hexString.end());
455     LOGDEBUG(
456       std::string msg = "Hex string (remove colons if exists): ";
457       msg += hexString;
458       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
459     );
460     anna::functions::fromHexString(hexString, db);
461     // Close file
462     infile.close();
463     return true;
464   }
465
466   return false;
467 }
468
469 int Launcher::clearBurst() throw() {
470   int size = a_burstMessages.size();
471
472   if(size) {
473     std::map<int, anna::diameter::comm::Message*>::const_iterator it;
474     std::map<int, anna::diameter::comm::Message*>::const_iterator it_min(a_burstMessages.begin());
475     std::map<int, anna::diameter::comm::Message*>::const_iterator it_max(a_burstMessages.end());
476
477     for(it = it_min; it != it_max; it++) G_commMessages.release((*it).second);
478
479     a_burstMessages.clear();
480   } else {
481     std::string msg = "Burst list already empty. Nothing done";
482     std::cout << msg << std::endl;
483     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
484   }
485
486   a_burstActive = false;
487   a_burstLoadIndx = 0;
488   a_burstDeliveryIt = a_burstMessages.begin();
489   return size;
490 }
491
492
493 int Launcher::loadBurstMessage(const anna::DataBlock & db) throw(anna::RuntimeException) {
494   anna::diameter::comm::Message *msg = G_commMessages.create();
495   msg->setBody(db);
496   a_burstMessages[a_burstLoadIndx++] = msg;
497   return (a_burstLoadIndx - 1);
498 }
499
500 int Launcher::stopBurst() throw() {
501   if(!a_burstActive) {
502     std::string msg = "Burst launch is already stopped. Nothing done";
503     std::cout << msg << std::endl;
504     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
505     return -1;
506   }
507
508   a_burstActive = false;
509   // Remaining on cycle:
510   return (a_burstMessages.size() - (*a_burstDeliveryIt).first);
511 }
512
513 int Launcher::popBurst(int releaseAmount) throw() {
514   if(!a_burstActive) {
515     std::string msg = "Burst launch is stopped. Nothing done";
516     std::cout << msg << std::endl;
517     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
518     return -1;
519   }
520
521   if(releaseAmount < 1) {
522     std::string msg = "No valid release amount is specified. Ignoring burst pop";
523     std::cout << msg << std::endl;
524     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
525     return -2;
526   }
527
528   int currentOTArequests = a_entity->getOTARequests();
529   a_burstPopCounter = (releaseAmount > currentOTArequests) ? currentOTArequests : releaseAmount;
530   return a_burstPopCounter;
531 }
532
533 int Launcher::pushBurst(int loadAmount) throw() {
534   if(a_burstMessages.size() == 0) {
535     std::string msg = "Burst data not found (empty list). Ignoring burst launch";
536     std::cout << msg << std::endl;
537     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
538     return -1;
539   }
540
541   if(loadAmount < 1) {
542     std::string msg = "No valid load amount is specified. Ignoring burst push";
543     std::cout << msg << std::endl;
544     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
545     return -2;
546   }
547
548   a_burstActive = true;
549   int count;
550
551   for(count = 0; count < loadAmount; count++)
552     if(!sendBurstMessage()) break;
553
554   return count;
555 }
556
557
558 int Launcher::sendBurst(int loadAmount) throw() {
559   if(a_burstMessages.size() == 0) {
560     std::string msg = "Burst data not found (empty list). Ignoring burst launch";
561     std::cout << msg << std::endl;
562     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
563     return -1;
564   }
565
566   if(loadAmount < 1) {
567     std::string msg = "No valid load amount is specified. Ignoring burst send";
568     std::cout << msg << std::endl;
569     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
570     return -2;
571   }
572
573   int count;
574
575   for(count = 0; count < loadAmount; count++)
576     if(!sendBurstMessage(true /* anyway */)) break;
577
578   return count;
579 }
580
581
582
583 int Launcher::startBurst(int initialLoad) throw() {
584   if(initialLoad < 1) {
585     std::string msg = "No initial load is specified. Ignoring burst start";
586     std::cout << msg << std::endl;
587     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
588     return -2;
589   }
590
591   a_burstActive = true;
592   a_burstCycle = 1;
593   a_burstDeliveryIt = a_burstMessages.begin();
594   return (pushBurst(initialLoad));
595 }
596
597 bool Launcher::sendBurstMessage(bool anyway) throw() {
598   if(!anyway && !burstActive()) return false;
599
600   if(a_burstPopCounter > 0) {
601     if(burstLogEnabled()) writeBurstLogFile("x");
602
603     a_burstPopCounter--;
604     return false;
605   }
606
607   if(a_burstDeliveryIt == a_burstMessages.end()) {
608     a_burstDeliveryIt = a_burstMessages.begin();
609
610     if(!anyway) {
611       if(a_burstRepeat) {
612         a_burstCycle++;
613
614         if(burstLogEnabled()) writeBurstLogFile(anna::functions::asString("\nCompleted burst cycle. Starting again (repeat mode) on cycle %d.\n", a_burstCycle));
615       } else {
616         if(burstLogEnabled()) writeBurstLogFile("\nCompleted burst cycle. Burst finished (repeat mode disabled).\n");
617
618         stopBurst();
619         return false;
620       }
621     }
622   }
623
624   anna::diameter::comm::Message *msg = (*a_burstDeliveryIt).second;
625   int order = (*a_burstDeliveryIt).first + 1;
626   a_burstDeliveryIt++;
627   bool dot = true;
628   // sending
629   bool result = a_entity->send(msg, anna::CommandLine::instantiate().exists("balance"));
630
631   if(burstLogEnabled()) {
632     if(a_burstMessages.size() >= 100)
633       dot = (order  % (a_burstMessages.size() / 100));
634
635     if(dot) {
636       writeBurstLogFile(".");
637     } else {
638       writeBurstLogFile(anna::functions::asString(" %d", order));
639       int otaReqs  = a_entity->getOTARequests();
640
641       if(result && (otaReqs != a_otaRequest)) {
642         // false if was a sending after an answer received (no OTA change in this case)
643         // true after push and pop operations
644         a_otaRequest = otaReqs;
645         writeBurstLogFile(anna::functions::asString("[OTA %d]", a_otaRequest));
646       }
647     }
648   }
649
650   // Detailed log:
651   if(logEnabled()) {
652     anna::diameter::comm::Server *usedServer = a_entity->getLastUsedResource();
653     anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
654     std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
655     writeLogFile(msg->getBody(), (result ? "sent2e" : "send2eError"), detail);
656   }
657
658   return result;
659 }
660
661
662 std::string Launcher::lookBurst(int order) const throw() {
663   std::string result = "No message found for order provided (";
664   result += anna::functions::asString(order);
665   result += ")";
666   std::map<int, anna::diameter::comm::Message*>::const_iterator it = a_burstMessages.find(order - 1);
667
668   if(it != a_burstMessages.end()) {
669     // Decode
670     try { G_codecMsg.decode((*it).second->getBody()); } catch(anna::RuntimeException &ex) { ex.trace(); }
671
672     result = G_codecMsg.asXMLString();
673   }
674
675   return result;
676 }
677
678 std::string Launcher::gotoBurst(int order) throw() {
679   std::string result = "Position not found for order provided (";
680   std::map<int, anna::diameter::comm::Message*>::iterator it = a_burstMessages.find(order - 1);
681
682   if(it != a_burstMessages.end()) {
683     a_burstDeliveryIt = it;
684     result = "Position updated for order provided (";
685   }
686
687   result += anna::functions::asString(order);
688   result += ")";
689   return result;
690 }
691
692 ////////////////////////////////////////////////////
693
694
695 void Launcher::resetCounters() throw() {
696   // Diameter::comm module:
697   anna::diameter::comm::OamModule & oamDiameterComm = anna::diameter::comm::OamModule::instantiate();
698   oamDiameterComm.resetCounters();
699 }
700
701 void Launcher::signalUSR2() throw(anna::RuntimeException) {
702   LOGNOTICE(
703     std::string msg = "Captured signal SIGUSR2. Reading tasks at '";
704     msg += SIGUSR2_TASKS_INPUT_FILENAME;
705     msg += "' (results will be written at '";
706     msg += SIGUSR2_TASKS_OUTPUT_FILENAME;
707     msg += "')";
708     anna::Logger::notice(msg, ANNA_FILE_LOCATION);
709   );
710   // Operation:
711   std::string line;
712   std::string response_content;
713   std::ifstream in_file(SIGUSR2_TASKS_INPUT_FILENAME);
714   std::ofstream out_file(SIGUSR2_TASKS_OUTPUT_FILENAME);
715
716   if(!in_file.is_open()) throw RuntimeException("Unable to read tasks", ANNA_FILE_LOCATION);
717
718   if(!out_file.is_open()) throw RuntimeException("Unable to write tasks", ANNA_FILE_LOCATION);
719
720   while(getline(in_file, line)) {
721     LOGDEBUG(
722       std::string msg = "Processing line: ";
723       msg += line;
724       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
725     );
726
727     try {
728       eventOperation(line, response_content);
729     } catch(RuntimeException &ex) {
730       ex.trace();
731     }
732
733     out_file << response_content;
734   }
735
736   in_file.close();
737   out_file.close();
738 }
739
740
741 std::string Launcher::help() const throw() {
742   std::string result = "\n";
743   result += "\n                     ------------- HELP -------------\n";
744   result += "\n";
745   result += "\nOVERVIEW";
746   result += "\n--------";
747   result += "\n";
748   result += "\nThe ADL (ANNA Diameter Launcher) process is a complete diameter agent with client and server";
749   result += "\n capabilities as well as balancer (proxy) features. It could be used as diameter server";
750   result += "\n (i.e. to simulate PCRF nodes, OCS systems, etc.), as diameter client (GGSNs, DPIs, etc.),";
751   result += "\n and balancer systems to provide failover to external round-robin launchers. Also, auxiliary";
752   result += "\n encoder/decoder/loader function could be deployed to reinterpret certain external flow and";
753   result += "\n send it to another process.";
754   result += "\n";
755   result += "\nThe ANNA::diameter_comm built-in module provides a great set of characteristics as multiple connections";
756   result += "\n on both server and client side, definition for multiple-server entities (and not only two as standard";
757   result += "\n establish as minimum), separate statistics analyzer per each resource, automatic CER/CEA and DWR/DWA";
758   result += "\n generation, expiration control and many more features.";
759   result += "\n";
760   result += "\nProcess traces are dump on \"launcher.trace\" and could have any trace level (POSIX levels), usually";
761   result += "\n 'debug' or 'warning'. See ANNA documentation for more details.";
762   result += "\n";
763   result += "\nAs any other ANNA process, context dump could be retrieved sending SIGUSR1 signal:";
764   result += "\n   kill -10 <pid>";
765   result += "\n    or";
766   result += "\n   kill -s SIGUSR1 <pid>";
767   result += "\n    and then";
768   result += "\n   vi /var/tmp/anna.context.<pid>";
769   result += "\n";
770   result += "\nA complete xml report will show all the context information (counters, alarms, statistics,";
771   result += "\n handlers, diameter dictionary, etc.), and a powerful log module could dump all the events";
772   result += "\n processed and flow information. Statistics could be analized at context dump and optionally";
773   result += "\n written to disk as sample files (useful for graphs and spreadsheet reports) with all the";
774   result += "\n measurements.";
775   result += "\n";
776   result += "\nAlso SIGUSR2 is handled for management purposes. We will talk later about this.";
777   result += "\n";
778   result += "\n";
779   result += "\nCOMMAND LINE";
780   result += "\n------------";
781   result += "\n";
782   result += "\nStart the launcher process without arguments in order to see all the startup configuration";
783   result += "\n posibilities, many of which could be modified on the air through the management interface";
784   result += "\n (we will talk later about this great feature). Some of the more common parameters are:";
785   result += "\n";
786   result += "\nAs mandatory, the stack definition given through the xml dictionary:";
787   result += "\n   -dictionary <path to dictionary file>";
788   result += "\n";
789   result += "\nActing as a diameter server (accepting i.e. 10 connections), you would have:";
790   result += "\n   -diameterServer localhost:3868 -diameterServerSessions 10 -entityServerSessions 0";
791   result += "\n";
792   result += "\nActing as a diameter client (launching i.e. 10 connections to each entity server), you would have:";
793   result += "\n   -entity 192.168.12.11:3868,192.168.12.21:3868 -entityServerSessions 10 -diameterServerSessions 0";
794   result += "\n";
795   result += "\nIf you act as a proxy or a translation agent, you need to combine both former setups, and probably";
796   result += "\n will need to program the answers to be replied through the operations interface. To balance the";
797   result += "\n traffic at your client side you shall use '-balance' and '-sessionBasedModelsClientSocketSelection'";
798   result += "\n arguments in order to define the balancing behaviour.";
799   result += "\n";
800   result += "\nThe process builds automatically CER and DWR messages as a client, but you could specify your own";
801   result += "\n customized ones using '-cer <xml message file>' and '-dwr <xml message file>'.";
802   result += "\nThe process builds automatically CEA and DWA messages as a server, but you could program your own";
803   result += "\n customized ones using operations interface.";
804   result += "\n";
805   result += "\n";
806   result += "\nDYNAMIC OPERATIONS";
807   result += "\n------------------";
808   result += "\n";
809   result += "\nADL supports several operations which could be reconized via HTTP interface or SIGUSR2 caugh.";
810   result += "\nAn operation is specified by mean a string containing the operation name and needed arguments";
811   result += "\n separated by pipes. These are the available commands:";
812   result += "\n";
813   result += "\n--------------------------------------------------------------------------------------- General purpose";
814   result += "\n";
815   result += "\nhelp                                 This help. Startup information-level traces also dump this help.";
816   result += "\n";
817   result += "\n------------------------------------------------------------------------------------ Parsing operations";
818   result += "\n";
819   result += "\ncode|<source_file>|<target_file>     Encodes source file (pathfile) into target file (pathfile).";
820   result += "\ndecode|<source_file>|<target_file>   Decodes source file (pathfile) into target file (pathfile).";
821   result += "\nloadxml|<source_file>                Reinterpret xml source file (pathfile).";
822   result += "\n";
823   result += "\n------------------------------------------------------------------------------------------- Hot changes";
824   result += "\n";
825   result += "\ndiameterServerSessions|<integer>     Updates the maximum number of accepted connections to diameter";
826   result += "\n                                      server socket.";
827   result += "\ncollect                              Reset statistics and counters to start a new test stage of";
828   result += "\n                                      performance measurement. Context data is written at";
829   result += "\n                                      '/var/tmp/anna.context.<pid>' by mean 'kill -10 <pid>'.";
830   result += "\n";
831   result += "\n<visibility action>|[<address>:<port>]|[socket id]";
832   result += "\n";
833   result += "\n       Actions: hide, show (update state) and hidden, shown (query state).";
834   result += "\n       Acts over a client session for messages delivery (except CER/A, DWR/A, DPR/A).";
835   result += "\n       If missing server (first parameter) all applications sockets will be affected.";
836   result += "\n       If missing socket (second parameter) for specific server, all its sockets will be affected.";
837   result += "\n";
838   result += "\n       All application client sessions are shown on startup, but standard delivery only use primary";
839   result += "\n        server ones except if fails. Balance configuration use all the allowed sockets. You could also";
840   result += "\n        use command line 'sessionBasedModelsClientSocketSelection' to force traffic flow over certain";
841   result += "\n        client sessions, but for this, hide/show feature seems easier.";
842   result += "\n";
843   result += "\n--------------------------------------------------------------------------------------- Flow operations";
844   result += "\n";
845   result += "\nsendxml2e|<source_file>    Sends xml source file (pathfile) through configured entity.";
846   result += "\nsendxml2c|<source_file>    Sends xml source file (pathfile) to client.";
847   result += "\nsendxml|<source_file>      Same as 'sendxml2e'.";
848   result += "\nanswerxml2e|[source_file]  Answer xml source file (pathfile) for incoming request with same code from entity.";
849   result += "\n                           The answer is stored in a FIFO queue for a specific message code, then there are";
850   result += "\n                           as many queues as different message codes have been received.";
851   result += "\nanswerxml2c|[source_file]  Answer xml source file (pathfile) for incoming request with same code from client.";
852   result += "\n                           The answer is stored in a FIFO queue for a specific message code, then there are";
853   result += "\n                           as many queues as different message codes have been received.";
854   result += "\nanswerxml|[source_file]    Same as 'answerxml2c'.";
855   result += "\nanswerxml(2e/2c)           List programmed answers (to entity/client) if no parameter provided.";
856   result += "\nanswerxml(2e/2c)|dump      Write programmed answers (to entity/client) to file 'programmed_answer.<message code>.<sequence>',";
857   result += "\n                           where 'sequence' is the order of the answer in each FIFO code-queue of programmed answers.";
858   result += "\nanswerxml(2e/2c)|clear     Clear programmed answers (to entity/client).";
859   result += "\n";
860   result += "\nSend operations are available using hexadecimal content (hex formatted files) which also allow to test";
861   result += "\nspecial scenarios (protocol errors):";
862   result += "\n";
863   result += "\nsendhex2e|<source_file>    Sends hex source file (pathfile) through configured entity.";
864   result += "\nsendhex2c|<source_file>    Sends hex source file (pathfile) to client.";
865   result += "\nsendhex|<source_file>      Same as 'sendhex2e'.";
866   result += "\n";
867   result += "\nAnswer programming in hexadecimal is not really neccessary (you could use send primitives) and also";
868   result += "\n is intended to be used with decoded messages in order to replace things like hop by hop, end to end,";
869   result += "\n subscriber id, session id, etc. Anyway you could use 'decode' operation and then program the xml created.";
870   result += "\n";
871   result += "\nIf a request is received, answer map (built with 'answerxml<[2c] or 2e>' operations) will be";
872   result += "\n checked to find a corresponding programmed answer to be replied(*). If no ocurrence is found,";
873   result += "\n or answer message was received, the message is forwarded to the other side (entity or client),";
874   result += "\n or nothing but trace when no peer at that side is configured. Answer to client have sense when";
875   result += "\n diameter server socket is configured, answer to entity have sense when entity does.";
876   result += "\n";
877   result += "\nIn the most complete situation (process with both client and server side) there are internally";
878   result += "\n two maps with N FIFO queues, one for each different message code within programmed answers.";
879   result += "\nOne map is for answers towards the client, and the other is to react entity requests. Then in";
880   result += "\n each one we could program different answers corresponding to different request codes received.";
881   result += "\n";
882   result += "\n(*) sequence values (hop-by-hop and end-to-end), Session-Id and Subscription-Id avps, are mirrored";
883   result += "\n    to the peer which sent the request. If user wants to test a specific answer without changing it,";
884   result += "\n    use sendxml/sendhex operations better than programming.";
885   result += "\n";
886   result += "\nBalance ('-balance' command line parameter) could be used to forward server socket receptions through";
887   result += "\n entity servers by mean a round-robin algorithm. Both diameter server socket and entity targets should";
888   result += "\n have been configured, that is to say: launcher acts as client and server. If no balance is used, an";
889   result += "\n standard delivery is performed: first primary entity server, secondary when fails, etc.";
890   result += "\n";
891   result += "\n--------------------------------------------------------------------------- Processing types (log tags)";
892   result += "\n";
893   result += "\nUsed as log file extensions (when '-splitLog' is provided on command line) and context preffixes on log";
894   result += "\n details when unique log file is dumped:";
895   result += "\n";
896   result += "\n   [sent2e/send2eError]   Send to entity (success/error)";
897   result += "\n   [sent2c/send2cError]   Send to client (success/error)";
898   result += "\n   [fwd2e/fwd2eError]     Forward to entity a reception from client (success/error)";
899   result += "\n   [fwd2c/fwd2cError]     Forward to client a reception from entity (success/error)";
900   result += "\n   [recvfc]               Reception from client";
901   result += "\n   [recvfe]               Reception from entity";
902   result += "\n   [req2c-expired]        A request sent to client has been expired";
903   result += "\n   [req2e-expired]        A request sent to entity has been expired";
904   result += "\n   [recvfc-ans-unknown]   Reception from client of an unknown answer (probably former [req2c-expired]";
905   result += "\n                           has been logged)";
906   result += "\n   [recvfe-ans-unknown]   Reception from entity of an unknown answer (probably former [req2e-expired]";
907   result += "\n                           has been logged)";
908   result += "\n";
909   result += "\n-------------------------------------------------------------------------------------------- Load tests";
910   result += "\n";
911   result += "\nburst|<action>|[parameter]     Used for performance testing, we first program diameter requests";
912   result += "\n                                messages in order to launch them from client side to the configured";
913   result += "\n                                diameter entity. We could start the burst with an initial load";
914   result += "\n                                (non-asynchronous sending), after this, a new request will be sent";
915   result += "\n                                per answer received or expired context. There are 10 actions: clear,";
916   result += "\n                                load, start, push, pop, stop, repeat, send, goto and look.";
917   result += "\n";
918   result += "\n   burst|clear                 Clears all loaded burst messages.";
919   result += "\n   burst|load|<source_file>    Loads the next diameter message into launcher burst.";
920   result += "\n   burst|start|<initial load>  Starts (or restarts if already in progress) the message sending with";
921   result += "\n                                a certain initial load.";
922   result += "\n   burst|push|<load amount>    Sends specific non-aynchronous load.";
923   result += "\n   burst|pop|<release amount>  Skip send burst messages in order to reduce over-the-air requests.";
924   result += "\n                               Popping all OTA requests implies burst stop because no more answer";
925   result += "\n                                will arrive to the process. Burst output file (-burstLog command";
926   result += "\n                                line parameter) shows popped messages with crosses (x). Each cross";
927   result += "\n                                represents one received answer for which no new request is sent.";
928   result += "\n   burst|stop                  Stops the burst cycle. You can resume pushing 1 load amount.";
929   result += "\n   burst|repeat|[[yes]|no]     Restarts the burst launch when finish. If initial load or push load";
930   result += "\n                                amount is greater than burst list size, they will be limited when";
931   result += "\n                                the list is processed except when repeat mode is enabled.";
932   result += "\n   burst|send|<amount>         Sends messages from burst list. The main difference with start/push";
933   result += "\n                                operations is that burst won't be awaken. Externally we could control";
934   result += "\n                                sending time (no request will be sent for answers).";
935   result += "\n   burst|goto|<order>          Updates current burst pointer position.";
936   result += "\n   burst|look|<order>          Show programmed burst message for order provided.";
937   result += "\n";
938   result += "\n";
939   result += "\nUSING OPERATIONS INTERFACE";
940   result += "\n--------------------------";
941   result += "\n";
942   result += "\n------------------------------------------------------------------------- Operations via HTTP interface";
943   result += "\n";
944   result += "\nAll the operations described above can be used through the optional HTTP interface. You only have";
945   result += "\n to define the http server at the command line with something like: '-httpServer localhost:9000'.";
946   result += "\nTo send the task, we shall build the http request body with the operation string. Some examples";
947   result += "\n using curl client could be:";
948   result += "\n";
949   result += "\n   curl -m 1 --data \"diameterServerSessions|4\" localhost:9000";
950   result += "\n   curl -m 1 --data \"code|ccr.xml\" localhost:9000";
951   result += "\n   curl -m 1 --data \"decode|ccr.hex\" localhost:9000";
952   result += "\n   curl -m 1 --data \"sendxml2e|ccr.xml\" localhost:9000";
953   result += "\n   etc.";
954   result += "\n";
955   result += "\n------------------------------------------------------------------------- Operations via SIGUSR2 signal";
956   result += "\n";
957   result += "\nThe alternative using SIGUSR2 signal requires the creation of the task(s) file which will be read at";
958   result += "\n signal event:";
959   result += "\n   echo \"<<operation>\" > "; result += SIGUSR2_TASKS_INPUT_FILENAME;
960   result += "\n    then";
961   result += "\n   kill -12 <pid>";
962   result += "\n    or";
963   result += "\n   kill -s SIGUSR2 <pid>";
964   result += "\n    and then see the results:";
965   result += "\n   cat "; result += SIGUSR2_TASKS_OUTPUT_FILENAME;
966   result += "\n";
967   result += "\nYou could place more than one line (task) in the input file. Output reports will be appended in that";
968   result += "\n case over the output file. Take into account that all the content of the task file will be executed";
969   result += "\n sinchronously by the process. If you are planning traffic load, better use the asynchronous http";
970   result += "\n interface.";
971   result += "\n";
972   result += "\n";
973   return result;
974 }
975
976
977 void MyCommunicator::prepareAnswer(anna::diameter::codec::Message *answer, const anna::DataBlock &request) const throw() {
978   // Sequence values (hop-by-hop and end-to-end), session-id and subscription-id avps, are mirrored to the peer which sent the request.
979   // If user wants to test a specific answer without changing it, use send operations better than programming.
980   // Sequence substitution:
981   answer->setHopByHop(anna::diameter::codec::functions::getHopByHop(request));
982   answer->setEndToEnd(anna::diameter::codec::functions::getEndToEnd(request));
983
984   // Session-Id substitution:
985   try {
986     std::string sessionId = anna::diameter::helpers::base::functions::getSessionId(request);
987     LOGDEBUG(
988       std::string msg = "Extracted Session-Id: ";
989       msg += sessionId;
990       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
991     );
992     answer->getAvp("Session-Id")->getUTF8String()->setValue(sessionId);
993   } catch(anna::RuntimeException &ex) {
994     ex.trace();
995   }
996
997   // Subscription-Id substitution: is not usual to carry Subscription-Id on answer messages, but if programmed answer have this information,
998   // then it will be adapted with the received data at request.
999   if(answer->countAvp("Subscription-Id") > 0) {
1000     std::string msisdn = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(request, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_E164);
1001     std::string imsi = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(request, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_IMSI);
1002
1003     if((msisdn != "") || (imsi != "")) {  // Both request & answer have SID: replace answer one with the request information:
1004       answer->removeAvp("Subscription-Id", 0 /* remove all */);
1005     }
1006
1007     // Replacements:
1008     if(msisdn != "") {
1009       anna::diameter::codec::Avp *sid = answer->addAvp("Subscription-Id");
1010       sid->addAvp("Subscription-Id-Type")->getEnumerated()->setValue(anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_E164);
1011       sid->addAvp("Subscription-Id-Data")->getUTF8String()->setValue(msisdn);
1012     }
1013
1014     if(imsi != "") {
1015       anna::diameter::codec::Avp *sid = answer->addAvp("Subscription-Id"); // another
1016       sid->addAvp("Subscription-Id-Type")->getEnumerated()->setValue(anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_IMSI);
1017       sid->addAvp("Subscription-Id-Data")->getUTF8String()->setValue(imsi);
1018     }
1019   }
1020 }
1021
1022 // HTTP
1023 void MyCommunicator::eventReceiveMessage(anna::comm::ClientSocket& clientSocket, const anna::comm::Message& message)
1024 throw(anna::RuntimeException) {
1025   LOGMETHOD(anna::TraceMethod tm("MyCommunicator", "eventReceiveMessage", ANNA_FILE_LOCATION));
1026
1027   if(clientSocket.support(anna::http::Transport::className()) == false)
1028     return;
1029
1030   MyHandler& httpHandler = a_contexts.get();
1031   httpHandler.apply(clientSocket, message);
1032 }
1033
1034 using namespace std;
1035 using namespace anna::diameter;
1036
1037 int main(int argc, const char** argv) {
1038   anna::Logger::setLevel(anna::Logger::Warning);
1039   anna::Logger::initialize("launcher", new TraceWriter("launcher.trace", 2048000));
1040   anna::time::functions::initialize(); // before application instantiation (it have a anna::time object)
1041   anna::time::functions::setControlPoint(); // start control point (application lifetime)
1042   Launcher app;
1043   anna::http::functions::initialize();
1044
1045   try {
1046     CommandLine& commandLine(anna::CommandLine::instantiate());
1047     // General
1048     commandLine.add("trace", anna::CommandLine::Argument::Optional, "Trace level (emergency, alert, critical, error, warning, notice, information, debug, local0..local7)");
1049     commandLine.add("log", anna::CommandLine::Argument::Optional, "Process log file (operations result, traffic log, etc.). By default 'launcher.log'. Empty string or \"null\" name, to disable. Warning: there is no rotation for log files (use logrotate or whatever)");
1050     commandLine.add("splitLog", anna::CommandLine::Argument::Optional, "Splits log file (appends to log filename, extensions with the type of event: see help on startup information-level traces). No log files for code/decode and load operations are created", false);
1051     commandLine.add("detailedLog", anna::CommandLine::Argument::Optional, "Insert detailed information at log files. Should be disabled on automatic tests. Useful on '-balance' mode to know messages flow along the sockets", false);
1052     commandLine.add("logStatisticSamples", anna::CommandLine::Argument::Optional, "Log statistics samples for the provided concept id list, over './sample.<concept id>.csv' files. For example: \"1,2\" will log concepts 1 and 2. Reserved word \"all\" activates all registered statistics concept identifiers. That ids are shown at context dump (see help to get it).");
1053     commandLine.add("burstLog", anna::CommandLine::Argument::Optional, "Burst operations log file. By default 'launcher.burst'. Empty string or \"null\" name, to disable. Warning: there is no rotation for log files (use logrotate or whatever). Output: dot (.) for each burst message sent/pushed, cross (x) for popped ones, and order number when multiple of 1% of burst list size, plus OTA requests when changed.");
1054     commandLine.add("cntDir", anna::CommandLine::Argument::Optional, "Counters directory. By default is the current execution directory. Warning: a counter file will be dump per record period; take care about the possible accumulation of files");
1055     commandLine.add("cntRecordPeriod", anna::CommandLine::Argument::Optional, "Counters record procedure period in milliseconds. If missing, default value of 300000 (5 minutes) will be assigned. Value of 0 disables the record procedure.");
1056     // Communications
1057     commandLine.add("httpServer", anna::CommandLine::Argument::Optional, "HTTP Management interface address (using i.e. curl tool) in '<address>:<port>' format. For example: 10.20.30.40:8080");
1058     commandLine.add("httpServerShared", anna::CommandLine::Argument::Optional, "Enables shared bind for HTTP Management interface address. It would be useful i.e. to allow a great amount of curl operations per second", false);
1059     commandLine.add("diameterServer", anna::CommandLine::Argument::Optional, "Diameter own server address in '<address>:<port>' format. For example: 10.20.30.40:3868");
1060     commandLine.add("diameterServerSessions", anna::CommandLine::Argument::Optional, "Diameter own server available connections (0: diameter server disabled). Default value of 1");
1061     commandLine.add("entity", anna::CommandLine::Argument::Optional, "Target diameter entity (comma-separated '<address>:<port>' format). For example: 10.20.30.40:3868,10.20.30.41:3868");
1062     commandLine.add("entityServerSessions", anna::CommandLine::Argument::Optional, "Diameter entity server sessions (0: diameter entity disabled). Default value of 1");
1063     commandLine.add("balance", anna::CommandLine::Argument::Optional, "Balance over entity servers instead of doing standard behaviour (first primary, secondary if fails, etc.)", false);
1064     commandLine.add("sessionBasedModelsClientSocketSelection", anna::CommandLine::Argument::Optional, "By default, round-robin will be applied for IEC model (SMS/MMS), and Session-Id Low Part will be analyzed for ECUR/SCUR model (data, voice and content). You could change ECUR/SCUR analysis behaviour providing 'SessionIdHighPart', 'SessionIdOptionalPart' (atoi applied; usually subscriber id data, i.e. MSISDN or IMSI) and 'RoundRobin'.");
1065     commandLine.add("dictionary", anna::CommandLine::Argument::Mandatory, "Diameter dictionary pathfiles (could be one or more ocurrences in a comma separated list, in order to accumulate loads). For example: avps_etsi.xml,avps_ietf.xml,avps_tgpp.xml,commands_qosControl.xml");
1066     commandLine.add("ignoreFlags", anna::CommandLine::Argument::Optional, "Ignore flags on validation (at the moment only bits M & P from AVPs, because V bit is too important; no operation flags could be checked). Also force compact xml presentation ignoring flags during dictionary elements identification", false);
1067     commandLine.add("ignoreErrors", anna::CommandLine::Argument::Optional, "Local server skips requests errors analysis which would prepare automatic answers for them when a problem is found. If no answer is programmed and entity is configured, a failed request would be forwarded (delegates at the end point) even if this parameter is missing", false);
1068     commandLine.add("allowedInactivityTime", anna::CommandLine::Argument::Optional, "Milliseconds for the maximum allowed inactivity time on server sessions born over the local server before being reset. If missing, default value of 90000 will be assigned");
1069     commandLine.add("tcpConnectDelay", anna::CommandLine::Argument::Optional, "Milliseconds to wait TCP connect to any server. If missing, default value of 200 will be assigned");
1070     commandLine.add("answersTimeout", anna::CommandLine::Argument::Optional, "Milliseconds to wait pending application answers from diameter peers. If missing, default value of 10000 will be assigned");
1071     commandLine.add("ceaTimeout", anna::CommandLine::Argument::Optional, "Milliseconds to wait CEA from diameter server. If missing, default value of 'answersTimeout' will be assigned");
1072     commandLine.add("watchdogPeriod", anna::CommandLine::Argument::Optional, "Milliseconds for watchdog timer (Tw) for diameter keep-alive procedure. If missing, default value of 30000 will be assigned");
1073     commandLine.add("reconnectionPeriod", anna::CommandLine::Argument::Optional, "Milliseconds to recover diameter client-session when server connection has been broken. If missing, default value of 10000 will be assigned");
1074     commandLine.add("cer", anna::CommandLine::Argument::Optional, "Pathfile for the Capabilities Exchange Request xml message. If missing, \"cer.xml\" is searched. If missing again, process creates own CER");
1075     commandLine.add("dwr", anna::CommandLine::Argument::Optional, "Pathfile for the Device Watchdog Request xml message. If missing, \"dwr.xml\" is searched. If missing again, process creates own DWR");
1076     commandLine.add("originHost", anna::CommandLine::Argument::Optional, "Diameter application host name (system name). If missing, process sets o.s. hostname");
1077     commandLine.add("originRealm", anna::CommandLine::Argument::Optional, "Diameter application node realm name. If missing, process sets domain name");
1078     commandLine.add("integrationAndDebugging", anna::CommandLine::Argument::Optional, "Sets validation mode to 'Always' (default validates only after decoding), and validation depth to 'Complete' (default validates until 'FirstError')", false);
1079 //      commandLine.add("clone", anna::CommandLine::Argument::Optional, "Enables fork mode for request processing", false);
1080     commandLine.initialize(argv, argc);
1081     commandLine.verify();
1082     std::cout << commandLine.asString() << std::endl;
1083     app.start();
1084   } catch(Exception& ex) {
1085     cout << ex.asString() << endl;
1086   }
1087
1088   return 0;
1089 }
1090
1091 Launcher::Launcher() : anna::comm::Application("launcher", "DiameterLauncher", "1.1"), a_communicator(NULL) {
1092   a_myDiameterEngine = new MyDiameterEngine();
1093   a_myDiameterEngine->setRealm("ADL.ericsson.com");
1094   a_myDiameterEngine->setAutoBind(false);  // allow to create client-sessions without binding them, in order to set timeouts.
1095   //a_myDiameterEngine->setFreezeEndToEndOnSending();
1096   a_logFile = "launcher.log";
1097   a_burstLogFile = "launcher.burst";
1098   a_splitLog = false;
1099   a_detailedLog = false;
1100   a_timeEngine = NULL;
1101   a_counterRecorder = NULL;
1102   a_counterRecorderClock = NULL;
1103   a_entity = NULL;
1104   a_diameterLocalServer = NULL;
1105   a_cerPathfile = "cer.xml";
1106   a_dwrPathfile = "dwr.xml";
1107   // Burst
1108   a_burstCycle = 1;
1109   a_burstRepeat = false;
1110   a_burstActive = false;
1111   //a_burstMessages.clear();
1112   a_burstLoadIndx = 0;
1113   a_burstDeliveryIt = a_burstMessages.begin();
1114   a_otaRequest = 0;
1115   a_burstPopCounter = 0;
1116 }
1117
1118 void Launcher::baseProtocolSetupAsClient(void) throw(anna::RuntimeException) {
1119   // Build CER
1120   //   <CER> ::= < Diameter Header: 257, REQ >
1121   //             { Origin-Host } 264 diameterIdentity
1122   //             { Origin-Realm } 296 idem
1123   //          1* { Host-IP-Address } 257, address
1124   //             { Vendor-Id } 266 Unsigned32
1125   //             { Product-Name } 269 UTF8String
1126   //             [Origin-State-Id] 278 Unsigned32
1127   //           * [ Supported-Vendor-Id ]  265 Unsigned32
1128   //           * [ Auth-Application-Id ] 258 Unsigned32
1129   //           * [Acct-Application-Id]  259 Unsigned32
1130   anna::diameter::codec::Message diameterCER;
1131   int applicationId = 0 /*anna::diameter::helpers::APPID__3GPP_Rx*/; // Unsigned32
1132   std::string OH = a_myDiameterEngine->getHost();
1133   std::string OR = a_myDiameterEngine->getRealm();
1134   std::string hostIP = anna::functions::getHostnameIP(); // Address
1135   int vendorId = anna::diameter::helpers::VENDORID__tgpp; // Unsigned32
1136   std::string productName = "ANNA Diameter Launcher"; // UTF8String
1137   bool loadingError = false;
1138
1139   try {
1140     diameterCER.loadXML(a_cerPathfile);
1141   } catch(anna::RuntimeException &ex) {
1142     //ex.trace();
1143     loadingError = true;
1144   }
1145
1146   if(loadingError) {
1147     LOGWARNING(anna::Logger::warning("CER file not found. Get harcoded.", ANNA_FILE_LOCATION));
1148     diameterCER.setId(anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request);
1149     diameterCER.setApplicationId(applicationId);
1150     diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
1151     diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
1152     diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Host_IP_Address)->getAddress()->fromPrintableString(hostIP.c_str()); // supported by Address class, anyway is better to provide "1|<ip address>"
1153     diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Vendor_Id)->getUnsigned32()->setValue(vendorId);
1154     diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Product_Name)->getUTF8String()->setValue(productName);
1155     diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Auth_Application_Id)->getUnsigned32()->setValue(applicationId);
1156   }
1157
1158   // Build DWR
1159   //   <DWR>  ::= < Diameter Header: 280, REQ >
1160   //              { Origin-Host }
1161   //              { Origin-Realm }
1162   anna::diameter::codec::Message diameterDWR;
1163   loadingError = false;
1164
1165   try {
1166     diameterDWR.loadXML(a_dwrPathfile);
1167   } catch(anna::RuntimeException &ex) {
1168     //ex.trace();
1169     loadingError = true;
1170   }
1171
1172   if(loadingError) {
1173     LOGWARNING(anna::Logger::warning("DWR file not found. Get harcoded.", ANNA_FILE_LOCATION));
1174     diameterDWR.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Request);
1175     diameterDWR.setApplicationId(applicationId);
1176     diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
1177     diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
1178   }
1179
1180 //////////////////////////
1181 // IDEM FOR CEA AND DWA //
1182 //////////////////////////
1183 //            // Build CER
1184 //            //   <CER> ::= < Diameter Header: 257, REQ >
1185 //            //             { Origin-Host } 264 diameterIdentity
1186 //            //             { Origin-Realm } 296 idem
1187 //            //          1* { Host-IP-Address } 257, address
1188 //            //             { Vendor-Id } 266 Unsigned32
1189 //            //             { Product-Name } 269 UTF8String
1190 //            //             [Origin-State-Id] 278 Unsigned32
1191 //            //           * [ Supported-Vendor-Id ]  265 Unsigned32
1192 //            //           * [ Auth-Application-Id ] 258 Unsigned32
1193 //            //           * [Acct-Application-Id]  259 Unsigned32
1194 //            anna::diameter::codec::Message diameterCER;
1195 //            int applicationId = 0 /*anna::diameter::helpers::APPID__3GPP_Rx*/; // Unsigned32
1196 //            std::string OH = a_myDiameterEngine->getHost();
1197 //            std::string OR = a_myDiameterEngine->getRealm();
1198 //            std::string hostIP = anna::functions::getHostnameIP(); // Address
1199 //            int vendorId = anna::diameter::helpers::VENDORID__tgpp; // Unsigned32
1200 //            std::string productName = "ANNA Diameter Launcher"; // UTF8String
1201 //            bool loadingError = false;
1202 //
1203 //            try {
1204 //               diameterCER.loadXML("cer.xml");
1205 //            } catch (anna::RuntimeException &ex) {
1206 //               ex.trace();
1207 //               loadingError = true;
1208 //            }
1209 //
1210 //            if (loadingError) {
1211 //               LOGWARNING(anna::Logger::warning("CER file not found. Get harcoded.", ANNA_FILE_LOCATION));
1212 //               diameterCER.setId(anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request);
1213 //               diameterCER.setApplicationId(applicationId);
1214 //               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
1215 //               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
1216 //               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Host_IP_Address)->getAddress()->fromPrintableString(hostIP.c_str()); // supported by Address class, anyway is better to provide "1|<ip address>"
1217 //               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Vendor_Id)->getUnsigned32()->setValue(vendorId);
1218 //               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Product_Name)->getUTF8String()->setValue(productName);
1219 //               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Auth_Application_Id)->getUnsigned32()->setValue(applicationId);
1220 //            }
1221 //
1222 //            // Build DWR
1223 //            //   <DWR>  ::= < Diameter Header: 280, REQ >
1224 //            //              { Origin-Host }
1225 //            //              { Origin-Realm }
1226 //            anna::diameter::codec::Message diameterDWR;
1227 //            loadingError = false;
1228 //
1229 //            try {
1230 //               diameterDWR.loadXML("dwr.xml");
1231 //            } catch (anna::RuntimeException &ex) {
1232 //               ex.trace();
1233 //               loadingError = true;
1234 //            }
1235 //
1236 //            if (loadingError) {
1237 //               LOGWARNING(anna::Logger::warning("DWR file not found. Get harcoded.", ANNA_FILE_LOCATION));
1238 //               diameterDWR.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Request);
1239 //               diameterDWR.setApplicationId(applicationId);
1240 //               diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
1241 //               diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
1242 //            }
1243   // Assignment for CER/DWR and CEA/DWA:
1244   a_myDiameterEngine->setCERandDWR(diameterCER.code(), diameterDWR.code());
1245   //a_myDiameterEngine->setCEAandDWA(diameterCEA.code(), diameterDWA.code());
1246 }
1247
1248 void Launcher::writeLogFile(const anna::DataBlock & db, const std::string &logExtension, const std::string &detail) const throw() {
1249 //   if (!logEnabled()) return;
1250
1251   // Decode
1252   try { G_codecMsg.decode(db); } catch(anna::RuntimeException &ex) { ex.trace(); }
1253
1254   writeLogFile(G_codecMsg, logExtension, detail);
1255 }
1256
1257
1258 // Si ya lo tengo decodificado:
1259 void Launcher::writeLogFile(const anna::diameter::codec::Message & decodedMessage, const std::string &logExtension, const std::string &detail) const throw() {
1260 //   if (!logEnabled()) return;
1261   // Open target file:
1262   std::string targetFile = a_logFile;
1263
1264   if(a_splitLog) {
1265     targetFile += ".";
1266     targetFile += logExtension;
1267   }
1268
1269   ofstream out(targetFile.c_str(), ifstream::out | ifstream::app);
1270   // Set text to dump:
1271   std::string title = "[";
1272   title += logExtension;
1273   title += "]";
1274   // Build complete log:
1275   std::string log = "\n";
1276
1277   if(a_detailedLog) {
1278     anna::time::Date now;
1279     now.setNow();
1280     title += " ";
1281     title += now.asString();
1282     log += anna::functions::highlight(title, anna::functions::TextHighlightMode::OverAndUnderline);
1283     log += decodedMessage.asXMLString();
1284     log += "\n";
1285     log += anna::functions::highlight("Used resource");
1286     log += detail;
1287     log += "\n";
1288   } else {
1289     log += title;
1290     log += "\n";
1291     log += decodedMessage.asXMLString();
1292     log += "\n";
1293   }
1294
1295   // Write and close
1296   out.write(log.c_str(), log.size());
1297   out.close();
1298 }
1299
1300
1301 void Launcher::writeBurstLogFile(const std::string &buffer) throw() {
1302   ofstream out(a_burstLogFile.c_str(), ifstream::out | ifstream::app);
1303   out.write(buffer.c_str(), buffer.size());
1304   out.close();    // close() will be called when the object is destructed (i.e., when it goes out of scope).
1305   // you'd call close() only if you indeed for some reason wanted to close the filestream
1306   // earlier than it goes out of scope.
1307 }
1308
1309
1310 void Launcher::checkTimeMeasure(const char * commandLineParameter, bool optional) throw(anna::RuntimeException) {
1311   CommandLine& cl(anna::CommandLine::instantiate());
1312
1313   if(!cl.exists(commandLineParameter) && optional) return;  // start error if mandatory
1314
1315   std::string parameter = cl.getValue(commandLineParameter);
1316
1317   if(anna::functions::isLike("^[0-9]+$", parameter)) {  // para incluir numeros decimales: ^[0-9]+(.[0-9]+)?$
1318     int msecs = cl.getIntegerValue(commandLineParameter);
1319
1320     if(msecs > a_timeEngine->getMaxTimeout()) {
1321       std::string msg = "Commandline parameter '";
1322       msg += commandLineParameter;
1323       msg += "' is greater than allowed max timeout for timming engine: ";
1324       msg += anna::functions::asString(a_timeEngine->getMaxTimeout());
1325       throw RuntimeException(msg, ANNA_FILE_LOCATION);
1326     }
1327
1328     if(msecs <= a_timeEngine->getResolution()) {
1329       std::string msg = "Commandline parameter '";
1330       msg += commandLineParameter;
1331       msg += "' (and in general, all time measures) must be greater than timming engine resolution: ";
1332       msg += anna::functions::asString(a_timeEngine->getResolution());
1333       throw RuntimeException(msg, ANNA_FILE_LOCATION);
1334     }
1335
1336     return; // ok
1337   }
1338
1339   // Excepcion (por no ser entero):
1340   std::string msg = "Error at commandline parameter '";
1341   msg += commandLineParameter;
1342   msg += "' = '";
1343   msg += parameter;
1344   msg += "': must be a non-negative integer number";
1345   throw RuntimeException(msg, ANNA_FILE_LOCATION);
1346 }
1347
1348
1349 void Launcher::startDiameterServer(int diameterServerSessions) throw(anna::RuntimeException) {
1350   if(diameterServerSessions <= 0) return;
1351
1352   std::string address;
1353   int port;
1354   CommandLine& cl(anna::CommandLine::instantiate());
1355   anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("diameterServer"), address, port);
1356   //ServerSocket *createServerSocket(const std::string & addr, int port = Session::DefaultPort, int maxConnections = -1, int category = 1, const std::string & description = "")
1357   a_diameterLocalServer = a_myDiameterEngine->createLocalServer(address, port, diameterServerSessions);
1358   a_diameterLocalServer->setDescription("Launcher diameter local server");
1359   int allowedInactivityTime = 90000; // ms
1360
1361   if(cl.exists("allowedInactivityTime")) allowedInactivityTime = cl.getIntegerValue("allowedInactivityTime");
1362
1363   a_diameterLocalServer->setAllowedInactivityTime((anna::Millisecond)allowedInactivityTime);
1364 }
1365
1366
1367 void Launcher::initialize()
1368 throw(anna::RuntimeException) {
1369   anna::comm::Application::initialize();
1370   CommandLine& cl(anna::CommandLine::instantiate());
1371   anna::comm::Communicator::WorkMode::_v workMode(anna::comm::Communicator::WorkMode::Single);
1372 //   if (cl.exists ("clone"))
1373 //      workMode = anna::comm::Communicator::WorkMode::Clone;
1374   a_communicator = new MyCommunicator(workMode);
1375   a_timeEngine = new anna::timex::Engine((anna::Millisecond)300000, (anna::Millisecond)150);
1376   // Counters record procedure:
1377   anna::Millisecond cntRecordPeriod = (anna::Millisecond)300000; // ms
1378
1379   if(cl.exists("cntRecordPeriod")) cntRecordPeriod = cl.getIntegerValue("cntRecordPeriod");
1380
1381   if(cntRecordPeriod != 0) {
1382     checkTimeMeasure("cntRecordPeriod");
1383     a_counterRecorderClock = new MyCounterRecorderClock("Counters record procedure clock", cntRecordPeriod); // clock
1384     std::string cntDir = ".";
1385
1386     if(cl.exists("cntDir")) cntDir = cl.getValue("cntDir");
1387
1388     a_counterRecorder = new MyCounterRecorder(cntDir + anna::functions::asString("/Counters.Pid%d", (int)getPid()));
1389   }
1390 }
1391
1392 void Launcher::run()
1393 throw(anna::RuntimeException) {
1394   LOGMETHOD(anna::TraceMethod tm("Launcher", "run", ANNA_FILE_LOCATION));
1395   CommandLine& cl(anna::CommandLine::instantiate());
1396   // Start time:
1397   a_start_time.setNow();
1398   // Statistics:
1399   anna::statistics::Engine::instantiate().enable();
1400   ///////////////////////////////
1401   // Diameter library COUNTERS //
1402   ///////////////////////////////
1403   anna::diameter::comm::OamModule & oamDiameterComm = anna::diameter::comm::OamModule::instantiate();
1404   oamDiameterComm.initializeCounterScope(1);  // 1000 - 1999
1405   anna::diameter::codec::OamModule & oamDiameterCodec = anna::diameter::codec::OamModule::instantiate();
1406   oamDiameterCodec.initializeCounterScope(2);  // 2000 - 2999
1407   /////////////////
1408   // COMM MODULE //
1409   /////////////////
1410   /* Main events */
1411   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceived, "" /* get defaults for enum type*/, 0 /*1000*/);
1412   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceived,                 "", 1 /*1001*/);
1413   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnClientSession, "", 2 /*1002*/);
1414   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSession,  "", 3 /*1003*/);
1415   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnServerSession, "", 4 /* etc. */);
1416   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSession,  "", 5);
1417   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOK,                  "", 6);
1418   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentNOK,                 "", 7);
1419   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOK,                   "", 8);
1420   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentNOK,                  "", 9);
1421   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionOK,   "", 10);
1422   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionNOK,  "", 11);
1423   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionOK,    "", 12);
1424   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionNOK,   "", 13);
1425   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionOK,   "", 14);
1426   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionNOK,  "", 15);
1427   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionOK,    "", 16);
1428   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionNOK,   "", 17);
1429   /* Diameter Base (capabilities exchange & keep alive) */
1430   // as client
1431   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentOK,   "", 18);
1432   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentNOK,  "", 19);
1433   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEAReceived, "", 20);
1434   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentOK,   "", 21);
1435   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentNOK,  "", 22);
1436   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWAReceived, "", 23);
1437   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentOK,   "", 24);
1438   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentNOK,  "", 25);
1439   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPAReceived, "", 26);
1440   // as server
1441   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERReceived, "", 27);
1442   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentOK,   "", 28);
1443   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentNOK,  "", 29);
1444   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRReceived, "", 30);
1445   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentOK,   "", 31);
1446   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentNOK,  "", 32);
1447   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRReceived, "", 33);
1448   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentOK,   "", 34);
1449   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentNOK,  "", 35);
1450   /* server socket operations (enable/disable listening port for any local server) */
1451   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsOpened, "", 36);
1452   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsClosed, "", 37);
1453   /* Connectivity */
1454   // clients
1455   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverOverEntity,                  "", 38);
1456   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverClientSession,          "", 39);
1457   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverClientSession,     "", 40);
1458   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverServer,                 "", 41);
1459   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverServer,            "", 42);
1460   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEntity,                 "", 43);
1461   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEntity,            "", 44);
1462   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForEntities,      "", 45);
1463   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForEntities, "", 46);
1464   // servers
1465   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverToClient,                                    "", 47);
1466   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostConnectionForServerSession,                             "", 48);
1467   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnbindConnectionForServerSessionDueToInactivityTimeAnomaly, "", 49);
1468   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CreatedConnectionForServerSession,                          "", 50);
1469   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverLocalServer,                            "", 51);
1470   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverLocalServer,                       "", 52);
1471   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForLocalServers,                  "", 53);
1472   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForLocalServers,             "", 54);
1473   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentExpired,  "", 55);
1474   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionExpired,  "", 56);
1475   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionExpired,  "", 57);
1476   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedUnknown,  "", 58);
1477   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSessionUnknown,  "", 59);
1478   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSessionUnknown,  "", 60);
1479   //////////////////
1480   // CODEC MODULE //
1481   //////////////////
1482   /* Avp decoding */
1483   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength,                          "", 0 /*2000*/);
1484   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncoherenceBetweenActivatedVBitAndZeroedVendorIDValueReceived, "", 1 /*2001*/);
1485   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncorrectLength,                                               "", 2 /*2002*/);
1486   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__DataPartInconsistence,                                         "", 3 /*2003*/);
1487   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__UnknownAvpWithMandatoryBit,                                    "", 4 /*2004*/);
1488   /* Message decoding */
1489   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageHeaderLength, "", 5 /*2005*/);
1490   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageLength,       "", 6 /*2006*/);
1491   /* Avp validation */
1492   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__EnumeratedAvpWithValueDoesNotComplyRestriction, "", 10 /*2010*/);
1493   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__AvpFlagsDoesNotFulfillTheDefinedFlagRules,      "", 11 /*2011*/);
1494   /* Message validation */
1495   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__UnknownOperationUnableToValidate, "", 12 /*2012*/);
1496   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__OperationHaveIncoherentFlags,     "", 13 /*2013*/);
1497   /* Level validation */
1498   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__MissingFixedRule,                                       "", 14 /*2014*/);
1499   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinality,                               "", 15 /*2015*/);
1500   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityLessThanNeeded,                 "", 16 /*2016*/);
1501   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityMoreThanNeeded,                 "", 17 /*2017*/);
1502   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedGenericAvpRuleForCardinalityFoundDisregardedItem, "", 18 /*2018*/);
1503   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FoundDisregardedItemsAndGenericAVPWasNotSpecified,      "", 19 /*2019*/);
1504
1505   /////////////////////////////////
1506   // Counter recorder associated //
1507   /////////////////////////////////
1508   if(a_counterRecorderClock) {
1509     oamDiameterComm.setCounterRecorder(a_counterRecorder);
1510     oamDiameterCodec.setCounterRecorder(a_counterRecorder);
1511     a_timeEngine->activate(a_counterRecorderClock); // start clock
1512   }
1513
1514   // Checking command line parameters
1515   if(cl.exists("sessionBasedModelsClientSocketSelection")) {
1516     std::string type = cl.getValue("sessionBasedModelsClientSocketSelection");
1517
1518     if((type != "SessionIdHighPart") && (type != "SessionIdOptionalPart") && (type != "RoundRobin")) {
1519       throw anna::RuntimeException("Commandline option '-sessionBasedModelsClientSocketSelection' only accepts 'SessionIdHighPart'/'SessionIdOptionalPart'/'RoundRobin' as parameter values", ANNA_FILE_LOCATION);
1520     }
1521   }
1522
1523   // Tracing:
1524   if(cl.exists("trace"))
1525     anna::Logger::setLevel(anna::Logger::asLevel(cl.getValue("trace")));
1526
1527   LOGINFORMATION(
1528     // Help on startup traces:
1529     anna::Logger::information(help(), ANNA_FILE_LOCATION);
1530     // Test messages dtd:
1531     std::string msg = "\n                     ------------- TESTMESSAGES DTD -------------\n";
1532     msg += anna::diameter::codec::MessageDTD;
1533     anna::Logger::information(msg, ANNA_FILE_LOCATION);
1534   );
1535
1536   // HTTP Server:
1537   if(cl.exists("httpServer")) {
1538     anna::comm::Network& network = anna::comm::Network::instantiate();
1539     std::string address;
1540     int port;
1541     anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("httpServer"), address, port);
1542     //const anna::comm::Device* device = network.find(Device::asAddress(address)); // here provide IP
1543     const anna::comm::Device* device = *((network.resolve(address)->device_begin())); // trick to solve
1544     a_httpServerSocket = new anna::comm::ServerSocket(anna::comm::INetAddress(device, port), cl.exists("httpServerShared") /* shared bind */, &anna::http::Transport::getFactory());
1545   }
1546
1547   // Stack:
1548   anna::diameter::codec::Engine *codecEngine = new anna::diameter::codec::Engine();
1549   anna::diameter::stack::Engine &stackEngine = anna::diameter::stack::Engine::instantiate();
1550   anna::diameter::stack::Dictionary * d = stackEngine.createDictionary(0 /* stack id; its value don't mind, is not used (ADL is monostack) */);
1551   // Analyze comma-separated list:
1552   anna::Tokenizer lst;
1553   std::string dictionaryParameter = cl.getValue("dictionary");
1554   lst.apply(dictionaryParameter, ",");
1555
1556   if(lst.size() >= 1) {  // always true (at least one, because -dictionary is mandatory)
1557     anna::Tokenizer::const_iterator tok_min(lst.begin());
1558     anna::Tokenizer::const_iterator tok_max(lst.end());
1559     anna::Tokenizer::const_iterator tok_iter;
1560     std::string pathFile;
1561     d->allowUpdates();
1562
1563     for(tok_iter = tok_min; tok_iter != tok_max; tok_iter++) {
1564       pathFile = anna::Tokenizer::data(tok_iter);
1565       d->load(pathFile);
1566     }
1567   }
1568
1569   codecEngine->setDictionary(d);
1570   LOGDEBUG(anna::Logger::debug(codecEngine->asString(), ANNA_FILE_LOCATION));
1571
1572   if(lst.size() > 1) {
1573     std::string all_in_one = "./dictionary-all-in-one.xml";
1574     std::ofstream out(all_in_one.c_str(), std::ifstream::out);
1575     std::string buffer = d->asXMLString();
1576     out.write(buffer.c_str(), buffer.size());
1577     out.close();
1578     std::cout << "Written accumulated '" << all_in_one << "' (provide it next time to be more comfortable)." << std::endl;
1579   }
1580
1581
1582
1583   // Integration (validation 'Complete' for receiving messages) and debugging (validation also before encoding: 'Always').
1584   // If missing 'integrationAndDebugging', default behaviour at engine is: mode 'AfterDecoding', depth 'FirstError':
1585   if(cl.exists("integrationAndDebugging")) {
1586     codecEngine->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Always);
1587     codecEngine->setValidationDepth(anna::diameter::codec::Engine::ValidationDepth::Complete);
1588   }
1589
1590   codecEngine->ignoreFlagsOnValidation(cl.exists("ignoreFlags"));
1591
1592   // Diameter Server:
1593   if(cl.exists("diameterServer"))
1594     startDiameterServer(cl.exists("diameterServerSessions") ? cl.getIntegerValue("diameterServerSessions") : 1);
1595
1596   // Optional command line parameters ////////////////////////////////////////////////////////
1597   checkTimeMeasure("allowedInactivityTime");
1598   checkTimeMeasure("tcpConnectDelay");
1599   checkTimeMeasure("answersTimeout");
1600   checkTimeMeasure("ceaTimeout");
1601   checkTimeMeasure("watchdogPeriod");
1602   checkTimeMeasure("reconnectionPeriod");
1603   int tcpConnectDelay = 200; // ms
1604   anna::Millisecond answersTimeout = (anna::Millisecond)10000; // ms
1605   anna::Millisecond ceaTimeout;
1606   anna::Millisecond watchdogPeriod = (anna::Millisecond)30000; // ms
1607   int reconnectionPeriod = 10000; // ms
1608
1609   if(cl.exists("tcpConnectDelay"))         tcpConnectDelay = cl.getIntegerValue("tcpConnectDelay");
1610
1611   if(cl.exists("answersTimeout"))          answersTimeout = cl.getIntegerValue("answersTimeout");
1612
1613   if(cl.exists("ceaTimeout"))              ceaTimeout = cl.getIntegerValue("ceaTimeout");
1614   else                                      ceaTimeout = answersTimeout;
1615
1616   if(cl.exists("watchdogPeriod"))          watchdogPeriod = cl.getIntegerValue("watchdogPeriod");
1617
1618   if(cl.exists("reconnectionPeriod"))      reconnectionPeriod = cl.getIntegerValue("reconnectionPeriod");
1619
1620   a_myDiameterEngine->setMaxConnectionDelay((anna::Millisecond)tcpConnectDelay);
1621   a_myDiameterEngine->setWatchdogPeriod(watchdogPeriod);
1622   std::string originHost = "";
1623   std::string originRealm = "";
1624
1625   if(cl.exists("cer"))                  a_cerPathfile = cl.getValue("cer");
1626
1627   if(cl.exists("dwr"))                  a_dwrPathfile = cl.getValue("dwr");
1628
1629   if(cl.exists("originHost"))           originHost = cl.getValue("originHost");
1630
1631   if(cl.exists("originRealm"))          originRealm = cl.getValue("originRealm");
1632
1633   a_myDiameterEngine->setHost(originHost);
1634   a_myDiameterEngine->setRealm(originRealm);
1635
1636   // Diameter entity:
1637   if(cl.exists("entity")) {
1638     int entityServerSessions = cl.exists("entityServerSessions") ? cl.getIntegerValue("entityServerSessions") : 1;
1639
1640     if(entityServerSessions > 0) {
1641       baseProtocolSetupAsClient(); // Same CER/CEA, DWR/DWA for all diameter servers
1642       anna::socket_v servers = anna::functions::getSocketVectorFromString(cl.getValue("entity"));
1643       a_myDiameterEngine->setNumberOfClientSessionsPerServer(entityServerSessions);
1644       a_entity = a_myDiameterEngine->createEntity(servers, "Launcher diameter entity");
1645       a_entity->setClassCodeTimeout(anna::diameter::comm::ClassCode::Bind, ceaTimeout);
1646       a_entity->setClassCodeTimeout(anna::diameter::comm::ClassCode::ApplicationMessage, answersTimeout);
1647       a_entity->bind();
1648     }
1649   }
1650
1651   // Logs
1652   if(cl.exists("log")) a_logFile = cl.getValue("log");
1653
1654   if(cl.exists("splitLog")) a_splitLog = true;
1655
1656   if(cl.exists("detailedLog")) a_detailedLog = true;
1657
1658   if(cl.exists("burstLog")) a_burstLogFile = cl.getValue("burstLog");
1659
1660   // Log statistics concepts
1661   if(cl.exists("logStatisticSamples")) {
1662     std::string list = cl.getValue("logStatisticSamples");
1663     anna::statistics::Engine &statEngine = anna::statistics::Engine::instantiate();
1664
1665     if(list == "all") {
1666       if(statEngine.enableSampleLog(/* -1: all concepts */))
1667         LOGDEBUG(anna::Logger::debug("Sample log activation for all statistic concepts", ANNA_FILE_LOCATION));
1668     } else {
1669       anna::Tokenizer lst;
1670       lst.apply(cl.getValue("logStatisticSamples"), ",");
1671
1672       if(lst.size() >= 1) {
1673         anna::Tokenizer::const_iterator tok_min(lst.begin());
1674         anna::Tokenizer::const_iterator tok_max(lst.end());
1675         anna::Tokenizer::const_iterator tok_iter;
1676         int conceptId;
1677
1678         for(tok_iter = tok_min; tok_iter != tok_max; tok_iter++) {
1679           conceptId = atoi(anna::Tokenizer::data(tok_iter));
1680
1681           if(statEngine.enableSampleLog(conceptId))
1682             LOGDEBUG(anna::Logger::debug(anna::functions::asString("Sample log activation for statistic concept id = %d", conceptId), ANNA_FILE_LOCATION));
1683         }
1684       }
1685     }
1686   }
1687
1688   a_communicator->setRecoveryTime((const anna::Millisecond)reconnectionPeriod);
1689
1690   if(cl.exists("httpServer")) a_communicator->attach(a_httpServerSocket);  // HTTP
1691
1692   a_communicator->accept();
1693 }
1694
1695 void MyCommunicator::eventBreakConnection(Server* server)
1696 throw() {
1697   LOGMETHOD(anna::TraceMethod tm("MyCommunicator", "eventBreakConnection", ANNA_FILE_LOCATION));
1698   terminate();
1699   anna::comm::Communicator::eventBreakConnection(server);
1700 }
1701
1702 void MyCommunicator::terminate()
1703 throw() {
1704   if(hasRequestedStop() == true)
1705     return;
1706
1707   requestStop();
1708 }
1709
1710 void MyHandler::evRequest(anna::comm::ClientSocket& clientSocket, const anna::http::Request& request)
1711 throw(anna::RuntimeException) {
1712   const anna::DataBlock& body = request.getBody();
1713
1714   if(body.getSize() == 0)
1715     throw anna::RuntimeException("Missing operation parameters on HTTP request", ANNA_FILE_LOCATION);
1716
1717   LOGINFORMATION(
1718     string msg("Received body: ");
1719     msg += anna::functions::asString(body);
1720     anna::Logger::information(msg, ANNA_FILE_LOCATION);
1721   );
1722   std::string body_content;
1723   body_content.assign(body.getData(), body.getSize());
1724   // Operation:
1725   std::string response_content;
1726
1727   try {
1728     Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
1729     my_app.eventOperation(body_content, response_content);
1730   } catch(RuntimeException &ex) {
1731     ex.trace();
1732   }
1733
1734   anna::http::Response* response = allocateResponse();
1735   response->setStatusCode(200);  // http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
1736   anna::DataBlock db_content(true);
1737   db_content = response_content;
1738   response->setBody(db_content);
1739 //   response->find(anna::http::Header::Type::Date)->setValue("Mon, 30 Jan 2006 14:36:18 GMT");
1740 //   anna::http::Header* keepAlive = response->find("Keep-Alive");
1741 //
1742 //   if (keepAlive == NULL)
1743 //      keepAlive = response->createHeader("Keep-Alive");
1744 //
1745 //   keepAlive->setValue("Verificacion del cambio 1.0.7");
1746
1747   try {
1748     clientSocket.send(*response);
1749   } catch(Exception& ex) {
1750     ex.trace();
1751   }
1752 }
1753
1754 void Launcher::eventOperation(const std::string &operation, std::string &response_content) throw(anna::RuntimeException) {
1755   LOGMETHOD(anna::TraceMethod tm("Launcher", "eventOperation", ANNA_FILE_LOCATION));
1756   CommandLine& cl(anna::CommandLine::instantiate());
1757   LOGDEBUG(anna::Logger::debug(operation, ANNA_FILE_LOCATION));
1758   response_content = "Operation processed with exception. See traces\n"; // supposed
1759   std::string result = "";
1760   anna::DataBlock db_aux(true);
1761
1762   ///////////////////////////////////////////////////////////////////
1763   // Simple operations without arguments:
1764
1765   // Help:
1766   if(operation == "help") {
1767     std::string s_help = help();
1768     std::cout << s_help << std::endl;
1769     LOGINFORMATION(anna::Logger::information(s_help, ANNA_FILE_LOCATION));
1770     response_content = "Help dumped on stdout and information-level traces (launcher.trace file)\n";
1771     return;
1772   }
1773
1774   // Reset performance data:
1775   if(operation == "collect") {
1776     resetCounters();
1777     resetStatistics();
1778     response_content = "All process counters & statistic information have been reset\n";
1779     return;
1780   }
1781
1782   ///////////////////////////////////////////////////////////////////
1783   // Tokenize operation
1784   Tokenizer params;
1785   params.apply(operation, "|");
1786   int numParams = params.size() - 1;
1787
1788   // No operation has more than 2 arguments ...
1789   if(numParams > 2) {
1790     LOGWARNING(anna::Logger::warning(help(), ANNA_FILE_LOCATION));
1791     throw anna::RuntimeException("Wrong body content format on HTTP Request", ANNA_FILE_LOCATION);
1792   }
1793
1794   // Get the operation type:
1795   Tokenizer::const_iterator tok_iter = params.begin();
1796   std::string opType = Tokenizer::data(tok_iter);
1797   // Check the number of parameters:
1798   bool wrongBody = false;
1799
1800   if(((opType == "code") || (opType == "decode")) && (numParams != 2)) wrongBody = true;
1801
1802   if(((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) && (numParams != 1)) wrongBody = true;
1803
1804   if((opType == "burst") && (numParams < 1)) wrongBody = true;
1805
1806   if(((opType == "sendxml2c") || (opType == "sendhex2c") || (opType == "loadxml") || (opType == "diameterServerSessions")) && (numParams != 1)) wrongBody = true;
1807
1808   if(wrongBody) {
1809     // Launch exception
1810     std::string msg = "Wrong body content format on HTTP Request for '";
1811     msg += opType;
1812     msg += "' operation (missing parameter/s)";
1813     throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1814   }
1815
1816   // All seems ok:
1817   std::string param1, param2;
1818
1819   if(numParams >= 1) { tok_iter++; param1 = Tokenizer::data(tok_iter); }
1820
1821   if(numParams == 2) { tok_iter++; param2 = Tokenizer::data(tok_iter); }
1822
1823   // Operations:
1824   if(opType == "code") {
1825     G_codecMsg.loadXML(param1);
1826     std::string hexString = anna::functions::asHexString(G_codecMsg.code());
1827     // write to outfile
1828     ofstream outfile(param2.c_str(), ifstream::out);
1829     outfile.write(hexString.c_str(), hexString.size());
1830     outfile.close();
1831   } else if(opType == "decode") {
1832     // Get DataBlock from file with hex content:
1833     if(!getDataBlockFromHexFile(param1, db_aux))
1834       throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
1835
1836     // Decode
1837     try { G_codecMsg.decode(db_aux); } catch(anna::RuntimeException &ex) { ex.trace(); }
1838
1839     std::string xmlString = G_codecMsg.asXMLString();
1840     // write to outfile
1841     ofstream outfile(param2.c_str(), ifstream::out);
1842     outfile.write(xmlString.c_str(), xmlString.size());
1843     outfile.close();
1844   } else if((opType == "hide") || (opType == "show") || (opType == "hidden") || (opType == "shown")) {
1845     anna::diameter::comm::Entity *entity = getEntity();
1846
1847     if(!entity) throw anna::RuntimeException("No entity configured to send messages", ANNA_FILE_LOCATION);
1848
1849     if(param1 != "") {
1850       if(param2 != "") {
1851         std::string key = param1;
1852         key += "|";
1853         key += param2;
1854
1855         if(opType == "hide") getMyDiameterEngine()->findClientSession(key)->hide();
1856
1857         if(opType == "show") getMyDiameterEngine()->findClientSession(key)->show();
1858
1859         if(opType == "hidden") result = getMyDiameterEngine()->findClientSession(key)->hidden() ? "true" : "false";
1860
1861         if(opType == "shown") result = getMyDiameterEngine()->findClientSession(key)->shown() ? "true" : "false";
1862       } else {
1863         std::string address;
1864         int port;
1865         anna::functions::getAddressAndPortFromSocketLiteral(param1, address, port);
1866
1867         if(opType == "hide") getMyDiameterEngine()->findServer(address, port)->hide();
1868
1869         if(opType == "show") getMyDiameterEngine()->findServer(address, port)->show();
1870
1871         if(opType == "hidden") result = getMyDiameterEngine()->findServer(address, port)->hidden() ? "true" : "false";
1872
1873         if(opType == "shown") result = getMyDiameterEngine()->findServer(address, port)->shown() ? "true" : "false";
1874       }
1875     } else {
1876       if(opType == "hide") entity->hide();
1877
1878       if(opType == "show") entity->show();
1879
1880       if(opType == "hidden") result = entity->hidden() ? "true" : "false";
1881
1882       if(opType == "shown") result = entity->shown() ? "true" : "false";
1883     }
1884   } else if((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) {
1885     anna::diameter::comm::Entity *entity = getEntity();
1886
1887     if(!entity) throw anna::RuntimeException("No entity configured to send the message", ANNA_FILE_LOCATION);
1888
1889     if((opType == "sendxml") || (opType == "sendxml2e")) {
1890       G_codecMsg.loadXML(param1);
1891       G_commMsgSent2e.clearBody();
1892       try { G_codecMsg.valid(); } catch(anna::RuntimeException &ex) { ex.trace(); }  // at least we need to see validation errors although it will continue sending (see validation mode configured in launcher)
1893
1894       G_commMsgSent2e.setBody(G_codecMsg.code());
1895     } else {
1896       // Get DataBlock from file with hex content:
1897       if(!getDataBlockFromHexFile(param1, db_aux))
1898         throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
1899
1900       G_commMsgSent2e.setBody(db_aux);
1901     }
1902
1903     bool success = entity->send(G_commMsgSent2e, cl.exists("balance"));
1904
1905     // Detailed log:
1906     if(logEnabled()) {
1907       anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
1908       anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
1909       std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
1910       writeLogFile(G_codecMsg, (success ? "sent2e" : "send2eError"), detail);
1911     }
1912   } else if((opType == "burst")) {
1913     anna::diameter::comm::Entity *entity = getEntity();
1914
1915     if(!entity) throw anna::RuntimeException("No entity configured to use burst feature", ANNA_FILE_LOCATION);
1916
1917     // burst|clear                     clears all loaded burst messages.
1918     // burst|load|<source_file>        loads the next diameter message into launcher burst.
1919     // burst|start|<initial load>      starts the message sending with a certain initial load.
1920     // burst|push|<load amount>        sends specific non-aynchronous load.
1921     // burst|stop                      stops the burst cycle.
1922     // burst|repeat|[[yes]|no]         restarts the burst launch when finish.
1923     // burst|send|<amount>             send messages from burst list. The main difference with
1924     //                                 start/push operations is that burst won't be awaken.
1925     //                                 Externally we could control sending time (no request
1926     //                                 will be sent for answers).
1927     // burst|goto|<order>              Updates current burst pointer position.
1928     // burst|look|<order>              Show programmed burst message for order provided.
1929
1930     if(param1 == "clear") {
1931       result = "Removed ";
1932       result += anna::functions::asString(clearBurst());
1933       result += " elements.";
1934     } else if(param1 == "load") {
1935       if(param2 == "") throw anna::RuntimeException("Missing xml path file for burst load operation", ANNA_FILE_LOCATION);
1936
1937       G_codecMsg.loadXML(param2);
1938
1939       if(G_codecMsg.isAnswer()) throw anna::RuntimeException("Cannot load diameter answers for burst feature", ANNA_FILE_LOCATION);
1940       try { G_codecMsg.valid(); } catch(anna::RuntimeException &ex) { ex.trace(); }  // at least we need to see validation errors although it will continue loading (see validation mode configured in launcher)
1941
1942       int position = loadBurstMessage(G_codecMsg.code());
1943       result = "Loaded '";
1944       result += param2;
1945       result += "' file into burst list position ";
1946       result += anna::functions::asString(position);
1947     } else if(param1 == "start") {
1948       if(param2 == "") throw anna::RuntimeException("Missing initial load for burst start operation", ANNA_FILE_LOCATION);
1949
1950       int initialLoad = atoi(param2.c_str());
1951       int processed = startBurst(initialLoad);
1952
1953       if(processed > 0) {
1954         result = "Initial load completed for ";
1955         result += anna::functions::entriesAsString(processed, "message");
1956         result += ".";
1957       }
1958     } else if(param1 == "push") {
1959       if(param2 == "") throw anna::RuntimeException("Missing load amount for burst push operation", ANNA_FILE_LOCATION);
1960
1961       int pushed = pushBurst(atoi(param2.c_str()));
1962
1963       if(pushed > 0) {
1964         result = "Pushed ";
1965         result += anna::functions::entriesAsString(pushed, "message");
1966         result += ".";
1967       }
1968     } else if(param1 == "pop") {
1969       if(param2 == "") throw anna::RuntimeException("Missing amount for burst pop operation", ANNA_FILE_LOCATION);
1970
1971       int releaseLoad = atoi(param2.c_str());
1972       int popped = popBurst(releaseLoad);
1973
1974       if(popped > 0) {
1975         result = "Burst popped for ";
1976         result += anna::functions::entriesAsString(popped, "message");
1977         result += ".";
1978       }
1979     } else if(param1 == "stop") {
1980       int left = stopBurst();
1981
1982       if(left != -1) {
1983         result += anna::functions::entriesAsString(left, "message");
1984         result += " left to the end of the cycle.";
1985       }
1986     } else if(param1 == "repeat") {
1987       if(param2 == "") param2 = "yes";
1988
1989       bool repeat = (param2 == "yes");
1990       repeatBurst(repeat);
1991       result += (repeat ? "Mode on." : "Mode off.");
1992     } else if(param1 == "send") {
1993       if(param2 == "") throw anna::RuntimeException("Missing amount for burst send operation", ANNA_FILE_LOCATION);
1994
1995       int sent = sendBurst(atoi(param2.c_str()));
1996
1997       if(sent > 0) {
1998         result = "Sent ";
1999         result += anna::functions::entriesAsString(sent, "message");
2000         result += ".";
2001       }
2002     } else if(param1 == "goto") {
2003       if(param2 == "") throw anna::RuntimeException("Missing order position for burst goto operation", ANNA_FILE_LOCATION);
2004
2005       result = gotoBurst(atoi(param2.c_str()));
2006       result += ".";
2007     } else if(param1 == "look") {
2008       if(param2 == "") throw anna::RuntimeException("Missing order position for burst look operation", ANNA_FILE_LOCATION);
2009
2010       result = "\n\n";
2011       result += lookBurst(atoi(param2.c_str()));
2012       result += "\n\n";
2013     } else {
2014       throw anna::RuntimeException("Wrong body content format on HTTP Request for 'burst' operation (unexpected action parameter). See help", ANNA_FILE_LOCATION);
2015     }
2016   } else if((opType == "sendxml2c") || (opType == "sendhex2c")) {
2017     anna::diameter::comm::LocalServer *localServer = getDiameterLocalServer();
2018
2019     if(!localServer) throw anna::RuntimeException("No local server configured to send the message", ANNA_FILE_LOCATION);
2020
2021     if(opType == "sendxml2c") {
2022       G_codecMsg.loadXML(param1);
2023       G_commMsgSent2c.clearBody();
2024       try { G_codecMsg.valid(); } catch(anna::RuntimeException &ex) { ex.trace(); }  // at least we need to see validation errors although it will continue sending (see validation mode configured in launcher)
2025
2026       G_commMsgSent2c.setBody(G_codecMsg.code());
2027     } else {
2028       // Get DataBlock from file with hex content:
2029       if(!getDataBlockFromHexFile(param1, db_aux))
2030         throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
2031
2032       G_commMsgSent2c.setBody(db_aux);
2033     }
2034
2035     bool success = localServer->send(G_commMsgSent2c);
2036
2037     // Detailed log:
2038     if(logEnabled()) {
2039       anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource();
2040       std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // esto no deberia ocurrir
2041       writeLogFile(G_codecMsg, (success ? "sent2c" : "send2cError"), detail);
2042     }
2043   } else if(opType == "loadxml") {
2044     G_codecMsg.loadXML(param1);
2045     std::string xmlString = G_codecMsg.asXMLString();
2046     std::cout << xmlString << std::endl;
2047   } else if(opType == "diameterServerSessions") {
2048     int diameterServerSessions = atoi(param1.c_str());
2049
2050     if(!getDiameterLocalServer())
2051       startDiameterServer(diameterServerSessions);
2052     else
2053       getDiameterLocalServer()->setMaxConnections(diameterServerSessions);
2054   } else if((opType == "answerxml") || (opType == "answerxml2c")) {
2055     anna::diameter::comm::LocalServer *localServer = getDiameterLocalServer();
2056
2057     if(!localServer)
2058       throw anna::RuntimeException("Operation not applicable (no own diameter server has been configured)", ANNA_FILE_LOCATION);
2059
2060     if(param1 == "") { // programmed answers FIFO's to stdout
2061       std::cout << std::endl << std::endl;
2062       std::cout << "          ------------- CURRENT PROGRAMMED ANSWERS TO CLIENT -------------\n\n";
2063       std::cout << G_reactingAnswers2C.asString() << std::endl;
2064       response_content = "Programmed answers dumped on stdout\n";
2065       return;
2066     } else if (param1 == "clear") {
2067       G_reactingAnswers2C.clear();
2068     } else if (param1 == "dump") {
2069       G_reactingAnswers2C.dump();
2070     } else {
2071       anna::diameter::codec::Engine *engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION);
2072       anna::diameter::codec::Message *message = engine->createMessage(param1);
2073       LOGDEBUG
2074       (
2075         anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
2076       );
2077
2078       if(message->isRequest())
2079         throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
2080
2081       int code = message->getId().first;
2082       LOGDEBUG(anna::Logger::debug("Adding a new programed 'answer to client' to the FIFO queue corresponding to its message code ...", ANNA_FILE_LOCATION));
2083       G_reactingAnswers2C.addMessage(code, message);
2084     }
2085   } else if(opType == "answerxml2e") {
2086     anna::diameter::comm::Entity *entity = getEntity();
2087
2088     if(!entity)
2089       throw anna::RuntimeException("Operation not applicable (no diameter entity has been configured)", ANNA_FILE_LOCATION);
2090
2091     if(param1 == "") { // programmed answers FIFO's to stdout
2092       std::cout << std::endl << std::endl;
2093       std::cout << "          ------------- CURRENT PROGRAMMED ANSWERS TO ENTITY -------------\n\n";
2094       std::cout << G_reactingAnswers2E.asString() << std::endl;
2095       response_content = "Programmed answers dumped on stdout\n";
2096       return;
2097     } else if (param1 == "clear") {
2098       G_reactingAnswers2E.clear();
2099     } else if (param1 == "dump") {
2100       G_reactingAnswers2E.dump();
2101     } else { 
2102       anna::diameter::codec::Engine *engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION);
2103       anna::diameter::codec::Message *message = engine->createMessage(param1);
2104       LOGDEBUG
2105       (
2106         anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
2107       );
2108
2109       if(message->isRequest())
2110         throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
2111
2112       int code = message->getId().first;
2113       LOGDEBUG(anna::Logger::debug("Adding a new programed 'answer to entity' to the FIFO queue corresponding to its message code ...", ANNA_FILE_LOCATION));
2114       G_reactingAnswers2E.addMessage(code, message);
2115     }
2116   } else {
2117     LOGWARNING(anna::Logger::warning(help(), ANNA_FILE_LOCATION));
2118     throw anna::RuntimeException("Wrong body content format on HTTP Request. Unsupported/unrecognized operation type", ANNA_FILE_LOCATION);
2119   }
2120
2121   // HTTP response
2122   response_content = "Operation processed; ";
2123
2124   if((opType == "decode") || (opType == "code")) {
2125     response_content += "File '";
2126     response_content += param2;
2127     response_content += "' created.";
2128     response_content += "\n";
2129   } else if((opType == "hide") || (opType == "show")) {
2130     response_content += "Resource '";
2131     response_content += ((param1 != "") ? param1 : "Entity");
2132
2133     if(param2 != "") {
2134       response_content += "|";
2135       response_content += param2;
2136     }
2137
2138     response_content += "' ";
2139
2140     if(opType == "hide") response_content += "has been hidden.";
2141
2142     if(opType == "show") response_content += "has been shown.";
2143
2144     response_content += "\n";
2145   } else if((opType == "hidden") || (opType == "shown")) {
2146     response_content += "Result: ";
2147     response_content += result;
2148     response_content += "\n";
2149   } else if((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) {
2150     response_content += "Message '";
2151     response_content += param1;
2152     response_content += "' sent to entity.";
2153     response_content += "\n";
2154   } else if(opType == "burst") {
2155     response_content += "Burst '";
2156     response_content += param1;
2157     response_content += "' executed. ";
2158     response_content += result;
2159     response_content += "\n";
2160   } else if((opType == "sendxml2c") || (opType == "sendhex2c")) {
2161     response_content += "Message '";
2162     response_content += param1;
2163     response_content += "' sent to client.";
2164     response_content += "\n";
2165   } else if(opType == "loadxml") {
2166     response_content += "Message '";
2167     response_content += param1;
2168     response_content += "' loaded.";
2169     response_content += "\n";
2170   } else if((opType == "answerxml") || (opType == "answerxml2c")) {
2171     response_content += "Answer to client '";
2172     response_content += param1;
2173     response_content += "' programmed.";
2174     response_content += "\n";
2175   } else if(opType == "answerxml2e") {
2176     response_content += "Answer to entity '";
2177     response_content += param1;
2178     response_content += "' programmed.";
2179     response_content += "\n";
2180   } else if(opType == "diameterServerSessions") {
2181     response_content += "Maximum server socket connections updated to '";
2182     response_content += param1;
2183     response_content += "'.";
2184     response_content += "\n";
2185   }
2186 }
2187
2188
2189 int MyDiameterEntity::readSocketId(const anna::diameter::comm::Message* message, int maxClientSessions) const throw() {
2190   CommandLine& cl(anna::CommandLine::instantiate());
2191   std::string sessionBasedModelsType = (cl.exists("sessionBasedModelsClientSocketSelection") ? cl.getValue("sessionBasedModelsClientSocketSelection") : "SessionIdLowPart");
2192
2193   if(sessionBasedModelsType == "RoundRobin") return -1;  // IEC also would return -1
2194
2195   try {
2196     // Service-Context-Id:
2197     anna::diameter::helpers::dcca::ChargingContext::_v chargingContext;
2198     std::string scid = anna::diameter::helpers::dcca::functions::getServiceContextId(message->getBody(), chargingContext);
2199
2200     switch(chargingContext) {
2201     case anna::diameter::helpers::dcca::ChargingContext::Data:
2202     case anna::diameter::helpers::dcca::ChargingContext::Voice:
2203     case anna::diameter::helpers::dcca::ChargingContext::Content: {
2204       // Session-Id: '<DiameterIdentity>;<high 32 bits>;<low 32 bits>[;<optional value>="">]'
2205       std::string sid = anna::diameter::helpers::base::functions::getSessionId(message->getBody());
2206       std::string diameterIdentity, optional;
2207       anna::U32 high, low;
2208       anna::diameter::helpers::base::functions::decodeSessionId(sid, diameterIdentity, high, low /* context-teid */, optional);
2209
2210       if(sessionBasedModelsType == "SessionIdLowPart") return (low % maxClientSessions);
2211
2212       if(sessionBasedModelsType == "SessionIdHighPart") return (high % maxClientSessions);
2213
2214       if(sessionBasedModelsType == "SessionIdOptionalPart") return (atoi(optional.c_str()) % maxClientSessions);
2215     }
2216     //case anna::diameter::helpers::dcca::ChargingContext::SMS:
2217     //case anna::diameter::helpers::dcca::ChargingContext::MMS:
2218     //default:
2219     //   return -1; // IEC model and Unknown traffic types
2220     }
2221   } catch(anna::RuntimeException &ex) {
2222     LOGDEBUG(
2223       std::string msg = ex.getText();
2224       msg += " | Round-robin between sessions will be used to send";
2225       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2226     );
2227   }
2228
2229   return -1;
2230 }
2231
2232
2233 void MyDiameterEntity::eventRequest(anna::diameter::comm::ClientSession *clientSession, const anna::DataBlock &message)
2234 throw(anna::RuntimeException) {
2235   LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventRequest", ANNA_FILE_LOCATION));
2236   // Performance stats:
2237   Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2238   CommandLine& cl(anna::CommandLine::instantiate());
2239   // CommandId:
2240   anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
2241   LOGDEBUG
2242   (
2243     std::string msg = "Request received: ";
2244     msg += anna::diameter::functions::commandIdAsPairString(cid);
2245     msg += " | DiameterServer: ";
2246     msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort());
2247     msg += " | EventTime: ";
2248     msg += anna::time::functions::currentTimeAsString();
2249     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2250   );
2251
2252   // Write reception
2253   if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfe", clientSession->asString());
2254
2255   // Lookup reacting answers list:
2256   int code = cid.first;
2257   anna::diameter::codec::Message *answer_message = G_reactingAnswers2E.getMessage(code);
2258   if (answer_message) {
2259     // Prepare answer:
2260     my_app.getCommunicator()->prepareAnswer(answer_message, message);
2261
2262     try {
2263       G_commMsgSent2e.setBody(answer_message->code());
2264       /* response = NULL =*/clientSession->send(&G_commMsgSent2e);
2265
2266       if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "sent2e", clientSession->asString());
2267     } catch(anna::RuntimeException &ex) {
2268       ex.trace();
2269
2270       if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "send2eError", clientSession->asString());
2271     }
2272
2273     // Pop front the reacting answer:
2274     G_reactingAnswers2E.nextMessage(code);
2275     return;
2276   }
2277
2278   LOGDEBUG
2279   (
2280     std::string msg = "No answers programmed (maybe sold out) for request coming from entity: ";
2281     msg += anna::diameter::functions::commandIdAsPairString(cid);
2282     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2283   );
2284
2285   // not found: forward to client (if exists)
2286   // Forward to client:
2287   anna::diameter::comm::LocalServer *localServer = my_app.getDiameterLocalServer();
2288
2289   if(localServer && (cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) /* don't forward CER */) {
2290     try {
2291       anna::diameter::comm::Message *msg = G_commMessages.create();
2292       msg->setBody(message);
2293       msg->setRequestClientSessionKey(clientSession->getKey());
2294       bool success = localServer->send(msg);
2295
2296       // Detailed log:
2297       if(my_app.logEnabled()) {
2298         anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource();
2299         std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // esto no deberia ocurrir
2300         my_app.writeLogFile(message, (success ? "fwd2c" : "fwd2cError"), detail);
2301       }
2302     } catch(anna::RuntimeException &ex) {
2303       ex.trace();
2304     }
2305   }
2306 }
2307
2308
2309 void MyDiameterEntity::eventResponse(const anna::diameter::comm::Response &response)
2310 throw(anna::RuntimeException) {
2311   LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventResponse", ANNA_FILE_LOCATION));
2312   Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2313   CommandLine& cl(anna::CommandLine::instantiate());
2314   anna::diameter::comm::ClassCode::_v code = response.getClassCode();
2315   anna::diameter::comm::Response::ResultCode::_v result = response.getResultCode();
2316   anna::diameter::comm::Message* request = const_cast<anna::diameter::comm::Message*>(response.getRequest());
2317   const anna::DataBlock* message = response.getMessage();
2318   const anna::diameter::comm::ClientSession *clientSession = static_cast<const anna::diameter::comm::ClientSession *>(response.getSession());
2319   bool isBindResponse = (code == anna::diameter::comm::ClassCode::Bind);
2320   bool isApplicationMessage = (code == anna::diameter::comm::ClassCode::ApplicationMessage);
2321   bool contextExpired = (result == anna::diameter::comm::Response::ResultCode::Timeout);
2322   bool isUnavailable = (result == anna::diameter::comm::Response::ResultCode::DiameterUnavailable);
2323   bool isOK = (result == anna::diameter::comm::Response::ResultCode::Success);
2324   // CommandId:
2325   anna::diameter::CommandId request_cid = request->getCommandId();
2326   LOGDEBUG
2327   (
2328     std::string msg = "Response received for original diameter request: ";
2329     msg += anna::diameter::functions::commandIdAsPairString(request_cid);
2330     msg += " | Response: ";
2331     msg += response.asString();
2332     msg += " | DiameterServer: ";
2333     msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort());
2334     msg += " | EventTime: ";
2335     msg += anna::time::functions::currentTimeAsString();
2336     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2337   );
2338
2339   if(isUnavailable) {
2340     //if (isApplicationMessage)
2341     LOGWARNING(anna::Logger::warning("Diameter entity unavailable for Diameter Request", ANNA_FILE_LOCATION));
2342   }
2343
2344   if(contextExpired) {
2345     //if (isApplicationMessage)
2346     LOGWARNING(anna::Logger::warning("Context Expired for Diameter Request which was sent to the entity", ANNA_FILE_LOCATION));
2347
2348     if(request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) {  // don't trace CEA
2349       if(my_app.logEnabled()) my_app.writeLogFile(*request, "req2e-expired", clientSession->asString());
2350     }
2351   }
2352
2353   if(isOK) {
2354     LOGDEBUG(
2355       std::string msg = "Received response for diameter message:  ";
2356       msg += anna::diameter::functions::commandIdAsPairString(request_cid);
2357       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2358     );
2359     // Write reception
2360     bool alreadyDecodedOnG_codecMsg = false;
2361
2362     if(request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) {  // don't trace CEA
2363       if(my_app.logEnabled()) {
2364         my_app.writeLogFile(*message, "recvfe", clientSession->asString());
2365         alreadyDecodedOnG_codecMsg = true;
2366       }
2367     }
2368
2369     // Forward to client:
2370     anna::diameter::comm::LocalServer *localServer = my_app.getDiameterLocalServer();
2371
2372     if(localServer && (request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) /* don't forward CEA */) {
2373       try {
2374         G_commMsgFwd2c.setBody(*message);
2375         bool success = localServer->send(&G_commMsgFwd2c, request->getRequestServerSessionKey());
2376         G_commMessages.release(request);
2377         // Detailed log:
2378         anna::diameter::comm::ServerSession *usedServerSession = my_app.getMyDiameterEngine()->findServerSession(request->getRequestServerSessionKey());
2379         std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // esto no deberia ocurrir
2380
2381         if(my_app.logEnabled()) {
2382           if(alreadyDecodedOnG_codecMsg)
2383             my_app.writeLogFile(G_codecMsg, (success ? "fwd2c" : "fwd2cError"), detail);
2384           else
2385             my_app.writeLogFile(*message, (success ? "fwd2c" : "fwd2cError"), detail);
2386         }
2387       } catch(anna::RuntimeException &ex) {
2388         ex.trace();
2389       }
2390     }
2391   }
2392
2393   // Triggering burst:
2394   if(isOK || contextExpired) my_app.sendBurstMessage();
2395 }
2396
2397
2398 void MyDiameterEntity::eventUnknownResponse(anna::diameter::comm::ClientSession *clientSession, const anna::DataBlock &message)
2399 throw(anna::RuntimeException) {
2400   LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventUnknownResponse", ANNA_FILE_LOCATION));
2401   // Performance stats:
2402   Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2403   // CommandId:
2404   anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
2405   LOGDEBUG
2406   (
2407     std::string msg = "Out-of-context response received from entity: ";
2408     msg += anna::diameter::functions::commandIdAsPairString(cid);
2409     msg += " | DiameterServer: ";
2410     msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort());
2411     msg += " | EventTime: ";
2412     msg += anna::time::functions::currentTimeAsString();
2413     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2414   );
2415
2416   // Write reception
2417   if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfe-ans-unknown", clientSession->asString());
2418 }
2419
2420
2421
2422
2423 void MyLocalServer::eventRequest(anna::diameter::comm::ServerSession *serverSession, const anna::DataBlock &message)
2424 throw(anna::RuntimeException) {
2425   LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventRequest", ANNA_FILE_LOCATION));
2426   // Performance stats:
2427   Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2428   CommandLine& cl(anna::CommandLine::instantiate());
2429   // CommandId:
2430   anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
2431   LOGDEBUG
2432   (
2433     std::string msg = "Request received: ";
2434     msg += anna::diameter::functions::commandIdAsPairString(cid);
2435     msg += " | DiameterServer: ";
2436     msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort());
2437     msg += " | EventTime: ";
2438     msg += anna::time::functions::currentTimeAsString();
2439     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2440   );
2441
2442   // Write reception
2443   if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfc", serverSession->asString());
2444
2445   // If no answer is programmed and entity is configured, the failed request would be forwarded even being wrong (delegates at the end point)
2446   int code = cid.first;
2447   anna::diameter::codec::Message *programmed_answer = G_reactingAnswers2C.getMessage(code);
2448   bool programmed = (programmed_answer != NULL);
2449
2450   anna::diameter::comm::Entity *entity = my_app.getEntity();
2451   if(!programmed && entity) {  // forward condition (no programmed answer + entity available)
2452     anna::diameter::comm::Message *msg = G_commMessages.create();
2453     msg->setBody(message);
2454     msg->setRequestServerSessionKey(serverSession->getKey());
2455     bool success = entity->send(msg, cl.exists("balance"));
2456
2457     // Detailed log:
2458     if(my_app.logEnabled()) {
2459       anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
2460       anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
2461       std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
2462       my_app.writeLogFile(message, (success ? "fwd2e" : "fwd2eError"), detail); // forwarded
2463     }
2464
2465     return;
2466   }
2467
2468   // Error analisys:
2469   bool analysisOK = true; // by default
2470   anna::diameter::codec::Message *answer_message = NULL;
2471
2472   if(!cl.exists("ignoreErrors")) {  // Error analysis
2473     answer_message = (anna::diameter::codec::Message*) & G_codecAnsMsg;
2474     answer_message->clear();
2475
2476     // Decode
2477     try { G_codecMsg.decode(message, answer_message); } catch(anna::RuntimeException &ex) { ex.trace(); }
2478
2479     answer_message->setStandardToAnswer(G_codecMsg, my_app.getMyDiameterEngine()->getHost(), my_app.getMyDiameterEngine()->getRealm());
2480     analysisOK = (answer_message->getResultCode() == anna::diameter::helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS);
2481   }
2482
2483   // Programmed answer only when all is ok
2484   if(analysisOK) {
2485     if(programmed) {
2486       answer_message = programmed_answer;
2487       // Prepare answer:
2488       my_app.getCommunicator()->prepareAnswer(answer_message, message);
2489     } else return; // nothing done
2490   }
2491
2492   anna::diameter::codec::Engine *codecEngine = (anna::functions::component <anna::diameter::codec::Engine> (ANNA_FILE_LOCATION));
2493   anna::diameter::codec::Engine::ValidationMode::_v backupVM = codecEngine->getValidationMode();
2494
2495   if(!analysisOK)
2496     codecEngine->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Never);
2497
2498   try {
2499     G_commMsgSent2c.setBody(answer_message->code());
2500     /* response = NULL =*/serverSession->send(&G_commMsgSent2c);
2501
2502     if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "sent2c", serverSession->asString());
2503   } catch(anna::RuntimeException &ex) {
2504     ex.trace();
2505
2506     if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "send2cError", serverSession->asString());
2507   }
2508
2509   // Restore validation mode
2510   codecEngine->setValidationMode(backupVM);
2511
2512   // Pop front the reacting answer:
2513   if(analysisOK && programmed) G_reactingAnswers2C.nextMessage(code);
2514 }
2515
2516 void MyLocalServer::eventResponse(const anna::diameter::comm::Response &response)
2517 throw(anna::RuntimeException) {
2518   LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventResponse", ANNA_FILE_LOCATION));
2519   Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2520   CommandLine& cl(anna::CommandLine::instantiate());
2521   anna::diameter::comm::ClassCode::_v code = response.getClassCode();
2522   anna::diameter::comm::Response::ResultCode::_v result = response.getResultCode();
2523   anna::diameter::comm::Message* request = const_cast<anna::diameter::comm::Message*>(response.getRequest());
2524   const anna::DataBlock* message = response.getMessage();
2525   const anna::diameter::comm::ServerSession *serverSession = static_cast<const anna::diameter::comm::ServerSession *>(response.getSession());
2526   bool isBindResponse = (code == anna::diameter::comm::ClassCode::Bind);
2527   bool isApplicationMessage = (code == anna::diameter::comm::ClassCode::ApplicationMessage);
2528   bool contextExpired = (result == anna::diameter::comm::Response::ResultCode::Timeout);
2529   bool isUnavailable = (result == anna::diameter::comm::Response::ResultCode::DiameterUnavailable);
2530   bool isOK = (result == anna::diameter::comm::Response::ResultCode::Success);
2531   // CommandId:
2532   anna::diameter::CommandId request_cid = request->getCommandId();
2533   LOGDEBUG
2534   (
2535     std::string msg = "Response received for original diameter request: ";
2536     msg += anna::diameter::functions::commandIdAsPairString(request_cid);
2537     msg += " | Response: ";
2538     msg += response.asString();
2539     msg += " | LocalServer: ";
2540     msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort());
2541     msg += " | EventTime: ";
2542     msg += anna::time::functions::currentTimeAsString();
2543     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2544   );
2545
2546   if(isUnavailable) {
2547     //if (isApplicationMessage)
2548     LOGWARNING(anna::Logger::warning("Diameter client unavailable for Diameter Request", ANNA_FILE_LOCATION));
2549   }
2550
2551   if(contextExpired) {
2552     //if (isApplicationMessage)
2553     LOGWARNING(anna::Logger::warning("Context Expired for Diameter Request which was sent to the client", ANNA_FILE_LOCATION));
2554
2555     if(request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) {  // don't trace CEA
2556       if(my_app.logEnabled()) my_app.writeLogFile(*request, "req2c-expired", serverSession->asString());
2557     }
2558   }
2559
2560   if(isOK) {
2561     LOGDEBUG(
2562       std::string msg = "Received response for diameter message:  ";
2563       msg += anna::diameter::functions::commandIdAsPairString(request_cid);
2564       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2565     );
2566
2567     // Write reception
2568     if(my_app.logEnabled()) my_app.writeLogFile(*message, "recvfc", serverSession->asString());
2569
2570     // This is not very usual, but answers could arrive from clients:
2571     anna::diameter::comm::Entity *entity = my_app.getEntity();
2572
2573     if(entity) {
2574       anna::diameter::comm::ClientSession *usedClientSession = my_app.getMyDiameterEngine()->findClientSession(request->getRequestClientSessionKey());
2575       std::string detail;
2576
2577       if(my_app.logEnabled()) detail = usedClientSession ? usedClientSession->asString() : "<null client session>";  // esto no deberia ocurrir
2578
2579       try {
2580         G_commMsgFwd2e.setBody(*message);
2581
2582         // Metodo 1:
2583         if(usedClientSession) /* response = NULL =*/usedClientSession->send(&G_commMsgFwd2e);
2584
2585         // Metodo 2:
2586         //G_commMsgFwd2e.setRequestClientSessionKey(request->getRequestClientSessionKey());
2587         //bool success = entity->send(G_commMsgFwd2e);
2588         G_commMessages.release(request);
2589
2590         if(my_app.logEnabled()) my_app.writeLogFile(*message, "fwd2e", detail);  // forwarded
2591       } catch(anna::RuntimeException &ex) {
2592         ex.trace();
2593
2594         if(my_app.logEnabled()) my_app.writeLogFile(*message, "fwd2eError", detail);  // forwarded
2595       }
2596     }
2597   }
2598 }
2599
2600 void MyLocalServer::eventUnknownResponse(anna::diameter::comm::ServerSession *serverSession, const anna::DataBlock &message)
2601 throw(anna::RuntimeException) {
2602   LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventUnknownResponse", ANNA_FILE_LOCATION));
2603   // Performance stats:
2604   Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2605   // CommandId:
2606   anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
2607   LOGDEBUG
2608   (
2609     std::string msg = "Out-of-context response received from client: ";
2610     msg += anna::diameter::functions::commandIdAsPairString(cid);
2611     msg += " | DiameterServer: ";
2612     msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort());
2613     msg += " | EventTime: ";
2614     msg += anna::time::functions::currentTimeAsString();
2615     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2616   );
2617
2618   if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfc-ans-unknown", serverSession->asString());
2619 }
2620
2621
2622 anna::xml::Node* Launcher::asXML(anna::xml::Node* parent) const
2623 throw() {
2624   anna::xml::Node* result = parent->createChild("launcher");
2625   anna::comm::Application::asXML(result);
2626   // Timming:
2627   result->createAttribute("StartTime", a_start_time.asString());
2628   result->createAttribute("SecondsLifeTime", anna::time::functions::lapsedMilliseconds() / 1000);
2629   // Diameter:
2630   (anna::functions::component <anna::diameter::codec::Engine> (ANNA_FILE_LOCATION))->asXML(result);
2631   // OAM:
2632   anna::diameter::comm::OamModule::instantiate().asXML(result);
2633   anna::diameter::codec::OamModule::instantiate().asXML(result);
2634   // Statistics:
2635   anna::statistics::Engine::instantiate().asXML(result);
2636   return result;
2637 }
2638