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