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