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