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