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