]> git.stg.codes - stg.git/blob - projects/stargazer/plugins/authorization/inetaccess/inetaccess.cpp
Introduced logger for plugins.
[stg.git] / projects / stargazer / plugins / authorization / inetaccess / inetaccess.cpp
1 /*
2  *    This program is free software; you can redistribute it and/or modify
3  *    it under the terms of the GNU General Public License as published by
4  *    the Free Software Foundation; either version 2 of the License, or
5  *    (at your option) any later version.
6  *
7  *    This program is distributed in the hope that it will be useful,
8  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
9  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  *    GNU General Public License for more details.
11  *
12  *    You should have received a copy of the GNU General Public License
13  *    along with this program; if not, write to the Free Software
14  *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
15  */
16
17 /*
18  *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
19  */
20
21 /*
22  $Revision: 1.79 $
23  $Date: 2010/03/25 15:18:48 $
24  $Author: faust $
25  */
26  
27 #ifndef _GNU_SOURCE
28 #define _GNU_SOURCE
29 #endif
30
31 #include <sys/types.h>
32 #include <sys/socket.h>
33 #include <unistd.h> // close
34
35 #include <csignal>
36 #include <cstdlib>
37 #include <cstdio> // snprintf
38 #include <cerrno>
39 #include <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       errorStr(),
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       phaseTime(),
178       flog(NULL)
179 {
180 gettimeofday(&phaseTime, NULL);
181 }
182 #else
183 IA_PHASE::IA_PHASE()
184     : phase(1),
185       phaseTime()
186 {
187 gettimeofday(&phaseTime, NULL);
188 }
189 #endif
190 //-----------------------------------------------------------------------------
191 IA_PHASE::~IA_PHASE()
192 {
193 #ifdef IA_PHASE_DEBUG
194 flog = fopen(log.c_str(), "at");
195 if (flog)
196     {
197     fprintf(flog, "IA %s D\n", login.c_str());
198     fclose(flog);
199     }
200 #endif
201 }
202 //-----------------------------------------------------------------------------
203 #ifdef IA_PHASE_DEBUG
204 void IA_PHASE::SetLogFileName(const string & logFileName)
205 {
206 log = logFileName + ".ia.log";
207 }
208 //-----------------------------------------------------------------------------
209 void IA_PHASE::SetUserLogin(const string & login)
210 {
211 IA_PHASE::login = login;
212 }
213 //-----------------------------------------------------------------------------
214 void IA_PHASE::WritePhaseChange(int newPhase)
215 {
216 UTIME newPhaseTime;
217 gettimeofday(&newPhaseTime, NULL);
218 flog = fopen(log.c_str(), "at");
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     : ctxS(),
302       errorStr(),
303       iaSettings(),
304       settings(),
305       nonstop(false),
306       isRunningRun(false),
307       isRunningRunTimeouter(false),
308       users(NULL),
309       stgSettings(NULL),
310       ip2user(),
311       recvThread(),
312       timeouterThread(),
313       mutex(),
314       listenSocket(-1),
315       connSynAck6(),
316       connSynAck8(),
317       disconnSynAck6(),
318       disconnSynAck8(),
319       aliveSyn6(),
320       aliveSyn8(),
321       fin6(),
322       fin8(),
323       packetTypes(),
324       enabledDirs(0xFFffFFff),
325       onDelUserNotifier(*this),
326       logger(GetPluginLogger(GetStgLogger(), "auth_ia"))
327 {
328 InitEncrypt(&ctxS, "pr7Hhen");
329
330 pthread_mutexattr_t attr;
331 pthread_mutexattr_init(&attr);
332 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
333 pthread_mutex_init(&mutex, &attr);
334
335 memset(&connSynAck6, 0, sizeof(CONN_SYN_ACK_6));
336 memset(&connSynAck8, 0, sizeof(CONN_SYN_ACK_8));
337 memset(&disconnSynAck6, 0, sizeof(DISCONN_SYN_ACK_6));
338 memset(&disconnSynAck8, 0, sizeof(DISCONN_SYN_ACK_8));
339 memset(&aliveSyn6, 0, sizeof(ALIVE_SYN_6));
340 memset(&aliveSyn8, 0, sizeof(ALIVE_SYN_8));
341 memset(&fin6, 0, sizeof(FIN_6));
342 memset(&fin8, 0, sizeof(FIN_8));
343
344 printfd(__FILE__, "sizeof(CONN_SYN_6) = %d %d\n",           sizeof(CONN_SYN_6),     Min8(sizeof(CONN_SYN_6)));
345 printfd(__FILE__, "sizeof(CONN_SYN_8) = %d %d\n",           sizeof(CONN_SYN_8),     Min8(sizeof(CONN_SYN_8)));
346 printfd(__FILE__, "sizeof(CONN_SYN_ACK_6) = %d %d\n",       sizeof(CONN_SYN_ACK_6), Min8(sizeof(CONN_SYN_ACK_6)));
347 printfd(__FILE__, "sizeof(CONN_SYN_ACK_8) = %d %d\n",       sizeof(CONN_SYN_ACK_8), Min8(sizeof(CONN_SYN_ACK_8)));
348 printfd(__FILE__, "sizeof(CONN_ACK_6) = %d %d\n",           sizeof(CONN_ACK_6),     Min8(sizeof(CONN_ACK_6)));
349 printfd(__FILE__, "sizeof(ALIVE_SYN_6) = %d %d\n",          sizeof(ALIVE_SYN_6),    Min8(sizeof(ALIVE_SYN_6)));
350 printfd(__FILE__, "sizeof(ALIVE_SYN_8) = %d %d\n",          sizeof(ALIVE_SYN_8),    Min8(sizeof(ALIVE_SYN_8)));
351 printfd(__FILE__, "sizeof(ALIVE_ACK_6) = %d %d\n",          sizeof(ALIVE_ACK_6),    Min8(sizeof(ALIVE_ACK_6)));
352 printfd(__FILE__, "sizeof(DISCONN_SYN_6) = %d %d\n",        sizeof(DISCONN_SYN_6),  Min8(sizeof(DISCONN_SYN_6)));
353 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_6) = %d %d\n",    sizeof(DISCONN_SYN_ACK_6), Min8(sizeof(DISCONN_SYN_ACK_6)));
354 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_8) = %d %d\n",    sizeof(DISCONN_SYN_ACK_8), Min8(sizeof(DISCONN_SYN_ACK_8)));
355 printfd(__FILE__, "sizeof(DISCONN_ACK_6) = %d %d\n",        sizeof(DISCONN_ACK_6),  Min8(sizeof(DISCONN_ACK_6)));
356 printfd(__FILE__, "sizeof(FIN_6) = %d %d\n",                sizeof(FIN_6),          Min8(sizeof(FIN_6)));
357 printfd(__FILE__, "sizeof(FIN_8) = %d %d\n",                sizeof(FIN_8),          Min8(sizeof(FIN_8)));
358 printfd(__FILE__, "sizeof(ERR) = %d %d\n",                  sizeof(ERR),            Min8(sizeof(ERR)));
359 printfd(__FILE__, "sizeof(INFO_6) = %d %d\n",               sizeof(INFO_6),         Min8(sizeof(INFO_6)));
360 printfd(__FILE__, "sizeof(INFO_7) = %d %d\n",               sizeof(INFO_7),         Min8(sizeof(INFO_7)));
361 printfd(__FILE__, "sizeof(INFO_8) = %d %d\n",               sizeof(INFO_8),         Min8(sizeof(INFO_8)));
362
363 packetTypes["CONN_SYN"] = CONN_SYN_N;
364 packetTypes["CONN_SYN_ACK"] = CONN_SYN_ACK_N;
365 packetTypes["CONN_ACK"] = CONN_ACK_N;
366 packetTypes["ALIVE_SYN"] = ALIVE_SYN_N;
367 packetTypes["ALIVE_ACK"] = ALIVE_ACK_N;
368 packetTypes["DISCONN_SYN"] = DISCONN_SYN_N;
369 packetTypes["DISCONN_SYN_ACK"] = DISCONN_SYN_ACK_N;
370 packetTypes["DISCONN_ACK"] = DISCONN_ACK_N;
371 packetTypes["FIN"] = FIN_N;
372 packetTypes["ERR"] = ERROR_N;
373 }
374 //-----------------------------------------------------------------------------
375 AUTH_IA::~AUTH_IA()
376 {
377 pthread_mutex_destroy(&mutex);
378 }
379 //-----------------------------------------------------------------------------
380 int AUTH_IA::Start()
381 {
382 users->AddNotifierUserDel(&onDelUserNotifier);
383 nonstop = true;
384
385 if (PrepareNet())
386     {
387     return -1;
388     }
389
390 if (!isRunningRun)
391     {
392     if (pthread_create(&recvThread, NULL, Run, this))
393         {
394         errorStr = "Cannot create thread.";
395         printfd(__FILE__, "Cannot create recv thread\n");
396         return -1;
397         }
398     }
399
400 if (!isRunningRunTimeouter)
401     {
402     if (pthread_create(&timeouterThread, NULL, RunTimeouter, this))
403         {
404         errorStr = "Cannot create thread.";
405         printfd(__FILE__, "Cannot create timeouter thread\n");
406         return -1;
407         }
408     }
409 errorStr = "";
410 return 0;
411 }
412 //-----------------------------------------------------------------------------
413 int AUTH_IA::Stop()
414 {
415 if (!IsRunning())
416     return 0;
417
418 nonstop = false;
419
420 std::for_each(
421         ip2user.begin(),
422         ip2user.end(),
423         UnauthorizeUser(this)
424         );
425
426 if (isRunningRun)
427     {
428     //5 seconds to thread stops itself
429     for (int i = 0; i < 25 && isRunningRun; i++)
430         {
431         struct timespec ts = {0, 200000000};
432         nanosleep(&ts, NULL);
433         }
434     }
435
436 FinalizeNet();
437
438 if (isRunningRunTimeouter)
439     {
440     //5 seconds to thread stops itself
441     for (int i = 0; i < 25 && isRunningRunTimeouter; i++)
442         {
443         struct timespec ts = {0, 200000000};
444         nanosleep(&ts, NULL);
445         }
446     }
447
448 users->DelNotifierUserDel(&onDelUserNotifier);
449
450 if (isRunningRun || isRunningRunTimeouter)
451     return -1;
452
453 printfd(__FILE__, "AUTH_IA::Stoped successfully.\n");
454 return 0;
455 }
456 //-----------------------------------------------------------------------------
457 void * AUTH_IA::Run(void * d)
458 {
459 sigset_t signalSet;
460 sigfillset(&signalSet);
461 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
462
463 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
464
465 ia->isRunningRun = true;
466
467 char buffer[512];
468
469 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
470
471 while (ia->nonstop)
472     {
473     ia->RecvData(buffer, sizeof(buffer));
474     if ((touchTime + MONITOR_TIME_DELAY_SEC <= stgTime) && ia->stgSettings->GetMonitoring())
475         {
476         touchTime = stgTime;
477         string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_r";
478         TouchFile(monFile.c_str());
479         }
480     }
481
482 ia->isRunningRun = false;
483 return NULL;
484 }
485 //-----------------------------------------------------------------------------
486 void * AUTH_IA::RunTimeouter(void * d)
487 {
488 sigset_t signalSet;
489 sigfillset(&signalSet);
490 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
491
492 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
493
494 ia->isRunningRunTimeouter = true;
495
496 int a = -1;
497 string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_t";
498 while (ia->nonstop)
499     {
500     struct timespec ts = {0, 20000000};
501     nanosleep(&ts, NULL);
502     ia->Timeouter();
503     // TODO change counter to timer and MONITOR_TIME_DELAY_SEC
504     if (++a % (50 * 60) == 0 && ia->stgSettings->GetMonitoring())
505         {
506         TouchFile(monFile.c_str());
507         }
508     }
509
510 ia->isRunningRunTimeouter = false;
511 return NULL;
512 }
513 //-----------------------------------------------------------------------------
514 int AUTH_IA::ParseSettings()
515 {
516 int ret = iaSettings.ParseSettings(settings);
517 if (ret)
518     errorStr = iaSettings.GetStrError();
519 return ret;
520 }
521 //-----------------------------------------------------------------------------
522 int AUTH_IA::PrepareNet()
523 {
524 struct sockaddr_in listenAddr;
525
526 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
527
528 if (listenSocket < 0)
529     {
530     errorStr = "Cannot create socket.";
531     return -1;
532     }
533
534 listenAddr.sin_family = AF_INET;
535 listenAddr.sin_port = htons(iaSettings.GetUserPort());
536 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
537
538 if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
539     {
540     errorStr = "AUTH_IA: Bind failed.";
541     return -1;
542     }
543
544 return 0;
545 }
546 //-----------------------------------------------------------------------------
547 int AUTH_IA::FinalizeNet()
548 {
549 close(listenSocket);
550 return 0;
551 }
552 //-----------------------------------------------------------------------------
553 int AUTH_IA::RecvData(char * buffer, int bufferSize)
554 {
555 if (!WaitPackets(listenSocket)) // Timeout
556     {
557     return 0;
558     }
559
560 struct sockaddr_in outerAddr;
561 socklen_t outerAddrLen(sizeof(outerAddr));
562 int dataLen = recvfrom(listenSocket, buffer, bufferSize, 0, (struct sockaddr *)&outerAddr, &outerAddrLen);
563
564 if (!dataLen) // EOF
565     {
566     return 0;
567     }
568
569 if (dataLen <= 0) // Error
570     {
571     if (errno != EINTR)
572         {
573         printfd(__FILE__, "recvfrom res=%d, error: '%s'\n", dataLen, strerror(errno));
574         return -1;
575         }
576     return 0;
577     }
578
579 if (dataLen > 256)
580     return -1;
581
582 int protoVer;
583 if (CheckHeader(buffer, &protoVer))
584     return -1;
585
586 char login[PASSWD_LEN];  //TODO why PASSWD_LEN ?
587 memset(login, 0, PASSWD_LEN);
588
589 Decrypt(&ctxS, login, buffer + 8, PASSWD_LEN / 8);
590
591 uint32_t sip = outerAddr.sin_addr.s_addr;
592 uint16_t sport = htons(outerAddr.sin_port);
593
594 USER_PTR user;
595 if (users->FindByName(login, &user))
596     {
597     logger("User's connect failed: user '%s' not found. IP %s",
598            login,
599            inet_ntostring(sip).c_str());
600     printfd(__FILE__, "User '%s' NOT found!\n", login);
601     SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉÎ!");
602     return -1;
603     }
604
605 printfd(__FILE__, "User '%s' FOUND!\n", user->GetLogin().c_str());
606
607 if (user->GetProperty().disabled.Get())
608     {
609     SendError(sip, sport, protoVer, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÂÌÏËÉÒÏ×ÁÎÁ");
610     return 0;
611     }
612
613 if (user->GetProperty().passive.Get())
614     {
615     SendError(sip, sport, protoVer, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÍÏÒÏÖÅÎÁ");
616     return 0;
617     }
618
619 if (!user->GetProperty().ips.Get().IsIPInIPS(sip))
620     {
621     printfd(__FILE__, "User %s. IP address is incorrect. IP %s\n",
622             user->GetLogin().c_str(), inet_ntostring(sip).c_str());
623     logger("User %s. IP address is incorrect. IP %s",
624            user->GetLogin().c_str(), inet_ntostring(sip).c_str());
625     SendError(sip, sport, protoVer, "ðÏÌØÚÏ×ÁÔÅÌØ ÎÅ ÏÐÏÚÎÁÎ! ðÒÏ×ÅÒØÔÅ IP ÁÄÒÅÓ.");
626     return 0;
627     }
628
629 return PacketProcessor(buffer, dataLen, sip, sport, protoVer, user);
630 }
631 //-----------------------------------------------------------------------------
632 int AUTH_IA::CheckHeader(const char * buffer, int * protoVer)
633 {
634 if (strncmp(IA_ID, buffer, strlen(IA_ID)) != 0)
635     {
636     //SendError(userIP, updateMsg);
637     printfd(__FILE__, "update needed - IA_ID\n");
638     //SendError(userIP, "Incorrect header!");
639     return -1;
640     }
641
642 if (buffer[6] != 0) //proto[0] shoud be 0
643     {
644     printfd(__FILE__, "update needed - PROTO major: %d\n", buffer[6]);
645     //SendError(userIP, updateMsg);
646     return -1;
647     }
648
649 if (buffer[7] < 6)
650     {
651     // need update
652     //SendError(userIP, updateMsg);
653     printfd(__FILE__, "update needed - PROTO minor: %d\n", buffer[7]);
654     return -1;
655     }
656 else
657     {
658     *protoVer = buffer[7];
659     }
660 return 0;
661 }
662 //-----------------------------------------------------------------------------
663 int AUTH_IA::Timeouter()
664 {
665 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
666
667 map<uint32_t, IA_USER>::iterator it;
668 it = ip2user.begin();
669 uint32_t sip;
670
671 while (it != ip2user.end())
672     {
673     sip = it->first;
674
675     static UTIME currTime;
676     gettimeofday(&currTime, NULL);
677
678     if ((it->second.phase.GetPhase() == 2)
679         && (currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay())
680         {
681         it->second.phase.SetPhase1();
682         printfd(__FILE__, "Phase changed from 2 to 1. Reason: timeout\n");
683         ip2user.erase(it++);
684         continue;
685         }
686
687     if (it->second.phase.GetPhase() == 3)
688         {
689         if (!it->second.messagesToSend.empty())
690             {
691             if (it->second.protoVer == 6)
692                 RealSendMessage6(*it->second.messagesToSend.begin(), sip, it->second);
693
694             if (it->second.protoVer == 7)
695                 RealSendMessage7(*it->second.messagesToSend.begin(), sip, it->second);
696
697             if (it->second.protoVer == 8)
698                 RealSendMessage8(*it->second.messagesToSend.begin(), sip, it->second);
699
700             it->second.messagesToSend.erase(it->second.messagesToSend.begin());
701             }
702
703         if((currTime - it->second.lastSendAlive) > iaSettings.GetUserDelay())
704             {
705             switch (it->second.protoVer)
706                 {
707                 case 6:
708                     Send_ALIVE_SYN_6(&(it->second), sip);
709                     break;
710                 case 7:
711                     Send_ALIVE_SYN_7(&(it->second), sip);
712                     break;
713                 case 8:
714                     Send_ALIVE_SYN_8(&(it->second), sip);
715                     break;
716                 }
717
718             gettimeofday(&it->second.lastSendAlive, NULL);
719             }
720
721         if ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserTimeout())
722             {
723             users->Unauthorize(it->second.user->GetLogin(), this);
724             ip2user.erase(it++);
725             continue;
726             }
727         }
728
729     if ((it->second.phase.GetPhase() == 4)
730         && ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay()))
731         {
732         it->second.phase.SetPhase3();
733         printfd(__FILE__, "Phase changed from 4 to 3. Reason: timeout\n");
734         }
735
736     ++it;
737     }
738
739 return 0;
740 }
741 //-----------------------------------------------------------------------------
742 int AUTH_IA::PacketProcessor(char * buff, int dataLen, uint32_t sip, uint16_t sport, int protoVer, USER_PTR user)
743 {
744 std::string login(user->GetLogin());
745 const int offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer;
746
747 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
748 map<uint32_t, IA_USER>::iterator it(ip2user.find(sip));
749
750 if (it == ip2user.end())
751     {
752     USER_PTR userPtr;
753     if (!users->FindByIPIdx(sip, &userPtr))
754         {
755         if (userPtr->GetID() != user->GetID())
756             {
757             printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
758                     userPtr->GetLogin().c_str(),
759                     inet_ntostring(sip).c_str(),
760                    login.c_str());
761             logger("IP address already in use by user '%s'. IP %s, login: '%s'",
762                    userPtr->GetLogin().c_str(),
763                    inet_ntostring(sip).c_str(),
764                    login.c_str());
765             SendError(sip, sport, protoVer, "÷ÁÛ IP ÁÄÒÅÓ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
766             return 0;
767             }
768         }
769
770     printfd(__FILE__, "Add new user '%s' from ip %s\n",
771             login.c_str(), inet_ntostring(sip).c_str());
772     std::pair<std::map<uint32_t, IA_USER>::iterator, bool> res;
773     res = ip2user.insert(std::make_pair(sip, IA_USER(login, user, sport, protoVer)));
774     it = res.first;
775     #ifdef IA_PHASE_DEBUG
776     it->second.phase.SetLogFileName(stgSettings->GetLogFileName());
777     it->second.phase.SetUserLogin(login);
778     #endif
779     }
780 else if (user->GetID() != it->second.user->GetID())
781     {
782     printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
783             it->second.user->GetLogin().c_str(),
784             inet_ntostring(sip).c_str(),
785             user->GetLogin().c_str());
786     logger("IP address already in use by user '%s'. IP %s, login: '%s'",
787            it->second.user->GetLogin().c_str(),
788            inet_ntostring(sip).c_str(),
789            user->GetLogin().c_str());
790     SendError(sip, sport, protoVer, "÷ÁÛ IP ÁÄÒÅÓ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
791     return 0;
792     }
793
794 IA_USER * iaUser = &(it->second);
795
796 if (iaUser->password != user->GetProperty().password.Get())
797     {
798     InitEncrypt(&iaUser->ctx, user->GetProperty().password.Get());
799     iaUser->password = user->GetProperty().password.Get();
800     }
801
802 buff += offset;
803 Decrypt(&iaUser->ctx, buff, buff, (dataLen - offset) / 8);
804
805 char packetName[IA_MAX_TYPE_LEN];
806 strncpy(packetName,  buff + 4, IA_MAX_TYPE_LEN);
807 packetName[IA_MAX_TYPE_LEN - 1] = 0;
808
809 map<string, int>::iterator pi(packetTypes.find(packetName));
810 if (pi == packetTypes.end())
811     {
812     SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉΠÉÌÉ ÐÁÒÏÌØ!");
813     printfd(__FILE__, "Login or password is wrong!\n");
814     logger("User's connect failed. User: '%s', ip %s. Wrong login or password",
815            login.c_str(),
816            inet_ntostring(sip).c_str());
817     ip2user.erase(it);
818     return 0;
819     }
820
821 if (user->IsAuthorizedBy(this) && user->GetCurrIP() != sip)
822     {
823     printfd(__FILE__, "Login %s already in use from ip %s. IP %s\n",
824             login.c_str(), inet_ntostring(user->GetCurrIP()).c_str(),
825             inet_ntostring(sip).c_str());
826     logger("Login %s already in use from ip %s. IP %s",
827            login.c_str(),
828            inet_ntostring(user->GetCurrIP()).c_str(),
829            inet_ntostring(sip).c_str());
830     SendError(sip, sport, protoVer, "÷ÁÛ ÌÏÇÉΠÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!");
831     ip2user.erase(it);
832     return 0;
833     }
834
835 switch (pi->second)
836     {
837     case CONN_SYN_N:
838         switch (protoVer)
839             {
840             case 6:
841                 if (Process_CONN_SYN_6((CONN_SYN_6 *)(buff - offset), &(it->second), sip))
842                     return -1;
843                 return Send_CONN_SYN_ACK_6(iaUser, sip);
844             case 7:
845                 if (Process_CONN_SYN_7((CONN_SYN_7 *)(buff - offset), &(it->second), sip))
846                     return -1;
847                 return Send_CONN_SYN_ACK_7(iaUser, sip);
848             case 8:
849                 if (Process_CONN_SYN_8((CONN_SYN_8 *)(buff - offset), &(it->second), sip))
850                     return -1;
851                 return Send_CONN_SYN_ACK_8(iaUser, sip);
852             }
853         break;
854
855     case CONN_ACK_N:
856         switch (protoVer)
857             {
858             case 6:
859                 if (Process_CONN_ACK_6((CONN_ACK_6 *)(buff - offset), iaUser, sip))
860                     return -1;
861                 return Send_ALIVE_SYN_6(iaUser, sip);
862             case 7:
863                 if (Process_CONN_ACK_7((CONN_ACK_6 *)(buff - offset), iaUser, sip))
864                     return -1;
865                 return Send_ALIVE_SYN_7(iaUser, sip);
866             case 8:
867                 if (Process_CONN_ACK_8((CONN_ACK_8 *)(buff - offset), iaUser, sip))
868                     return -1;
869                 return Send_ALIVE_SYN_8(iaUser, sip);
870             }
871         break;
872
873     case ALIVE_ACK_N:
874         switch (protoVer)
875             {
876             case 6:
877                 return Process_ALIVE_ACK_6((ALIVE_ACK_6 *)(buff - offset), iaUser, sip);
878             case 7:
879                 return Process_ALIVE_ACK_7((ALIVE_ACK_6 *)(buff - offset), iaUser, sip);
880             case 8:
881                 return Process_ALIVE_ACK_8((ALIVE_ACK_8 *)(buff - offset), iaUser, sip);
882             }
883         break;
884
885     case DISCONN_SYN_N:
886         switch (protoVer)
887             {
888             case 6:
889                 if (Process_DISCONN_SYN_6((DISCONN_SYN_6 *)(buff - offset), iaUser, sip))
890                     return -1;
891                 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
892             case 7:
893                 if (Process_DISCONN_SYN_7((DISCONN_SYN_6 *)(buff - offset), iaUser, sip))
894                     return -1;
895                 return Send_DISCONN_SYN_ACK_7(iaUser, sip);
896             case 8:
897                 if (Process_DISCONN_SYN_8((DISCONN_SYN_8 *)(buff - offset), iaUser, sip))
898                     return -1;
899                 return Send_DISCONN_SYN_ACK_8(iaUser, sip);
900             }
901         break;
902
903     case DISCONN_ACK_N:
904         switch (protoVer)
905             {
906             case 6:
907                 if (Process_DISCONN_ACK_6((DISCONN_ACK_6 *)(buff - offset), iaUser, sip, it))
908                     return -1;
909                 return Send_FIN_6(iaUser, sip, it);
910             case 7:
911                 if (Process_DISCONN_ACK_7((DISCONN_ACK_6 *)(buff - offset), iaUser, sip, it))
912                     return -1;
913                 return Send_FIN_7(iaUser, sip, it);
914             case 8:
915                 if (Process_DISCONN_ACK_8((DISCONN_ACK_8 *)(buff - offset), iaUser, sip, it))
916                     return -1;
917                 return Send_FIN_8(iaUser, sip, it);
918             }
919         break;
920     }
921
922 return -1;
923 }
924 //-----------------------------------------------------------------------------
925 void AUTH_IA::DelUser(USER_PTR u)
926 {
927
928 uint32_t ip = u->GetCurrIP();
929
930 if (!ip)
931     return;
932
933 map<uint32_t, IA_USER>::iterator it;
934
935 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
936 it = ip2user.find(ip);
937 if (it == ip2user.end())
938     {
939     //Nothing to delete
940     printfd(__FILE__, "Nothing to delete\n");
941     return;
942     }
943
944 if (it->second.user == u)
945     {
946     printfd(__FILE__, "User removed!\n");
947     users->Unauthorize(u->GetLogin(), this);
948     ip2user.erase(it);
949     }
950 }
951 //-----------------------------------------------------------------------------
952 int AUTH_IA::SendError(uint32_t ip, uint16_t port, int protoVer, const string & text)
953 {
954 struct sockaddr_in sendAddr;
955 switch (protoVer)
956     {
957     int res;
958     case 6:
959     case 7:
960         ERR err;
961         memset(&err, 0, sizeof(ERR));
962
963         sendAddr.sin_family = AF_INET;
964         sendAddr.sin_port = htons(port);
965         sendAddr.sin_addr.s_addr = ip;
966
967         err.len = 1;
968         strncpy((char*)err.type, "ERR", 16);
969         strncpy((char*)err.text, text.c_str(), MAX_MSG_LEN);
970
971         #ifdef ARCH_BE
972         SwapBytes(err.len);
973         #endif
974
975         res = sendto(listenSocket, &err, sizeof(err), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
976         printfd(__FILE__, "SendError %d bytes sent\n", res);
977         break;
978
979     case 8:
980         ERR_8 err8;
981         memset(&err8, 0, sizeof(ERR_8));
982
983         sendAddr.sin_family = AF_INET;
984         sendAddr.sin_port = htons(port);
985         sendAddr.sin_addr.s_addr = ip;
986
987         err8.len = 256;
988         strncpy((char*)err8.type, "ERR", 16);
989         strncpy((char*)err8.text, text.c_str(), MAX_MSG_LEN);
990
991         #ifdef ARCH_BE
992         SwapBytes(err8.len);
993         #endif
994
995         res = sendto(listenSocket, &err8, sizeof(err8), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
996         printfd(__FILE__, "SendError_8 %d bytes sent\n", res);
997         break;
998     }
999
1000 return 0;
1001 }
1002 //-----------------------------------------------------------------------------
1003 int AUTH_IA::Send(uint32_t ip, uint16_t port, const char * buffer, int len)
1004 {
1005 struct sockaddr_in sendAddr;
1006
1007 sendAddr.sin_family = AF_INET;
1008 sendAddr.sin_port = htons(port);
1009 sendAddr.sin_addr.s_addr = ip;
1010
1011 int res = sendto(listenSocket, buffer, len, 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1012
1013 if (res == len)
1014     return 0;
1015
1016 return -1;
1017 }
1018 //-----------------------------------------------------------------------------
1019 int AUTH_IA::SendMessage(const STG_MSG & msg, uint32_t ip) const
1020 {
1021 printfd(__FILE__, "SendMessage userIP=%s\n", inet_ntostring(ip).c_str());
1022
1023 map<uint32_t, IA_USER>::iterator it;
1024
1025 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1026 it = ip2user.find(ip);
1027 if (it == ip2user.end())
1028     {
1029     errorStr = "Unknown user.";
1030     return -1;
1031     }
1032 it->second.messagesToSend.push_back(msg);
1033 return 0;
1034 }
1035 //-----------------------------------------------------------------------------
1036 int AUTH_IA::RealSendMessage6(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1037 {
1038 printfd(__FILE__, "RealSendMessage 6 user=%s\n", user.login.c_str());
1039
1040 INFO_6 info;
1041 memset(&info, 0, sizeof(INFO_6));
1042
1043 info.len = 256;
1044 strncpy((char*)info.type, "INFO", 16);
1045 info.infoType = 'I';
1046 strncpy((char*)info.text, msg.text.c_str(), 235);
1047 info.text[234] = 0;
1048
1049 size_t len = info.len;
1050 #ifdef ARCH_BE
1051 SwapBytes(info.len);
1052 #endif
1053
1054 char buffer[256];
1055 memcpy(buffer, &info, sizeof(INFO_6));
1056 Encrypt(&user.ctx, buffer, buffer, len / 8);
1057 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1058 }
1059 //-----------------------------------------------------------------------------
1060 int AUTH_IA::RealSendMessage7(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1061 {
1062 printfd(__FILE__, "RealSendMessage 7 user=%s\n", user.login.c_str());
1063
1064 INFO_7 info;
1065 memset(&info, 0, sizeof(INFO_7));
1066
1067 info.len = 264;
1068 strncpy((char*)info.type, "INFO_7", 16);
1069 info.infoType = msg.header.type;
1070 info.showTime = msg.header.showTime;
1071 info.sendTime = msg.header.creationTime;
1072
1073 size_t len = info.len;
1074 #ifdef ARCH_BE
1075 SwapBytes(info.len);
1076 SwapBytes(info.sendTime);
1077 #endif
1078
1079 strncpy((char*)info.text, msg.text.c_str(), MAX_MSG_LEN - 1);
1080 info.text[MAX_MSG_LEN - 1] = 0;
1081
1082 char buffer[300];
1083 memcpy(buffer, &info, sizeof(INFO_7));
1084
1085 Encrypt(&user.ctx, buffer, buffer, len / 8);
1086 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1087 }
1088 //-----------------------------------------------------------------------------
1089 int AUTH_IA::RealSendMessage8(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1090 {
1091 printfd(__FILE__, "RealSendMessage 8 user=%s\n", user.login.c_str());
1092
1093 INFO_8 info;
1094 memset(&info, 0, sizeof(INFO_8));
1095
1096 info.len = 1056;
1097 strncpy((char*)info.type, "INFO_8", 16);
1098 info.infoType = msg.header.type;
1099 info.showTime = msg.header.showTime;
1100 info.sendTime = msg.header.creationTime;
1101
1102 strncpy((char*)info.text, msg.text.c_str(), IA_MAX_MSG_LEN_8 - 1);
1103 info.text[IA_MAX_MSG_LEN_8 - 1] = 0;
1104
1105 size_t len = info.len;
1106 #ifdef ARCH_BE
1107 SwapBytes(info.len);
1108 SwapBytes(info.sendTime);
1109 #endif
1110
1111 char buffer[1500];
1112 memcpy(buffer, &info, sizeof(INFO_8));
1113
1114 Encrypt(&user.ctx, buffer, buffer, len / 8);
1115 return Send(ip, user.port, buffer, len);
1116 }
1117 //-----------------------------------------------------------------------------
1118 int AUTH_IA::Process_CONN_SYN_6(CONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1119 {
1120 if (!(iaUser->phase.GetPhase() == 1 || iaUser->phase.GetPhase() == 3))
1121     return -1;
1122
1123 enabledDirs = 0xFFffFFff;
1124
1125 iaUser->phase.SetPhase2();
1126 printfd(__FILE__, "Phase changed from %d to 2. Reason: CONN_SYN_6\n", iaUser->phase.GetPhase());
1127 return 0;
1128 }
1129 //-----------------------------------------------------------------------------
1130 int AUTH_IA::Process_CONN_SYN_7(CONN_SYN_7 * connSyn, IA_USER * iaUser, uint32_t sip)
1131 {
1132 return Process_CONN_SYN_6(connSyn, iaUser, sip);
1133 }
1134 //-----------------------------------------------------------------------------
1135 int AUTH_IA::Process_CONN_SYN_8(CONN_SYN_8 * connSyn, IA_USER * iaUser, uint32_t sip)
1136 {
1137 #ifdef ARCH_BE
1138 SwapBytes(connSyn->dirs);
1139 #endif
1140 int ret = Process_CONN_SYN_6((CONN_SYN_6*)connSyn, iaUser, sip);
1141 enabledDirs = connSyn->dirs;
1142 return ret;
1143 }
1144 //-----------------------------------------------------------------------------
1145 int AUTH_IA::Process_CONN_ACK_6(CONN_ACK_6 * connAck, IA_USER * iaUser, uint32_t sip)
1146 {
1147 #ifdef ARCH_BE
1148 SwapBytes(connAck->len);
1149 SwapBytes(connAck->rnd);
1150 #endif
1151 printfd( __FILE__, "CONN_ACK_6 %s\n", connAck->type);
1152
1153 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1154     {
1155     iaUser->phase.UpdateTime();
1156
1157     iaUser->lastSendAlive = iaUser->phase.GetTime();
1158     if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1159         {
1160         iaUser->phase.SetPhase3();
1161         printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_6\n");
1162         return 0;
1163         }
1164     else
1165         {
1166         errorStr = iaUser->user->GetStrError();
1167         iaUser->phase.SetPhase1();
1168         ip2user.erase(sip);
1169         printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1170         return -1;
1171         }
1172     }
1173 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1174 return -1;
1175 }
1176 //-----------------------------------------------------------------------------
1177 int AUTH_IA::Process_CONN_ACK_7(CONN_ACK_7 * connAck, IA_USER * iaUser, uint32_t sip)
1178 {
1179 return Process_CONN_ACK_6(connAck, iaUser, sip);
1180 }
1181 //-----------------------------------------------------------------------------
1182 int AUTH_IA::Process_CONN_ACK_8(CONN_ACK_8 * connAck, IA_USER * iaUser, uint32_t sip)
1183 {
1184 #ifdef ARCH_BE
1185 SwapBytes(connAck->len);
1186 SwapBytes(connAck->rnd);
1187 #endif
1188 printfd( __FILE__, "CONN_ACK_8 %s\n", connAck->type);
1189
1190 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1191     {
1192     iaUser->phase.UpdateTime();
1193     iaUser->lastSendAlive = iaUser->phase.GetTime();
1194     if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1195         {
1196         iaUser->phase.SetPhase3();
1197         printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_8\n");
1198         return 0;
1199         }
1200     else
1201         {
1202         errorStr = iaUser->user->GetStrError();
1203         iaUser->phase.SetPhase1();
1204         ip2user.erase(sip);
1205         printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1206         return -1;
1207         }
1208     }
1209 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1210 return -1;
1211 }
1212 //-----------------------------------------------------------------------------
1213 int AUTH_IA::Process_ALIVE_ACK_6(ALIVE_ACK_6 * aliveAck, IA_USER * iaUser, uint32_t)
1214 {
1215 #ifdef ARCH_BE
1216 SwapBytes(aliveAck->len);
1217 SwapBytes(aliveAck->rnd);
1218 #endif
1219 printfd(__FILE__, "ALIVE_ACK_6\n");
1220 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1221     {
1222     iaUser->phase.UpdateTime();
1223     #ifdef IA_DEBUG
1224     iaUser->aliveSent = false;
1225     #endif
1226     }
1227 return 0;
1228 }
1229 //-----------------------------------------------------------------------------
1230 int AUTH_IA::Process_ALIVE_ACK_7(ALIVE_ACK_7 * aliveAck, IA_USER * iaUser, uint32_t sip)
1231 {
1232 return Process_ALIVE_ACK_6(aliveAck, iaUser, sip);
1233 }
1234 //-----------------------------------------------------------------------------
1235 int AUTH_IA::Process_ALIVE_ACK_8(ALIVE_ACK_8 * aliveAck, IA_USER * iaUser, uint32_t)
1236 {
1237 #ifdef ARCH_BE
1238 SwapBytes(aliveAck->len);
1239 SwapBytes(aliveAck->rnd);
1240 #endif
1241 printfd(__FILE__, "ALIVE_ACK_8\n");
1242 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1243     {
1244     iaUser->phase.UpdateTime();
1245     #ifdef IA_DEBUG
1246     iaUser->aliveSent = false;
1247     #endif
1248     }
1249 return 0;
1250 }
1251 //-----------------------------------------------------------------------------
1252 int AUTH_IA::Process_DISCONN_SYN_6(DISCONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1253 {
1254 printfd(__FILE__, "DISCONN_SYN_6\n");
1255 if (iaUser->phase.GetPhase() != 3)
1256     {
1257     printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1258     errorStr = "Incorrect request DISCONN_SYN";
1259     return -1;
1260     }
1261
1262 iaUser->phase.SetPhase4();
1263 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1264
1265 return 0;
1266 }
1267 //-----------------------------------------------------------------------------
1268 int AUTH_IA::Process_DISCONN_SYN_7(DISCONN_SYN_7 * disconnSyn, IA_USER * iaUser, uint32_t sip)
1269 {
1270 return Process_DISCONN_SYN_6(disconnSyn, iaUser, sip);
1271 }
1272 //-----------------------------------------------------------------------------
1273 int AUTH_IA::Process_DISCONN_SYN_8(DISCONN_SYN_8 *, IA_USER * iaUser, uint32_t)
1274 {
1275 if (iaUser->phase.GetPhase() != 3)
1276     {
1277     errorStr = "Incorrect request DISCONN_SYN";
1278     printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1279     return -1;
1280     }
1281
1282 iaUser->phase.SetPhase4();
1283 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1284
1285 return 0;
1286 }
1287 //-----------------------------------------------------------------------------
1288 int AUTH_IA::Process_DISCONN_ACK_6(DISCONN_ACK_6 * disconnAck,
1289                                    IA_USER * iaUser,
1290                                    uint32_t,
1291                                    map<uint32_t, IA_USER>::iterator)
1292 {
1293 #ifdef ARCH_BE
1294 SwapBytes(disconnAck->len);
1295 SwapBytes(disconnAck->rnd);
1296 #endif
1297 printfd(__FILE__, "DISCONN_ACK_6\n");
1298 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1299     {
1300     printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1301     return -1;
1302     }
1303
1304 return 0;
1305 }
1306 //-----------------------------------------------------------------------------
1307 int AUTH_IA::Process_DISCONN_ACK_7(DISCONN_ACK_7 * disconnAck, IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1308 {
1309 return Process_DISCONN_ACK_6(disconnAck, iaUser, sip, it);
1310 }
1311 //-----------------------------------------------------------------------------
1312 int AUTH_IA::Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnAck, IA_USER * iaUser, uint32_t, map<uint32_t, IA_USER>::iterator)
1313 {
1314 #ifdef ARCH_BE
1315 SwapBytes(disconnAck->len);
1316 SwapBytes(disconnAck->rnd);
1317 #endif
1318 printfd(__FILE__, "DISCONN_ACK_8\n");
1319 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1320     {
1321     printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1322     return -1;
1323     }
1324
1325 return 0;
1326 }
1327 //-----------------------------------------------------------------------------
1328 int AUTH_IA::Send_CONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1329 {
1330 //+++ Fill static data in connSynAck +++
1331 // TODO Move this code. It must be executed only once
1332 connSynAck6.len = Min8(sizeof(CONN_SYN_ACK_6));
1333 strcpy((char*)connSynAck6.type, "CONN_SYN_ACK");
1334 for (int j = 0; j < DIR_NUM; j++)
1335     {
1336     strncpy((char*)connSynAck6.dirName[j],
1337             stgSettings->GetDirName(j).c_str(),
1338             sizeof(string16));
1339
1340     connSynAck6.dirName[j][sizeof(string16) - 1] = 0;
1341     }
1342 //--- Fill static data in connSynAck ---
1343
1344 iaUser->rnd = random();
1345 connSynAck6.rnd = iaUser->rnd;
1346
1347 connSynAck6.userTimeOut = iaSettings.GetUserTimeout();
1348 connSynAck6.aliveDelay = iaSettings.GetUserDelay();
1349
1350 #ifdef ARCH_BE
1351 SwapBytes(connSynAck6.len);
1352 SwapBytes(connSynAck6.rnd);
1353 SwapBytes(connSynAck6.userTimeOut);
1354 SwapBytes(connSynAck6.aliveDelay);
1355 #endif
1356
1357 Encrypt(&iaUser->ctx, (char*)&connSynAck6, (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6))/8);
1358 return Send(sip, iaSettings.GetUserPort(), (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)));;
1359 }
1360 //-----------------------------------------------------------------------------
1361 int AUTH_IA::Send_CONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1362 {
1363 return Send_CONN_SYN_ACK_6(iaUser, sip);
1364 }
1365 //-----------------------------------------------------------------------------
1366 int AUTH_IA::Send_CONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1367 {
1368 strcpy((char*)connSynAck8.hdr.magic, IA_ID);
1369 connSynAck8.hdr.protoVer[0] = 0;
1370 connSynAck8.hdr.protoVer[1] = 8;
1371
1372 //+++ Fill static data in connSynAck +++
1373 // TODO Move this code. It must be executed only once
1374 connSynAck8.len = Min8(sizeof(CONN_SYN_ACK_8));
1375 strcpy((char*)connSynAck8.type, "CONN_SYN_ACK");
1376 for (int j = 0; j < DIR_NUM; j++)
1377     {
1378     strncpy((char*)connSynAck8.dirName[j],
1379             stgSettings->GetDirName(j).c_str(),
1380             sizeof(string16));
1381
1382     connSynAck8.dirName[j][sizeof(string16) - 1] = 0;
1383     }
1384 //--- Fill static data in connSynAck ---
1385
1386 iaUser->rnd = random();
1387 connSynAck8.rnd = iaUser->rnd;
1388
1389 connSynAck8.userTimeOut = iaSettings.GetUserTimeout();
1390 connSynAck8.aliveDelay = iaSettings.GetUserDelay();
1391
1392 #ifdef ARCH_BE
1393 SwapBytes(connSynAck8.len);
1394 SwapBytes(connSynAck8.rnd);
1395 SwapBytes(connSynAck8.userTimeOut);
1396 SwapBytes(connSynAck8.aliveDelay);
1397 #endif
1398
1399 Encrypt(&iaUser->ctx, (char*)&connSynAck8, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8))/8);
1400 return Send(sip, iaUser->port, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)));
1401 }
1402 //-----------------------------------------------------------------------------
1403 int AUTH_IA::Send_ALIVE_SYN_6(IA_USER * iaUser, uint32_t sip)
1404 {
1405 aliveSyn6.len = Min8(sizeof(ALIVE_SYN_6));
1406 aliveSyn6.rnd = iaUser->rnd = random();
1407
1408 strcpy((char*)aliveSyn6.type, "ALIVE_SYN");
1409
1410 for (int i = 0; i < DIR_NUM; i++)
1411     {
1412     aliveSyn6.md[i] = iaUser->user->GetProperty().down.Get()[i];
1413     aliveSyn6.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1414
1415     aliveSyn6.sd[i] = iaUser->user->GetSessionDownload()[i];
1416     aliveSyn6.su[i] = iaUser->user->GetSessionUpload()[i];
1417     }
1418
1419 //TODO
1420 int dn = iaSettings.GetFreeMbShowType();
1421 const TARIFF * tf = iaUser->user->GetTariff();
1422
1423 if (dn < DIR_NUM)
1424     {
1425     double p = tf->GetPriceWithTraffType(aliveSyn6.mu[dn],
1426                                          aliveSyn6.md[dn],
1427                                          dn,
1428                                          stgTime);
1429     p *= (1024 * 1024);
1430     if (p == 0)
1431         {
1432         snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "---");
1433         }
1434     else
1435         {
1436         double fmb = iaUser->user->GetProperty().freeMb;
1437         fmb = fmb < 0 ? 0 : fmb;
1438         snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1439         }
1440     }
1441 else
1442     {
1443     if (freeMbNone == iaSettings.GetFreeMbShowType())
1444         {
1445         aliveSyn6.freeMb[0] = 0;
1446         }
1447     else
1448         {
1449         double fmb = iaUser->user->GetProperty().freeMb;
1450         fmb = fmb < 0 ? 0 : fmb;
1451         snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1452         }
1453     }
1454
1455 #ifdef IA_DEBUG
1456 if (iaUser->aliveSent)
1457     {
1458     printfd(__FILE__, "========= ALIVE_ACK_6(7) TIMEOUT !!! %s =========\n", iaUser->login.c_str());
1459     }
1460 iaUser->aliveSent = true;
1461 #endif
1462
1463 aliveSyn6.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1464 if (!stgSettings->GetShowFeeInCash())
1465     aliveSyn6.cash -= (int64_t)(tf->GetFee() * 1000.0);
1466
1467 #ifdef ARCH_BE
1468 SwapBytes(aliveSyn6.len);
1469 SwapBytes(aliveSyn6.rnd);
1470 SwapBytes(aliveSyn6.cash);
1471 for (int i = 0; i < DIR_NUM; ++i)
1472     {
1473     SwapBytes(aliveSyn6.mu[i]);
1474     SwapBytes(aliveSyn6.md[i]);
1475     SwapBytes(aliveSyn6.su[i]);
1476     SwapBytes(aliveSyn6.sd[i]);
1477     }
1478 #endif
1479
1480 Encrypt(&(iaUser->ctx), (char*)&aliveSyn6, (char*)&aliveSyn6, Min8(sizeof(aliveSyn6))/8);
1481 return Send(sip, iaSettings.GetUserPort(), (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)));
1482 }
1483 //-----------------------------------------------------------------------------
1484 int AUTH_IA::Send_ALIVE_SYN_7(IA_USER * iaUser, uint32_t sip)
1485 {
1486 return Send_ALIVE_SYN_6(iaUser, sip);
1487 }
1488 //-----------------------------------------------------------------------------
1489 int AUTH_IA::Send_ALIVE_SYN_8(IA_USER * iaUser, uint32_t sip)
1490 {
1491 strcpy((char*)aliveSyn8.hdr.magic, IA_ID);
1492 aliveSyn8.hdr.protoVer[0] = 0;
1493 aliveSyn8.hdr.protoVer[1] = 8;
1494
1495 aliveSyn8.len = Min8(sizeof(ALIVE_SYN_8));
1496 aliveSyn8.rnd = iaUser->rnd = random();
1497
1498 strcpy((char*)aliveSyn8.type, "ALIVE_SYN");
1499
1500 for (int i = 0; i < DIR_NUM; i++)
1501     {
1502     aliveSyn8.md[i] = iaUser->user->GetProperty().down.Get()[i];
1503     aliveSyn8.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1504
1505     aliveSyn8.sd[i] = iaUser->user->GetSessionDownload()[i];
1506     aliveSyn8.su[i] = iaUser->user->GetSessionUpload()[i];
1507     }
1508
1509 //TODO
1510 int dn = iaSettings.GetFreeMbShowType();
1511
1512 if (dn < DIR_NUM)
1513     {
1514     const TARIFF * tf = iaUser->user->GetTariff();
1515     double p = tf->GetPriceWithTraffType(aliveSyn8.mu[dn],
1516                                          aliveSyn8.md[dn],
1517                                          dn,
1518                                          stgTime);
1519     p *= (1024 * 1024);
1520     if (p == 0)
1521         {
1522         snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "---");
1523         }
1524     else
1525         {
1526         double fmb = iaUser->user->GetProperty().freeMb;
1527         fmb = fmb < 0 ? 0 : fmb;
1528         snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1529         }
1530     }
1531 else
1532     {
1533     if (freeMbNone == iaSettings.GetFreeMbShowType())
1534         {
1535         aliveSyn8.freeMb[0] = 0;
1536         }
1537     else
1538         {
1539         double fmb = iaUser->user->GetProperty().freeMb;
1540         fmb = fmb < 0 ? 0 : fmb;
1541         snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1542         }
1543     }
1544
1545 #ifdef IA_DEBUG
1546 if (iaUser->aliveSent)
1547     {
1548     printfd(__FILE__, "========= ALIVE_ACK_8 TIMEOUT !!! =========\n");
1549     }
1550 iaUser->aliveSent = true;
1551 #endif
1552
1553 const TARIFF * tf = iaUser->user->GetTariff();
1554
1555 aliveSyn8.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1556 if (!stgSettings->GetShowFeeInCash())
1557     aliveSyn8.cash -= (int64_t)(tf->GetFee() * 1000.0);
1558
1559 #ifdef ARCH_BE
1560 SwapBytes(aliveSyn8.len);
1561 SwapBytes(aliveSyn8.rnd);
1562 SwapBytes(aliveSyn8.cash);
1563 SwapBytes(aliveSyn8.status);
1564 for (int i = 0; i < DIR_NUM; ++i)
1565     {
1566     SwapBytes(aliveSyn8.mu[i]);
1567     SwapBytes(aliveSyn8.md[i]);
1568     SwapBytes(aliveSyn8.su[i]);
1569     SwapBytes(aliveSyn8.sd[i]);
1570     }
1571 #endif
1572
1573 Encrypt(&(iaUser->ctx), (char*)&aliveSyn8, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8))/8);
1574 return Send(sip, iaUser->port, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)));
1575 }
1576 //-----------------------------------------------------------------------------
1577 int AUTH_IA::Send_DISCONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1578 {
1579 disconnSynAck6.len = Min8(sizeof(DISCONN_SYN_ACK_6));
1580 strcpy((char*)disconnSynAck6.type, "DISCONN_SYN_ACK");
1581 disconnSynAck6.rnd = iaUser->rnd = random();
1582
1583 #ifdef ARCH_BE
1584 SwapBytes(disconnSynAck6.len);
1585 SwapBytes(disconnSynAck6.rnd);
1586 #endif
1587
1588 Encrypt(&iaUser->ctx, (char*)&disconnSynAck6, (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6))/8);
1589 return Send(sip, iaSettings.GetUserPort(), (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)));
1590 }
1591 //-----------------------------------------------------------------------------
1592 int AUTH_IA::Send_DISCONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1593 {
1594 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
1595 }
1596 //-----------------------------------------------------------------------------
1597 int AUTH_IA::Send_DISCONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1598 {
1599 strcpy((char*)disconnSynAck8.hdr.magic, IA_ID);
1600 disconnSynAck8.hdr.protoVer[0] = 0;
1601 disconnSynAck8.hdr.protoVer[1] = 8;
1602
1603 disconnSynAck8.len = Min8(sizeof(DISCONN_SYN_ACK_8));
1604 strcpy((char*)disconnSynAck8.type, "DISCONN_SYN_ACK");
1605 disconnSynAck8.rnd = iaUser->rnd = random();
1606
1607 #ifdef ARCH_BE
1608 SwapBytes(disconnSynAck8.len);
1609 SwapBytes(disconnSynAck8.rnd);
1610 #endif
1611
1612 Encrypt(&iaUser->ctx, (char*)&disconnSynAck8, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8))/8);
1613 return Send(sip, iaUser->port, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)));
1614 }
1615 //-----------------------------------------------------------------------------
1616 int AUTH_IA::Send_FIN_6(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1617 {
1618 fin6.len = Min8(sizeof(FIN_6));
1619 strcpy((char*)fin6.type, "FIN");
1620 strcpy((char*)fin6.ok, "OK");
1621
1622 #ifdef ARCH_BE
1623 SwapBytes(fin6.len);
1624 #endif
1625
1626 Encrypt(&iaUser->ctx, (char*)&fin6, (char*)&fin6, Min8(sizeof(fin6))/8);
1627
1628 users->Unauthorize(iaUser->login, this);
1629
1630 int res = Send(sip, iaSettings.GetUserPort(), (char*)&fin6, Min8(sizeof(fin6)));
1631
1632 ip2user.erase(it);
1633
1634 return res;
1635 }
1636 //-----------------------------------------------------------------------------
1637 int AUTH_IA::Send_FIN_7(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1638 {
1639 return Send_FIN_6(iaUser, sip, it);
1640 }
1641 //-----------------------------------------------------------------------------
1642 int AUTH_IA::Send_FIN_8(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
1643 {
1644 strcpy((char*)fin8.hdr.magic, IA_ID);
1645 fin8.hdr.protoVer[0] = 0;
1646 fin8.hdr.protoVer[1] = 8;
1647
1648 fin8.len = Min8(sizeof(FIN_8));
1649 strcpy((char*)fin8.type, "FIN");
1650 strcpy((char*)fin8.ok, "OK");
1651
1652 #ifdef ARCH_BE
1653 SwapBytes(fin8.len);
1654 #endif
1655
1656 Encrypt(&iaUser->ctx, (char*)&fin8, (char*)&fin8, Min8(sizeof(fin8))/8);
1657
1658 users->Unauthorize(iaUser->login, this);
1659
1660 int res = Send(sip, iaUser->port, (char*)&fin8, Min8(sizeof(fin8)));
1661
1662 ip2user.erase(it);
1663
1664 return res;
1665 }
1666 //-----------------------------------------------------------------------------
1667 inline
1668 void InitEncrypt(BLOWFISH_CTX * ctx, const string & password)
1669 {
1670 unsigned char keyL[PASSWD_LEN];
1671 memset(keyL, 0, PASSWD_LEN);
1672 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
1673 Blowfish_Init(ctx, keyL, PASSWD_LEN);
1674 }
1675 //-----------------------------------------------------------------------------
1676 inline
1677 void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
1678 {
1679 for (int i = 0; i < len8; i++)
1680     DecodeString(dst + i * 8, src + i * 8, ctx);
1681 }
1682 //-----------------------------------------------------------------------------
1683 inline
1684 void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
1685 {
1686 for (int i = 0; i < len8; i++)
1687     EncodeString(dst + i * 8, src + i * 8, ctx);
1688 }