]> git.stg.codes - stg.git/blob - projects/stargazer/plugins/authorization/inetaccess/inetaccess.cpp
Code cleanup.
[stg.git] / projects / stargazer / plugins / authorization / inetaccess / inetaccess.cpp
1 /*
2  *    This program is free software; you can redistribute it and/or modify
3  *    it under the terms of the GNU General Public License as published by
4  *    the Free Software Foundation; either version 2 of the License, or
5  *    (at your option) any later version.
6  *
7  *    This program is distributed in the hope that it will be useful,
8  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
9  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  *    GNU General Public License for more details.
11  *
12  *    You should have received a copy of the GNU General Public License
13  *    along with this program; if not, write to the Free Software
14  *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
15  */
16
17 /*
18  *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
19  */
20
21 /*
22  $Revision: 1.79 $
23  $Date: 2010/03/25 15:18:48 $
24  $Author: faust $
25  */
26  
27 #ifndef _GNU_SOURCE
28 #define _GNU_SOURCE
29 #endif
30
31 #include <sys/types.h>
32 #include <sys/socket.h>
33 #include <unistd.h> // close
34
35 #include <csignal>
36 #include <cstdlib>
37 #include <cstdio> // snprintf
38 #include <cerrno>
39 #include <cmath>
40 #include <algorithm>
41
42 #include "stg/common.h"
43 #include "stg/locker.h"
44 #include "stg/tariff.h"
45 #include "stg/user_property.h"
46 #include "stg/settings.h"
47 #include "stg/plugin_creator.h"
48 #include "inetaccess.h"
49
50 extern volatile const time_t stgTime;
51
52 void InitEncrypt(BLOWFISH_CTX * ctx, const string & password);
53 void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
54 void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
55
56 //-----------------------------------------------------------------------------
57 //-----------------------------------------------------------------------------
58 //-----------------------------------------------------------------------------
59 PLUGIN_CREATOR<AUTH_IA> iac;
60 //-----------------------------------------------------------------------------
61 //-----------------------------------------------------------------------------
62 //-----------------------------------------------------------------------------
63 PLUGIN * GetPlugin()
64 {
65 return iac.GetPlugin();
66 }
67 //-----------------------------------------------------------------------------
68 //-----------------------------------------------------------------------------
69 //-----------------------------------------------------------------------------
70 AUTH_IA_SETTINGS::AUTH_IA_SETTINGS()
71     : userDelay(0),
72       userTimeout(0),
73       port(0),
74       errorStr(),
75       freeMbShowType(freeMbCash)
76 {
77 }
78 //-----------------------------------------------------------------------------
79 int AUTH_IA_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
80 {
81 int p;
82 PARAM_VALUE pv;
83 vector<PARAM_VALUE>::const_iterator pvi;
84 ///////////////////////////
85 pv.param = "Port";
86 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
87 if (pvi == s.moduleParams.end())
88     {
89     errorStr = "Parameter \'Port\' not found.";
90     printfd(__FILE__, "Parameter 'Port' not found\n");
91     return -1;
92     }
93 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
94     {
95     errorStr = "Cannot parse parameter \'Port\': " + errorStr;
96     printfd(__FILE__, "Cannot parse parameter 'Port'\n");
97     return -1;
98     }
99 port = p;
100 ///////////////////////////
101 pv.param = "UserDelay";
102 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
103 if (pvi == s.moduleParams.end())
104     {
105     errorStr = "Parameter \'UserDelay\' not found.";
106     printfd(__FILE__, "Parameter 'UserDelay' not found\n");
107     return -1;
108     }
109
110 if (ParseIntInRange(pvi->value[0], 5, 600, &userDelay))
111     {
112     errorStr = "Cannot parse parameter \'UserDelay\': " + errorStr;
113     printfd(__FILE__, "Cannot parse parameter 'UserDelay'\n");
114     return -1;
115     }
116 ///////////////////////////
117 pv.param = "UserTimeout";
118 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
119 if (pvi == s.moduleParams.end())
120     {
121     errorStr = "Parameter \'UserTimeout\' not found.";
122     printfd(__FILE__, "Parameter 'UserTimeout' not found\n");
123     return -1;
124     }
125
126 if (ParseIntInRange(pvi->value[0], 15, 1200, &userTimeout))
127     {
128     errorStr = "Cannot parse parameter \'UserTimeout\': " + errorStr;
129     printfd(__FILE__, "Cannot parse parameter 'UserTimeout'\n");
130     return -1;
131     }
132 /////////////////////////////////////////////////////////////
133 string freeMbType;
134 int n = 0;
135 pv.param = "FreeMb";
136 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
137 if (pvi == s.moduleParams.end())
138     {
139     errorStr = "Parameter \'FreeMb\' not found.";
140     printfd(__FILE__, "Parameter 'FreeMb' not found\n");
141     return -1;
142     }
143 freeMbType = pvi->value[0];
144
145 if (strcasecmp(freeMbType.c_str(), "cash") == 0)
146     {
147     freeMbShowType = freeMbCash;
148     }
149 else if (strcasecmp(freeMbType.c_str(), "none") == 0)
150     {
151     freeMbShowType = freeMbNone;
152     }
153 else if (!str2x(freeMbType.c_str(), n))
154     {
155     if (n < 0 || n >= DIR_NUM)
156         {
157         errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
158         printfd(__FILE__, "%s\n", errorStr.c_str());
159         return -1;
160         }
161     freeMbShowType = (FREEMB)(freeMb0 + n);
162     }
163 else
164     {
165     errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
166     printfd(__FILE__, "%s\n", errorStr.c_str());
167     return -1;
168     }
169 /////////////////////////////////////////////////////////////
170 return 0;
171 }
172 //-----------------------------------------------------------------------------
173 //-----------------------------------------------------------------------------
174 //-----------------------------------------------------------------------------
175 #ifdef IA_PHASE_DEBUG
176 IA_PHASE::IA_PHASE()
177     : phase(1),
178       phaseTime(),
179       flog(NULL)
180 {
181 gettimeofday(&phaseTime, NULL);
182 }
183 #else
184 IA_PHASE::IA_PHASE()
185     : phase(1),
186       phaseTime()
187 {
188 gettimeofday(&phaseTime, NULL);
189 }
190 #endif
191 //-----------------------------------------------------------------------------
192 IA_PHASE::~IA_PHASE()
193 {
194 #ifdef IA_PHASE_DEBUG
195 flog = fopen(log.c_str(), "at");
196 if (flog)
197     {
198     fprintf(flog, "IA %s D\n", login.c_str());
199     fclose(flog);
200     }
201 #endif
202 }
203 //-----------------------------------------------------------------------------
204 #ifdef IA_PHASE_DEBUG
205 void IA_PHASE::SetLogFileName(const string & logFileName)
206 {
207 log = logFileName + ".ia.log";
208 }
209 //-----------------------------------------------------------------------------
210 void IA_PHASE::SetUserLogin(const string & login)
211 {
212 IA_PHASE::login = login;
213 }
214 //-----------------------------------------------------------------------------
215 void IA_PHASE::WritePhaseChange(int newPhase)
216 {
217 UTIME newPhaseTime;
218 gettimeofday(&newPhaseTime, NULL);
219 flog = fopen(log.c_str(), "at");
220 if (flog)
221     {
222     string action = newPhase == phase ? "U" : "C";
223     double delta = newPhaseTime.GetSec() - phaseTime.GetSec();
224     delta += (newPhaseTime.GetUSec() - phaseTime.GetUSec()) * 1.0e-6;
225     fprintf(flog, "IA %s %s oldPhase = %d, newPhase = %d. dt = %.6f\n",
226             login.c_str(),
227             action.c_str(),
228             phase,
229             newPhase,
230             delta);
231     fclose(flog);
232     }
233 }
234 #endif
235 //-----------------------------------------------------------------------------
236 void IA_PHASE::SetPhase1()
237 {
238 #ifdef IA_PHASE_DEBUG
239 WritePhaseChange(1);
240 #endif
241 phase = 1;
242 gettimeofday(&phaseTime, NULL);
243 }
244 //-----------------------------------------------------------------------------
245 void IA_PHASE::SetPhase2()
246 {
247 #ifdef IA_PHASE_DEBUG
248 WritePhaseChange(2);
249 #endif
250 phase = 2;
251 gettimeofday(&phaseTime, NULL);
252 }
253 //-----------------------------------------------------------------------------
254 void IA_PHASE::SetPhase3()
255 {
256 #ifdef IA_PHASE_DEBUG
257 WritePhaseChange(3);
258 #endif
259 phase = 3;
260 gettimeofday(&phaseTime, NULL);
261 }
262 //-----------------------------------------------------------------------------
263 void IA_PHASE::SetPhase4()
264 {
265 #ifdef IA_PHASE_DEBUG
266 WritePhaseChange(4);
267 #endif
268 phase = 4;
269 gettimeofday(&phaseTime, NULL);
270 }
271 //-----------------------------------------------------------------------------
272 void IA_PHASE::SetPhase5()
273 {
274 #ifdef IA_PHASE_DEBUG
275 WritePhaseChange(5);
276 #endif
277 phase = 5;
278 gettimeofday(&phaseTime, NULL);
279 }
280 //-----------------------------------------------------------------------------
281 int IA_PHASE::GetPhase() const
282 {
283 return phase;
284 }
285 //-----------------------------------------------------------------------------
286 void IA_PHASE::UpdateTime()
287 {
288 #ifdef IA_PHASE_DEBUG
289 WritePhaseChange(phase);
290 #endif
291 gettimeofday(&phaseTime, NULL);
292 }
293 //-----------------------------------------------------------------------------
294 const UTIME & IA_PHASE::GetTime() const
295 {
296 return phaseTime;
297 }
298 //-----------------------------------------------------------------------------
299 //-----------------------------------------------------------------------------
300 //-----------------------------------------------------------------------------
301 AUTH_IA::AUTH_IA()
302     : ctxS(),
303       errorStr(),
304       iaSettings(),
305       settings(),
306       nonstop(false),
307       isRunningRun(false),
308       isRunningRunTimeouter(false),
309       users(NULL),
310       stgSettings(NULL),
311       ip2user(),
312       recvThread(),
313       timeouterThread(),
314       mutex(),
315       listenSocket(-1),
316       connSynAck6(),
317       connSynAck8(),
318       disconnSynAck6(),
319       disconnSynAck8(),
320       aliveSyn6(),
321       aliveSyn8(),
322       fin6(),
323       fin8(),
324       packetTypes(),
325       enabledDirs(0xFFffFFff),
326       onDelUserNotifier(*this),
327       logger(GetPluginLogger(GetStgLogger(), "auth_ia"))
328 {
329 InitEncrypt(&ctxS, "pr7Hhen");
330
331 pthread_mutexattr_t attr;
332 pthread_mutexattr_init(&attr);
333 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
334 pthread_mutex_init(&mutex, &attr);
335
336 memset(&connSynAck6, 0, sizeof(CONN_SYN_ACK_6));
337 memset(&connSynAck8, 0, sizeof(CONN_SYN_ACK_8));
338 memset(&disconnSynAck6, 0, sizeof(DISCONN_SYN_ACK_6));
339 memset(&disconnSynAck8, 0, sizeof(DISCONN_SYN_ACK_8));
340 memset(&aliveSyn6, 0, sizeof(ALIVE_SYN_6));
341 memset(&aliveSyn8, 0, sizeof(ALIVE_SYN_8));
342 memset(&fin6, 0, sizeof(FIN_6));
343 memset(&fin8, 0, sizeof(FIN_8));
344
345 printfd(__FILE__, "sizeof(CONN_SYN_6) = %d %d\n",           sizeof(CONN_SYN_6),     Min8(sizeof(CONN_SYN_6)));
346 printfd(__FILE__, "sizeof(CONN_SYN_8) = %d %d\n",           sizeof(CONN_SYN_8),     Min8(sizeof(CONN_SYN_8)));
347 printfd(__FILE__, "sizeof(CONN_SYN_ACK_6) = %d %d\n",       sizeof(CONN_SYN_ACK_6), Min8(sizeof(CONN_SYN_ACK_6)));
348 printfd(__FILE__, "sizeof(CONN_SYN_ACK_8) = %d %d\n",       sizeof(CONN_SYN_ACK_8), Min8(sizeof(CONN_SYN_ACK_8)));
349 printfd(__FILE__, "sizeof(CONN_ACK_6) = %d %d\n",           sizeof(CONN_ACK_6),     Min8(sizeof(CONN_ACK_6)));
350 printfd(__FILE__, "sizeof(ALIVE_SYN_6) = %d %d\n",          sizeof(ALIVE_SYN_6),    Min8(sizeof(ALIVE_SYN_6)));
351 printfd(__FILE__, "sizeof(ALIVE_SYN_8) = %d %d\n",          sizeof(ALIVE_SYN_8),    Min8(sizeof(ALIVE_SYN_8)));
352 printfd(__FILE__, "sizeof(ALIVE_ACK_6) = %d %d\n",          sizeof(ALIVE_ACK_6),    Min8(sizeof(ALIVE_ACK_6)));
353 printfd(__FILE__, "sizeof(DISCONN_SYN_6) = %d %d\n",        sizeof(DISCONN_SYN_6),  Min8(sizeof(DISCONN_SYN_6)));
354 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_6) = %d %d\n",    sizeof(DISCONN_SYN_ACK_6), Min8(sizeof(DISCONN_SYN_ACK_6)));
355 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_8) = %d %d\n",    sizeof(DISCONN_SYN_ACK_8), Min8(sizeof(DISCONN_SYN_ACK_8)));
356 printfd(__FILE__, "sizeof(DISCONN_ACK_6) = %d %d\n",        sizeof(DISCONN_ACK_6),  Min8(sizeof(DISCONN_ACK_6)));
357 printfd(__FILE__, "sizeof(FIN_6) = %d %d\n",                sizeof(FIN_6),          Min8(sizeof(FIN_6)));
358 printfd(__FILE__, "sizeof(FIN_8) = %d %d\n",                sizeof(FIN_8),          Min8(sizeof(FIN_8)));
359 printfd(__FILE__, "sizeof(ERR) = %d %d\n",                  sizeof(ERR),            Min8(sizeof(ERR)));
360 printfd(__FILE__, "sizeof(INFO_6) = %d %d\n",               sizeof(INFO_6),         Min8(sizeof(INFO_6)));
361 printfd(__FILE__, "sizeof(INFO_7) = %d %d\n",               sizeof(INFO_7),         Min8(sizeof(INFO_7)));
362 printfd(__FILE__, "sizeof(INFO_8) = %d %d\n",               sizeof(INFO_8),         Min8(sizeof(INFO_8)));
363
364 packetTypes["CONN_SYN"] = CONN_SYN_N;
365 packetTypes["CONN_SYN_ACK"] = CONN_SYN_ACK_N;
366 packetTypes["CONN_ACK"] = CONN_ACK_N;
367 packetTypes["ALIVE_SYN"] = ALIVE_SYN_N;
368 packetTypes["ALIVE_ACK"] = ALIVE_ACK_N;
369 packetTypes["DISCONN_SYN"] = DISCONN_SYN_N;
370 packetTypes["DISCONN_SYN_ACK"] = DISCONN_SYN_ACK_N;
371 packetTypes["DISCONN_ACK"] = DISCONN_ACK_N;
372 packetTypes["FIN"] = FIN_N;
373 packetTypes["ERR"] = ERROR_N;
374 }
375 //-----------------------------------------------------------------------------
376 AUTH_IA::~AUTH_IA()
377 {
378 pthread_mutex_destroy(&mutex);
379 }
380 //-----------------------------------------------------------------------------
381 int AUTH_IA::Start()
382 {
383 users->AddNotifierUserDel(&onDelUserNotifier);
384 nonstop = true;
385
386 if (PrepareNet())
387     {
388     return -1;
389     }
390
391 if (!isRunningRun)
392     {
393     if (pthread_create(&recvThread, NULL, Run, this))
394         {
395         errorStr = "Cannot create thread.";
396         printfd(__FILE__, "Cannot create recv thread\n");
397         logger("Cannot create recv thread.");
398         return -1;
399         }
400     }
401
402 if (!isRunningRunTimeouter)
403     {
404     if (pthread_create(&timeouterThread, NULL, RunTimeouter, this))
405         {
406         errorStr = "Cannot create thread.";
407         printfd(__FILE__, "Cannot create timeouter thread\n");
408         logger("Cannot create timeouter thread.");
409         return -1;
410         }
411     }
412 errorStr = "";
413 return 0;
414 }
415 //-----------------------------------------------------------------------------
416 int AUTH_IA::Stop()
417 {
418 if (!IsRunning())
419     return 0;
420
421 nonstop = false;
422
423 std::for_each(
424         ip2user.begin(),
425         ip2user.end(),
426         UnauthorizeUser(this)
427         );
428
429 if (isRunningRun)
430     {
431     //5 seconds to thread stops itself
432     for (int i = 0; i < 25 && isRunningRun; i++)
433         {
434         struct timespec ts = {0, 200000000};
435         nanosleep(&ts, NULL);
436         }
437     }
438
439 FinalizeNet();
440
441 if (isRunningRunTimeouter)
442     {
443     //5 seconds to thread stops itself
444     for (int i = 0; i < 25 && isRunningRunTimeouter; i++)
445         {
446         struct timespec ts = {0, 200000000};
447         nanosleep(&ts, NULL);
448         }
449     }
450
451 users->DelNotifierUserDel(&onDelUserNotifier);
452
453 if (isRunningRun || isRunningRunTimeouter)
454     return -1;
455
456 printfd(__FILE__, "AUTH_IA::Stoped successfully.\n");
457 return 0;
458 }
459 //-----------------------------------------------------------------------------
460 void * AUTH_IA::Run(void * d)
461 {
462 sigset_t signalSet;
463 sigfillset(&signalSet);
464 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
465
466 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
467
468 ia->isRunningRun = true;
469
470 char buffer[512];
471
472 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
473
474 while (ia->nonstop)
475     {
476     ia->RecvData(buffer, sizeof(buffer));
477     if ((touchTime + MONITOR_TIME_DELAY_SEC <= stgTime) && ia->stgSettings->GetMonitoring())
478         {
479         touchTime = stgTime;
480         string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_r";
481         TouchFile(monFile.c_str());
482         }
483     }
484
485 ia->isRunningRun = false;
486 return NULL;
487 }
488 //-----------------------------------------------------------------------------
489 void * AUTH_IA::RunTimeouter(void * d)
490 {
491 sigset_t signalSet;
492 sigfillset(&signalSet);
493 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
494
495 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
496
497 ia->isRunningRunTimeouter = true;
498
499 int a = -1;
500 string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_t";
501 while (ia->nonstop)
502     {
503     struct timespec ts = {0, 20000000};
504     nanosleep(&ts, NULL);
505     ia->Timeouter();
506     // TODO change counter to timer and MONITOR_TIME_DELAY_SEC
507     if (++a % (50 * 60) == 0 && ia->stgSettings->GetMonitoring())
508         {
509         TouchFile(monFile.c_str());
510         }
511     }
512
513 ia->isRunningRunTimeouter = false;
514 return NULL;
515 }
516 //-----------------------------------------------------------------------------
517 int AUTH_IA::ParseSettings()
518 {
519 int ret = iaSettings.ParseSettings(settings);
520 if (ret)
521     errorStr = iaSettings.GetStrError();
522 return ret;
523 }
524 //-----------------------------------------------------------------------------
525 int AUTH_IA::PrepareNet()
526 {
527 struct sockaddr_in listenAddr;
528
529 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
530
531 if (listenSocket < 0)
532     {
533     errorStr = "Cannot create socket.";
534     logger("Cannot create a socket: %s", strerror(errno));
535     return -1;
536     }
537
538 listenAddr.sin_family = AF_INET;
539 listenAddr.sin_port = htons(iaSettings.GetUserPort());
540 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
541
542 if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
543     {
544     errorStr = "AUTH_IA: Bind failed.";
545     logger("Cannot bind the socket: %s", strerror(errno));
546     return -1;
547     }
548
549 return 0;
550 }
551 //-----------------------------------------------------------------------------
552 int AUTH_IA::FinalizeNet()
553 {
554 close(listenSocket);
555 return 0;
556 }
557 //-----------------------------------------------------------------------------
558 int AUTH_IA::RecvData(char * buffer, int bufferSize)
559 {
560 if (!WaitPackets(listenSocket)) // Timeout
561     {
562     return 0;
563     }
564
565 struct sockaddr_in outerAddr;
566 socklen_t outerAddrLen(sizeof(outerAddr));
567 int dataLen = recvfrom(listenSocket, buffer, bufferSize, 0, (struct sockaddr *)&outerAddr, &outerAddrLen);
568
569 if (!dataLen) // EOF
570     {
571     return 0;
572     }
573
574 if (dataLen <= 0) // Error
575     {
576     if (errno != EINTR)
577         {
578         printfd(__FILE__, "recvfrom res=%d, error: '%s'\n", dataLen, strerror(errno));
579         logger("recvfrom error: %s", strerror(errno));
580         return -1;
581         }
582     return 0;
583     }
584
585 if (dataLen > 256)
586     return -1;
587
588 int protoVer;
589 if (CheckHeader(buffer, &protoVer))
590     return -1;
591
592 char login[PASSWD_LEN];  //TODO why PASSWD_LEN ?
593 memset(login, 0, PASSWD_LEN);
594
595 Decrypt(&ctxS, login, buffer + 8, PASSWD_LEN / 8);
596
597 uint32_t sip = outerAddr.sin_addr.s_addr;
598 uint16_t sport = htons(outerAddr.sin_port);
599
600 USER_PTR user;
601 if (users->FindByName(login, &user))
602     {
603     logger("User's connect failed: user '%s' not found. IP %s",
604            login,
605            inet_ntostring(sip).c_str());
606     printfd(__FILE__, "User '%s' NOT found!\n", login);
607     SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉÎ!");
608     return -1;
609     }
610
611 printfd(__FILE__, "User '%s' FOUND!\n", user->GetLogin().c_str());
612
613 if (user->GetProperty().disabled.Get())
614     {
615     logger("Cannont authorize '%s', user is disabled.", login);
616     SendError(sip, sport, protoVer, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÂÌÏËÉÒÏ×ÁÎÁ");
617     return 0;
618     }
619
620 if (user->GetProperty().passive.Get())
621     {
622     logger("Cannont authorize '%s', user is passive.", login);
623     SendError(sip, sport, protoVer, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÍÏÒÏÖÅÎÁ");
624     return 0;
625     }
626
627 if (!user->GetProperty().ips.Get().IsIPInIPS(sip))
628     {
629     printfd(__FILE__, "User %s. IP address is incorrect. IP %s\n",
630             user->GetLogin().c_str(), inet_ntostring(sip).c_str());
631     logger("User %s. IP address is incorrect. IP %s",
632            user->GetLogin().c_str(), inet_ntostring(sip).c_str());
633     SendError(sip, sport, protoVer, "ðÏÌØÚÏ×ÁÔÅÌØ ÎÅ ÏÐÏÚÎÁÎ! ðÒÏ×ÅÒØÔÅ IP ÁÄÒÅÓ.");
634     return 0;
635     }
636
637 return PacketProcessor(buffer, dataLen, sip, sport, protoVer, user);
638 }
639 //-----------------------------------------------------------------------------
640 int AUTH_IA::CheckHeader(const char * buffer, int * protoVer)
641 {
642 if (strncmp(IA_ID, buffer, strlen(IA_ID)) != 0)
643     {
644     //SendError(userIP, updateMsg);
645     printfd(__FILE__, "update needed - IA_ID\n");
646     //SendError(userIP, "Incorrect header!");
647     return -1;
648     }
649
650 if (buffer[6] != 0) //proto[0] shoud be 0
651     {
652     printfd(__FILE__, "update needed - PROTO major: %d\n", buffer[6]);
653     //SendError(userIP, updateMsg);
654     return -1;
655     }
656
657 if (buffer[7] < 6)
658     {
659     // need update
660     //SendError(userIP, updateMsg);
661     printfd(__FILE__, "update needed - PROTO minor: %d\n", buffer[7]);
662     return -1;
663     }
664 else
665     {
666     *protoVer = buffer[7];
667     }
668 return 0;
669 }
670 //-----------------------------------------------------------------------------
671 int AUTH_IA::Timeouter()
672 {
673 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
674
675 map<uint32_t, IA_USER>::iterator it;
676 it = ip2user.begin();
677 uint32_t sip;
678
679 while (it != ip2user.end())
680     {
681     sip = it->first;
682
683     static UTIME currTime;
684     gettimeofday(&currTime, NULL);
685
686     if ((it->second.phase.GetPhase() == 2)
687         && (currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay())
688         {
689         it->second.phase.SetPhase1();
690         printfd(__FILE__, "Phase changed from 2 to 1. Reason: timeout\n");
691         ip2user.erase(it++);
692         continue;
693         }
694
695     if (it->second.phase.GetPhase() == 3)
696         {
697         if (!it->second.messagesToSend.empty())
698             {
699             if (it->second.protoVer == 6)
700                 RealSendMessage6(*it->second.messagesToSend.begin(), sip, it->second);
701
702             if (it->second.protoVer == 7)
703                 RealSendMessage7(*it->second.messagesToSend.begin(), sip, it->second);
704
705             if (it->second.protoVer == 8)
706                 RealSendMessage8(*it->second.messagesToSend.begin(), sip, it->second);
707
708             it->second.messagesToSend.erase(it->second.messagesToSend.begin());
709             }
710
711         if((currTime - it->second.lastSendAlive) > iaSettings.GetUserDelay())
712             {
713             switch (it->second.protoVer)
714                 {
715                 case 6:
716                     Send_ALIVE_SYN_6(&(it->second), sip);
717                     break;
718                 case 7:
719                     Send_ALIVE_SYN_7(&(it->second), sip);
720                     break;
721                 case 8:
722                     Send_ALIVE_SYN_8(&(it->second), sip);
723                     break;
724                 }
725
726             gettimeofday(&it->second.lastSendAlive, NULL);
727             }
728
729         if ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserTimeout())
730             {
731             users->Unauthorize(it->second.user->GetLogin(), this);
732             ip2user.erase(it++);
733             continue;
734             }
735         }
736
737     if ((it->second.phase.GetPhase() == 4)
738         && ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay()))
739         {
740         it->second.phase.SetPhase3();
741         printfd(__FILE__, "Phase changed from 4 to 3. Reason: timeout\n");
742         }
743
744     ++it;
745     }
746
747 return 0;
748 }
749 //-----------------------------------------------------------------------------
750 int AUTH_IA::PacketProcessor(char * buff, int dataLen, uint32_t sip, uint16_t sport, int protoVer, USER_PTR user)
751 {
752 std::string login(user->GetLogin());
753 const int offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer;
754
755 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
756 map<uint32_t, IA_USER>::iterator it(ip2user.find(sip));
757
758 if (it == ip2user.end())
759     {
760     USER_PTR userPtr;
761     if (!users->FindByIPIdx(sip, &userPtr))
762         {
763         if (userPtr->GetID() != user->GetID())
764             {
765             printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
766                     userPtr->GetLogin().c_str(),
767                     inet_ntostring(sip).c_str(),
768                    login.c_str());
769             logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
770                    userPtr->GetLogin().c_str(),
771                    inet_ntostring(sip).c_str(),
772                    login.c_str());
773             SendError(sip, sport, protoVer, "÷ÁÛ IP ÁÄÒÅÓ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
774             return 0;
775             }
776         }
777
778     printfd(__FILE__, "Add new user '%s' from ip %s\n",
779             login.c_str(), inet_ntostring(sip).c_str());
780     std::pair<std::map<uint32_t, IA_USER>::iterator, bool> res;
781     res = ip2user.insert(std::make_pair(sip, IA_USER(login, user, sport, protoVer)));
782     it = res.first;
783     #ifdef IA_PHASE_DEBUG
784     it->second.phase.SetLogFileName(stgSettings->GetLogFileName());
785     it->second.phase.SetUserLogin(login);
786     #endif
787     }
788 else if (user->GetID() != it->second.user->GetID())
789     {
790     printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
791             it->second.user->GetLogin().c_str(),
792             inet_ntostring(sip).c_str(),
793             user->GetLogin().c_str());
794     logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
795            it->second.user->GetLogin().c_str(),
796            inet_ntostring(sip).c_str(),
797            user->GetLogin().c_str());
798     SendError(sip, sport, protoVer, "÷ÁÛ IP ÁÄÒÅÓ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
799     return 0;
800     }
801
802 IA_USER * iaUser = &(it->second);
803
804 if (iaUser->password != user->GetProperty().password.Get())
805     {
806     InitEncrypt(&iaUser->ctx, user->GetProperty().password.Get());
807     iaUser->password = user->GetProperty().password.Get();
808     }
809
810 buff += offset;
811 Decrypt(&iaUser->ctx, buff, buff, (dataLen - offset) / 8);
812
813 char packetName[IA_MAX_TYPE_LEN];
814 strncpy(packetName,  buff + 4, IA_MAX_TYPE_LEN);
815 packetName[IA_MAX_TYPE_LEN - 1] = 0;
816
817 map<string, int>::iterator pi(packetTypes.find(packetName));
818 if (pi == packetTypes.end())
819     {
820     SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉΠÉÌÉ ÐÁÒÏÌØ!");
821     printfd(__FILE__, "Login or password is wrong!\n");
822     logger("User's connect failed. User: '%s', ip %s. Wrong login or password",
823            login.c_str(),
824            inet_ntostring(sip).c_str());
825     ip2user.erase(it);
826     return 0;
827     }
828
829 if (user->IsAuthorizedBy(this) && user->GetCurrIP() != sip)
830     {
831     printfd(__FILE__, "Login %s already in use from ip %s. IP %s\n",
832             login.c_str(), inet_ntostring(user->GetCurrIP()).c_str(),
833             inet_ntostring(sip).c_str());
834     logger("Login '%s' is already in use from ip %s. IP %s",
835            login.c_str(),
836            inet_ntostring(user->GetCurrIP()).c_str(),
837            inet_ntostring(sip).c_str());
838     SendError(sip, sport, protoVer, "÷ÁÛ ÌÏÇÉΠÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
839     ip2user.erase(it);
840     return 0;
841     }
842
843 switch (pi->second)
844     {
845     case CONN_SYN_N:
846         switch (protoVer)
847             {
848             case 6:
849                 if (Process_CONN_SYN_6((CONN_SYN_6 *)(buff - offset), &(it->second), sip))
850                     return -1;
851                 return Send_CONN_SYN_ACK_6(iaUser, sip);
852             case 7:
853                 if (Process_CONN_SYN_7((CONN_SYN_7 *)(buff - offset), &(it->second), sip))
854                     return -1;
855                 return Send_CONN_SYN_ACK_7(iaUser, sip);
856             case 8:
857                 if (Process_CONN_SYN_8((CONN_SYN_8 *)(buff - offset), &(it->second), sip))
858                     return -1;
859                 return Send_CONN_SYN_ACK_8(iaUser, sip);
860             }
861         break;
862
863     case CONN_ACK_N:
864         switch (protoVer)
865             {
866             case 6:
867                 if (Process_CONN_ACK_6((CONN_ACK_6 *)(buff - offset), iaUser, sip))
868                     return -1;
869                 return Send_ALIVE_SYN_6(iaUser, sip);
870             case 7:
871                 if (Process_CONN_ACK_7((CONN_ACK_6 *)(buff - offset), iaUser, sip))
872                     return -1;
873                 return Send_ALIVE_SYN_7(iaUser, sip);
874             case 8:
875                 if (Process_CONN_ACK_8((CONN_ACK_8 *)(buff - offset), iaUser, sip))
876                     return -1;
877                 return Send_ALIVE_SYN_8(iaUser, sip);
878             }
879         break;
880
881     case ALIVE_ACK_N:
882         switch (protoVer)
883             {
884             case 6:
885                 return Process_ALIVE_ACK_6((ALIVE_ACK_6 *)(buff - offset), iaUser, sip);
886             case 7:
887                 return Process_ALIVE_ACK_7((ALIVE_ACK_6 *)(buff - offset), iaUser, sip);
888             case 8:
889                 return Process_ALIVE_ACK_8((ALIVE_ACK_8 *)(buff - offset), iaUser, sip);
890             }
891         break;
892
893     case DISCONN_SYN_N:
894         switch (protoVer)
895             {
896             case 6:
897                 if (Process_DISCONN_SYN_6((DISCONN_SYN_6 *)(buff - offset), iaUser, sip))
898                     return -1;
899                 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
900             case 7:
901                 if (Process_DISCONN_SYN_7((DISCONN_SYN_6 *)(buff - offset), iaUser, sip))
902                     return -1;
903                 return Send_DISCONN_SYN_ACK_7(iaUser, sip);
904             case 8:
905                 if (Process_DISCONN_SYN_8((DISCONN_SYN_8 *)(buff - offset), iaUser, sip))
906                     return -1;
907                 return Send_DISCONN_SYN_ACK_8(iaUser, sip);
908             }
909         break;
910
911     case DISCONN_ACK_N:
912         switch (protoVer)
913             {
914             case 6:
915                 if (Process_DISCONN_ACK_6((DISCONN_ACK_6 *)(buff - offset), iaUser, sip, it))
916                     return -1;
917                 return Send_FIN_6(iaUser, sip, it);
918             case 7:
919                 if (Process_DISCONN_ACK_7((DISCONN_ACK_6 *)(buff - offset), iaUser, sip, it))
920                     return -1;
921                 return Send_FIN_7(iaUser, sip, it);
922             case 8:
923                 if (Process_DISCONN_ACK_8((DISCONN_ACK_8 *)(buff - offset), iaUser, sip, it))
924                     return -1;
925                 return Send_FIN_8(iaUser, sip, it);
926             }
927         break;
928     }
929
930 return -1;
931 }
932 //-----------------------------------------------------------------------------
933 void AUTH_IA::DelUser(USER_PTR u)
934 {
935
936 uint32_t ip = u->GetCurrIP();
937
938 if (!ip)
939     return;
940
941 map<uint32_t, IA_USER>::iterator it;
942
943 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
944 it = ip2user.find(ip);
945 if (it == ip2user.end())
946     {
947     //Nothing to delete
948     printfd(__FILE__, "Nothing to delete\n");
949     return;
950     }
951
952 if (it->second.user == u)
953     {
954     printfd(__FILE__, "User removed!\n");
955     users->Unauthorize(u->GetLogin(), this);
956     ip2user.erase(it);
957     }
958 }
959 //-----------------------------------------------------------------------------
960 int AUTH_IA::SendError(uint32_t ip, uint16_t port, int protoVer, const string & text)
961 {
962 struct sockaddr_in sendAddr;
963 switch (protoVer)
964     {
965     int res;
966     case 6:
967     case 7:
968         ERR err;
969         memset(&err, 0, sizeof(ERR));
970
971         sendAddr.sin_family = AF_INET;
972         sendAddr.sin_port = htons(port);
973         sendAddr.sin_addr.s_addr = ip;
974
975         err.len = 1;
976         strncpy((char*)err.type, "ERR", 16);
977         strncpy((char*)err.text, text.c_str(), MAX_MSG_LEN);
978
979         #ifdef ARCH_BE
980         SwapBytes(err.len);
981         #endif
982
983         res = sendto(listenSocket, &err, sizeof(err), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
984         printfd(__FILE__, "SendError %d bytes sent\n", res);
985         break;
986
987     case 8:
988         ERR_8 err8;
989         memset(&err8, 0, sizeof(ERR_8));
990
991         sendAddr.sin_family = AF_INET;
992         sendAddr.sin_port = htons(port);
993         sendAddr.sin_addr.s_addr = ip;
994
995         err8.len = 256;
996         strncpy((char*)err8.type, "ERR", 16);
997         strncpy((char*)err8.text, text.c_str(), MAX_MSG_LEN);
998
999         #ifdef ARCH_BE
1000         SwapBytes(err8.len);
1001         #endif
1002
1003         res = sendto(listenSocket, &err8, sizeof(err8), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1004         printfd(__FILE__, "SendError_8 %d bytes sent\n", res);
1005         break;
1006     }
1007
1008 return 0;
1009 }
1010 //-----------------------------------------------------------------------------
1011 int AUTH_IA::Send(uint32_t ip, uint16_t port, const char * buffer, int len)
1012 {
1013 struct sockaddr_in sendAddr;
1014
1015 sendAddr.sin_family = AF_INET;
1016 sendAddr.sin_port = htons(port);
1017 sendAddr.sin_addr.s_addr = ip;
1018
1019 int res = sendto(listenSocket, buffer, len, 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1020
1021 if (res == len)
1022     return 0;
1023
1024 return -1;
1025 }
1026 //-----------------------------------------------------------------------------
1027 int AUTH_IA::SendMessage(const STG_MSG & msg, uint32_t ip) const
1028 {
1029 printfd(__FILE__, "SendMessage userIP=%s\n", inet_ntostring(ip).c_str());
1030
1031 map<uint32_t, IA_USER>::iterator it;
1032
1033 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1034 it = ip2user.find(ip);
1035 if (it == ip2user.end())
1036     {
1037     errorStr = "Unknown user.";
1038     return -1;
1039     }
1040 it->second.messagesToSend.push_back(msg);
1041 return 0;
1042 }
1043 //-----------------------------------------------------------------------------
1044 int AUTH_IA::RealSendMessage6(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1045 {
1046 printfd(__FILE__, "RealSendMessage 6 user=%s\n", user.login.c_str());
1047
1048 INFO_6 info;
1049 memset(&info, 0, sizeof(INFO_6));
1050
1051 info.len = 256;
1052 strncpy((char*)info.type, "INFO", 16);
1053 info.infoType = 'I';
1054 strncpy((char*)info.text, msg.text.c_str(), 235);
1055 info.text[234] = 0;
1056
1057 size_t len = info.len;
1058 #ifdef ARCH_BE
1059 SwapBytes(info.len);
1060 #endif
1061
1062 char buffer[256];
1063 memcpy(buffer, &info, sizeof(INFO_6));
1064 Encrypt(&user.ctx, buffer, buffer, len / 8);
1065 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1066 }
1067 //-----------------------------------------------------------------------------
1068 int AUTH_IA::RealSendMessage7(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1069 {
1070 printfd(__FILE__, "RealSendMessage 7 user=%s\n", user.login.c_str());
1071
1072 INFO_7 info;
1073 memset(&info, 0, sizeof(INFO_7));
1074
1075 info.len = 264;
1076 strncpy((char*)info.type, "INFO_7", 16);
1077 info.infoType = msg.header.type;
1078 info.showTime = msg.header.showTime;
1079 info.sendTime = msg.header.creationTime;
1080
1081 size_t len = info.len;
1082 #ifdef ARCH_BE
1083 SwapBytes(info.len);
1084 SwapBytes(info.sendTime);
1085 #endif
1086
1087 strncpy((char*)info.text, msg.text.c_str(), MAX_MSG_LEN - 1);
1088 info.text[MAX_MSG_LEN - 1] = 0;
1089
1090 char buffer[300];
1091 memcpy(buffer, &info, sizeof(INFO_7));
1092
1093 Encrypt(&user.ctx, buffer, buffer, len / 8);
1094 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1095 }
1096 //-----------------------------------------------------------------------------
1097 int AUTH_IA::RealSendMessage8(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1098 {
1099 printfd(__FILE__, "RealSendMessage 8 user=%s\n", user.login.c_str());
1100
1101 INFO_8 info;
1102 memset(&info, 0, sizeof(INFO_8));
1103
1104 info.len = 1056;
1105 strncpy((char*)info.type, "INFO_8", 16);
1106 info.infoType = msg.header.type;
1107 info.showTime = msg.header.showTime;
1108 info.sendTime = msg.header.creationTime;
1109
1110 strncpy((char*)info.text, msg.text.c_str(), IA_MAX_MSG_LEN_8 - 1);
1111 info.text[IA_MAX_MSG_LEN_8 - 1] = 0;
1112
1113 size_t len = info.len;
1114 #ifdef ARCH_BE
1115 SwapBytes(info.len);
1116 SwapBytes(info.sendTime);
1117 #endif
1118
1119 char buffer[1500];
1120 memcpy(buffer, &info, sizeof(INFO_8));
1121
1122 Encrypt(&user.ctx, buffer, buffer, len / 8);
1123 return Send(ip, user.port, buffer, len);
1124 }
1125 //-----------------------------------------------------------------------------
1126 int AUTH_IA::Process_CONN_SYN_6(CONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1127 {
1128 if (!(iaUser->phase.GetPhase() == 1 || iaUser->phase.GetPhase() == 3))
1129     return -1;
1130
1131 enabledDirs = 0xFFffFFff;
1132
1133 iaUser->phase.SetPhase2();
1134 printfd(__FILE__, "Phase changed from %d to 2. Reason: CONN_SYN_6\n", iaUser->phase.GetPhase());
1135 return 0;
1136 }
1137 //-----------------------------------------------------------------------------
1138 int AUTH_IA::Process_CONN_SYN_7(CONN_SYN_7 * connSyn, IA_USER * iaUser, uint32_t sip)
1139 {
1140 return Process_CONN_SYN_6(connSyn, iaUser, sip);
1141 }
1142 //-----------------------------------------------------------------------------
1143 int AUTH_IA::Process_CONN_SYN_8(CONN_SYN_8 * connSyn, IA_USER * iaUser, uint32_t sip)
1144 {
1145 #ifdef ARCH_BE
1146 SwapBytes(connSyn->dirs);
1147 #endif
1148 int ret = Process_CONN_SYN_6((CONN_SYN_6*)connSyn, iaUser, sip);
1149 enabledDirs = connSyn->dirs;
1150 return ret;
1151 }
1152 //-----------------------------------------------------------------------------
1153 int AUTH_IA::Process_CONN_ACK_6(CONN_ACK_6 * connAck, IA_USER * iaUser, uint32_t sip)
1154 {
1155 #ifdef ARCH_BE
1156 SwapBytes(connAck->len);
1157 SwapBytes(connAck->rnd);
1158 #endif
1159 printfd( __FILE__, "CONN_ACK_6 %s\n", connAck->type);
1160
1161 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1162     {
1163     iaUser->phase.UpdateTime();
1164
1165     iaUser->lastSendAlive = iaUser->phase.GetTime();
1166     if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1167         {
1168         iaUser->phase.SetPhase3();
1169         printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_6\n");
1170         return 0;
1171         }
1172     else
1173         {
1174         errorStr = iaUser->user->GetStrError();
1175         iaUser->phase.SetPhase1();
1176         ip2user.erase(sip);
1177         printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1178         return -1;
1179         }
1180     }
1181 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1182 return -1;
1183 }
1184 //-----------------------------------------------------------------------------
1185 int AUTH_IA::Process_CONN_ACK_7(CONN_ACK_7 * connAck, IA_USER * iaUser, uint32_t sip)
1186 {
1187 return Process_CONN_ACK_6(connAck, iaUser, sip);
1188 }
1189 //-----------------------------------------------------------------------------
1190 int AUTH_IA::Process_CONN_ACK_8(CONN_ACK_8 * connAck, IA_USER * iaUser, uint32_t sip)
1191 {
1192 #ifdef ARCH_BE
1193 SwapBytes(connAck->len);
1194 SwapBytes(connAck->rnd);
1195 #endif
1196 printfd( __FILE__, "CONN_ACK_8 %s\n", connAck->type);
1197
1198 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1199     {
1200     iaUser->phase.UpdateTime();
1201     iaUser->lastSendAlive = iaUser->phase.GetTime();
1202     if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1203         {
1204         iaUser->phase.SetPhase3();
1205         printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_8\n");
1206         return 0;
1207         }
1208     else
1209         {
1210         errorStr = iaUser->user->GetStrError();
1211         iaUser->phase.SetPhase1();
1212         ip2user.erase(sip);
1213         printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1214         return -1;
1215         }
1216     }
1217 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1218 return -1;
1219 }
1220 //-----------------------------------------------------------------------------
1221 int AUTH_IA::Process_ALIVE_ACK_6(ALIVE_ACK_6 * aliveAck, IA_USER * iaUser, uint32_t)
1222 {
1223 #ifdef ARCH_BE
1224 SwapBytes(aliveAck->len);
1225 SwapBytes(aliveAck->rnd);
1226 #endif
1227 printfd(__FILE__, "ALIVE_ACK_6\n");
1228 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1229     {
1230     iaUser->phase.UpdateTime();
1231     #ifdef IA_DEBUG
1232     iaUser->aliveSent = false;
1233     #endif
1234     }
1235 return 0;
1236 }
1237 //-----------------------------------------------------------------------------
1238 int AUTH_IA::Process_ALIVE_ACK_7(ALIVE_ACK_7 * aliveAck, IA_USER * iaUser, uint32_t sip)
1239 {
1240 return Process_ALIVE_ACK_6(aliveAck, iaUser, sip);
1241 }
1242 //-----------------------------------------------------------------------------
1243 int AUTH_IA::Process_ALIVE_ACK_8(ALIVE_ACK_8 * aliveAck, IA_USER * iaUser, uint32_t)
1244 {
1245 #ifdef ARCH_BE
1246 SwapBytes(aliveAck->len);
1247 SwapBytes(aliveAck->rnd);
1248 #endif
1249 printfd(__FILE__, "ALIVE_ACK_8\n");
1250 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1251     {
1252     iaUser->phase.UpdateTime();
1253     #ifdef IA_DEBUG
1254     iaUser->aliveSent = false;
1255     #endif
1256     }
1257 return 0;
1258 }
1259 //-----------------------------------------------------------------------------
1260 int AUTH_IA::Process_DISCONN_SYN_6(DISCONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1261 {
1262 printfd(__FILE__, "DISCONN_SYN_6\n");
1263 if (iaUser->phase.GetPhase() != 3)
1264     {
1265     printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1266     errorStr = "Incorrect request DISCONN_SYN";
1267     return -1;
1268     }
1269
1270 iaUser->phase.SetPhase4();
1271 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1272
1273 return 0;
1274 }
1275 //-----------------------------------------------------------------------------
1276 int AUTH_IA::Process_DISCONN_SYN_7(DISCONN_SYN_7 * disconnSyn, IA_USER * iaUser, uint32_t sip)
1277 {
1278 return Process_DISCONN_SYN_6(disconnSyn, iaUser, sip);
1279 }
1280 //-----------------------------------------------------------------------------
1281 int AUTH_IA::Process_DISCONN_SYN_8(DISCONN_SYN_8 *, IA_USER * iaUser, uint32_t)
1282 {
1283 if (iaUser->phase.GetPhase() != 3)
1284     {
1285     errorStr = "Incorrect request DISCONN_SYN";
1286     printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1287     return -1;
1288     }
1289
1290 iaUser->phase.SetPhase4();
1291 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1292
1293 return 0;
1294 }
1295 //-----------------------------------------------------------------------------
1296 int AUTH_IA::Process_DISCONN_ACK_6(DISCONN_ACK_6 * disconnAck,
1297                                    IA_USER * iaUser,
1298                                    uint32_t,
1299                                    map<uint32_t, IA_USER>::iterator)
1300 {
1301 #ifdef ARCH_BE
1302 SwapBytes(disconnAck->len);
1303 SwapBytes(disconnAck->rnd);
1304 #endif
1305 printfd(__FILE__, "DISCONN_ACK_6\n");
1306 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1307     {
1308     printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1309     return -1;
1310     }
1311
1312 return 0;
1313 }
1314 //-----------------------------------------------------------------------------
1315 int AUTH_IA::Process_DISCONN_ACK_7(DISCONN_ACK_7 * disconnAck, IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1316 {
1317 return Process_DISCONN_ACK_6(disconnAck, iaUser, sip, it);
1318 }
1319 //-----------------------------------------------------------------------------
1320 int AUTH_IA::Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnAck, IA_USER * iaUser, uint32_t, map<uint32_t, IA_USER>::iterator)
1321 {
1322 #ifdef ARCH_BE
1323 SwapBytes(disconnAck->len);
1324 SwapBytes(disconnAck->rnd);
1325 #endif
1326 printfd(__FILE__, "DISCONN_ACK_8\n");
1327 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1328     {
1329     printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1330     return -1;
1331     }
1332
1333 return 0;
1334 }
1335 //-----------------------------------------------------------------------------
1336 int AUTH_IA::Send_CONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1337 {
1338 //+++ Fill static data in connSynAck +++
1339 // TODO Move this code. It must be executed only once
1340 connSynAck6.len = Min8(sizeof(CONN_SYN_ACK_6));
1341 strcpy((char*)connSynAck6.type, "CONN_SYN_ACK");
1342 for (int j = 0; j < DIR_NUM; j++)
1343     {
1344     strncpy((char*)connSynAck6.dirName[j],
1345             stgSettings->GetDirName(j).c_str(),
1346             sizeof(string16));
1347
1348     connSynAck6.dirName[j][sizeof(string16) - 1] = 0;
1349     }
1350 //--- Fill static data in connSynAck ---
1351
1352 iaUser->rnd = random();
1353 connSynAck6.rnd = iaUser->rnd;
1354
1355 connSynAck6.userTimeOut = iaSettings.GetUserTimeout();
1356 connSynAck6.aliveDelay = iaSettings.GetUserDelay();
1357
1358 #ifdef ARCH_BE
1359 SwapBytes(connSynAck6.len);
1360 SwapBytes(connSynAck6.rnd);
1361 SwapBytes(connSynAck6.userTimeOut);
1362 SwapBytes(connSynAck6.aliveDelay);
1363 #endif
1364
1365 Encrypt(&iaUser->ctx, (char*)&connSynAck6, (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6))/8);
1366 return Send(sip, iaSettings.GetUserPort(), (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)));;
1367 }
1368 //-----------------------------------------------------------------------------
1369 int AUTH_IA::Send_CONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1370 {
1371 return Send_CONN_SYN_ACK_6(iaUser, sip);
1372 }
1373 //-----------------------------------------------------------------------------
1374 int AUTH_IA::Send_CONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1375 {
1376 strcpy((char*)connSynAck8.hdr.magic, IA_ID);
1377 connSynAck8.hdr.protoVer[0] = 0;
1378 connSynAck8.hdr.protoVer[1] = 8;
1379
1380 //+++ Fill static data in connSynAck +++
1381 // TODO Move this code. It must be executed only once
1382 connSynAck8.len = Min8(sizeof(CONN_SYN_ACK_8));
1383 strcpy((char*)connSynAck8.type, "CONN_SYN_ACK");
1384 for (int j = 0; j < DIR_NUM; j++)
1385     {
1386     strncpy((char*)connSynAck8.dirName[j],
1387             stgSettings->GetDirName(j).c_str(),
1388             sizeof(string16));
1389
1390     connSynAck8.dirName[j][sizeof(string16) - 1] = 0;
1391     }
1392 //--- Fill static data in connSynAck ---
1393
1394 iaUser->rnd = random();
1395 connSynAck8.rnd = iaUser->rnd;
1396
1397 connSynAck8.userTimeOut = iaSettings.GetUserTimeout();
1398 connSynAck8.aliveDelay = iaSettings.GetUserDelay();
1399
1400 #ifdef ARCH_BE
1401 SwapBytes(connSynAck8.len);
1402 SwapBytes(connSynAck8.rnd);
1403 SwapBytes(connSynAck8.userTimeOut);
1404 SwapBytes(connSynAck8.aliveDelay);
1405 #endif
1406
1407 Encrypt(&iaUser->ctx, (char*)&connSynAck8, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8))/8);
1408 return Send(sip, iaUser->port, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)));
1409 }
1410 //-----------------------------------------------------------------------------
1411 int AUTH_IA::Send_ALIVE_SYN_6(IA_USER * iaUser, uint32_t sip)
1412 {
1413 aliveSyn6.len = Min8(sizeof(ALIVE_SYN_6));
1414 aliveSyn6.rnd = iaUser->rnd = random();
1415
1416 strcpy((char*)aliveSyn6.type, "ALIVE_SYN");
1417
1418 for (int i = 0; i < DIR_NUM; i++)
1419     {
1420     aliveSyn6.md[i] = iaUser->user->GetProperty().down.Get()[i];
1421     aliveSyn6.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1422
1423     aliveSyn6.sd[i] = iaUser->user->GetSessionDownload()[i];
1424     aliveSyn6.su[i] = iaUser->user->GetSessionUpload()[i];
1425     }
1426
1427 //TODO
1428 int dn = iaSettings.GetFreeMbShowType();
1429 const TARIFF * tf = iaUser->user->GetTariff();
1430
1431 if (dn < DIR_NUM)
1432     {
1433     double p = tf->GetPriceWithTraffType(aliveSyn6.mu[dn],
1434                                          aliveSyn6.md[dn],
1435                                          dn,
1436                                          stgTime);
1437     p *= 1024 * 1024;
1438     if (std::fabs(p) < 1.0e-3)
1439         {
1440         snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "---");
1441         }
1442     else
1443         {
1444         double fmb = iaUser->user->GetProperty().freeMb;
1445         fmb = fmb < 0 ? 0 : fmb;
1446         snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1447         }
1448     }
1449 else
1450     {
1451     if (freeMbNone == iaSettings.GetFreeMbShowType())
1452         {
1453         aliveSyn6.freeMb[0] = 0;
1454         }
1455     else
1456         {
1457         double fmb = iaUser->user->GetProperty().freeMb;
1458         fmb = fmb < 0 ? 0 : fmb;
1459         snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1460         }
1461     }
1462
1463 #ifdef IA_DEBUG
1464 if (iaUser->aliveSent)
1465     {
1466     printfd(__FILE__, "========= ALIVE_ACK_6(7) TIMEOUT !!! %s =========\n", iaUser->login.c_str());
1467     }
1468 iaUser->aliveSent = true;
1469 #endif
1470
1471 aliveSyn6.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1472 if (!stgSettings->GetShowFeeInCash())
1473     aliveSyn6.cash -= (int64_t)(tf->GetFee() * 1000.0);
1474
1475 #ifdef ARCH_BE
1476 SwapBytes(aliveSyn6.len);
1477 SwapBytes(aliveSyn6.rnd);
1478 SwapBytes(aliveSyn6.cash);
1479 for (int i = 0; i < DIR_NUM; ++i)
1480     {
1481     SwapBytes(aliveSyn6.mu[i]);
1482     SwapBytes(aliveSyn6.md[i]);
1483     SwapBytes(aliveSyn6.su[i]);
1484     SwapBytes(aliveSyn6.sd[i]);
1485     }
1486 #endif
1487
1488 Encrypt(&(iaUser->ctx), (char*)&aliveSyn6, (char*)&aliveSyn6, Min8(sizeof(aliveSyn6))/8);
1489 return Send(sip, iaSettings.GetUserPort(), (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)));
1490 }
1491 //-----------------------------------------------------------------------------
1492 int AUTH_IA::Send_ALIVE_SYN_7(IA_USER * iaUser, uint32_t sip)
1493 {
1494 return Send_ALIVE_SYN_6(iaUser, sip);
1495 }
1496 //-----------------------------------------------------------------------------
1497 int AUTH_IA::Send_ALIVE_SYN_8(IA_USER * iaUser, uint32_t sip)
1498 {
1499 strcpy((char*)aliveSyn8.hdr.magic, IA_ID);
1500 aliveSyn8.hdr.protoVer[0] = 0;
1501 aliveSyn8.hdr.protoVer[1] = 8;
1502
1503 aliveSyn8.len = Min8(sizeof(ALIVE_SYN_8));
1504 aliveSyn8.rnd = iaUser->rnd = random();
1505
1506 strcpy((char*)aliveSyn8.type, "ALIVE_SYN");
1507
1508 for (int i = 0; i < DIR_NUM; i++)
1509     {
1510     aliveSyn8.md[i] = iaUser->user->GetProperty().down.Get()[i];
1511     aliveSyn8.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1512
1513     aliveSyn8.sd[i] = iaUser->user->GetSessionDownload()[i];
1514     aliveSyn8.su[i] = iaUser->user->GetSessionUpload()[i];
1515     }
1516
1517 //TODO
1518 int dn = iaSettings.GetFreeMbShowType();
1519
1520 if (dn < DIR_NUM)
1521     {
1522     const TARIFF * tf = iaUser->user->GetTariff();
1523     double p = tf->GetPriceWithTraffType(aliveSyn8.mu[dn],
1524                                          aliveSyn8.md[dn],
1525                                          dn,
1526                                          stgTime);
1527     p *= 1024 * 1024;
1528     if (std::fabs(p) < 1.0e-3)
1529         {
1530         snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "---");
1531         }
1532     else
1533         {
1534         double fmb = iaUser->user->GetProperty().freeMb;
1535         fmb = fmb < 0 ? 0 : fmb;
1536         snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1537         }
1538     }
1539 else
1540     {
1541     if (freeMbNone == iaSettings.GetFreeMbShowType())
1542         {
1543         aliveSyn8.freeMb[0] = 0;
1544         }
1545     else
1546         {
1547         double fmb = iaUser->user->GetProperty().freeMb;
1548         fmb = fmb < 0 ? 0 : fmb;
1549         snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1550         }
1551     }
1552
1553 #ifdef IA_DEBUG
1554 if (iaUser->aliveSent)
1555     {
1556     printfd(__FILE__, "========= ALIVE_ACK_8 TIMEOUT !!! =========\n");
1557     }
1558 iaUser->aliveSent = true;
1559 #endif
1560
1561 const TARIFF * tf = iaUser->user->GetTariff();
1562
1563 aliveSyn8.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1564 if (!stgSettings->GetShowFeeInCash())
1565     aliveSyn8.cash -= (int64_t)(tf->GetFee() * 1000.0);
1566
1567 #ifdef ARCH_BE
1568 SwapBytes(aliveSyn8.len);
1569 SwapBytes(aliveSyn8.rnd);
1570 SwapBytes(aliveSyn8.cash);
1571 SwapBytes(aliveSyn8.status);
1572 for (int i = 0; i < DIR_NUM; ++i)
1573     {
1574     SwapBytes(aliveSyn8.mu[i]);
1575     SwapBytes(aliveSyn8.md[i]);
1576     SwapBytes(aliveSyn8.su[i]);
1577     SwapBytes(aliveSyn8.sd[i]);
1578     }
1579 #endif
1580
1581 Encrypt(&(iaUser->ctx), (char*)&aliveSyn8, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8))/8);
1582 return Send(sip, iaUser->port, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)));
1583 }
1584 //-----------------------------------------------------------------------------
1585 int AUTH_IA::Send_DISCONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1586 {
1587 disconnSynAck6.len = Min8(sizeof(DISCONN_SYN_ACK_6));
1588 strcpy((char*)disconnSynAck6.type, "DISCONN_SYN_ACK");
1589 disconnSynAck6.rnd = iaUser->rnd = random();
1590
1591 #ifdef ARCH_BE
1592 SwapBytes(disconnSynAck6.len);
1593 SwapBytes(disconnSynAck6.rnd);
1594 #endif
1595
1596 Encrypt(&iaUser->ctx, (char*)&disconnSynAck6, (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6))/8);
1597 return Send(sip, iaSettings.GetUserPort(), (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)));
1598 }
1599 //-----------------------------------------------------------------------------
1600 int AUTH_IA::Send_DISCONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1601 {
1602 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
1603 }
1604 //-----------------------------------------------------------------------------
1605 int AUTH_IA::Send_DISCONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1606 {
1607 strcpy((char*)disconnSynAck8.hdr.magic, IA_ID);
1608 disconnSynAck8.hdr.protoVer[0] = 0;
1609 disconnSynAck8.hdr.protoVer[1] = 8;
1610
1611 disconnSynAck8.len = Min8(sizeof(DISCONN_SYN_ACK_8));
1612 strcpy((char*)disconnSynAck8.type, "DISCONN_SYN_ACK");
1613 disconnSynAck8.rnd = iaUser->rnd = random();
1614
1615 #ifdef ARCH_BE
1616 SwapBytes(disconnSynAck8.len);
1617 SwapBytes(disconnSynAck8.rnd);
1618 #endif
1619
1620 Encrypt(&iaUser->ctx, (char*)&disconnSynAck8, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8))/8);
1621 return Send(sip, iaUser->port, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)));
1622 }
1623 //-----------------------------------------------------------------------------
1624 int AUTH_IA::Send_FIN_6(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1625 {
1626 fin6.len = Min8(sizeof(FIN_6));
1627 strcpy((char*)fin6.type, "FIN");
1628 strcpy((char*)fin6.ok, "OK");
1629
1630 #ifdef ARCH_BE
1631 SwapBytes(fin6.len);
1632 #endif
1633
1634 Encrypt(&iaUser->ctx, (char*)&fin6, (char*)&fin6, Min8(sizeof(fin6))/8);
1635
1636 users->Unauthorize(iaUser->login, this);
1637
1638 int res = Send(sip, iaSettings.GetUserPort(), (char*)&fin6, Min8(sizeof(fin6)));
1639
1640 ip2user.erase(it);
1641
1642 return res;
1643 }
1644 //-----------------------------------------------------------------------------
1645 int AUTH_IA::Send_FIN_7(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1646 {
1647 return Send_FIN_6(iaUser, sip, it);
1648 }
1649 //-----------------------------------------------------------------------------
1650 int AUTH_IA::Send_FIN_8(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1651 {
1652 strcpy((char*)fin8.hdr.magic, IA_ID);
1653 fin8.hdr.protoVer[0] = 0;
1654 fin8.hdr.protoVer[1] = 8;
1655
1656 fin8.len = Min8(sizeof(FIN_8));
1657 strcpy((char*)fin8.type, "FIN");
1658 strcpy((char*)fin8.ok, "OK");
1659
1660 #ifdef ARCH_BE
1661 SwapBytes(fin8.len);
1662 #endif
1663
1664 Encrypt(&iaUser->ctx, (char*)&fin8, (char*)&fin8, Min8(sizeof(fin8))/8);
1665
1666 users->Unauthorize(iaUser->login, this);
1667
1668 int res = Send(sip, iaUser->port, (char*)&fin8, Min8(sizeof(fin8)));
1669
1670 ip2user.erase(it);
1671
1672 return res;
1673 }
1674 //-----------------------------------------------------------------------------
1675 inline
1676 void InitEncrypt(BLOWFISH_CTX * ctx, const string & password)
1677 {
1678 unsigned char keyL[PASSWD_LEN];
1679 memset(keyL, 0, PASSWD_LEN);
1680 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
1681 Blowfish_Init(ctx, keyL, PASSWD_LEN);
1682 }
1683 //-----------------------------------------------------------------------------
1684 inline
1685 void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
1686 {
1687 for (int i = 0; i < len8; i++)
1688     DecodeString(dst + i * 8, src + i * 8, ctx);
1689 }
1690 //-----------------------------------------------------------------------------
1691 inline
1692 void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
1693 {
1694 for (int i = 0; i < len8; i++)
1695     EncodeString(dst + i * 8, src + i * 8, ctx);
1696 }