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