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.
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.
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
18 * Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
23 $Date: 2010/03/25 15:18:48 $
31 #include <sys/types.h>
32 #include <sys/socket.h>
33 #include <unistd.h> // close
37 #include <cstdio> // snprintf
42 #include "stg/common.h"
43 #include "stg/locker.h"
44 #include "stg/tariff.h"
45 #include "stg/user_property.h"
46 #include "stg/settings.h"
47 #include "stg/plugin_creator.h"
48 #include "inetaccess.h"
50 extern volatile time_t stgTime;
52 //-----------------------------------------------------------------------------
53 //-----------------------------------------------------------------------------
54 //-----------------------------------------------------------------------------
57 PLUGIN_CREATOR<AUTH_IA> iac;
60 extern "C" PLUGIN * GetPlugin();
61 //-----------------------------------------------------------------------------
62 //-----------------------------------------------------------------------------
63 //-----------------------------------------------------------------------------
66 return iac.GetPlugin();
68 //-----------------------------------------------------------------------------
69 //-----------------------------------------------------------------------------
70 //-----------------------------------------------------------------------------
71 AUTH_IA_SETTINGS::AUTH_IA_SETTINGS()
76 freeMbShowType(freeMbCash),
77 logProtocolErrors(false)
80 //-----------------------------------------------------------------------------
81 int AUTH_IA_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
85 std::vector<PARAM_VALUE>::const_iterator pvi;
86 ///////////////////////////
88 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
89 if (pvi == s.moduleParams.end() || pvi->value.empty())
91 errorStr = "Parameter \'Port\' not found.";
92 printfd(__FILE__, "Parameter 'Port' not found\n");
95 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
97 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
98 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
101 port = static_cast<uint16_t>(p);
102 ///////////////////////////
103 pv.param = "UserDelay";
104 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
105 if (pvi == s.moduleParams.end() || pvi->value.empty())
107 errorStr = "Parameter \'UserDelay\' not found.";
108 printfd(__FILE__, "Parameter 'UserDelay' not found\n");
112 if (ParseIntInRange(pvi->value[0], 5, 600, &userDelay))
114 errorStr = "Cannot parse parameter \'UserDelay\': " + errorStr;
115 printfd(__FILE__, "Cannot parse parameter 'UserDelay'\n");
118 ///////////////////////////
119 pv.param = "UserTimeout";
120 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
121 if (pvi == s.moduleParams.end() || pvi->value.empty())
123 errorStr = "Parameter \'UserTimeout\' not found.";
124 printfd(__FILE__, "Parameter 'UserTimeout' not found\n");
128 if (ParseIntInRange(pvi->value[0], 15, 1200, &userTimeout))
130 errorStr = "Cannot parse parameter \'UserTimeout\': " + errorStr;
131 printfd(__FILE__, "Cannot parse parameter 'UserTimeout'\n");
134 ///////////////////////////
135 pv.param = "LogProtocolErrors";
136 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
137 if (pvi == s.moduleParams.end() || pvi->value.empty())
138 logProtocolErrors = false;
139 else if (ParseYesNo(pvi->value[0], &logProtocolErrors))
141 errorStr = "Cannot parse parameter \'LogProtocolErrors\': " + errorStr;
142 printfd(__FILE__, "Cannot parse parameter 'LogProtocolErrors'\n");
145 /////////////////////////////////////////////////////////////
146 std::string freeMbType;
149 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
150 if (pvi == s.moduleParams.end() || pvi->value.empty())
152 errorStr = "Parameter \'FreeMb\' not found.";
153 printfd(__FILE__, "Parameter 'FreeMb' not found\n");
156 freeMbType = pvi->value[0];
158 if (strcasecmp(freeMbType.c_str(), "cash") == 0)
160 freeMbShowType = freeMbCash;
162 else if (strcasecmp(freeMbType.c_str(), "none") == 0)
164 freeMbShowType = freeMbNone;
166 else if (!str2x(freeMbType.c_str(), n))
168 if (n < 0 || n >= DIR_NUM)
170 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
171 printfd(__FILE__, "%s\n", errorStr.c_str());
174 freeMbShowType = (FREEMB)(freeMb0 + n);
178 errorStr = "Incorrect parameter \'" + freeMbType + "\'.";
179 printfd(__FILE__, "%s\n", errorStr.c_str());
182 /////////////////////////////////////////////////////////////
185 //-----------------------------------------------------------------------------
186 //-----------------------------------------------------------------------------
187 //-----------------------------------------------------------------------------
188 #ifdef IA_PHASE_DEBUG
193 gettimeofday(&phaseTime, NULL);
199 gettimeofday(&phaseTime, NULL);
202 //-----------------------------------------------------------------------------
203 IA_PHASE::~IA_PHASE()
205 #ifdef IA_PHASE_DEBUG
206 flog = fopen(log.c_str(), "at");
209 fprintf(flog, "IA %s D\n", login.c_str());
214 //-----------------------------------------------------------------------------
215 #ifdef IA_PHASE_DEBUG
216 void IA_PHASE::SetLogFileName(const string & logFileName)
218 log = logFileName + ".ia.log";
220 //-----------------------------------------------------------------------------
221 void IA_PHASE::SetUserLogin(const string & login)
223 IA_PHASE::login = login;
225 //-----------------------------------------------------------------------------
226 void IA_PHASE::WritePhaseChange(int newPhase)
229 gettimeofday(&newPhaseTime, NULL);
230 flog = fopen(log.c_str(), "at");
233 string action = newPhase == phase ? "U" : "C";
234 double delta = newPhaseTime.GetSec() - phaseTime.GetSec();
235 delta += (newPhaseTime.GetUSec() - phaseTime.GetUSec()) * 1.0e-6;
236 fprintf(flog, "IA %s %s oldPhase = %d, newPhase = %d. dt = %.6f\n",
246 //-----------------------------------------------------------------------------
247 void IA_PHASE::SetPhase1()
249 #ifdef IA_PHASE_DEBUG
253 gettimeofday(&phaseTime, NULL);
255 //-----------------------------------------------------------------------------
256 void IA_PHASE::SetPhase2()
258 #ifdef IA_PHASE_DEBUG
262 gettimeofday(&phaseTime, NULL);
264 //-----------------------------------------------------------------------------
265 void IA_PHASE::SetPhase3()
267 #ifdef IA_PHASE_DEBUG
271 gettimeofday(&phaseTime, NULL);
273 //-----------------------------------------------------------------------------
274 void IA_PHASE::SetPhase4()
276 #ifdef IA_PHASE_DEBUG
280 gettimeofday(&phaseTime, NULL);
282 //-----------------------------------------------------------------------------
283 int IA_PHASE::GetPhase() const
287 //-----------------------------------------------------------------------------
288 void IA_PHASE::UpdateTime()
290 #ifdef IA_PHASE_DEBUG
291 WritePhaseChange(phase);
293 gettimeofday(&phaseTime, NULL);
295 //-----------------------------------------------------------------------------
296 const UTIME & IA_PHASE::GetTime() const
300 //-----------------------------------------------------------------------------
301 //-----------------------------------------------------------------------------
302 //-----------------------------------------------------------------------------
310 isRunningRunTimeouter(false),
327 enabledDirs(0xFFffFFff),
328 onDelUserNotifier(*this),
329 logger(GetPluginLogger(GetStgLogger(), "auth_ia"))
331 InitContext("pr7Hhen", 7, &ctxS);
333 pthread_mutexattr_t attr;
334 pthread_mutexattr_init(&attr);
335 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
336 pthread_mutex_init(&mutex, &attr);
338 memset(&connSynAck6, 0, sizeof(CONN_SYN_ACK_6));
339 memset(&connSynAck8, 0, sizeof(CONN_SYN_ACK_8));
340 memset(&disconnSynAck6, 0, sizeof(DISCONN_SYN_ACK_6));
341 memset(&disconnSynAck8, 0, sizeof(DISCONN_SYN_ACK_8));
342 memset(&aliveSyn6, 0, sizeof(ALIVE_SYN_6));
343 memset(&aliveSyn8, 0, sizeof(ALIVE_SYN_8));
344 memset(&fin6, 0, sizeof(FIN_6));
345 memset(&fin8, 0, sizeof(FIN_8));
347 printfd(__FILE__, "sizeof(CONN_SYN_6) = %d %d\n", sizeof(CONN_SYN_6), Min8(sizeof(CONN_SYN_6)));
348 printfd(__FILE__, "sizeof(CONN_SYN_8) = %d %d\n", sizeof(CONN_SYN_8), Min8(sizeof(CONN_SYN_8)));
349 printfd(__FILE__, "sizeof(CONN_SYN_ACK_6) = %d %d\n", sizeof(CONN_SYN_ACK_6), Min8(sizeof(CONN_SYN_ACK_6)));
350 printfd(__FILE__, "sizeof(CONN_SYN_ACK_8) = %d %d\n", sizeof(CONN_SYN_ACK_8), Min8(sizeof(CONN_SYN_ACK_8)));
351 printfd(__FILE__, "sizeof(CONN_ACK_6) = %d %d\n", sizeof(CONN_ACK_6), Min8(sizeof(CONN_ACK_6)));
352 printfd(__FILE__, "sizeof(ALIVE_SYN_6) = %d %d\n", sizeof(ALIVE_SYN_6), Min8(sizeof(ALIVE_SYN_6)));
353 printfd(__FILE__, "sizeof(ALIVE_SYN_8) = %d %d\n", sizeof(ALIVE_SYN_8), Min8(sizeof(ALIVE_SYN_8)));
354 printfd(__FILE__, "sizeof(ALIVE_ACK_6) = %d %d\n", sizeof(ALIVE_ACK_6), Min8(sizeof(ALIVE_ACK_6)));
355 printfd(__FILE__, "sizeof(DISCONN_SYN_6) = %d %d\n", sizeof(DISCONN_SYN_6), Min8(sizeof(DISCONN_SYN_6)));
356 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_6) = %d %d\n", sizeof(DISCONN_SYN_ACK_6), Min8(sizeof(DISCONN_SYN_ACK_6)));
357 printfd(__FILE__, "sizeof(DISCONN_SYN_ACK_8) = %d %d\n", sizeof(DISCONN_SYN_ACK_8), Min8(sizeof(DISCONN_SYN_ACK_8)));
358 printfd(__FILE__, "sizeof(DISCONN_ACK_6) = %d %d\n", sizeof(DISCONN_ACK_6), Min8(sizeof(DISCONN_ACK_6)));
359 printfd(__FILE__, "sizeof(FIN_6) = %d %d\n", sizeof(FIN_6), Min8(sizeof(FIN_6)));
360 printfd(__FILE__, "sizeof(FIN_8) = %d %d\n", sizeof(FIN_8), Min8(sizeof(FIN_8)));
361 printfd(__FILE__, "sizeof(ERR) = %d %d\n", sizeof(ERR), Min8(sizeof(ERR)));
362 printfd(__FILE__, "sizeof(INFO_6) = %d %d\n", sizeof(INFO_6), Min8(sizeof(INFO_6)));
363 printfd(__FILE__, "sizeof(INFO_7) = %d %d\n", sizeof(INFO_7), Min8(sizeof(INFO_7)));
364 printfd(__FILE__, "sizeof(INFO_8) = %d %d\n", sizeof(INFO_8), Min8(sizeof(INFO_8)));
366 packetTypes["CONN_SYN"] = CONN_SYN_N;
367 packetTypes["CONN_SYN_ACK"] = CONN_SYN_ACK_N;
368 packetTypes["CONN_ACK"] = CONN_ACK_N;
369 packetTypes["ALIVE_SYN"] = ALIVE_SYN_N;
370 packetTypes["ALIVE_ACK"] = ALIVE_ACK_N;
371 packetTypes["DISCONN_SYN"] = DISCONN_SYN_N;
372 packetTypes["DISCONN_SYN_ACK"] = DISCONN_SYN_ACK_N;
373 packetTypes["DISCONN_ACK"] = DISCONN_ACK_N;
374 packetTypes["FIN"] = FIN_N;
375 packetTypes["ERR"] = ERROR_N;
377 //-----------------------------------------------------------------------------
380 pthread_mutex_destroy(&mutex);
382 //-----------------------------------------------------------------------------
385 users->AddNotifierUserDel(&onDelUserNotifier);
395 if (pthread_create(&recvThread, NULL, Run, this))
397 errorStr = "Cannot create thread.";
398 printfd(__FILE__, "Cannot create recv thread\n");
399 logger("Cannot create recv thread.");
404 if (!isRunningRunTimeouter)
406 if (pthread_create(&timeouterThread, NULL, RunTimeouter, this))
408 errorStr = "Cannot create thread.";
409 printfd(__FILE__, "Cannot create timeouter thread\n");
410 logger("Cannot create timeouter thread.");
417 //-----------------------------------------------------------------------------
428 UnauthorizeUser(this)
433 //5 seconds to thread stops itself
434 for (int i = 0; i < 25 && isRunningRun; i++)
436 struct timespec ts = {0, 200000000};
437 nanosleep(&ts, NULL);
443 if (isRunningRunTimeouter)
445 //5 seconds to thread stops itself
446 for (int i = 0; i < 25 && isRunningRunTimeouter; i++)
448 struct timespec ts = {0, 200000000};
449 nanosleep(&ts, NULL);
453 users->DelNotifierUserDel(&onDelUserNotifier);
455 if (isRunningRun || isRunningRunTimeouter)
458 printfd(__FILE__, "AUTH_IA::Stoped successfully.\n");
461 //-----------------------------------------------------------------------------
462 void * AUTH_IA::Run(void * d)
465 sigfillset(&signalSet);
466 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
468 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
470 ia->isRunningRun = true;
474 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
478 ia->RecvData(buffer, sizeof(buffer));
479 if ((touchTime + MONITOR_TIME_DELAY_SEC <= stgTime) && ia->stgSettings->GetMonitoring())
482 std::string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_r";
483 TouchFile(monFile.c_str());
487 ia->isRunningRun = false;
490 //-----------------------------------------------------------------------------
491 void * AUTH_IA::RunTimeouter(void * d)
494 sigfillset(&signalSet);
495 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
497 AUTH_IA * ia = static_cast<AUTH_IA *>(d);
499 ia->isRunningRunTimeouter = true;
502 std::string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_t";
505 struct timespec ts = {0, 20000000};
506 nanosleep(&ts, NULL);
508 // TODO change counter to timer and MONITOR_TIME_DELAY_SEC
509 if (++a % (50 * 60) == 0 && ia->stgSettings->GetMonitoring())
511 TouchFile(monFile.c_str());
515 ia->isRunningRunTimeouter = false;
518 //-----------------------------------------------------------------------------
519 int AUTH_IA::ParseSettings()
521 int ret = iaSettings.ParseSettings(settings);
523 errorStr = iaSettings.GetStrError();
526 //-----------------------------------------------------------------------------
527 int AUTH_IA::PrepareNet()
529 struct sockaddr_in listenAddr;
531 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
533 if (listenSocket < 0)
535 errorStr = "Cannot create socket.";
536 logger("Cannot create a socket: %s", strerror(errno));
540 listenAddr.sin_family = AF_INET;
541 listenAddr.sin_port = htons(static_cast<uint16_t>(iaSettings.GetUserPort()));
542 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
544 if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
546 errorStr = "AUTH_IA: Bind failed.";
547 logger("Cannot bind the socket: %s", strerror(errno));
553 //-----------------------------------------------------------------------------
554 int AUTH_IA::FinalizeNet()
559 //-----------------------------------------------------------------------------
560 int AUTH_IA::RecvData(char * buffer, int bufferSize)
562 if (!WaitPackets(listenSocket)) // Timeout
567 struct sockaddr_in outerAddr;
568 socklen_t outerAddrLen(sizeof(outerAddr));
569 ssize_t dataLen = recvfrom(listenSocket, buffer, bufferSize, 0, (struct sockaddr *)&outerAddr, &outerAddrLen);
576 if (dataLen <= 0) // Error
580 printfd(__FILE__, "recvfrom res=%d, error: '%s'\n", dataLen, strerror(errno));
581 logger("recvfrom error: %s", strerror(errno));
590 uint32_t sip = outerAddr.sin_addr.s_addr;
591 uint16_t sport = htons(outerAddr.sin_port);
594 if (CheckHeader(buffer, sip, &protoVer))
597 char login[PASSWD_LEN]; //TODO why PASSWD_LEN ?
598 memset(login, 0, PASSWD_LEN);
600 DecryptString(login, buffer + 8, PASSWD_LEN, &ctxS);
603 if (users->FindByName(login, &user))
605 logger("User's connect failed: user '%s' not found. IP %s",
607 inet_ntostring(sip).c_str());
608 printfd(__FILE__, "User '%s' NOT found!\n", login);
609 SendError(sip, sport, protoVer, IconvString("Неправильный логин.", "utf8", "koi8-ru"));
613 printfd(__FILE__, "User '%s' FOUND!\n", user->GetLogin().c_str());
615 if (user->GetProperty().disabled.Get())
617 logger("Cannont authorize '%s', user is disabled.", login);
618 SendError(sip, sport, protoVer, IconvString("Учетная запись заблокирована.", "utf8", "koi8-ru"));
622 if (user->GetProperty().passive.Get())
624 logger("Cannont authorize '%s', user is passive.", login);
625 SendError(sip, sport, protoVer, IconvString("Учетная запись заморожена.", "utf8", "koi8-ru"));
629 if (!user->GetProperty().ips.Get().IsIPInIPS(sip))
631 printfd(__FILE__, "User %s. IP address is incorrect. IP %s\n",
632 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
633 logger("User %s. IP address is incorrect. IP %s",
634 user->GetLogin().c_str(), inet_ntostring(sip).c_str());
635 SendError(sip, sport, protoVer, IconvString("Пользователь не опознан. Проверьте IP-адрес.", "utf8", "koi8-ru"));
639 return PacketProcessor(buffer, dataLen, sip, sport, protoVer, user);
641 //-----------------------------------------------------------------------------
642 int AUTH_IA::CheckHeader(const char * buffer, uint32_t sip, int * protoVer)
644 if (strncmp(IA_ID, buffer, strlen(IA_ID)) != 0)
646 printfd(__FILE__, "update needed - IA_ID\n");
647 if (iaSettings.LogProtocolErrors())
648 logger("IP: %s. Header: invalid packed signature.", inet_ntostring(sip).c_str());
652 if (buffer[6] != 0) //proto[0] shoud be 0
654 printfd(__FILE__, "update needed - PROTO major: %d\n", buffer[6]);
655 if (iaSettings.LogProtocolErrors())
656 logger("IP: %s. Header: invalid protocol major version: %d.", inet_ntostring(sip).c_str(), buffer[6]);
663 printfd(__FILE__, "update needed - PROTO minor: %d\n", buffer[7]);
664 if (iaSettings.LogProtocolErrors())
665 logger("IP: %s. Header: invalid protocol minor version: %d.", inet_ntostring(sip).c_str(), buffer[7]);
670 *protoVer = buffer[7];
674 //-----------------------------------------------------------------------------
675 int AUTH_IA::Timeouter()
677 STG_LOCKER lock(&mutex);
679 std::map<uint32_t, IA_USER>::iterator it;
680 it = ip2user.begin();
682 while (it != ip2user.end())
684 uint32_t sip = it->first;
686 static UTIME currTime;
687 gettimeofday(&currTime, NULL);
689 if ((it->second.phase.GetPhase() == 2)
690 && (currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay())
692 if (iaSettings.LogProtocolErrors())
693 logger("User '%s'. Protocol version: %d. Phase 2: connect request timeout (%f > %d).", it->second.login.c_str(), it->second.protoVer, (currTime - it->second.phase.GetTime()).AsDouble(), iaSettings.GetUserDelay());
694 it->second.phase.SetPhase1();
695 printfd(__FILE__, "Phase changed from 2 to 1. Reason: timeout\n");
700 if (it->second.phase.GetPhase() == 3)
702 if (!it->second.messagesToSend.empty())
704 if (it->second.protoVer == 6)
705 RealSendMessage6(*it->second.messagesToSend.begin(), sip, it->second);
707 if (it->second.protoVer == 7)
708 RealSendMessage7(*it->second.messagesToSend.begin(), sip, it->second);
710 if (it->second.protoVer == 8)
711 RealSendMessage8(*it->second.messagesToSend.begin(), sip, it->second);
713 it->second.messagesToSend.erase(it->second.messagesToSend.begin());
716 if((currTime - it->second.lastSendAlive) > iaSettings.GetUserDelay())
718 switch (it->second.protoVer)
721 Send_ALIVE_SYN_6(&(it->second), sip);
724 Send_ALIVE_SYN_7(&(it->second), sip);
727 Send_ALIVE_SYN_8(&(it->second), sip);
731 gettimeofday(&it->second.lastSendAlive, NULL);
734 if ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserTimeout())
736 if (iaSettings.LogProtocolErrors())
737 logger("User '%s'. Protocol version: %d. Phase 3: alive timeout (%f > %d).", it->second.login.c_str(), it->second.protoVer, (currTime - it->second.phase.GetTime()).AsDouble(), iaSettings.GetUserTimeout());
738 users->Unauthorize(it->second.user->GetLogin(), this);
744 if ((it->second.phase.GetPhase() == 4)
745 && ((currTime - it->second.phase.GetTime()) > iaSettings.GetUserDelay()))
747 if (iaSettings.LogProtocolErrors())
748 logger("User '%s'. Protocol version: %d. Phase 4: disconnect request timeout (%f > %d).", it->second.login.c_str(), it->second.protoVer, (currTime - it->second.phase.GetTime()).AsDouble(), iaSettings.GetUserDelay());
749 it->second.phase.SetPhase3();
750 printfd(__FILE__, "Phase changed from 4 to 3. Reason: timeout\n");
758 //-----------------------------------------------------------------------------
759 int AUTH_IA::PacketProcessor(void * buff, size_t dataLen, uint32_t sip, uint16_t sport, int protoVer, USER_PTR user)
761 std::string login(user->GetLogin());
762 const size_t offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer;
764 STG_LOCKER lock(&mutex);
765 std::map<uint32_t, IA_USER>::iterator it(ip2user.find(sip));
767 if (it == ip2user.end())
770 if (!users->FindByIPIdx(sip, &userPtr))
772 if (userPtr->GetID() != user->GetID())
774 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
775 userPtr->GetLogin().c_str(),
776 inet_ntostring(sip).c_str(),
778 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
779 userPtr->GetLogin().c_str(),
780 inet_ntostring(sip).c_str(),
782 SendError(sip, sport, protoVer, IconvString("IP-адрес уже сипользуется.", "utf8", "koi8-ru"));
787 printfd(__FILE__, "Add new user '%s' from ip %s\n",
788 login.c_str(), inet_ntostring(sip).c_str());
789 std::pair<std::map<uint32_t, IA_USER>::iterator, bool> res;
790 res = ip2user.insert(std::make_pair(sip, IA_USER(login, user, sport, protoVer)));
792 #ifdef IA_PHASE_DEBUG
793 it->second.phase.SetLogFileName(stgSettings->GetLogFileName());
794 it->second.phase.SetUserLogin(login);
797 else if (user->GetID() != it->second.user->GetID())
799 printfd(__FILE__, "IP address already in use by user '%s'. IP %s, login: '%s'\n",
800 it->second.user->GetLogin().c_str(),
801 inet_ntostring(sip).c_str(),
802 user->GetLogin().c_str());
803 logger("IP address is already in use by user '%s'. IP %s, login: '%s'",
804 it->second.user->GetLogin().c_str(),
805 inet_ntostring(sip).c_str(),
806 user->GetLogin().c_str());
807 SendError(sip, sport, protoVer, IconvString("IP-адрес уже используется.", "utf8", "koi8-ru"));
811 IA_USER * iaUser = &(it->second);
813 if (iaUser->password != user->GetProperty().password.Get())
815 const std::string & password = user->GetProperty().password.Get();
816 InitContext(password.c_str(), password.length(), &iaUser->ctx);
817 iaUser->password = user->GetProperty().password.Get();
820 DecryptString(static_cast<char *>(buff) + offset, static_cast<char *>(buff) + offset, (dataLen - offset), &iaUser->ctx);
822 char packetName[IA_MAX_TYPE_LEN];
823 strncpy(packetName, static_cast<char *>(buff) + offset + 4, IA_MAX_TYPE_LEN);
824 packetName[IA_MAX_TYPE_LEN - 1] = 0;
826 std::map<std::string, int>::iterator pi(packetTypes.find(packetName));
827 if (pi == packetTypes.end())
829 SendError(sip, sport, protoVer, IconvString("Неправильный логин или пароль.", "utf8", "koi8-ru"));
830 printfd(__FILE__, "Login or password is wrong!\n");
831 logger("User's connect failed. User: '%s', ip %s. Wrong login or password",
833 inet_ntostring(sip).c_str());
838 if (user->IsAuthorizedBy(this) && user->GetCurrIP() != sip)
840 printfd(__FILE__, "Login %s already in use from ip %s. IP %s\n",
841 login.c_str(), inet_ntostring(user->GetCurrIP()).c_str(),
842 inet_ntostring(sip).c_str());
843 logger("Login '%s' is already in use from ip %s. IP %s",
845 inet_ntostring(user->GetCurrIP()).c_str(),
846 inet_ntostring(sip).c_str());
847 SendError(sip, sport, protoVer, IconvString("Логин уже используется.", "utf8", "koi8-ru"));
858 if (Process_CONN_SYN_6(static_cast<CONN_SYN_6 *>(buff), &(it->second), sip))
860 return Send_CONN_SYN_ACK_6(iaUser, sip);
862 if (Process_CONN_SYN_7(static_cast<CONN_SYN_7 *>(buff), &(it->second), sip))
864 return Send_CONN_SYN_ACK_7(iaUser, sip);
866 if (Process_CONN_SYN_8(static_cast<CONN_SYN_8 *>(buff), &(it->second), sip))
868 return Send_CONN_SYN_ACK_8(iaUser, sip);
876 if (Process_CONN_ACK_6(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
878 return Send_ALIVE_SYN_6(iaUser, sip);
880 if (Process_CONN_ACK_7(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
882 return Send_ALIVE_SYN_7(iaUser, sip);
884 if (Process_CONN_ACK_8(static_cast<CONN_ACK_8 *>(buff), iaUser, sip))
886 return Send_ALIVE_SYN_8(iaUser, sip);
894 return Process_ALIVE_ACK_6(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
896 return Process_ALIVE_ACK_7(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
898 return Process_ALIVE_ACK_8(static_cast<ALIVE_ACK_8 *>(buff), iaUser, sip);
906 if (Process_DISCONN_SYN_6(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
908 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
910 if (Process_DISCONN_SYN_7(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
912 return Send_DISCONN_SYN_ACK_7(iaUser, sip);
914 if (Process_DISCONN_SYN_8(static_cast<DISCONN_SYN_8 *>(buff), iaUser, sip))
916 return Send_DISCONN_SYN_ACK_8(iaUser, sip);
924 if (Process_DISCONN_ACK_6(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
926 return Send_FIN_6(iaUser, sip, it);
928 if (Process_DISCONN_ACK_7(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
930 return Send_FIN_7(iaUser, sip, it);
932 if (Process_DISCONN_ACK_8(static_cast<DISCONN_ACK_8 *>(buff), iaUser, sip, it))
934 return Send_FIN_8(iaUser, sip, it);
941 //-----------------------------------------------------------------------------
942 void AUTH_IA::DelUser(USER_PTR u)
945 uint32_t ip = u->GetCurrIP();
950 std::map<uint32_t, IA_USER>::iterator it;
952 STG_LOCKER lock(&mutex);
953 it = ip2user.find(ip);
954 if (it == ip2user.end())
957 printfd(__FILE__, "Nothing to delete\n");
961 if (it->second.user == u)
963 printfd(__FILE__, "User removed!\n");
964 users->Unauthorize(u->GetLogin(), this);
968 //-----------------------------------------------------------------------------
969 int AUTH_IA::SendError(uint32_t ip, uint16_t port, int protoVer, const std::string & text)
971 struct sockaddr_in sendAddr;
978 memset(&err, 0, sizeof(ERR));
980 sendAddr.sin_family = AF_INET;
981 sendAddr.sin_port = htons(port);
982 sendAddr.sin_addr.s_addr = ip;
985 strncpy((char*)err.type, "ERR", 16);
986 strncpy((char*)err.text, text.c_str(), MAX_MSG_LEN);
992 res = sendto(listenSocket, &err, sizeof(err), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
993 printfd(__FILE__, "SendError %d bytes sent\n", res);
998 memset(&err8, 0, sizeof(ERR_8));
1000 sendAddr.sin_family = AF_INET;
1001 sendAddr.sin_port = htons(port);
1002 sendAddr.sin_addr.s_addr = ip;
1005 strncpy((char*)err8.type, "ERR", 16);
1006 strncpy((char*)err8.text, text.c_str(), MAX_MSG_LEN);
1009 SwapBytes(err8.len);
1012 res = sendto(listenSocket, &err8, sizeof(err8), 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
1013 printfd(__FILE__, "SendError_8 %d bytes sent\n", res);
1019 //-----------------------------------------------------------------------------
1020 int AUTH_IA::Send(uint32_t ip, uint16_t port, const char * buffer, size_t len)
1022 struct sockaddr_in sendAddr;
1024 sendAddr.sin_family = AF_INET;
1025 sendAddr.sin_port = htons(port);
1026 sendAddr.sin_addr.s_addr = ip;
1028 if (sendto(listenSocket, buffer, len, 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr)) == static_cast<ssize_t>(len))
1033 //-----------------------------------------------------------------------------
1034 int AUTH_IA::SendMessage(const STG_MSG & msg, uint32_t ip) const
1036 printfd(__FILE__, "SendMessage userIP=%s\n", inet_ntostring(ip).c_str());
1038 std::map<uint32_t, IA_USER>::iterator it;
1040 STG_LOCKER lock(&mutex);
1041 it = ip2user.find(ip);
1042 if (it == ip2user.end())
1044 errorStr = "Unknown user.";
1047 it->second.messagesToSend.push_back(msg);
1050 //-----------------------------------------------------------------------------
1051 int AUTH_IA::RealSendMessage6(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1053 printfd(__FILE__, "RealSendMessage 6 user=%s\n", user.login.c_str());
1056 memset(&info, 0, sizeof(INFO_6));
1059 strncpy((char*)info.type, "INFO", 16);
1060 info.infoType = 'I';
1061 strncpy((char*)info.text, msg.text.c_str(), 235);
1064 size_t len = info.len;
1066 SwapBytes(info.len);
1070 memcpy(buffer, &info, sizeof(INFO_6));
1071 EncryptString(buffer, buffer, len, &user.ctx);
1072 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1074 //-----------------------------------------------------------------------------
1075 int AUTH_IA::RealSendMessage7(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1077 printfd(__FILE__, "RealSendMessage 7 user=%s\n", user.login.c_str());
1080 memset(&info, 0, sizeof(INFO_7));
1083 strncpy((char*)info.type, "INFO_7", 16);
1084 info.infoType = static_cast<int8_t>(msg.header.type);
1085 info.showTime = static_cast<int8_t>(msg.header.showTime);
1086 info.sendTime = msg.header.creationTime;
1088 size_t len = info.len;
1090 SwapBytes(info.len);
1091 SwapBytes(info.sendTime);
1094 strncpy((char*)info.text, msg.text.c_str(), MAX_MSG_LEN - 1);
1095 info.text[MAX_MSG_LEN - 1] = 0;
1098 memcpy(buffer, &info, sizeof(INFO_7));
1100 EncryptString(buffer, buffer, len, &user.ctx);
1101 return Send(ip, iaSettings.GetUserPort(), buffer, len);
1103 //-----------------------------------------------------------------------------
1104 int AUTH_IA::RealSendMessage8(const STG_MSG & msg, uint32_t ip, IA_USER & user)
1106 printfd(__FILE__, "RealSendMessage 8 user=%s\n", user.login.c_str());
1109 memset(&info, 0, sizeof(INFO_8));
1112 strncpy((char*)info.type, "INFO_8", 16);
1113 info.infoType = static_cast<int8_t>(msg.header.type);
1114 info.showTime = static_cast<int8_t>(msg.header.showTime);
1115 info.sendTime = msg.header.creationTime;
1117 strncpy((char*)info.text, msg.text.c_str(), IA_MAX_MSG_LEN_8 - 1);
1118 info.text[IA_MAX_MSG_LEN_8 - 1] = 0;
1120 size_t len = info.len;
1122 SwapBytes(info.len);
1123 SwapBytes(info.sendTime);
1127 memcpy(buffer, &info, sizeof(INFO_8));
1129 EncryptString(buffer, buffer, len, &user.ctx);
1130 return Send(ip, user.port, buffer, len);
1132 //-----------------------------------------------------------------------------
1133 int AUTH_IA::Process_CONN_SYN_6(CONN_SYN_6 *, IA_USER * iaUser, uint32_t)
1135 if (!(iaUser->phase.GetPhase() == 1 || iaUser->phase.GetPhase() == 3))
1138 enabledDirs = 0xFFffFFff;
1140 iaUser->phase.SetPhase2();
1141 printfd(__FILE__, "Phase changed from %d to 2. Reason: CONN_SYN_6\n", iaUser->phase.GetPhase());
1144 //-----------------------------------------------------------------------------
1145 int AUTH_IA::Process_CONN_SYN_7(CONN_SYN_7 * connSyn, IA_USER * iaUser, uint32_t sip)
1147 return Process_CONN_SYN_6(connSyn, iaUser, sip);
1149 //-----------------------------------------------------------------------------
1150 int AUTH_IA::Process_CONN_SYN_8(CONN_SYN_8 * connSyn, IA_USER * iaUser, uint32_t sip)
1153 SwapBytes(connSyn->dirs);
1155 int ret = Process_CONN_SYN_6(reinterpret_cast<CONN_SYN_6 *>(connSyn), iaUser, sip);
1156 enabledDirs = connSyn->dirs;
1159 //-----------------------------------------------------------------------------
1160 int AUTH_IA::Process_CONN_ACK_6(CONN_ACK_6 * connAck, IA_USER * iaUser, uint32_t sip)
1163 SwapBytes(connAck->len);
1164 SwapBytes(connAck->rnd);
1166 printfd( __FILE__, "CONN_ACK_6 %s\n", connAck->type);
1168 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1170 iaUser->phase.UpdateTime();
1172 iaUser->lastSendAlive = iaUser->phase.GetTime();
1173 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1175 iaUser->phase.SetPhase3();
1176 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_6\n");
1181 errorStr = iaUser->user->GetStrError();
1182 if (iaSettings.LogProtocolErrors())
1183 logger("IP: %s. User '%s'. Protocol version: %d. CONN_ACK: phase 2, authorization error ('%s').", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, errorStr.c_str());
1184 iaUser->phase.SetPhase1();
1186 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1190 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1191 if (iaSettings.LogProtocolErrors())
1193 if (iaUser->phase.GetPhase() != 2)
1194 logger("IP: %s. User '%s'. Protocol version: %d. CONN_ACK: invalid phase, expected 2, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, iaUser->phase.GetPhase());
1195 if (connAck->rnd != iaUser->rnd + 1)
1196 logger("IP: %s. User '%s'. Protocol version: %d. CONN_ACK: invalid control number, expected %d, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, (iaUser->rnd + 1), connAck->rnd);
1200 //-----------------------------------------------------------------------------
1201 int AUTH_IA::Process_CONN_ACK_7(CONN_ACK_7 * connAck, IA_USER * iaUser, uint32_t sip)
1203 return Process_CONN_ACK_6(connAck, iaUser, sip);
1205 //-----------------------------------------------------------------------------
1206 int AUTH_IA::Process_CONN_ACK_8(CONN_ACK_8 * connAck, IA_USER * iaUser, uint32_t sip)
1209 SwapBytes(connAck->len);
1210 SwapBytes(connAck->rnd);
1212 printfd( __FILE__, "CONN_ACK_8 %s\n", connAck->type);
1214 if ((iaUser->phase.GetPhase() == 2) && (connAck->rnd == iaUser->rnd + 1))
1216 iaUser->phase.UpdateTime();
1217 iaUser->lastSendAlive = iaUser->phase.GetTime();
1218 if (users->Authorize(iaUser->login, sip, enabledDirs, this))
1220 iaUser->phase.SetPhase3();
1221 printfd(__FILE__, "Phase changed from 2 to 3. Reason: CONN_ACK_8\n");
1226 errorStr = iaUser->user->GetStrError();
1227 if (iaSettings.LogProtocolErrors())
1228 logger("IP: %s. User '%s'. Protocol version: %d. CONN_ACK: phase 2, authorization error ('%s').", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, errorStr.c_str());
1229 iaUser->phase.SetPhase1();
1231 printfd(__FILE__, "Phase changed from 2 to 1. Reason: failed to authorize user\n");
1235 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), connAck->rnd);
1236 if (iaSettings.LogProtocolErrors())
1238 if (iaUser->phase.GetPhase() != 2)
1239 logger("IP: %s. User '%s'. Protocol version: %d. CONN_ACK: invalid phase, expected 2, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, iaUser->phase.GetPhase());
1240 if (connAck->rnd != iaUser->rnd + 1)
1241 logger("IP: %s. User '%s'. Protocol version: %d. CONN_ACK: invalid control number, expected %d, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, (iaUser->rnd + 1), connAck->rnd);
1245 //-----------------------------------------------------------------------------
1246 int AUTH_IA::Process_ALIVE_ACK_6(ALIVE_ACK_6 * aliveAck, IA_USER * iaUser, uint32_t)
1249 SwapBytes(aliveAck->len);
1250 SwapBytes(aliveAck->rnd);
1252 printfd(__FILE__, "ALIVE_ACK_6\n");
1253 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1255 iaUser->phase.UpdateTime();
1257 iaUser->aliveSent = false;
1262 //-----------------------------------------------------------------------------
1263 int AUTH_IA::Process_ALIVE_ACK_7(ALIVE_ACK_7 * aliveAck, IA_USER * iaUser, uint32_t sip)
1265 return Process_ALIVE_ACK_6(aliveAck, iaUser, sip);
1267 //-----------------------------------------------------------------------------
1268 int AUTH_IA::Process_ALIVE_ACK_8(ALIVE_ACK_8 * aliveAck, IA_USER * iaUser, uint32_t)
1271 SwapBytes(aliveAck->len);
1272 SwapBytes(aliveAck->rnd);
1274 printfd(__FILE__, "ALIVE_ACK_8\n");
1275 if ((iaUser->phase.GetPhase() == 3) && (aliveAck->rnd == iaUser->rnd + 1))
1277 iaUser->phase.UpdateTime();
1279 iaUser->aliveSent = false;
1284 //-----------------------------------------------------------------------------
1285 int AUTH_IA::Process_DISCONN_SYN_6(DISCONN_SYN_6 *, IA_USER * iaUser, uint32_t sip)
1287 printfd(__FILE__, "DISCONN_SYN_6\n");
1288 if (iaUser->phase.GetPhase() != 3)
1290 if (iaSettings.LogProtocolErrors())
1291 logger("IP: %s. User '%s'. Protocol version: %d. DISCONN_SYN: invalid phase, expected 3, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, iaUser->phase.GetPhase());
1292 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1293 errorStr = "Incorrect request DISCONN_SYN";
1297 iaUser->phase.SetPhase4();
1298 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1302 //-----------------------------------------------------------------------------
1303 int AUTH_IA::Process_DISCONN_SYN_7(DISCONN_SYN_7 * disconnSyn, IA_USER * iaUser, uint32_t sip)
1305 return Process_DISCONN_SYN_6(disconnSyn, iaUser, sip);
1307 //-----------------------------------------------------------------------------
1308 int AUTH_IA::Process_DISCONN_SYN_8(DISCONN_SYN_8 *, IA_USER * iaUser, uint32_t sip)
1310 if (iaUser->phase.GetPhase() != 3)
1312 if (iaSettings.LogProtocolErrors())
1313 logger("IP: %s. User '%s'. Protocol version: %d. DISCONN_SYN: invalid phase, expected 3, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, iaUser->phase.GetPhase());
1314 errorStr = "Incorrect request DISCONN_SYN";
1315 printfd(__FILE__, "Invalid phase. Expected 3, actual %d\n", iaUser->phase.GetPhase());
1319 iaUser->phase.SetPhase4();
1320 printfd(__FILE__, "Phase changed from 3 to 4. Reason: DISCONN_SYN_6\n");
1324 //-----------------------------------------------------------------------------
1325 int AUTH_IA::Process_DISCONN_ACK_6(DISCONN_ACK_6 * disconnAck,
1328 std::map<uint32_t, IA_USER>::iterator)
1331 SwapBytes(disconnAck->len);
1332 SwapBytes(disconnAck->rnd);
1334 printfd(__FILE__, "DISCONN_ACK_6\n");
1335 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1337 if (iaSettings.LogProtocolErrors())
1339 if (iaUser->phase.GetPhase() != 4)
1340 logger("IP: %s. User '%s'. Protocol version: %d. DISCONN_ACK: invalid phase, expected 4, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, iaUser->phase.GetPhase());
1341 if (disconnAck->rnd != iaUser->rnd + 1)
1342 logger("IP: %s. User '%s'. Protocol version: %d. DISCONN_ACK: invalid control number, expected %d, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, (iaUser->rnd + 1), disconnAck->rnd);
1344 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1350 //-----------------------------------------------------------------------------
1351 int AUTH_IA::Process_DISCONN_ACK_7(DISCONN_ACK_7 * disconnAck, IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1353 return Process_DISCONN_ACK_6(disconnAck, iaUser, sip, it);
1355 //-----------------------------------------------------------------------------
1356 int AUTH_IA::Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnAck, IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator)
1359 SwapBytes(disconnAck->len);
1360 SwapBytes(disconnAck->rnd);
1362 printfd(__FILE__, "DISCONN_ACK_8\n");
1363 if (!((iaUser->phase.GetPhase() == 4) && (disconnAck->rnd == iaUser->rnd + 1)))
1365 if (iaSettings.LogProtocolErrors())
1367 if (iaUser->phase.GetPhase() != 4)
1368 logger("IP: %s. User '%s'. Protocol version: %d. DISCONN_ACK: invalid phase, expected 4, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, iaUser->phase.GetPhase());
1369 if (disconnAck->rnd != iaUser->rnd + 1)
1370 logger("IP: %s. User '%s'. Protocol version: %d. DISCONN_ACK: invalid control number, expected %d, got %d.", inet_ntostring(sip).c_str(), iaUser->login.c_str(), iaUser->protoVer, (iaUser->rnd + 1), disconnAck->rnd);
1372 printfd(__FILE__, "Invalid phase or control number. Phase: %d. Control number: %d\n", iaUser->phase.GetPhase(), disconnAck->rnd);
1378 //-----------------------------------------------------------------------------
1379 int AUTH_IA::Send_CONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1381 //+++ Fill static data in connSynAck +++
1382 // TODO Move this code. It must be executed only once
1383 connSynAck6.len = Min8(sizeof(CONN_SYN_ACK_6));
1384 strcpy((char*)connSynAck6.type, "CONN_SYN_ACK");
1385 for (int j = 0; j < DIR_NUM; j++)
1387 strncpy((char*)connSynAck6.dirName[j],
1388 stgSettings->GetDirName(j).c_str(),
1391 connSynAck6.dirName[j][sizeof(string16) - 1] = 0;
1393 //--- Fill static data in connSynAck ---
1395 iaUser->rnd = static_cast<uint32_t>(random());
1396 connSynAck6.rnd = iaUser->rnd;
1398 connSynAck6.userTimeOut = iaSettings.GetUserTimeout();
1399 connSynAck6.aliveDelay = iaSettings.GetUserDelay();
1402 SwapBytes(connSynAck6.len);
1403 SwapBytes(connSynAck6.rnd);
1404 SwapBytes(connSynAck6.userTimeOut);
1405 SwapBytes(connSynAck6.aliveDelay);
1408 EncryptString((char*)&connSynAck6, (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)), &iaUser->ctx);
1409 return Send(sip, iaSettings.GetUserPort(), (char*)&connSynAck6, Min8(sizeof(CONN_SYN_ACK_6)));;
1411 //-----------------------------------------------------------------------------
1412 int AUTH_IA::Send_CONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1414 return Send_CONN_SYN_ACK_6(iaUser, sip);
1416 //-----------------------------------------------------------------------------
1417 int AUTH_IA::Send_CONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1419 strcpy((char*)connSynAck8.hdr.magic, IA_ID);
1420 connSynAck8.hdr.protoVer[0] = 0;
1421 connSynAck8.hdr.protoVer[1] = 8;
1423 //+++ Fill static data in connSynAck +++
1424 // TODO Move this code. It must be executed only once
1425 connSynAck8.len = Min8(sizeof(CONN_SYN_ACK_8));
1426 strcpy((char*)connSynAck8.type, "CONN_SYN_ACK");
1427 for (int j = 0; j < DIR_NUM; j++)
1429 strncpy((char*)connSynAck8.dirName[j],
1430 stgSettings->GetDirName(j).c_str(),
1433 connSynAck8.dirName[j][sizeof(string16) - 1] = 0;
1435 //--- Fill static data in connSynAck ---
1437 iaUser->rnd = static_cast<uint32_t>(random());
1438 connSynAck8.rnd = iaUser->rnd;
1440 connSynAck8.userTimeOut = iaSettings.GetUserTimeout();
1441 connSynAck8.aliveDelay = iaSettings.GetUserDelay();
1444 SwapBytes(connSynAck8.len);
1445 SwapBytes(connSynAck8.rnd);
1446 SwapBytes(connSynAck8.userTimeOut);
1447 SwapBytes(connSynAck8.aliveDelay);
1450 EncryptString((char*)&connSynAck8, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)), &iaUser->ctx);
1451 return Send(sip, iaUser->port, (char*)&connSynAck8, Min8(sizeof(CONN_SYN_ACK_8)));
1453 //-----------------------------------------------------------------------------
1454 int AUTH_IA::Send_ALIVE_SYN_6(IA_USER * iaUser, uint32_t sip)
1456 aliveSyn6.len = Min8(sizeof(ALIVE_SYN_6));
1457 aliveSyn6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1459 strcpy((char*)aliveSyn6.type, "ALIVE_SYN");
1461 for (int i = 0; i < DIR_NUM; i++)
1463 aliveSyn6.md[i] = iaUser->user->GetProperty().down.Get()[i];
1464 aliveSyn6.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1466 aliveSyn6.sd[i] = iaUser->user->GetSessionDownload()[i];
1467 aliveSyn6.su[i] = iaUser->user->GetSessionUpload()[i];
1471 int dn = iaSettings.GetFreeMbShowType();
1472 const TARIFF * tf = iaUser->user->GetTariff();
1476 double p = tf->GetPriceWithTraffType(aliveSyn6.mu[dn],
1481 if (std::fabs(p) < 1.0e-3)
1483 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "---");
1487 double fmb = iaUser->user->GetProperty().freeMb;
1488 fmb = fmb < 0 ? 0 : fmb;
1489 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1494 if (freeMbNone == iaSettings.GetFreeMbShowType())
1496 aliveSyn6.freeMb[0] = 0;
1500 double fmb = iaUser->user->GetProperty().freeMb;
1501 fmb = fmb < 0 ? 0 : fmb;
1502 snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1507 if (iaUser->aliveSent)
1509 printfd(__FILE__, "========= ALIVE_ACK_6(7) TIMEOUT !!! %s =========\n", iaUser->login.c_str());
1511 iaUser->aliveSent = true;
1514 aliveSyn6.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1515 if (!stgSettings->GetShowFeeInCash())
1516 aliveSyn6.cash -= (int64_t)(tf->GetFee() * 1000.0);
1519 SwapBytes(aliveSyn6.len);
1520 SwapBytes(aliveSyn6.rnd);
1521 SwapBytes(aliveSyn6.cash);
1522 for (int i = 0; i < DIR_NUM; ++i)
1524 SwapBytes(aliveSyn6.mu[i]);
1525 SwapBytes(aliveSyn6.md[i]);
1526 SwapBytes(aliveSyn6.su[i]);
1527 SwapBytes(aliveSyn6.sd[i]);
1531 EncryptString((char*)&aliveSyn6, (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)), &iaUser->ctx);
1532 return Send(sip, iaSettings.GetUserPort(), (char*)&aliveSyn6, Min8(sizeof(aliveSyn6)));
1534 //-----------------------------------------------------------------------------
1535 int AUTH_IA::Send_ALIVE_SYN_7(IA_USER * iaUser, uint32_t sip)
1537 return Send_ALIVE_SYN_6(iaUser, sip);
1539 //-----------------------------------------------------------------------------
1540 int AUTH_IA::Send_ALIVE_SYN_8(IA_USER * iaUser, uint32_t sip)
1542 strcpy((char*)aliveSyn8.hdr.magic, IA_ID);
1543 aliveSyn8.hdr.protoVer[0] = 0;
1544 aliveSyn8.hdr.protoVer[1] = 8;
1546 aliveSyn8.len = Min8(sizeof(ALIVE_SYN_8));
1547 aliveSyn8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1549 strcpy((char*)aliveSyn8.type, "ALIVE_SYN");
1551 for (int i = 0; i < DIR_NUM; i++)
1553 aliveSyn8.md[i] = iaUser->user->GetProperty().down.Get()[i];
1554 aliveSyn8.mu[i] = iaUser->user->GetProperty().up.Get()[i];
1556 aliveSyn8.sd[i] = iaUser->user->GetSessionDownload()[i];
1557 aliveSyn8.su[i] = iaUser->user->GetSessionUpload()[i];
1561 int dn = iaSettings.GetFreeMbShowType();
1565 const TARIFF * tf = iaUser->user->GetTariff();
1566 double p = tf->GetPriceWithTraffType(aliveSyn8.mu[dn],
1571 if (std::fabs(p) < 1.0e-3)
1573 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "---");
1577 double fmb = iaUser->user->GetProperty().freeMb;
1578 fmb = fmb < 0 ? 0 : fmb;
1579 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p);
1584 if (freeMbNone == iaSettings.GetFreeMbShowType())
1586 aliveSyn8.freeMb[0] = 0;
1590 double fmb = iaUser->user->GetProperty().freeMb;
1591 fmb = fmb < 0 ? 0 : fmb;
1592 snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "C%.3f", fmb);
1597 if (iaUser->aliveSent)
1599 printfd(__FILE__, "========= ALIVE_ACK_8 TIMEOUT !!! =========\n");
1601 iaUser->aliveSent = true;
1604 const TARIFF * tf = iaUser->user->GetTariff();
1606 aliveSyn8.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0);
1607 if (!stgSettings->GetShowFeeInCash())
1608 aliveSyn8.cash -= (int64_t)(tf->GetFee() * 1000.0);
1611 SwapBytes(aliveSyn8.len);
1612 SwapBytes(aliveSyn8.rnd);
1613 SwapBytes(aliveSyn8.cash);
1614 SwapBytes(aliveSyn8.status);
1615 for (int i = 0; i < DIR_NUM; ++i)
1617 SwapBytes(aliveSyn8.mu[i]);
1618 SwapBytes(aliveSyn8.md[i]);
1619 SwapBytes(aliveSyn8.su[i]);
1620 SwapBytes(aliveSyn8.sd[i]);
1624 EncryptString((char*)&aliveSyn8, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)), &iaUser->ctx);
1625 return Send(sip, iaUser->port, (char*)&aliveSyn8, Min8(sizeof(aliveSyn8)));
1627 //-----------------------------------------------------------------------------
1628 int AUTH_IA::Send_DISCONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip)
1630 disconnSynAck6.len = Min8(sizeof(DISCONN_SYN_ACK_6));
1631 strcpy((char*)disconnSynAck6.type, "DISCONN_SYN_ACK");
1632 disconnSynAck6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1635 SwapBytes(disconnSynAck6.len);
1636 SwapBytes(disconnSynAck6.rnd);
1639 EncryptString((char*)&disconnSynAck6, (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)), &iaUser->ctx);
1640 return Send(sip, iaSettings.GetUserPort(), (char*)&disconnSynAck6, Min8(sizeof(disconnSynAck6)));
1642 //-----------------------------------------------------------------------------
1643 int AUTH_IA::Send_DISCONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip)
1645 return Send_DISCONN_SYN_ACK_6(iaUser, sip);
1647 //-----------------------------------------------------------------------------
1648 int AUTH_IA::Send_DISCONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip)
1650 strcpy((char*)disconnSynAck8.hdr.magic, IA_ID);
1651 disconnSynAck8.hdr.protoVer[0] = 0;
1652 disconnSynAck8.hdr.protoVer[1] = 8;
1654 disconnSynAck8.len = Min8(sizeof(DISCONN_SYN_ACK_8));
1655 strcpy((char*)disconnSynAck8.type, "DISCONN_SYN_ACK");
1656 disconnSynAck8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
1659 SwapBytes(disconnSynAck8.len);
1660 SwapBytes(disconnSynAck8.rnd);
1663 EncryptString((char*)&disconnSynAck8, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)), &iaUser->ctx);
1664 return Send(sip, iaUser->port, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)));
1666 //-----------------------------------------------------------------------------
1667 int AUTH_IA::Send_FIN_6(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1669 fin6.len = Min8(sizeof(FIN_6));
1670 strcpy((char*)fin6.type, "FIN");
1671 strcpy((char*)fin6.ok, "OK");
1674 SwapBytes(fin6.len);
1677 EncryptString((char*)&fin6, (char*)&fin6, Min8(sizeof(fin6)), &iaUser->ctx);
1679 users->Unauthorize(iaUser->login, this);
1681 int res = Send(sip, iaSettings.GetUserPort(), (char*)&fin6, Min8(sizeof(fin6)));
1687 //-----------------------------------------------------------------------------
1688 int AUTH_IA::Send_FIN_7(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1690 return Send_FIN_6(iaUser, sip, it);
1692 //-----------------------------------------------------------------------------
1693 int AUTH_IA::Send_FIN_8(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
1695 strcpy((char*)fin8.hdr.magic, IA_ID);
1696 fin8.hdr.protoVer[0] = 0;
1697 fin8.hdr.protoVer[1] = 8;
1699 fin8.len = Min8(sizeof(FIN_8));
1700 strcpy((char*)fin8.type, "FIN");
1701 strcpy((char*)fin8.ok, "OK");
1704 SwapBytes(fin8.len);
1707 EncryptString((char*)&fin8, (char*)&fin8, Min8(sizeof(fin8)), &iaUser->ctx);
1709 users->Unauthorize(iaUser->login, this);
1711 int res = Send(sip, iaUser->port, (char*)&fin8, Min8(sizeof(fin8)));