]> git.stg.codes - stg.git/blob - projects/stargazer/plugins/authorization/inetaccess/inetaccess.cpp
Ticket 26. The iaSettings object is assigned the newIaSettings object values.
[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 iaSettings = newIaSettings;
542 return 0;
543 }
544 //-----------------------------------------------------------------------------
545 int AUTH_IA::PrepareNet()
546 {
547 struct sockaddr_in listenAddr;
548
549 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
550
551 if (listenSocket < 0)
552     {
553     errorStr = "Cannot create socket.";
554     logger("Cannot create a socket: %s", strerror(errno));
555     return -1;
556     }
557
558 listenAddr.sin_family = AF_INET;
559 listenAddr.sin_port = htons(static_cast<uint16_t>(iaSettings.GetUserPort()));
560 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
561
562 if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
563     {
564     errorStr = "AUTH_IA: Bind failed.";
565     logger("Cannot bind the socket: %s", strerror(errno));
566     return -1;
567     }
568
569 return 0;
570 }
571 //-----------------------------------------------------------------------------
572 int AUTH_IA::FinalizeNet()
573 {
574 close(listenSocket);
575 return 0;
576 }
577 //-----------------------------------------------------------------------------
578 int AUTH_IA::RecvData(char * buffer, int bufferSize)
579 {
580 if (!WaitPackets(listenSocket)) // Timeout
581     {
582     return 0;
583     }
584
585 struct sockaddr_in outerAddr;
586 socklen_t outerAddrLen(sizeof(outerAddr));
587 ssize_t dataLen = recvfrom(listenSocket, buffer, bufferSize, 0, (struct sockaddr *)&outerAddr, &outerAddrLen);
588
589 if (!dataLen) // EOF
590     {
591     return 0;
592     }
593
594 if (dataLen <= 0) // Error
595     {
596     if (errno != EINTR)
597         {
598         printfd(__FILE__, "recvfrom res=%d, error: '%s'\n", dataLen, strerror(errno));
599         logger("recvfrom error: %s", strerror(errno));
600         return -1;
601         }
602     return 0;
603     }
604
605 if (dataLen > 256)
606     return -1;
607
608 uint32_t sip = outerAddr.sin_addr.s_addr;
609 uint16_t sport = htons(outerAddr.sin_port);
610
611 int protoVer;
612 if (CheckHeader(buffer, sip, &protoVer))
613     return -1;
614
615 char login[PASSWD_LEN];  //TODO why PASSWD_LEN ?
616 memset(login, 0, PASSWD_LEN);
617
618 DecryptString(login, buffer + 8, PASSWD_LEN, &ctxS);
619
620 USER_PTR user;
621 if (users->FindByName(login, &user))
622     {
623     logger("User's connect failed: user '%s' not found. IP %s",
624            login,
625            inet_ntostring(sip).c_str());
626     printfd(__FILE__, "User '%s' NOT found!\n", login);
627     SendError(sip, sport, protoVer, IconvString("Неправильный логин.", "utf8", "koi8-ru"));
628     return -1;
629     }
630
631 printfd(__FILE__, "User '%s' FOUND!\n", user->GetLogin().c_str());
632
633 if (user->GetProperty().disabled.Get())
634     {
635     logger("Cannont authorize '%s', user is disabled.", login);
636     SendError(sip, sport, protoVer, IconvString("Учетная запись заблокирована.", "utf8", "koi8-ru"));
637     return 0;
638     }
639
640 if (user->GetProperty().passive.Get())
641     {
642     logger("Cannont authorize '%s', user is passive.", login);
643     SendError(sip, sport, protoVer, IconvString("Учетная запись заморожена.", "utf8", "koi8-ru"));
644     return 0;
645     }
646
647 if (!user->GetProperty().ips.Get().IsIPInIPS(sip))
648     {
649     printfd(__FILE__, "User %s. IP address is incorrect. IP %s\n",
650             user->GetLogin().c_str(), inet_ntostring(sip).c_str());
651     logger("User %s. IP address is incorrect. IP %s",
652            user->GetLogin().c_str(), inet_ntostring(sip).c_str());
653     SendError(sip, sport, protoVer, IconvString("Пользователь не опознан. Проверьте IP-адрес.", "utf8", "koi8-ru"));
654     return 0;
655     }
656
657 return PacketProcessor(buffer, dataLen, sip, sport, protoVer, user);
658 }
659 //-----------------------------------------------------------------------------
660 int AUTH_IA::CheckHeader(const char * buffer, uint32_t sip, int * protoVer)
661 {
662 if (strncmp(IA_ID, buffer, strlen(IA_ID)) != 0)
663     {
664     printfd(__FILE__, "update needed - IA_ID\n");
665     if (iaSettings.LogProtocolErrors())
666         logger("IP: %s. Header: invalid packed signature.", inet_ntostring(sip).c_str());
667     return -1;
668     }
669
670 if (buffer[6] != 0) //proto[0] shoud be 0
671     {
672     printfd(__FILE__, "update needed - PROTO major: %d\n", buffer[6]);
673     if (iaSettings.LogProtocolErrors())
674         logger("IP: %s. Header: invalid protocol major version: %d.", inet_ntostring(sip).c_str(), buffer[6]);
675     return -1;
676     }
677
678 if (buffer[7] < 6)
679     {
680     // need update
681     printfd(__FILE__, "update needed - PROTO minor: %d\n", buffer[7]);
682     if (iaSettings.LogProtocolErrors())
683         logger("IP: %s. Header: invalid protocol minor version: %d.", inet_ntostring(sip).c_str(), buffer[7]);
684     return -1;
685     }
686 else
687     {
688     *protoVer = buffer[7];
689     }
690 return 0;
691 }
692 //-----------------------------------------------------------------------------
693 int AUTH_IA::Timeouter()
694 {
695 STG_LOCKER lock(&mutex);
696
697 std::map<uint32_t, IA_USER>::iterator it;
698 it = ip2user.begin();
699
700 while (it != ip2user.end())
701     {
702     uint32_t sip = it->first;
703
704     static UTIME currTime;
705     gettimeofday(&currTime, NULL);
706
707     if ((it->second.phase.GetPhase() == 2)
708         && (currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay())
709         {
710         if (iaSettings.LogProtocolErrors())
711             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());
712         it->second.phase.SetPhase1();
713         printfd(__FILE__, "Phase changed from 2 to 1. Reason: timeout\n");
714         ip2user.erase(it++);
715         continue;
716         }
717
718     if (it->second.phase.GetPhase() == 3)
719         {
720         if (!it->second.messagesToSend.empty())
721             {
722             if (it->second.protoVer == 6)
723                 RealSendMessage6(*it->second.messagesToSend.begin(), sip, it->second);
724
725             if (it->second.protoVer == 7)
726                 RealSendMessage7(*it->second.messagesToSend.begin(), sip, it->second);
727
728             if (it->second.protoVer == 8)
729                 RealSendMessage8(*it->second.messagesToSend.begin(), sip, it->second);
730
731             it->second.messagesToSend.erase(it->second.messagesToSend.begin());
732             }
733
734         if((currTime - it->second.lastSendAlive) > iaSettings.GetUserDelay())
735             {
736             switch (it->second.protoVer)
737                 {
738                 case 6:
739                     Send_ALIVE_SYN_6(&(it->second), sip);
740                     break;
741                 case 7:
742                     Send_ALIVE_SYN_7(&(it->second), sip);
743                     break;
744                 case 8:
745                     Send_ALIVE_SYN_8(&(it->second), sip);
746                     break;
747                 }
748
749             gettimeofday(&it->second.lastSendAlive, NULL);
750             }
751
752         if ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserTimeout())
753             {
754             if (iaSettings.LogProtocolErrors())
755                 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());
756             users->Unauthorize(it->second.user->GetLogin(), this);
757             ip2user.erase(it++);
758             continue;
759             }
760         }
761
762     if ((it->second.phase.GetPhase() == 4)
763         && ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay()))
764         {
765         if (iaSettings.LogProtocolErrors())
766             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());
767         it->second.phase.SetPhase3();
768         printfd(__FILE__, "Phase changed from 4 to 3. Reason: timeout\n");
769         }
770
771     ++it;
772     }
773
774 return 0;
775 }
776 //-----------------------------------------------------------------------------
777 int AUTH_IA::PacketProcessor(void * buff, size_t dataLen, uint32_t sip, uint16_t sport, int protoVer, USER_PTR user)
778 {
779 std::string login(user->GetLogin());
780 const size_t offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer;
781
782 STG_LOCKER lock(&mutex);
783 std::map<uint32_t, IA_USER>::iterator it(ip2user.find(sip));
784
785 if (it == ip2user.end())
786     {
787     USER_PTR userPtr;
788     if (!users->FindByIPIdx(sip, &userPtr))
789         {
790         if (userPtr->GetID() != user->GetID())
791             {
792             printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
793                     userPtr->GetLogin().c_str(),
794                     inet_ntostring(sip).c_str(),
795                    login.c_str());
796             logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
797                    userPtr->GetLogin().c_str(),
798                    inet_ntostring(sip).c_str(),
799                    login.c_str());
800             SendError(sip, sport, protoVer, IconvString("IP-адрес уже сипользуется.", "utf8", "koi8-ru"));
801             return 0;
802             }
803         }
804
805     printfd(__FILE__, "Add new user '%s' from ip %s\n",
806             login.c_str(), inet_ntostring(sip).c_str());
807     std::pair<std::map<uint32_t, IA_USER>::iterator, bool> res;
808     res = ip2user.insert(std::make_pair(sip, IA_USER(login, user, sport, protoVer)));
809     it = res.first;
810     #ifdef IA_PHASE_DEBUG
811     it->second.phase.SetLogFileName(stgSettings->GetLogFileName());
812     it->second.phase.SetUserLogin(login);
813     #endif
814     }
815 else if (user->GetID() != it->second.user->GetID())
816     {
817     printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
818             it->second.user->GetLogin().c_str(),
819             inet_ntostring(sip).c_str(),
820             user->GetLogin().c_str());
821     logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
822            it->second.user->GetLogin().c_str(),
823            inet_ntostring(sip).c_str(),
824            user->GetLogin().c_str());
825     SendError(sip, sport, protoVer, IconvString("IP-адрес уже используется.", "utf8", "koi8-ru"));
826     return 0;
827     }
828
829 IA_USER * iaUser = &(it->second);
830
831 if (iaUser->password != user->GetProperty().password.Get())
832     {
833     const std::string & password = user->GetProperty().password.Get();
834     InitContext(password.c_str(), password.length(), &iaUser->ctx);
835     iaUser->password = user->GetProperty().password.Get();
836     }
837
838 DecryptString(static_cast<char *>(buff) + offset, static_cast<char *>(buff) + offset, (dataLen - offset), &iaUser->ctx);
839
840 char packetName[IA_MAX_TYPE_LEN];
841 strncpy(packetName,  static_cast<char *>(buff) + offset + 4, IA_MAX_TYPE_LEN);
842 packetName[IA_MAX_TYPE_LEN - 1] = 0;
843
844 std::map<std::string, int>::iterator pi(packetTypes.find(packetName));
845 if (pi == packetTypes.end())
846     {
847     SendError(sip, sport, protoVer, IconvString("Неправильный логин или пароль.", "utf8", "koi8-ru"));
848     printfd(__FILE__, "Login or password is wrong!\n");
849     logger("User's connect failed. User: '%s', ip %s. Wrong login or password",
850            login.c_str(),
851            inet_ntostring(sip).c_str());
852     ip2user.erase(it);
853     return 0;
854     }
855
856 if (user->IsAuthorizedBy(this) && user->GetCurrIP() != sip)
857     {
858     printfd(__FILE__, "Login %s already in use from ip %s. IP %s\n",
859             login.c_str(), inet_ntostring(user->GetCurrIP()).c_str(),
860             inet_ntostring(sip).c_str());
861     logger("Login '%s' is already in use from ip %s. IP %s",
862            login.c_str(),
863            inet_ntostring(user->GetCurrIP()).c_str(),
864            inet_ntostring(sip).c_str());
865     SendError(sip, sport, protoVer, IconvString("Логин уже используется.", "utf8", "koi8-ru"));
866     ip2user.erase(it);
867     return 0;
868     }
869
870 switch (pi->second)
871     {
872     case CONN_SYN_N:
873         switch (protoVer)
874             {
875             case 6:
876                 if (Process_CONN_SYN_6(static_cast<CONN_SYN_6 *>(buff), &(it->second), sip))
877                     return -1;
878                 return Send_CONN_SYN_ACK_6(iaUser, sip);
879             case 7:
880                 if (Process_CONN_SYN_7(static_cast<CONN_SYN_7 *>(buff), &(it->second), sip))
881                     return -1;
882                 return Send_CONN_SYN_ACK_7(iaUser, sip);
883             case 8:
884                 if (Process_CONN_SYN_8(static_cast<CONN_SYN_8 *>(buff), &(it->second), sip))
885                     return -1;
886                 return Send_CONN_SYN_ACK_8(iaUser, sip);
887             }
888         break;
889
890     case CONN_ACK_N:
891         switch (protoVer)
892             {
893             case 6:
894                 if (Process_CONN_ACK_6(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
895                     return -1;
896                 return Send_ALIVE_SYN_6(iaUser, sip);
897             case 7:
898                 if (Process_CONN_ACK_7(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
899                     return -1;
900                 return Send_ALIVE_SYN_7(iaUser, sip);
901             case 8:
902                 if (Process_CONN_ACK_8(static_cast<CONN_ACK_8 *>(buff), iaUser, sip))
903                     return -1;
904                 return Send_ALIVE_SYN_8(iaUser, sip);
905             }
906         break;
907
908     case ALIVE_ACK_N:
909         switch (protoVer)
910             {
911             case 6:
912                 return Process_ALIVE_ACK_6(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
913             case 7:
914                 return Process_ALIVE_ACK_7(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
915             case 8:
916                 return Process_ALIVE_ACK_8(static_cast<ALIVE_ACK_8 *>(buff), iaUser, sip);
917             }
918         break;
919
920     case DISCONN_SYN_N:
921         switch (protoVer)
922             {
923             case 6:
924                 if (Process_DISCONN_SYN_6(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
925                     return -1;
926                 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
927             case 7:
928                 if (Process_DISCONN_SYN_7(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
929                     return -1;
930                 return Send_DISCONN_SYN_ACK_7(iaUser, sip);
931             case 8:
932                 if (Process_DISCONN_SYN_8(static_cast<DISCONN_SYN_8 *>(buff), iaUser, sip))
933                     return -1;
934                 return Send_DISCONN_SYN_ACK_8(iaUser, sip);
935             }
936         break;
937
938     case DISCONN_ACK_N:
939         switch (protoVer)
940             {
941             case 6:
942                 if (Process_DISCONN_ACK_6(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
943                     return -1;
944                 return Send_FIN_6(iaUser, sip, it);
945             case 7:
946                 if (Process_DISCONN_ACK_7(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
947                     return -1;
948                 return Send_FIN_7(iaUser, sip, it);
949             case 8:
950                 if (Process_DISCONN_ACK_8(static_cast<DISCONN_ACK_8 *>(buff), iaUser, sip, it))
951                     return -1;
952                 return Send_FIN_8(iaUser, sip, it);
953             }
954         break;
955     }
956
957 return -1;
958 }
959 //-----------------------------------------------------------------------------
960 void AUTH_IA::DelUser(USER_PTR u)
961 {
962
963 uint32_t ip = u->GetCurrIP();
964
965 if (!ip)
966     return;
967
968 std::map<uint32_t, IA_USER>::iterator it;
969
970 STG_LOCKER lock(&mutex);
971 it = ip2user.find(ip);
972 if (it == ip2user.end())
973     {
974     //Nothing to delete
975     printfd(__FILE__, "Nothing to delete\n");
976     return;
977     }
978
979 if (it->second.user == u)
980     {
981     printfd(__FILE__, "User removed!\n");
982     users->Unauthorize(u->GetLogin(), this);
983     ip2user.erase(it);
984     }
985 }
986 //-----------------------------------------------------------------------------
987 int AUTH_IA::SendError(uint32_t ip, uint16_t port, int protoVer, const std::string & text)
988 {
989 struct sockaddr_in sendAddr;
990 ssize_t res;
991 switch (protoVer)
992     {
993     case 6:
994     case 7:
995         ERR err;
996         memset(&err, 0, sizeof(ERR));
997
998         sendAddr.sin_family = AF_INET;
999         sendAddr.sin_port = htons(port);
1000         sendAddr.sin_addr.s_addr = ip;
1001
1002         err.len = 1;
1003         strncpy((char*)err.type, "ERR", 16);
1004         strncpy((char*)err.text, text.c_str(), MAX_MSG_LEN);
1005
1006         #ifdef ARCH_BE
1007         SwapBytes(err.len);
1008         #endif
1009
1010         res = sendto(listenSocket, &err, sizeof(err), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1011         printfd(__FILE__, "SendError %d bytes sent\n", res);
1012         break;
1013
1014     case 8:
1015         ERR_8 err8;
1016         memset(&err8, 0, sizeof(ERR_8));
1017
1018         sendAddr.sin_family = AF_INET;
1019         sendAddr.sin_port = htons(port);
1020         sendAddr.sin_addr.s_addr = ip;
1021
1022         err8.len = 256;
1023         strncpy((char*)err8.type, "ERR", 16);
1024         strncpy((char*)err8.text, text.c_str(), MAX_MSG_LEN);
1025
1026         #ifdef ARCH_BE
1027         SwapBytes(err8.len);
1028         #endif
1029
1030         res = sendto(listenSocket, &err8, sizeof(err8), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1031         printfd(__FILE__, "SendError_8 %d bytes sent\n", res);
1032         break;
1033     }
1034
1035 return 0;
1036 }
1037 //-----------------------------------------------------------------------------
1038 int AUTH_IA::Send(uint32_t ip, uint16_t port, const char * buffer, size_t len)
1039 {
1040 struct sockaddr_in sendAddr;
1041
1042 sendAddr.sin_family = AF_INET;
1043 sendAddr.sin_port = htons(port);
1044 sendAddr.sin_addr.s_addr = ip;
1045
1046 if (sendto(listenSocket, buffer, len, 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr)) == static_cast<ssize_t>(len))
1047     return 0;
1048
1049 return -1;
1050 }
1051 //-----------------------------------------------------------------------------
1052 int AUTH_IA::SendMessage(const STG_MSG & msg, uint32_t ip) const
1053 {
1054 printfd(__FILE__, "SendMessage userIP=%s\n", inet_ntostring(ip).c_str());
1055
1056 std::map<uint32_t, IA_USER>::iterator it;
1057
1058 STG_LOCKER lock(&mutex);
1059 it = ip2user.find(ip);
1060 if (it == ip2user.end())
1061     {
1062     errorStr = "Unknown user.";
1063     return -1;
1064     }
1065 it->second.messagesToSend.push_back(msg);
1066 return 0;
1067 }
1068 //-----------------------------------------------------------------------------
1069 int AUTH_IA::RealSendMessage6(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1070 {
1071 printfd(__FILE__, "RealSendMessage 6 user=%s\n", user.login.c_str());
1072
1073 INFO_6 info;
1074 memset(&info, 0, sizeof(INFO_6));
1075
1076 info.len = 256;
1077 strncpy((char*)info.type, "INFO", 16);
1078 info.infoType = 'I';
1079 strncpy((char*)info.text, msg.text.c_str(), 235);
1080 info.text[234] = 0;
1081
1082 size_t len = info.len;
1083 #ifdef ARCH_BE
1084 SwapBytes(info.len);
1085 #endif
1086
1087 char buffer[256];
1088 memcpy(buffer, &info, sizeof(INFO_6));
1089 EncryptString(buffer, buffer, len, &user.ctx);
1090 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1091 }
1092 //-----------------------------------------------------------------------------
1093 int AUTH_IA::RealSendMessage7(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1094 {
1095 printfd(__FILE__, "RealSendMessage 7 user=%s\n", user.login.c_str());
1096
1097 INFO_7 info;
1098 memset(&info, 0, sizeof(INFO_7));
1099
1100 info.len = 264;
1101 strncpy((char*)info.type, "INFO_7", 16);
1102 info.infoType = static_cast<int8_t>(msg.header.type);
1103 info.showTime = static_cast<int8_t>(msg.header.showTime);
1104 info.sendTime = msg.header.creationTime;
1105
1106 size_t len = info.len;
1107 #ifdef ARCH_BE
1108 SwapBytes(info.len);
1109 SwapBytes(info.sendTime);
1110 #endif
1111
1112 strncpy((char*)info.text, msg.text.c_str(), MAX_MSG_LEN - 1);
1113 info.text[MAX_MSG_LEN - 1] = 0;
1114
1115 char buffer[300];
1116 memcpy(buffer, &info, sizeof(INFO_7));
1117
1118 EncryptString(buffer, buffer, len, &user.ctx);
1119 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1120 }
1121 //-----------------------------------------------------------------------------
1122 int AUTH_IA::RealSendMessage8(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1123 {
1124 printfd(__FILE__, "RealSendMessage 8 user=%s\n", user.login.c_str());
1125
1126 INFO_8 info;
1127 memset(&info, 0, sizeof(INFO_8));
1128
1129 info.len = 1056;
1130 strncpy((char*)info.type, "INFO_8", 16);
1131 info.infoType = static_cast<int8_t>(msg.header.type);
1132 info.showTime = static_cast<int8_t>(msg.header.showTime);
1133 info.sendTime = msg.header.creationTime;
1134
1135 strncpy((char*)info.text, msg.text.c_str(), IA_MAX_MSG_LEN_8 - 1);
1136 info.text[IA_MAX_MSG_LEN_8 - 1] = 0;
1137
1138 size_t len = info.len;
1139 #ifdef ARCH_BE
1140 SwapBytes(info.len);
1141 SwapBytes(info.sendTime);
1142 #endif
1143
1144 char buffer[1500];
1145 memcpy(buffer, &info, sizeof(INFO_8));
1146
1147 EncryptString(buffer, buffer, len, &user.ctx);
1148 return Send(ip, user.port, buffer, len);
1149 }
1150 //-----------------------------------------------------------------------------
1151 int AUTH_IA::Process_CONN_SYN_6(CONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1152 {
1153 if (!(iaUser->phase.GetPhase() == 1 || iaUser->phase.GetPhase() == 3))
1154     return -1;
1155
1156 enabledDirs = 0xFFffFFff;
1157
1158 iaUser->phase.SetPhase2();
1159 printfd(__FILE__, "Phase changed from %d to 2. Reason: CONN_SYN_6\n", iaUser->phase.GetPhase());
1160 return 0;
1161 }
1162 //-----------------------------------------------------------------------------
1163 int AUTH_IA::Process_CONN_SYN_7(CONN_SYN_7 * connSyn, IA_USER * iaUser, uint32_t sip)
1164 {
1165 return Process_CONN_SYN_6(connSyn, iaUser, sip);
1166 }
1167 //-----------------------------------------------------------------------------
1168 int AUTH_IA::Process_CONN_SYN_8(CONN_SYN_8 * connSyn, IA_USER * iaUser, uint32_t sip)
1169 {
1170 #ifdef ARCH_BE
1171 SwapBytes(connSyn->dirs);
1172 #endif
1173 int ret = Process_CONN_SYN_6(reinterpret_cast<CONN_SYN_6 *>(connSyn), iaUser, sip);
1174 enabledDirs = connSyn->dirs;
1175 return ret;
1176 }
1177 //-----------------------------------------------------------------------------
1178 int AUTH_IA::Process_CONN_ACK_6(CONN_ACK_6 * connAck, IA_USER * iaUser, uint32_t sip)
1179 {
1180 #ifdef ARCH_BE
1181 SwapBytes(connAck->len);
1182 SwapBytes(connAck->rnd);
1183 #endif
1184 printfd( __FILE__, "CONN_ACK_6 %s\n", connAck->type);
1185
1186 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1187     {
1188     iaUser->phase.UpdateTime();
1189
1190     iaUser->lastSendAlive = iaUser->phase.GetTime();
1191     if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1192         {
1193         iaUser->phase.SetPhase3();
1194         printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_6\n");
1195         return 0;
1196         }
1197     else
1198         {
1199         errorStr = iaUser->user->GetStrError();
1200         if (iaSettings.LogProtocolErrors())
1201             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());
1202         iaUser->phase.SetPhase1();
1203         ip2user.erase(sip);
1204         printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1205         return -1;
1206         }
1207     }
1208 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1209 if (iaSettings.LogProtocolErrors())
1210     {
1211     if (iaUser->phase.GetPhase() != 2)
1212         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());
1213     if (connAck->rnd != iaUser->rnd + 1)
1214         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);
1215     }
1216 return -1;
1217 }
1218 //-----------------------------------------------------------------------------
1219 int AUTH_IA::Process_CONN_ACK_7(CONN_ACK_7 * connAck, IA_USER * iaUser, uint32_t sip)
1220 {
1221 return Process_CONN_ACK_6(connAck, iaUser, sip);
1222 }
1223 //-----------------------------------------------------------------------------
1224 int AUTH_IA::Process_CONN_ACK_8(CONN_ACK_8 * connAck, IA_USER * iaUser, uint32_t sip)
1225 {
1226 #ifdef ARCH_BE
1227 SwapBytes(connAck->len);
1228 SwapBytes(connAck->rnd);
1229 #endif
1230 printfd( __FILE__, "CONN_ACK_8 %s\n", connAck->type);
1231
1232 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1233     {
1234     iaUser->phase.UpdateTime();
1235     iaUser->lastSendAlive = iaUser->phase.GetTime();
1236     if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1237         {
1238         iaUser->phase.SetPhase3();
1239         printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_8\n");
1240         return 0;
1241         }
1242     else
1243         {
1244         errorStr = iaUser->user->GetStrError();
1245         if (iaSettings.LogProtocolErrors())
1246             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());
1247         iaUser->phase.SetPhase1();
1248         ip2user.erase(sip);
1249         printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1250         return -1;
1251         }
1252     }
1253 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1254 if (iaSettings.LogProtocolErrors())
1255     {
1256     if (iaUser->phase.GetPhase() != 2)
1257         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());
1258     if (connAck->rnd != iaUser->rnd + 1)
1259         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);
1260     }
1261 return -1;
1262 }
1263 //-----------------------------------------------------------------------------
1264 int AUTH_IA::Process_ALIVE_ACK_6(ALIVE_ACK_6 * aliveAck, IA_USER * iaUser, uint32_t)
1265 {
1266 #ifdef ARCH_BE
1267 SwapBytes(aliveAck->len);
1268 SwapBytes(aliveAck->rnd);
1269 #endif
1270 printfd(__FILE__, "ALIVE_ACK_6\n");
1271 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1272     {
1273     iaUser->phase.UpdateTime();
1274     #ifdef IA_DEBUG
1275     iaUser->aliveSent = false;
1276     #endif
1277     }
1278 return 0;
1279 }
1280 //-----------------------------------------------------------------------------
1281 int AUTH_IA::Process_ALIVE_ACK_7(ALIVE_ACK_7 * aliveAck, IA_USER * iaUser, uint32_t sip)
1282 {
1283 return Process_ALIVE_ACK_6(aliveAck, iaUser, sip);
1284 }
1285 //-----------------------------------------------------------------------------
1286 int AUTH_IA::Process_ALIVE_ACK_8(ALIVE_ACK_8 * aliveAck, IA_USER * iaUser, uint32_t)
1287 {
1288 #ifdef ARCH_BE
1289 SwapBytes(aliveAck->len);
1290 SwapBytes(aliveAck->rnd);
1291 #endif
1292 printfd(__FILE__, "ALIVE_ACK_8\n");
1293 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1294     {
1295     iaUser->phase.UpdateTime();
1296     #ifdef IA_DEBUG
1297     iaUser->aliveSent = false;
1298     #endif
1299     }
1300 return 0;
1301 }
1302 //-----------------------------------------------------------------------------
1303 int AUTH_IA::Process_DISCONN_SYN_6(DISCONN_SYN_6 *, IA_USER * iaUser, uint32_t sip)
1304 {
1305 printfd(__FILE__, "DISCONN_SYN_6\n");
1306 if (iaUser->phase.GetPhase() != 3)
1307     {
1308     if (iaSettings.LogProtocolErrors())
1309         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());
1310     printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1311     errorStr = "Incorrect request DISCONN_SYN";
1312     return -1;
1313     }
1314
1315 iaUser->phase.SetPhase4();
1316 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1317
1318 return 0;
1319 }
1320 //-----------------------------------------------------------------------------
1321 int AUTH_IA::Process_DISCONN_SYN_7(DISCONN_SYN_7 * disconnSyn, IA_USER * iaUser, uint32_t sip)
1322 {
1323 return Process_DISCONN_SYN_6(disconnSyn, iaUser, sip);
1324 }
1325 //-----------------------------------------------------------------------------
1326 int AUTH_IA::Process_DISCONN_SYN_8(DISCONN_SYN_8 *, IA_USER * iaUser, uint32_t sip)
1327 {
1328 if (iaUser->phase.GetPhase() != 3)
1329     {
1330     if (iaSettings.LogProtocolErrors())
1331         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());
1332     errorStr = "Incorrect request DISCONN_SYN";
1333     printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1334     return -1;
1335     }
1336
1337 iaUser->phase.SetPhase4();
1338 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1339
1340 return 0;
1341 }
1342 //-----------------------------------------------------------------------------
1343 int AUTH_IA::Process_DISCONN_ACK_6(DISCONN_ACK_6 * disconnAck,
1344                                    IA_USER * iaUser,
1345                                    uint32_t sip,
1346                                    std::map<uint32_t, IA_USER>::iterator)
1347 {
1348 #ifdef ARCH_BE
1349 SwapBytes(disconnAck->len);
1350 SwapBytes(disconnAck->rnd);
1351 #endif
1352 printfd(__FILE__, "DISCONN_ACK_6\n");
1353 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1354     {
1355     if (iaSettings.LogProtocolErrors())
1356         {
1357         if (iaUser->phase.GetPhase() != 4)
1358             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());
1359         if (disconnAck->rnd != iaUser->rnd + 1)
1360             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);
1361         }
1362     printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1363     return -1;
1364     }
1365
1366 return 0;
1367 }
1368 //-----------------------------------------------------------------------------
1369 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)
1370 {
1371 return Process_DISCONN_ACK_6(disconnAck, iaUser, sip, it);
1372 }
1373 //-----------------------------------------------------------------------------
1374 int AUTH_IA::Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnAck, IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator)
1375 {
1376 #ifdef ARCH_BE
1377 SwapBytes(disconnAck->len);
1378 SwapBytes(disconnAck->rnd);
1379 #endif
1380 printfd(__FILE__, "DISCONN_ACK_8\n");
1381 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1382     {
1383     if (iaSettings.LogProtocolErrors())
1384         {
1385         if (iaUser->phase.GetPhase() != 4)
1386             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());
1387         if (disconnAck->rnd != iaUser->rnd + 1)
1388             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);
1389         }
1390     printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1391     return -1;
1392     }
1393
1394 return 0;
1395 }
1396 //-----------------------------------------------------------------------------
1397 int AUTH_IA::Send_CONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1398 {
1399 //+++ Fill static data in connSynAck +++
1400 // TODO Move this code. It must be executed only once
1401 connSynAck6.len = Min8(sizeof(CONN_SYN_ACK_6));
1402 strcpy((char*)connSynAck6.type, "CONN_SYN_ACK");
1403 for (int j = 0; j < DIR_NUM; j++)
1404     {
1405     strncpy((char*)connSynAck6.dirName[j],
1406             stgSettings->GetDirName(j).c_str(),
1407             sizeof(string16));
1408
1409     connSynAck6.dirName[j][sizeof(string16) - 1] = 0;
1410     }
1411 //--- Fill static data in connSynAck ---
1412
1413 iaUser->rnd = static_cast<uint32_t>(random());
1414 connSynAck6.rnd = iaUser->rnd;
1415
1416 connSynAck6.userTimeOut = iaSettings.GetUserTimeout();
1417 connSynAck6.aliveDelay = iaSettings.GetUserDelay();
1418
1419 #ifdef ARCH_BE
1420 SwapBytes(connSynAck6.len);
1421 SwapBytes(connSynAck6.rnd);
1422 SwapBytes(connSynAck6.userTimeOut);
1423 SwapBytes(connSynAck6.aliveDelay);
1424 #endif
1425
1426 EncryptString((char*)&connSynAck6, (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)), &iaUser->ctx);
1427 return Send(sip, iaSettings.GetUserPort(), (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)));;
1428 }
1429 //-----------------------------------------------------------------------------
1430 int AUTH_IA::Send_CONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1431 {
1432 return Send_CONN_SYN_ACK_6(iaUser, sip);
1433 }
1434 //-----------------------------------------------------------------------------
1435 int AUTH_IA::Send_CONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1436 {
1437 strcpy((char*)connSynAck8.hdr.magic, IA_ID);
1438 connSynAck8.hdr.protoVer[0] = 0;
1439 connSynAck8.hdr.protoVer[1] = 8;
1440
1441 //+++ Fill static data in connSynAck +++
1442 // TODO Move this code. It must be executed only once
1443 connSynAck8.len = Min8(sizeof(CONN_SYN_ACK_8));
1444 strcpy((char*)connSynAck8.type, "CONN_SYN_ACK");
1445 for (int j = 0; j < DIR_NUM; j++)
1446     {
1447     strncpy((char*)connSynAck8.dirName[j],
1448             stgSettings->GetDirName(j).c_str(),
1449             sizeof(string16));
1450
1451     connSynAck8.dirName[j][sizeof(string16) - 1] = 0;
1452     }
1453 //--- Fill static data in connSynAck ---
1454
1455 iaUser->rnd = static_cast<uint32_t>(random());
1456 connSynAck8.rnd = iaUser->rnd;
1457
1458 connSynAck8.userTimeOut = iaSettings.GetUserTimeout();
1459 connSynAck8.aliveDelay = iaSettings.GetUserDelay();
1460
1461 #ifdef ARCH_BE
1462 SwapBytes(connSynAck8.len);
1463 SwapBytes(connSynAck8.rnd);
1464 SwapBytes(connSynAck8.userTimeOut);
1465 SwapBytes(connSynAck8.aliveDelay);
1466 #endif
1467
1468 EncryptString((char*)&connSynAck8, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)), &iaUser->ctx);
1469 return Send(sip, iaUser->port, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)));
1470 }
1471 //-----------------------------------------------------------------------------
1472 int AUTH_IA::Send_ALIVE_SYN_6(IA_USER * iaUser, uint32_t sip)
1473 {
1474 aliveSyn6.len = Min8(sizeof(ALIVE_SYN_6));
1475 aliveSyn6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1476
1477 strcpy((char*)aliveSyn6.type, "ALIVE_SYN");
1478
1479 for (int i = 0; i < DIR_NUM; i++)
1480     {
1481     aliveSyn6.md[i] = iaUser->user->GetProperty().down.Get()[i];
1482     aliveSyn6.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1483
1484     aliveSyn6.sd[i] = iaUser->user->GetSessionDownload()[i];
1485     aliveSyn6.su[i] = iaUser->user->GetSessionUpload()[i];
1486     }
1487
1488 //TODO
1489 int dn = iaSettings.GetFreeMbShowType();
1490 const TARIFF * tf = iaUser->user->GetTariff();
1491
1492 if (dn < DIR_NUM)
1493     {
1494     double p = tf->GetPriceWithTraffType(aliveSyn6.mu[dn],
1495                                          aliveSyn6.md[dn],
1496                                          dn,
1497                                          stgTime);
1498     p *= 1024 * 1024;
1499     if (std::fabs(p) < 1.0e-3)
1500         {
1501         snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "---");
1502         }
1503     else
1504         {
1505         double fmb = iaUser->user->GetProperty().freeMb;
1506         fmb = fmb < 0 ? 0 : fmb;
1507         snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1508         }
1509     }
1510 else
1511     {
1512     if (freeMbNone == iaSettings.GetFreeMbShowType())
1513         {
1514         aliveSyn6.freeMb[0] = 0;
1515         }
1516     else
1517         {
1518         double fmb = iaUser->user->GetProperty().freeMb;
1519         fmb = fmb < 0 ? 0 : fmb;
1520         snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1521         }
1522     }
1523
1524 #ifdef IA_DEBUG
1525 if (iaUser->aliveSent)
1526     {
1527     printfd(__FILE__, "========= ALIVE_ACK_6(7) TIMEOUT !!! %s =========\n", iaUser->login.c_str());
1528     }
1529 iaUser->aliveSent = true;
1530 #endif
1531
1532 aliveSyn6.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1533 if (!stgSettings->GetShowFeeInCash())
1534     aliveSyn6.cash -= (int64_t)(tf->GetFee() * 1000.0);
1535
1536 #ifdef ARCH_BE
1537 SwapBytes(aliveSyn6.len);
1538 SwapBytes(aliveSyn6.rnd);
1539 SwapBytes(aliveSyn6.cash);
1540 for (int i = 0; i < DIR_NUM; ++i)
1541     {
1542     SwapBytes(aliveSyn6.mu[i]);
1543     SwapBytes(aliveSyn6.md[i]);
1544     SwapBytes(aliveSyn6.su[i]);
1545     SwapBytes(aliveSyn6.sd[i]);
1546     }
1547 #endif
1548
1549 EncryptString((char*)&aliveSyn6, (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)), &iaUser->ctx);
1550 return Send(sip, iaSettings.GetUserPort(), (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)));
1551 }
1552 //-----------------------------------------------------------------------------
1553 int AUTH_IA::Send_ALIVE_SYN_7(IA_USER * iaUser, uint32_t sip)
1554 {
1555 return Send_ALIVE_SYN_6(iaUser, sip);
1556 }
1557 //-----------------------------------------------------------------------------
1558 int AUTH_IA::Send_ALIVE_SYN_8(IA_USER * iaUser, uint32_t sip)
1559 {
1560 strcpy((char*)aliveSyn8.hdr.magic, IA_ID);
1561 aliveSyn8.hdr.protoVer[0] = 0;
1562 aliveSyn8.hdr.protoVer[1] = 8;
1563
1564 aliveSyn8.len = Min8(sizeof(ALIVE_SYN_8));
1565 aliveSyn8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1566
1567 strcpy((char*)aliveSyn8.type, "ALIVE_SYN");
1568
1569 for (int i = 0; i < DIR_NUM; i++)
1570     {
1571     aliveSyn8.md[i] = iaUser->user->GetProperty().down.Get()[i];
1572     aliveSyn8.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1573
1574     aliveSyn8.sd[i] = iaUser->user->GetSessionDownload()[i];
1575     aliveSyn8.su[i] = iaUser->user->GetSessionUpload()[i];
1576     }
1577
1578 //TODO
1579 int dn = iaSettings.GetFreeMbShowType();
1580
1581 if (dn < DIR_NUM)
1582     {
1583     const TARIFF * tf = iaUser->user->GetTariff();
1584     double p = tf->GetPriceWithTraffType(aliveSyn8.mu[dn],
1585                                          aliveSyn8.md[dn],
1586                                          dn,
1587                                          stgTime);
1588     p *= 1024 * 1024;
1589     if (std::fabs(p) < 1.0e-3)
1590         {
1591         snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "---");
1592         }
1593     else
1594         {
1595         double fmb = iaUser->user->GetProperty().freeMb;
1596         fmb = fmb < 0 ? 0 : fmb;
1597         snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1598         }
1599     }
1600 else
1601     {
1602     if (freeMbNone == iaSettings.GetFreeMbShowType())
1603         {
1604         aliveSyn8.freeMb[0] = 0;
1605         }
1606     else
1607         {
1608         double fmb = iaUser->user->GetProperty().freeMb;
1609         fmb = fmb < 0 ? 0 : fmb;
1610         snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1611         }
1612     }
1613
1614 #ifdef IA_DEBUG
1615 if (iaUser->aliveSent)
1616     {
1617     printfd(__FILE__, "========= ALIVE_ACK_8 TIMEOUT !!! =========\n");
1618     }
1619 iaUser->aliveSent = true;
1620 #endif
1621
1622 const TARIFF * tf = iaUser->user->GetTariff();
1623
1624 aliveSyn8.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1625 if (!stgSettings->GetShowFeeInCash())
1626     aliveSyn8.cash -= (int64_t)(tf->GetFee() * 1000.0);
1627
1628 #ifdef ARCH_BE
1629 SwapBytes(aliveSyn8.len);
1630 SwapBytes(aliveSyn8.rnd);
1631 SwapBytes(aliveSyn8.cash);
1632 SwapBytes(aliveSyn8.status);
1633 for (int i = 0; i < DIR_NUM; ++i)
1634     {
1635     SwapBytes(aliveSyn8.mu[i]);
1636     SwapBytes(aliveSyn8.md[i]);
1637     SwapBytes(aliveSyn8.su[i]);
1638     SwapBytes(aliveSyn8.sd[i]);
1639     }
1640 #endif
1641
1642 EncryptString((char*)&aliveSyn8, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)), &iaUser->ctx);
1643 return Send(sip, iaUser->port, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)));
1644 }
1645 //-----------------------------------------------------------------------------
1646 int AUTH_IA::Send_DISCONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1647 {
1648 disconnSynAck6.len = Min8(sizeof(DISCONN_SYN_ACK_6));
1649 strcpy((char*)disconnSynAck6.type, "DISCONN_SYN_ACK");
1650 disconnSynAck6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1651
1652 #ifdef ARCH_BE
1653 SwapBytes(disconnSynAck6.len);
1654 SwapBytes(disconnSynAck6.rnd);
1655 #endif
1656
1657 EncryptString((char*)&disconnSynAck6, (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)), &iaUser->ctx);
1658 return Send(sip, iaSettings.GetUserPort(), (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)));
1659 }
1660 //-----------------------------------------------------------------------------
1661 int AUTH_IA::Send_DISCONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1662 {
1663 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
1664 }
1665 //-----------------------------------------------------------------------------
1666 int AUTH_IA::Send_DISCONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1667 {
1668 strcpy((char*)disconnSynAck8.hdr.magic, IA_ID);
1669 disconnSynAck8.hdr.protoVer[0] = 0;
1670 disconnSynAck8.hdr.protoVer[1] = 8;
1671
1672 disconnSynAck8.len = Min8(sizeof(DISCONN_SYN_ACK_8));
1673 strcpy((char*)disconnSynAck8.type, "DISCONN_SYN_ACK");
1674 disconnSynAck8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1675
1676 #ifdef ARCH_BE
1677 SwapBytes(disconnSynAck8.len);
1678 SwapBytes(disconnSynAck8.rnd);
1679 #endif
1680
1681 EncryptString((char*)&disconnSynAck8, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)), &iaUser->ctx);
1682 return Send(sip, iaUser->port, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)));
1683 }
1684 //-----------------------------------------------------------------------------
1685 int AUTH_IA::Send_FIN_6(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1686 {
1687 fin6.len = Min8(sizeof(FIN_6));
1688 strcpy((char*)fin6.type, "FIN");
1689 strcpy((char*)fin6.ok, "OK");
1690
1691 #ifdef ARCH_BE
1692 SwapBytes(fin6.len);
1693 #endif
1694
1695 EncryptString((char*)&fin6, (char*)&fin6, Min8(sizeof(fin6)), &iaUser->ctx);
1696
1697 users->Unauthorize(iaUser->login, this);
1698
1699 int res = Send(sip, iaSettings.GetUserPort(), (char*)&fin6, Min8(sizeof(fin6)));
1700
1701 ip2user.erase(it);
1702
1703 return res;
1704 }
1705 //-----------------------------------------------------------------------------
1706 int AUTH_IA::Send_FIN_7(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1707 {
1708 return Send_FIN_6(iaUser, sip, it);
1709 }
1710 //-----------------------------------------------------------------------------
1711 int AUTH_IA::Send_FIN_8(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1712 {
1713 strcpy((char*)fin8.hdr.magic, IA_ID);
1714 fin8.hdr.protoVer[0] = 0;
1715 fin8.hdr.protoVer[1] = 8;
1716
1717 fin8.len = Min8(sizeof(FIN_8));
1718 strcpy((char*)fin8.type, "FIN");
1719 strcpy((char*)fin8.ok, "OK");
1720
1721 #ifdef ARCH_BE
1722 SwapBytes(fin8.len);
1723 #endif
1724
1725 EncryptString((char*)&fin8, (char*)&fin8, Min8(sizeof(fin8)), &iaUser->ctx);
1726
1727 users->Unauthorize(iaUser->login, this);
1728
1729 int res = Send(sip, iaUser->port, (char*)&fin8, Min8(sizeof(fin8)));
1730
1731 ip2user.erase(it);
1732
1733 return res;
1734 }