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