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