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