]> git.stg.codes - stg.git/blobdiff - projects/stargazer/plugins/store/files/file_store.cpp
Implemented daily fee charge with backward compatibility.
[stg.git] / projects / stargazer / plugins / store / files / file_store.cpp
index 21c6cb17701382d589fc6a1cb8afc1dd79f82a5f..fa0483a8894213944c1215a694c8eefb4fe82343 100644 (file)
@@ -30,7 +30,6 @@
 
 #include <pwd.h>
 #include <grp.h>
-#include <sys/types.h>
 #include <sys/stat.h>
 #include <unistd.h>
 #include <sys/time.h>
 #include <sstream>
 #include <algorithm>
 
-#include "common.h"
-#include "user_ips.h"
-#include "user_conf.h"
-#include "user_stat.h"
-#include "stg_const.h"
+#include "stg/common.h"
+#include "stg/user_ips.h"
+#include "stg/user_conf.h"
+#include "stg/user_stat.h"
+#include "stg/const.h"
+#include "stg/blowfish.h"
+#include "stg/logger.h"
+#include "stg/locker.h"
+#include "stg/plugin_creator.h"
 #include "file_store.h"
-#include "blowfish.h"
-#include "stg_logger.h"
-#include "stg_locker.h"
 
 #define DELETED_USERS_DIR   "deleted_users"
 
@@ -64,91 +64,38 @@ int GetFileList(vector<string> * fileList, const string & directory, mode_t mode
 
 const int pt_mega = 1024 * 1024;
 //-----------------------------------------------------------------------------
-class BAK_FILE
-{
-public:
-
-    //-------------------------------------------------------------------------
-    BAK_FILE(const string & fileName, bool removeBak)
-            : f(NULL),
-              removeBak(false)
-        {
-        bakSuccessed = false;
-        BAK_FILE::removeBak = removeBak;
-        fileNameBak = fileName + ".bak";
-        if (rename(fileName.c_str(), fileNameBak.c_str()))
-            {
-            printfd(__FILE__, "BAK_FILE::BAK_FILE - rename failed. Message: '%s'\n", strerror(errno));
-            }
-        else
-            {
-            bakSuccessed = true;
-            }
-
-        }
-    //-------------------------------------------------------------------------
-    ~BAK_FILE()
-        {
-        if(bakSuccessed && removeBak)
-            {
-            if (unlink(fileNameBak.c_str()))
-                {
-                printfd(__FILE__, "BAK_FILE::~BAK_FILE - unlink failed. Message: '%s'\n", strerror(errno));
-                }
-            }
-        }
-    //-------------------------------------------------------------------------
-
-private:
-    FILE * f;
-    bool bakSuccessed;
-    string fileNameBak;
-    bool removeBak;
-};
-//-----------------------------------------------------------------------------
-class FILES_STORE_CREATOR
-{
-private:
-    FILES_STORE * fs;
-
-public:
-    FILES_STORE_CREATOR()
-        : fs(new FILES_STORE())
-        {
-        };
-    ~FILES_STORE_CREATOR()
-        {
-        delete fs;
-        };
-
-    FILES_STORE * GetStore()
-    {
-        return fs;
-    };
-};
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
+PLUGIN_CREATOR<FILES_STORE> fsc;
 //-----------------------------------------------------------------------------
-FILES_STORE_CREATOR fsc;
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-BASE_STORE * GetStore()
+STORE * GetStore()
 {
-return fsc.GetStore();
+return fsc.GetPlugin();
 }
 //-----------------------------------------------------------------------------
 FILES_STORE_SETTINGS::FILES_STORE_SETTINGS()
     : settings(NULL),
+      errorStr(),
+      workDir(),
+      usersDir(),
+      adminsDir(),
+      tariffsDir(),
+      statMode(0),
+      statUID(0),
+      statGID(0),
+      confMode(0),
+      confUID(0),
+      confGID(0),
+      userLogMode(0),
+      userLogUID(0),
+      userLogGID(0),
       removeBak(true),
       readBak(true)
 {
 }
 //-----------------------------------------------------------------------------
-FILES_STORE_SETTINGS::~FILES_STORE_SETTINGS()
-{
-}
-//-----------------------------------------------------------------------------
 int FILES_STORE_SETTINGS::ParseOwner(const vector<PARAM_VALUE> & moduleParams, const string & owner, uid_t * uid)
 {
 PARAM_VALUE pv;
@@ -369,31 +316,6 @@ c = str[2] - '0';
 return 0;
 }
 //-----------------------------------------------------------------------------
-string FILES_STORE_SETTINGS::GetWorkDir() const
-{
-return workDir;
-}
-//-----------------------------------------------------------------------------
-string FILES_STORE_SETTINGS::GetUsersDir() const
-{
-return usersDir;
-}
-//-----------------------------------------------------------------------------
-string FILES_STORE_SETTINGS::GetAdminsDir() const
-{
-return adminsDir;
-}
-//-----------------------------------------------------------------------------
-string FILES_STORE_SETTINGS::GetTariffsDir() const
-{
-return tariffsDir;
-}
-//-----------------------------------------------------------------------------
-mode_t FILES_STORE_SETTINGS::GetStatMode() const
-{
-return statMode;
-}
-//-----------------------------------------------------------------------------
 mode_t FILES_STORE_SETTINGS::GetStatModeDir() const
 {
 mode_t mode = statMode;
@@ -403,21 +325,6 @@ if (statMode & S_IROTH) mode |= S_IXOTH;
 return mode;
 }
 //-----------------------------------------------------------------------------
-uid_t  FILES_STORE_SETTINGS::GetStatUID() const
-{
-return statUID;
-}
-//-----------------------------------------------------------------------------
-gid_t  FILES_STORE_SETTINGS::GetStatGID() const
-{
-return statGID;
-}
-//-----------------------------------------------------------------------------
-mode_t FILES_STORE_SETTINGS::GetConfMode() const
-{
-return confMode;
-}
-//-----------------------------------------------------------------------------
 mode_t FILES_STORE_SETTINGS::GetConfModeDir() const
 {
 mode_t mode = confMode;
@@ -427,63 +334,21 @@ if (confMode & S_IROTH) mode |= S_IXOTH;
 return mode;
 }
 //-----------------------------------------------------------------------------
-uid_t  FILES_STORE_SETTINGS::GetConfUID() const
-{
-return confUID;
-}
-//-----------------------------------------------------------------------------
-gid_t  FILES_STORE_SETTINGS::GetConfGID() const
-{
-return confGID;
-}
-//-----------------------------------------------------------------------------
-mode_t FILES_STORE_SETTINGS::GetLogMode() const
-{
-return userLogMode;
-}
-//-----------------------------------------------------------------------------
-uid_t  FILES_STORE_SETTINGS::GetLogUID() const
-{
-return userLogUID;
-}
-//-----------------------------------------------------------------------------
-gid_t FILES_STORE_SETTINGS::GetLogGID() const
-{
-return userLogGID;
-}
-//-----------------------------------------------------------------------------
-bool FILES_STORE_SETTINGS::GetRemoveBak() const
-{
-return removeBak;
-}
-//-----------------------------------------------------------------------------
-bool FILES_STORE_SETTINGS::GetReadBak() const
-{
-return readBak;
-}
-//-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 //-----------------------------------------------------------------------------
 FILES_STORE::FILES_STORE()
+    : errorStr(),
+      version("file_store v.1.04"),
+      storeSettings(),
+      settings(),
+      mutex()
 {
-version = "file_store v.1.04";
-
 pthread_mutexattr_t attr;
 pthread_mutexattr_init(&attr);
 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
 pthread_mutex_init(&mutex, &attr);
 };
 //-----------------------------------------------------------------------------
-FILES_STORE::~FILES_STORE()
-{
-
-};
-//-----------------------------------------------------------------------------
-void FILES_STORE::SetSettings(const MODULE_SETTINGS & s)
-{
-settings = s;
-}
-//-----------------------------------------------------------------------------
 int FILES_STORE::ParseSettings()
 {
 int ret = storeSettings.ParseSettings(settings);
@@ -495,17 +360,6 @@ if (ret)
 return ret;
 }
 //-----------------------------------------------------------------------------
-const string & FILES_STORE::GetStrError() const
-{
-STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-return errorStr;
-}
-//-----------------------------------------------------------------------------
-const string & FILES_STORE::GetVersion() const
-{
-return version;
-}
-//-----------------------------------------------------------------------------
 int FILES_STORE::GetUsersList(vector<string> * userList) const
 {
 vector<string> files;
@@ -562,40 +416,64 @@ return 0;
 //-----------------------------------------------------------------------------
 int FILES_STORE::RemoveDir(const char * path) const
 {
-vector<string> fileList;
+DIR * d = opendir(path);
 
-GetFileList(&fileList, path, S_IFREG, "");
+if (!d)
+    {
+    errorStr = "failed to open dir. Message: '";
+    errorStr += strerror(errno);
+    errorStr += "'";
+    printfd(__FILE__, "FILE_STORE::RemoveDir() - Failed to open dir '%s': '%s'\n", path, strerror(errno));
+    return -1;
+    }
 
-for (unsigned i = 0; i < fileList.size(); i++)
+dirent * entry;
+while ((entry = readdir(d)))
     {
-    string file = path + string("/") + fileList[i];
-    if (unlink(file.c_str()))
+    if (!(strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..")))
+        continue;
+
+    string str = path;
+    str += "/" + string(entry->d_name);
+
+    struct stat st;
+    if (stat(str.c_str(), &st))
+        continue;
+
+    if ((st.st_mode & S_IFREG))
         {
-        STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-        errorStr = "unlink failed. Message: '";
-        errorStr += strerror(errno);
-        errorStr += "'";
-        printfd(__FILE__, "FILES_STORE::RemoveDir - unlink failed. Message: '%s'\n", strerror(errno));
-        return -1;
+        if (unlink(str.c_str()))
+            {
+            STG_LOCKER lock(&mutex, __FILE__, __LINE__);
+            errorStr = "unlink failed. Message: '";
+            errorStr += strerror(errno);
+            errorStr += "'";
+            printfd(__FILE__, "FILES_STORE::RemoveDir() - unlink failed. Message: '%s'\n", strerror(errno));
+            closedir(d);
+            return -1;
+            }
         }
-    }
 
-fileList.clear();
-GetFileList(&fileList, path, S_IFDIR, "");
+    if (!(st.st_mode & S_IFDIR))
+        {
+        if (RemoveDir(str.c_str()))
+            {
+            closedir(d);
+            return -1;
+            }
 
-for (unsigned i = 0; i < fileList.size(); i++)
-    {
-    string dir = string(path) + "/" + fileList[i];
-    RemoveDir(dir.c_str());
+        }
     }
 
+closedir(d);
+
 if (rmdir(path))
     {
     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
     errorStr = "rmdir failed. Message: '";
     errorStr += strerror(errno);
     errorStr += "'";
-    printfd(__FILE__, "FILES_STORE::RemoveDir - rmdir failed. Message: '%s'\n", strerror(errno));
+    printfd(__FILE__, "FILES_STORE::RemoveDir() - rmdir failed. Message: '%s'\n", strerror(errno));
     return -1;
     }
 
@@ -624,27 +502,6 @@ if (Touch(fileName))
     printfd(__FILE__, "FILES_STORE::AddUser - fopen failed. Message: '%s'\n", strerror(errno));
     return -1;
     }
-/*f = fopen(fileName.c_str(), "wt");
-if (f)
-    {
-    if (fprintf(f, "\n") < 0)
-        {
-        STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-        errorStr = "fprintf failed. Message: '";
-        errorStr += strerror(errno);
-        errorStr += "'";
-        printfd(__FILE__, "FILES_STORE::AddUser - fprintf failed. Message: '%s'\n", strerror(errno));
-        return -1;
-        }
-    fclose(f);
-    }
-else
-    {
-    STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-    errorStr = "Cannot create file \"" + fileName + "\'";
-    printfd(__FILE__, "FILES_STORE::AddUser - fopen failed. Message: '%s'\n", strerror(errno));
-    return -1;
-    }*/
 
 strprintf(&fileName, "%s%s/stat", storeSettings.GetUsersDir().c_str(), login.c_str());
 if (Touch(fileName))
@@ -654,27 +511,6 @@ if (Touch(fileName))
     printfd(__FILE__, "FILES_STORE::AddUser - fopen failed. Message: '%s'\n", strerror(errno));
     return -1;
     }
-/*f = fopen(fileName.c_str(), "wt");
-if (f)
-    {
-    if (fprintf(f, "\n") < 0)
-        {
-        STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-        errorStr = "fprintf failed. Message: '";
-        errorStr += strerror(errno);
-        errorStr += "'";
-        printfd(__FILE__, "FILES_STORE::AddUser - fprintf failed. Message: '%s'\n", strerror(errno));
-        return -1;
-        }
-    fclose(f);
-    }
-else
-    {
-    STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-    errorStr = "Cannot create file \"" + fileName + "\'";
-    printfd(__FILE__, "FILES_STORE::AddUser - fopen failed. Message: '%s'\n", strerror(errno));
-    return -1;
-    }*/
 return 0;
 }
 //-----------------------------------------------------------------------------
@@ -784,7 +620,7 @@ try
     {
     i = StrToIPS(ipStr);
     }
-catch (string s)
+catch (const string & s)
     {
     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
     errorStr = "User \'" + login + "\' data not read. Parameter IP address. " + s;
@@ -957,8 +793,6 @@ int FILES_STORE::SaveUserConf(const USER_CONF & conf, const string & login) cons
 string fileName;
 fileName = storeSettings.GetUsersDir() + "/" + login + "/conf";
 
-//BAK_FILE bakFile(fileName, storeSettings.GetRemoveBak());
-
 CONFIGFILE cfstat(fileName, true);
 
 int e = cfstat.Error();
@@ -1016,8 +850,6 @@ char s[22];
 string fileName;
 fileName = storeSettings.GetUsersDir() + "/" + login + "/stat";
 
-//BAK_FILE bakFile(fileName, storeSettings.GetRemoveBak());
-
     {
     CONFIGFILE cfstat(fileName, true);
     int e = cfstat.Error();
@@ -1191,35 +1023,58 @@ return WriteLog2String(logStr.str(), login);
 //-----------------------------------------------------------------------------
 int FILES_STORE::SaveMonthStat(const USER_STAT & stat, int month, int year, const string & login) const
 {
-string str;
-int e;
-
-strprintf(&str,"%s/%s/stat.%d.%02d",
+// Classic stats
+string stat1;
+strprintf(&stat1,"%s/%s/stat.%d.%02d",
         storeSettings.GetUsersDir().c_str(), login.c_str(), year + 1900, month + 1);
 
-CONFIGFILE s(str, true);
-e = s.Error();
+CONFIGFILE s(stat1, true);
 
-if (e)
+if (s.Error())
     {
     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-    errorStr = "Cannot create file " + str;
+    errorStr = "Cannot create file '" + stat1 + "'";
     printfd(__FILE__, "FILES_STORE::SaveMonthStat - month stat write failed for user '%s'\n", login.c_str());
     return -1;
     }
 
-char dirName[3];
+// New stats
+string stat2;
+strprintf(&stat2,"%s/%s/stat2.%d.%02d",
+        storeSettings.GetUsersDir().c_str(), login.c_str(), year + 1900, month + 1);
 
-for (int i = 0; i < DIR_NUM; i++)
+CONFIGFILE s2(stat2, true);
+
+if (s2.Error())
     {
-    snprintf(dirName, 3, "U%d", i);
-    s.WriteInt(dirName, stat.up[i]);
-    snprintf(dirName, 3, "D%d", i);
-    s.WriteInt(dirName, stat.down[i]);
+    STG_LOCKER lock(&mutex, __FILE__, __LINE__);
+    errorStr = "Cannot create file '" + stat2 + "'";
+    printfd(__FILE__, "FILES_STORE::SaveMonthStat - month stat write failed for user '%s'\n", login.c_str());
+    return -1;
     }
 
+for (size_t i = 0; i < DIR_NUM; i++)
+    {
+    char dirName[3];
+    snprintf(dirName, 3, "U%llu", (unsigned long long)i);
+    s.WriteInt(dirName, stat.up[i]); // Classic
+    s2.WriteInt(dirName, stat.up[i]); // New
+    snprintf(dirName, 3, "D%llu", (unsigned long long)i);
+    s.WriteInt(dirName, stat.down[i]); // Classic
+    s2.WriteInt(dirName, stat.down[i]); // New
+    }
+
+// Classic
 s.WriteDouble("cash", stat.cash);
 
+// New
+s2.WriteDouble("Cash", stat.cash);
+s2.WriteDouble("FreeMb", stat.freeMb);
+s2.WriteDouble("LastCashAdd", stat.lastCashAdd);
+s2.WriteInt("LastCashAddTime", stat.lastCashAddTime);
+s2.WriteInt("PassiveTime", stat.passiveTime);
+s2.WriteInt("LastActivityTime", stat.lastActivityTime);
+
 return 0;
 }
 //-----------------------------------------------------------------------------*/
@@ -1302,6 +1157,8 @@ strprintf(&fileName, "%s/%s.adm", storeSettings.GetAdminsDir().c_str(), ac.login
     cf.WriteInt("UsrAddDel",   ac.priv.userAddDel);
     cf.WriteInt("ChgTariff",   ac.priv.tariffChg);
     cf.WriteInt("ChgAdmin",    ac.priv.adminChg);
+    cf.WriteInt("ChgService",  ac.priv.serviceChg);
+    cf.WriteInt("ChgCorp",     ac.priv.corpChg);
     }
 
 return 0;
@@ -1340,8 +1197,6 @@ if (cf.ReadString("password", &p, "*"))
 memset(passwordE, 0, sizeof(passwordE));
 strncpy(passwordE, p.c_str(), 2*ADM_PASSWD_LEN);
 
-//printfd(__FILE__, "passwordE %s\n", passwordE);
-
 memset(pass, 0, sizeof(pass));
 
 if (passwordE[0] != 0)
@@ -1431,6 +1286,16 @@ else
     return -1;
     }
 
+if (cf.ReadInt("ChgService", &a, 0) == 0)
+    ac->priv.serviceChg = a;
+else
+    ac->priv.serviceChg = 0;
+
+if (cf.ReadInt("ChgCorp", &a, 0) == 0)
+    ac->priv.corpChg = a;
+else
+    ac->priv.corpChg = 0;
+
 return 0;
 }
 //-----------------------------------------------------------------------------
@@ -1614,6 +1479,11 @@ else
                 printfd(__FILE__, "FILES_STORE::RestoreTariff - invalid trafftype for tariff '%s'\n", tariffName.c_str());
                 return -1;
                 }
+
+if (conf.ReadString("Period", &str, "month") < 0)
+    td->tariffConf.period = TARIFF::MONTH;
+else
+    td->tariffConf.period = TARIFF::StringToPeriod(str);
 return 0;
 }
 //-----------------------------------------------------------------------------
@@ -1689,6 +1559,8 @@ string fileName = storeSettings.GetTariffsDir() + "/" + tariffName + ".tf";
             cf.WriteString("TraffType", "max");
             break;
         }
+
+    cf.WriteString("Period", TARIFF::PeriodToString(td.tariffConf.period));
     }
 
 return 0;
@@ -1888,10 +1760,6 @@ return 0;
 //-----------------------------------------------------------------------------
 int FILES_STORE::AddMessage(STG_MSG * msg, const string & login) const
 {
-//ðÒÏ×ÅÒÉÔØ ÅÓÔØ ÌÉ ÄÉÒÅËÔÏÒÉÑ ÄÌÑ ÓÏÏÂÝÅÎÉÊ. åÓÌÉ ÎÅÔ - ÓÏÚÄÁÔØ.
-//úÁÔÅÍ ÐÏÌÏÖÉÔØ ÓÏÏÂÝÅÎÉÅ Ó ÉÍÅÎÅÍ ÆÁÊÌÁ - ×ÒÅÍÅÎÎOÊ ÍÅÔËÏÊ. úÁÐÉÓÁÔØ ÔÕÄÁ
-//ÔÅËÓÔ É ÐÒÉÏÒÉÔÅÔ.
-
 string fn;
 string dn;
 struct timeval tv;
@@ -1932,10 +1800,6 @@ return EditMessage(*msg, login);
 //-----------------------------------------------------------------------------
 int FILES_STORE::EditMessage(const STG_MSG & msg, const string & login) const
 {
-//ðÒÏ×ÅÒÉÔØ ÅÓÌÔØ ÌÉ ÄÉÒÅËÔÏÒÉÑ ÄÌÑ ÓÏÏÂÝÅÎÉÊ. åÓÌÉ ÎÅÔ - ÓÏÚÄÁÔØ.
-//úÁÔÅÍ ÐÏÌÏÖÉÔØ ÓÏÏÂÝÅÎÉÅ Ó ÉÍÅÎÅÍ ÆÁÊÌÁ - ×ÒÅÍÅÎÎOÊ ÍÅÔËÏÊ. úÁÐÉÓÁÔØ ÔÕÄÁ
-//ÔÅËÓÔ É ÐÒÉÏÒÉÔÅÔ.
-
 string fileName;
 
 FILE * msgFile;
@@ -1978,6 +1842,7 @@ if (!res)
     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
     errorStr = string("fprintf failed. Message: '") + strerror(errno) + "'";
     printfd(__FILE__, "FILES_STORE::EditMessage - fprintf failed. Message: '%s'\n", strerror(errno));
+    fclose(msgFile);
     return -1;
     }
 
@@ -1989,7 +1854,7 @@ if (rename((fileName + ".new").c_str(), fileName.c_str()) < 0)
     {
     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
     errorStr = "Error moving dir from " + fileName + ".new to " + fileName;
-    printfd(__FILE__, "FILES_STORE::SaveTariff - rename failed. Message: '%s'\n", strerror(errno));
+    printfd(__FILE__, "FILES_STORE::EditMessage - rename failed. Message: '%s'\n", strerror(errno));
     return -1;
     }
 
@@ -2016,8 +1881,6 @@ int FILES_STORE::GetMessageHdrs(vector<STG_MSG_HDR> * hdrsList, const string & l
 {
 string dn(storeSettings.GetUsersDir() + "/" + login + "/messages/");
 
-//hdrsList->resize(messages.size());
-
 if (access(dn.c_str(), F_OK) != 0)
     {
     return 0;
@@ -2169,8 +2032,6 @@ return -1;
 //-----------------------------------------------------------------------------
 int GetFileList(vector<string> * fileList, const string & directory, mode_t mode, const string & ext)
 {
-// æÕÎËÃÉÑ ÐÒÏÓÍÁÔÒÉ×ÁÅÔ ÓÏÄÅÒÖÉÍÏÅ ÄÉÒÅËÔÏÒÉÉ
-
 DIR * d = opendir(directory.c_str());
 
 if (!d)