]> git.stg.codes - stg.git/blob - projects/stargazer/plugins/store/files/file_store.cpp
USER_STAT refactoring.
[stg.git] / projects / stargazer / plugins / store / files / file_store.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.67 $
23  $Date: 2010/10/07 19:53:11 $
24  $Author: faust $
25  */
26
27 #ifndef _GNU_SOURCE
28 #define _GNU_SOURCE
29 #endif
30
31 #include <pwd.h>
32 #include <grp.h>
33 #include <sys/stat.h>
34 #include <unistd.h>
35 #include <sys/time.h>
36 #include <fcntl.h>
37 #include <dirent.h>
38
39 #include <cstdio>
40 #include <ctime>
41 #include <cerrno>
42 #include <cstring>
43 #include <sstream>
44 #include <algorithm>
45
46 #include "stg/common.h"
47 #include "stg/user_ips.h"
48 #include "stg/user_conf.h"
49 #include "stg/user_stat.h"
50 #include "stg/const.h"
51 #include "stg/blowfish.h"
52 #include "stg/logger.h"
53 #include "stg/locker.h"
54 #include "stg/plugin_creator.h"
55 #include "file_store.h"
56
57 #define DELETED_USERS_DIR   "deleted_users"
58
59 #define adm_enc_passwd "cjeifY8m3"
60
61 int GetFileList(std::vector<std::string> * fileList, const std::string & directory, mode_t mode, const std::string & ext);
62
63 const int pt_mega = 1024 * 1024;
64 //-----------------------------------------------------------------------------
65 //-----------------------------------------------------------------------------
66 //-----------------------------------------------------------------------------
67 namespace
68 {
69 PLUGIN_CREATOR<FILES_STORE> fsc;
70 }
71
72 extern "C" STORE * GetStore();
73 //-----------------------------------------------------------------------------
74 //-----------------------------------------------------------------------------
75 //-----------------------------------------------------------------------------
76 STORE * GetStore()
77 {
78 return fsc.GetPlugin();
79 }
80 //-----------------------------------------------------------------------------
81 FILES_STORE_SETTINGS::FILES_STORE_SETTINGS()
82     : settings(NULL),
83       errorStr(),
84       workDir(),
85       usersDir(),
86       adminsDir(),
87       tariffsDir(),
88       statMode(0),
89       statUID(0),
90       statGID(0),
91       confMode(0),
92       confUID(0),
93       confGID(0),
94       userLogMode(0),
95       userLogUID(0),
96       userLogGID(0),
97       removeBak(true),
98       readBak(true)
99 {
100 }
101 //-----------------------------------------------------------------------------
102 int FILES_STORE_SETTINGS::ParseOwner(const std::vector<PARAM_VALUE> & moduleParams, const std::string & owner, uid_t * uid)
103 {
104 PARAM_VALUE pv;
105 pv.param = owner;
106 std::vector<PARAM_VALUE>::const_iterator pvi;
107 pvi = find(moduleParams.begin(), moduleParams.end(), pv);
108 if (pvi == moduleParams.end())
109     {
110     errorStr = "Parameter \'" + owner + "\' not found.";
111     printfd(__FILE__, "%s\n", errorStr.c_str());
112     return -1;
113     }
114 if (User2UID(pvi->value[0].c_str(), uid) < 0)
115     {
116     errorStr = "Parameter \'" + owner + "\': Unknown user \'" + pvi->value[0] + "\'";
117     printfd(__FILE__, "%s\n", errorStr.c_str());
118     return -1;
119     }
120 return 0;
121 }
122 //-----------------------------------------------------------------------------
123 int FILES_STORE_SETTINGS::ParseGroup(const std::vector<PARAM_VALUE> & moduleParams, const std::string & group, gid_t * gid)
124 {
125 PARAM_VALUE pv;
126 pv.param = group;
127 std::vector<PARAM_VALUE>::const_iterator pvi;
128 pvi = find(moduleParams.begin(), moduleParams.end(), pv);
129 if (pvi == moduleParams.end())
130     {
131     errorStr = "Parameter \'" + group + "\' not found.";
132     printfd(__FILE__, "%s\n", errorStr.c_str());
133     return -1;
134     }
135 if (Group2GID(pvi->value[0].c_str(), gid) < 0)
136     {
137     errorStr = "Parameter \'" + group + "\': Unknown group \'" + pvi->value[0] + "\'";
138     printfd(__FILE__, "%s\n", errorStr.c_str());
139     return -1;
140     }
141 return 0;
142 }
143 //-----------------------------------------------------------------------------
144 int FILES_STORE_SETTINGS::ParseYesNo(const std::string & value, bool * val)
145 {
146 if (0 == strcasecmp(value.c_str(), "yes"))
147     {
148     *val = true;
149     return 0;
150     }
151 if (0 == strcasecmp(value.c_str(), "no"))
152     {
153     *val = false;
154     return 0;
155     }
156
157 errorStr = "Incorrect value \'" + value + "\'.";
158 return -1;
159 }
160 //-----------------------------------------------------------------------------
161 int FILES_STORE_SETTINGS::ParseMode(const std::vector<PARAM_VALUE> & moduleParams, const std::string & modeStr, mode_t * mode)
162 {
163 PARAM_VALUE pv;
164 pv.param = modeStr;
165 std::vector<PARAM_VALUE>::const_iterator pvi;
166 pvi = find(moduleParams.begin(), moduleParams.end(), pv);
167 if (pvi == moduleParams.end())
168     {
169     errorStr = "Parameter \'" + modeStr + "\' not found.";
170     printfd(__FILE__, "%s\n", errorStr.c_str());
171     return -1;
172     }
173 if (Str2Mode(pvi->value[0].c_str(), mode) < 0)
174     {
175     errorStr = "Parameter \'" + modeStr + "\': Incorrect mode \'" + pvi->value[0] + "\'";
176     printfd(__FILE__, "%s\n", errorStr.c_str());
177     return -1;
178     }
179 return 0;
180 }
181 //-----------------------------------------------------------------------------
182 int FILES_STORE_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
183 {
184 if (ParseOwner(s.moduleParams, "StatOwner", &statUID) < 0)
185     return -1;
186 if (ParseGroup(s.moduleParams, "StatGroup", &statGID) < 0)
187     return -1;
188 if (ParseMode(s.moduleParams, "StatMode", &statMode) < 0)
189     return -1;
190
191 if (ParseOwner(s.moduleParams, "ConfOwner", &confUID) < 0)
192     return -1;
193 if (ParseGroup(s.moduleParams, "ConfGroup", &confGID) < 0)
194     return -1;
195 if (ParseMode(s.moduleParams, "ConfMode", &confMode) < 0)
196     return -1;
197
198 if (ParseOwner(s.moduleParams, "UserLogOwner", &userLogUID) < 0)
199     return -1;
200 if (ParseGroup(s.moduleParams, "UserLogGroup", &userLogGID) < 0)
201     return -1;
202 if (ParseMode(s.moduleParams, "UserLogMode", &userLogMode) < 0)
203     return -1;
204
205 std::vector<PARAM_VALUE>::const_iterator pvi;
206 PARAM_VALUE pv;
207 pv.param = "RemoveBak";
208 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
209 if (pvi == s.moduleParams.end())
210     {
211     removeBak = true;
212     }
213 else
214     {
215     if (ParseYesNo(pvi->value[0], &removeBak))
216         {
217         printfd(__FILE__, "Cannot parse parameter 'RemoveBak'\n");
218         return -1;
219         }
220     }
221
222 pv.param = "ReadBak";
223 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
224 if (pvi == s.moduleParams.end())
225     {
226     readBak = false;
227     }
228 else
229     {
230     if (ParseYesNo(pvi->value[0], &readBak))
231         {
232         printfd(__FILE__, "Cannot parse parameter 'ReadBak'\n");
233         return -1;
234         }
235     }
236
237 pv.param = "WorkDir";
238 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
239 if (pvi == s.moduleParams.end())
240     {
241     errorStr = "Parameter \'WorkDir\' not found.";
242     printfd(__FILE__, "Parameter 'WorkDir' not found\n");
243     return -1;
244     }
245
246 workDir = pvi->value[0];
247 if (workDir.size() && workDir[workDir.size() - 1] == '/')
248     {
249     workDir.resize(workDir.size() - 1);
250     }
251 usersDir = workDir + "/users/";
252 tariffsDir = workDir + "/tariffs/";
253 adminsDir = workDir + "/admins/";
254
255 return 0;
256 }
257 //-----------------------------------------------------------------------------
258 const std::string & FILES_STORE_SETTINGS::GetStrError() const
259 {
260 return errorStr;
261 }
262 //-----------------------------------------------------------------------------
263 int FILES_STORE_SETTINGS::User2UID(const char * user, uid_t * uid)
264 {
265 struct passwd * pw;
266 pw = getpwnam(user);
267 if (!pw)
268     {
269     errorStr = std::string("User \'") + std::string(user) + std::string("\' not found in system.");
270     printfd(__FILE__, "%s\n", errorStr.c_str());
271     return -1;
272     }
273
274 *uid = pw->pw_uid;
275 return 0;
276 }
277 //-----------------------------------------------------------------------------
278 int FILES_STORE_SETTINGS::Group2GID(const char * gr, gid_t * gid)
279 {
280 struct group * grp;
281 grp = getgrnam(gr);
282 if (!grp)
283     {
284     errorStr = std::string("Group \'") + std::string(gr) + std::string("\' not found in system.");
285     printfd(__FILE__, "%s\n", errorStr.c_str());
286     return -1;
287     }
288
289 *gid = grp->gr_gid;
290 return 0;
291 }
292 //-----------------------------------------------------------------------------
293 int FILES_STORE_SETTINGS::Str2Mode(const char * str, mode_t * mode)
294 {
295 char a;
296 char b;
297 char c;
298 if (strlen(str) > 3)
299     {
300     errorStr = std::string("Error parsing mode \'") + str + std::string("\'");
301     printfd(__FILE__, "%s\n", errorStr.c_str());
302     return -1;
303     }
304
305 for (int i = 0; i < 3; i++)
306     if (str[i] > '7' || str[i] < '0')
307         {
308         errorStr = std::string("Error parsing mode \'") + str + std::string("\'");
309         printfd(__FILE__, "%s\n", errorStr.c_str());
310         return -1;
311         }
312
313 a = str[0] - '0';
314 b = str[1] - '0';
315 c = str[2] - '0';
316
317 *mode = ((mode_t)c) + ((mode_t)b << 3) + ((mode_t)a << 6);
318
319 return 0;
320 }
321 //-----------------------------------------------------------------------------
322 mode_t FILES_STORE_SETTINGS::GetStatModeDir() const
323 {
324 mode_t mode = statMode;
325 if (statMode & S_IRUSR) mode |= S_IXUSR;
326 if (statMode & S_IRGRP) mode |= S_IXGRP;
327 if (statMode & S_IROTH) mode |= S_IXOTH;
328 return mode;
329 }
330 //-----------------------------------------------------------------------------
331 mode_t FILES_STORE_SETTINGS::GetConfModeDir() const
332 {
333 mode_t mode = confMode;
334 if (confMode & S_IRUSR) mode |= S_IXUSR;
335 if (confMode & S_IRGRP) mode |= S_IXGRP;
336 if (confMode & S_IROTH) mode |= S_IXOTH;
337 return mode;
338 }
339 //-----------------------------------------------------------------------------
340 //-----------------------------------------------------------------------------
341 //-----------------------------------------------------------------------------
342 FILES_STORE::FILES_STORE()
343     : errorStr(),
344       version("file_store v.1.04"),
345       storeSettings(),
346       settings(),
347       mutex(),
348       logger(GetPluginLogger(GetStgLogger(), "store_files"))
349 {
350 pthread_mutexattr_t attr;
351 pthread_mutexattr_init(&attr);
352 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
353 pthread_mutex_init(&mutex, &attr);
354 }
355 //-----------------------------------------------------------------------------
356 int FILES_STORE::ParseSettings()
357 {
358 int ret = storeSettings.ParseSettings(settings);
359 if (ret)
360     {
361     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
362     errorStr = storeSettings.GetStrError();
363     }
364 return ret;
365 }
366 //-----------------------------------------------------------------------------
367 int FILES_STORE::GetUsersList(std::vector<std::string> * userList) const
368 {
369 std::vector<std::string> files;
370
371 if (GetFileList(&files, storeSettings.GetUsersDir(), S_IFDIR, ""))
372     {
373     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
374     errorStr = "Failed to open '" + storeSettings.GetUsersDir() + "': " + std::string(strerror(errno));
375     return -1;
376     }
377
378 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
379
380 userList->swap(files);
381
382 return 0;
383 }
384 //-----------------------------------------------------------------------------
385 int FILES_STORE::GetAdminsList(std::vector<std::string> * adminList) const
386 {
387 std::vector<std::string> files;
388
389 if (GetFileList(&files, storeSettings.GetAdminsDir(), S_IFREG, ".adm"))
390     {
391     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
392     errorStr = "Failed to open '" + storeSettings.GetAdminsDir() + "': " + std::string(strerror(errno));
393     return -1;
394     }
395
396 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
397
398 adminList->swap(files);
399
400 return 0;
401 }
402 //-----------------------------------------------------------------------------
403 int FILES_STORE::GetTariffsList(std::vector<std::string> * tariffList) const
404 {
405 std::vector<std::string> files;
406
407 if (GetFileList(&files, storeSettings.GetTariffsDir(), S_IFREG, ".tf"))
408     {
409     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
410     errorStr = "Failed to open '" + storeSettings.GetTariffsDir() + "': " + std::string(strerror(errno));
411     return -1;
412     }
413
414 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
415
416 tariffList->swap(files);
417
418 return 0;
419 }
420 //-----------------------------------------------------------------------------
421 int FILES_STORE::RemoveDir(const char * path) const
422 {
423 DIR * d = opendir(path);
424
425 if (!d)
426     {
427     errorStr = "failed to open dir. Message: '";
428     errorStr += strerror(errno);
429     errorStr += "'";
430     printfd(__FILE__, "FILE_STORE::RemoveDir() - Failed to open dir '%s': '%s'\n", path, strerror(errno));
431     return -1;
432     }
433
434 dirent * entry;
435 while ((entry = readdir(d)))
436     {
437     if (!(strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..")))
438         continue;
439
440     std::string str = path;
441     str += "/" + std::string(entry->d_name);
442
443     struct stat st;
444     if (stat(str.c_str(), &st))
445         continue;
446
447     if ((st.st_mode & S_IFREG))
448         {
449         if (unlink(str.c_str()))
450             {
451             STG_LOCKER lock(&mutex, __FILE__, __LINE__);
452             errorStr = "unlink failed. Message: '";
453             errorStr += strerror(errno);
454             errorStr += "'";
455             printfd(__FILE__, "FILES_STORE::RemoveDir() - unlink failed. Message: '%s'\n", strerror(errno));
456             closedir(d);
457             return -1;
458             }
459         }
460
461     if (!(st.st_mode & S_IFDIR))
462         {
463         if (RemoveDir(str.c_str()))
464             {
465             closedir(d);
466             return -1;
467             }
468
469         }
470     }
471
472 closedir(d);
473
474 if (rmdir(path))
475     {
476     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
477     errorStr = "rmdir failed. Message: '";
478     errorStr += strerror(errno);
479     errorStr += "'";
480     printfd(__FILE__, "FILES_STORE::RemoveDir() - rmdir failed. Message: '%s'\n", strerror(errno));
481     return -1;
482     }
483
484 return 0;
485 }
486 //-----------------------------------------------------------------------------
487 int FILES_STORE::AddUser(const std::string & login) const
488 {
489 std::string fileName;
490
491 strprintf(&fileName, "%s%s", storeSettings.GetUsersDir().c_str(), login.c_str());
492
493 if (mkdir(fileName.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == -1)
494     {
495     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
496     errorStr = std::string("mkdir failed. Message: '") + strerror(errno) + "'";
497     printfd(__FILE__, "FILES_STORE::AddUser - mkdir failed. Message: '%s'\n", strerror(errno));
498     return -1;
499     }
500
501 strprintf(&fileName, "%s%s/conf", storeSettings.GetUsersDir().c_str(), login.c_str());
502 if (Touch(fileName))
503     {
504     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
505     errorStr = "Cannot create file \"" + fileName + "\'";
506     printfd(__FILE__, "FILES_STORE::AddUser - fopen failed. Message: '%s'\n", strerror(errno));
507     return -1;
508     }
509
510 strprintf(&fileName, "%s%s/stat", storeSettings.GetUsersDir().c_str(), login.c_str());
511 if (Touch(fileName))
512     {
513     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
514     errorStr = "Cannot create file \"" + fileName + "\'";
515     printfd(__FILE__, "FILES_STORE::AddUser - fopen failed. Message: '%s'\n", strerror(errno));
516     return -1;
517     }
518 return 0;
519 }
520 //-----------------------------------------------------------------------------
521 int FILES_STORE::DelUser(const std::string & login) const
522 {
523 std::string dirName;
524 std::string dirName1;
525
526 strprintf(&dirName, "%s/%s", storeSettings.GetWorkDir().c_str(), DELETED_USERS_DIR);
527 if (access(dirName.c_str(), F_OK) != 0)
528     {
529     if (mkdir(dirName.c_str(), 0700) != 0)
530         {
531         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
532         errorStr = "Directory '" + dirName + "' cannot be created.";
533         printfd(__FILE__, "FILES_STORE::DelUser - mkdir failed. Message: '%s'\n", strerror(errno));
534         return -1;
535         }
536     }
537
538 if (access(dirName.c_str(), F_OK) == 0)
539     {
540     strprintf(&dirName, "%s/%s/%s.%lu", storeSettings.GetWorkDir().c_str(), DELETED_USERS_DIR, login.c_str(), time(NULL));
541     strprintf(&dirName1, "%s/%s", storeSettings.GetUsersDir().c_str(), login.c_str());
542     if (rename(dirName1.c_str(), dirName.c_str()))
543         {
544         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
545         errorStr = "Error moving dir from " + dirName1 + " to " + dirName;
546         printfd(__FILE__, "FILES_STORE::DelUser - rename failed. Message: '%s'\n", strerror(errno));
547         return -1;
548         }
549     }
550 else
551     {
552     strprintf(&dirName, "%s/%s", storeSettings.GetUsersDir().c_str(), login.c_str());
553     if (RemoveDir(dirName.c_str()))
554         {
555         return -1;
556         }
557     }
558 return 0;
559 }
560 //-----------------------------------------------------------------------------
561 int FILES_STORE::RestoreUserConf(USER_CONF * conf, const std::string & login) const
562 {
563 std::string fileName;
564 fileName = storeSettings.GetUsersDir() + "/" + login + "/conf";
565 if (RestoreUserConf(conf, login, fileName))
566     {
567     if (!storeSettings.GetReadBak())
568         {
569         return -1;
570         }
571     return RestoreUserConf(conf, login, fileName + ".bak");
572     }
573 return 0;
574 }
575 //-----------------------------------------------------------------------------
576 int FILES_STORE::RestoreUserConf(USER_CONF * conf, const std::string & login, const std::string & fileName) const
577 {
578 CONFIGFILE cf(fileName);
579 int e = cf.Error();
580 std::string str;
581
582 if (e)
583     {
584     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
585     errorStr = "User \'" + login + "\' data not read.";
586     printfd(__FILE__, "FILES_STORE::RestoreUserConf - conf read failed for user '%s'\n", login.c_str());
587     return -1;
588     }
589
590 if (cf.ReadString("Password", &conf->password, "") < 0)
591     {
592     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
593     errorStr = "User \'" + login + "\' data not read. Parameter Password.";
594     printfd(__FILE__, "FILES_STORE::RestoreUserConf - password read failed for user '%s'\n", login.c_str());
595     return -1;
596     }
597 if (conf->password.empty())
598     {
599     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
600     errorStr = "User \'" + login + "\' password is blank.";
601     printfd(__FILE__, "FILES_STORE::RestoreUserConf - password is blank for user '%s'\n", login.c_str());
602     return -1;
603     }
604
605 if (cf.ReadString("tariff", &conf->tariffName, "") < 0)
606     {
607     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
608     errorStr = "User \'" + login + "\' data not read. Parameter Tariff.";
609     printfd(__FILE__, "FILES_STORE::RestoreUserConf - tariff read failed for user '%s'\n", login.c_str());
610     return -1;
611     }
612 if (conf->tariffName.empty())
613     {
614     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
615     errorStr = "User \'" + login + "\' tariff is blank.";
616     printfd(__FILE__, "FILES_STORE::RestoreUserConf - tariff is blank for user '%s'\n", login.c_str());
617     return -1;
618     }
619
620 std::string ipStr;
621 cf.ReadString("IP", &ipStr, "?");
622 USER_IPS ips;
623 try
624     {
625     ips = StrToIPS(ipStr);
626     }
627 catch (const std::string & s)
628     {
629     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
630     errorStr = "User \'" + login + "\' data not read. Parameter IP address. " + s;
631     printfd(__FILE__, "FILES_STORE::RestoreUserConf - ip read failed for user '%s'\n", login.c_str());
632     return -1;
633     }
634 conf->ips = ips;
635
636 if (cf.ReadInt("alwaysOnline", &conf->alwaysOnline, 0) != 0)
637     {
638     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
639     errorStr = "User \'" + login + "\' data not read. Parameter AlwaysOnline.";
640     printfd(__FILE__, "FILES_STORE::RestoreUserConf - alwaysonline read failed for user '%s'\n", login.c_str());
641     return -1;
642     }
643
644 if (cf.ReadInt("down", &conf->disabled, 0) != 0)
645     {
646     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
647     errorStr = "User \'" + login + "\' data not read. Parameter Down.";
648     printfd(__FILE__, "FILES_STORE::RestoreUserConf - down read failed for user '%s'\n", login.c_str());
649     return -1;
650     }
651
652 if (cf.ReadInt("passive", &conf->passive, 0) != 0)
653     {
654     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
655     errorStr = "User \'" + login + "\' data not read. Parameter Passive.";
656     printfd(__FILE__, "FILES_STORE::RestoreUserConf - passive read failed for user '%s'\n", login.c_str());
657     return -1;
658     }
659
660 cf.ReadInt("DisabledDetailStat", &conf->disabledDetailStat, 0);
661 cf.ReadTime("CreditExpire", &conf->creditExpire, 0);
662 cf.ReadString("TariffChange", &conf->nextTariff, "");
663 cf.ReadString("Group", &conf->group, "");
664 cf.ReadString("RealName", &conf->realName, "");
665 cf.ReadString("Address", &conf->address, "");
666 cf.ReadString("Phone", &conf->phone, "");
667 cf.ReadString("Note", &conf->note, "");
668 cf.ReadString("email", &conf->email, "");
669
670 char userdataName[12];
671 for (int i = 0; i < USERDATA_NUM; i++)
672     {
673     snprintf(userdataName, 12, "Userdata%d", i);
674     cf.ReadString(userdataName, &conf->userdata[i], "");
675     }
676
677 if (cf.ReadDouble("Credit", &conf->credit, 0) != 0)
678     {
679     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
680     errorStr = "User \'" + login + "\' data not read. Parameter Credit.";
681     printfd(__FILE__, "FILES_STORE::RestoreUserConf - credit read failed for user '%s'\n", login.c_str());
682     return -1;
683     }
684
685 return 0;
686 }
687 //-----------------------------------------------------------------------------
688 int FILES_STORE::RestoreUserStat(USER_STAT * stat, const std::string & login) const
689 {
690 std::string fileName;
691 fileName = storeSettings.GetUsersDir() + "/" + login + "/stat";
692
693 if (RestoreUserStat(stat, login, fileName))
694     {
695     if (!storeSettings.GetReadBak())
696         {
697         return -1;
698         }
699     return RestoreUserStat(stat, login, fileName + ".bak");
700     }
701 return 0;
702 }
703 //-----------------------------------------------------------------------------
704 int FILES_STORE::RestoreUserStat(USER_STAT * stat, const std::string & login, const std::string & fileName) const
705 {
706 CONFIGFILE cf(fileName);
707
708 int e = cf.Error();
709
710 if (e)
711     {
712     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
713     errorStr = "User \'" + login + "\' stat not read. Cannot open file " + fileName + ".";
714     printfd(__FILE__, "FILES_STORE::RestoreUserStat - stat read failed for user '%s'\n", login.c_str());
715     return -1;
716     }
717
718 char s[22];
719
720 for (int i = 0; i < DIR_NUM; i++)
721     {
722     uint64_t traff;
723     snprintf(s, 22, "D%d", i);
724     if (cf.ReadULongLongInt(s, &traff, 0) != 0)
725         {
726         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
727         errorStr = "User \'" + login + "\' stat not read. Parameter " + std::string(s);
728         printfd(__FILE__, "FILES_STORE::RestoreUserStat - download stat read failed for user '%s'\n", login.c_str());
729         return -1;
730         }
731     stat->monthDown[i] = traff;
732
733     snprintf(s, 22, "U%d", i);
734     if (cf.ReadULongLongInt(s, &traff, 0) != 0)
735         {
736         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
737         errorStr =   "User \'" + login + "\' stat not read. Parameter " + std::string(s);
738         printfd(__FILE__, "FILES_STORE::RestoreUserStat - upload stat read failed for user '%s'\n", login.c_str());
739         return -1;
740         }
741     stat->monthUp[i] = traff;
742     }
743
744 if (cf.ReadDouble("Cash", &stat->cash, 0) != 0)
745     {
746     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
747     errorStr =   "User \'" + login + "\' stat not read. Parameter Cash";
748     printfd(__FILE__, "FILES_STORE::RestoreUserStat - cash read failed for user '%s'\n", login.c_str());
749     return -1;
750     }
751
752 if (cf.ReadDouble("FreeMb", &stat->freeMb, 0) != 0)
753     {
754     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
755     errorStr =   "User \'" + login + "\' stat not read. Parameter FreeMb";
756     printfd(__FILE__, "FILES_STORE::RestoreUserStat - freemb read failed for user '%s'\n", login.c_str());
757     return -1;
758     }
759
760 if (cf.ReadTime("LastCashAddTime", &stat->lastCashAddTime, 0) != 0)
761     {
762     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
763     errorStr =   "User \'" + login + "\' stat not read. Parameter LastCashAddTime";
764     printfd(__FILE__, "FILES_STORE::RestoreUserStat - lastcashaddtime read failed for user '%s'\n", login.c_str());
765     return -1;
766     }
767
768 if (cf.ReadTime("PassiveTime", &stat->passiveTime, 0) != 0)
769     {
770     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
771     errorStr =   "User \'" + login + "\' stat not read. Parameter PassiveTime";
772     printfd(__FILE__, "FILES_STORE::RestoreUserStat - passivetime read failed for user '%s'\n", login.c_str());
773     return -1;
774     }
775
776 if (cf.ReadDouble("LastCashAdd", &stat->lastCashAdd, 0) != 0)
777     {
778     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
779     errorStr =   "User \'" + login + "\' stat not read. Parameter LastCashAdd";
780     printfd(__FILE__, "FILES_STORE::RestoreUserStat - lastcashadd read failed for user '%s'\n", login.c_str());
781     return -1;
782     }
783
784 if (cf.ReadTime("LastActivityTime", &stat->lastActivityTime, 0) != 0)
785     {
786     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
787     errorStr =   "User \'" + login + "\' stat not read. Parameter LastActivityTime";
788     printfd(__FILE__, "FILES_STORE::RestoreUserStat - lastactivitytime read failed for user '%s'\n", login.c_str());
789     return -1;
790     }
791
792 return 0;
793 }
794 //-----------------------------------------------------------------------------
795 int FILES_STORE::SaveUserConf(const USER_CONF & conf, const std::string & login) const
796 {
797 std::string fileName;
798 fileName = storeSettings.GetUsersDir() + "/" + login + "/conf";
799
800 CONFIGFILE cfstat(fileName, true);
801
802 int e = cfstat.Error();
803
804 if (e)
805     {
806     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
807     errorStr = std::string("User \'") + login + "\' conf not written\n";
808     printfd(__FILE__, "FILES_STORE::SaveUserConf - conf write failed for user '%s'\n", login.c_str());
809     return -1;
810     }
811
812 e = chmod(fileName.c_str(), storeSettings.GetConfMode());
813 e += chown(fileName.c_str(), storeSettings.GetConfUID(), storeSettings.GetConfGID());
814
815 if (e)
816     {
817     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
818     printfd(__FILE__, "FILES_STORE::SaveUserConf - chmod/chown failed for user '%s'. Error: '%s'\n", login.c_str(), strerror(errno));
819     }
820
821 cfstat.WriteString("Password",     conf.password);
822 cfstat.WriteInt   ("Passive",      conf.passive);
823 cfstat.WriteInt   ("Down",         conf.disabled);
824 cfstat.WriteInt("DisabledDetailStat", conf.disabledDetailStat);
825 cfstat.WriteInt   ("AlwaysOnline", conf.alwaysOnline);
826 cfstat.WriteString("Tariff",       conf.tariffName);
827 cfstat.WriteString("Address",      conf.address);
828 cfstat.WriteString("Phone",        conf.phone);
829 cfstat.WriteString("Email",        conf.email);
830 cfstat.WriteString("Note",         conf.note);
831 cfstat.WriteString("RealName",     conf.realName);
832 cfstat.WriteString("Group",        conf.group);
833 cfstat.WriteDouble("Credit",       conf.credit);
834 cfstat.WriteString("TariffChange", conf.nextTariff);
835
836 char userdataName[12];
837 for (int i = 0; i < USERDATA_NUM; i++)
838     {
839     snprintf(userdataName, 12, "Userdata%d", i);
840     cfstat.WriteString(userdataName, conf.userdata[i]);
841     }
842 cfstat.WriteInt("CreditExpire",    conf.creditExpire);
843
844 std::ostringstream ipStr;
845 ipStr << conf.ips;
846 cfstat.WriteString("IP", ipStr.str());
847
848 return 0;
849 }
850 //-----------------------------------------------------------------------------
851 int FILES_STORE::SaveUserStat(const USER_STAT & stat, const std::string & login) const
852 {
853 char s[22];
854 std::string fileName;
855 fileName = storeSettings.GetUsersDir() + "/" + login + "/stat";
856
857     {
858     CONFIGFILE cfstat(fileName, true);
859     int e = cfstat.Error();
860
861     if (e)
862         {
863         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
864         errorStr = std::string("User \'") + login + "\' stat not written\n";
865         printfd(__FILE__, "FILES_STORE::SaveUserStat - stat write failed for user '%s'\n", login.c_str());
866         return -1;
867         }
868
869     for (int i = 0; i < DIR_NUM; i++)
870         {
871         snprintf(s, 22, "D%d", i);
872         cfstat.WriteInt(s, stat.monthDown[i]);
873         snprintf(s, 22, "U%d", i);
874         cfstat.WriteInt(s, stat.monthUp[i]);
875         }
876
877     cfstat.WriteDouble("Cash", stat.cash);
878     cfstat.WriteDouble("FreeMb", stat.freeMb);
879     cfstat.WriteDouble("LastCashAdd", stat.lastCashAdd);
880     cfstat.WriteInt("LastCashAddTime", stat.lastCashAddTime);
881     cfstat.WriteInt("PassiveTime", stat.passiveTime);
882     cfstat.WriteInt("LastActivityTime", stat.lastActivityTime);
883     }
884
885 int e = chmod(fileName.c_str(), storeSettings.GetStatMode());
886 e += chown(fileName.c_str(), storeSettings.GetStatUID(), storeSettings.GetStatGID());
887
888 if (e)
889     {
890     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
891     printfd(__FILE__, "FILES_STORE::SaveUserStat - chmod/chown failed for user '%s'. Error: '%s'\n", login.c_str(), strerror(errno));
892     }
893
894 return 0;
895 }
896 //-----------------------------------------------------------------------------
897 int FILES_STORE::WriteLogString(const std::string & str, const std::string & login) const
898 {
899 FILE * f;
900 time_t tm = time(NULL);
901 std::string fileName;
902 fileName = storeSettings.GetUsersDir() + "/" + login + "/log";
903 f = fopen(fileName.c_str(), "at");
904
905 if (f)
906     {
907     fprintf(f, "%s", LogDate(tm));
908     fprintf(f, " -- ");
909     fprintf(f, "%s", str.c_str());
910     fprintf(f, "\n");
911     fclose(f);
912     }
913 else
914     {
915     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
916     errorStr = "Cannot open \'" + fileName + "\'";
917     printfd(__FILE__, "FILES_STORE::WriteLogString - log write failed for user '%s'\n", login.c_str());
918     return -1;
919     }
920
921 int e = chmod(fileName.c_str(), storeSettings.GetLogMode());
922 e += chown(fileName.c_str(), storeSettings.GetLogUID(), storeSettings.GetLogGID());
923
924 if (e)
925     {
926     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
927     printfd(__FILE__, "FILES_STORE::WriteLogString - chmod/chown failed for user '%s'. Error: '%s'\n", login.c_str(), strerror(errno));
928     }
929
930 return 0;
931 }
932 //-----------------------------------------------------------------------------
933 int FILES_STORE::WriteLog2String(const std::string & str, const std::string & login) const
934 {
935 FILE * f;
936 time_t tm = time(NULL);
937 std::string fileName;
938 fileName = storeSettings.GetUsersDir() + "/" + login + "/log2";
939 f = fopen(fileName.c_str(), "at");
940
941 if (f)
942     {
943     fprintf(f, "%s", LogDate(tm));
944     fprintf(f, " -- ");
945     fprintf(f, "%s", str.c_str());
946     fprintf(f, "\n");
947     fclose(f);
948     }
949 else
950     {
951     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
952     errorStr = "Cannot open \'" + fileName + "\'";
953     printfd(__FILE__, "FILES_STORE::WriteLogString - log write failed for user '%s'\n", login.c_str());
954     return -1;
955     }
956
957 int e = chmod(fileName.c_str(), storeSettings.GetLogMode());
958 e += chown(fileName.c_str(), storeSettings.GetLogUID(), storeSettings.GetLogGID());
959
960 if (e)
961     {
962     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
963     printfd(__FILE__, "FILES_STORE::WriteLogString - chmod/chown failed for user '%s'. Error: '%s'\n", login.c_str(), strerror(errno));
964     }
965
966 return 0;
967 }
968 //-----------------------------------------------------------------------------
969 int FILES_STORE::WriteUserChgLog(const std::string & login,
970                                  const std::string & admLogin,
971                                  uint32_t       admIP,
972                                  const std::string & paramName,
973                                  const std::string & oldValue,
974                                  const std::string & newValue,
975                                  const std::string & message) const
976 {
977 std::string userLogMsg = "Admin \'" + admLogin + "\', " + inet_ntostring(admIP) + ": \'"
978     + paramName + "\' parameter changed from \'" + oldValue +
979     "\' to \'" + newValue + "\'. " + message;
980
981 return WriteLogString(userLogMsg, login);
982 }
983 //-----------------------------------------------------------------------------
984 int FILES_STORE::WriteUserConnect(const std::string & login, uint32_t ip) const
985 {
986 std::string logStr = "Connect, " + inet_ntostring(ip);
987 if (WriteLogString(logStr, login))
988     return -1;
989 return WriteLog2String(logStr, login);
990 }
991 //-----------------------------------------------------------------------------
992 int FILES_STORE::WriteUserDisconnect(const std::string & login,
993                                      const DIR_TRAFF & monthUp,
994                                      const DIR_TRAFF & monthDown,
995                                      const DIR_TRAFF & sessionUp,
996                                      const DIR_TRAFF & sessionDown,
997                                      double cash,
998                                      double freeMb,
999                                      const std::string & reason) const
1000 {
1001 std::ostringstream logStr;
1002 logStr << "Disconnect, "
1003        << " session upload: \'"
1004        << sessionUp
1005        << "\' session download: \'"
1006        << sessionDown
1007        << "\' month upload: \'"
1008        << monthUp
1009        << "\' month download: \'"
1010        << monthDown
1011        << "\' cash: \'"
1012        << cash
1013        << "\'";
1014
1015 if (WriteLogString(logStr.str(), login))
1016     return -1;
1017
1018 logStr << " freeMb: \'"
1019        << freeMb
1020        << "\'"
1021        << " reason: \'"
1022        << reason
1023        << "\'";
1024
1025 return WriteLog2String(logStr.str(), login);
1026 }
1027 //-----------------------------------------------------------------------------
1028 int FILES_STORE::SaveMonthStat(const USER_STAT & stat, int month, int year, const std::string & login) const
1029 {
1030 // Classic stats
1031 std::string stat1;
1032 strprintf(&stat1,"%s/%s/stat.%d.%02d",
1033         storeSettings.GetUsersDir().c_str(), login.c_str(), year + 1900, month + 1);
1034
1035 CONFIGFILE s(stat1, true);
1036
1037 if (s.Error())
1038     {
1039     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1040     errorStr = "Cannot create file '" + stat1 + "'";
1041     printfd(__FILE__, "FILES_STORE::SaveMonthStat - month stat write failed for user '%s'\n", login.c_str());
1042     return -1;
1043     }
1044
1045 // New stats
1046 std::string stat2;
1047 strprintf(&stat2,"%s/%s/stat2.%d.%02d",
1048         storeSettings.GetUsersDir().c_str(), login.c_str(), year + 1900, month + 1);
1049
1050 CONFIGFILE s2(stat2, true);
1051
1052 if (s2.Error())
1053     {
1054     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1055     errorStr = "Cannot create file '" + stat2 + "'";
1056     printfd(__FILE__, "FILES_STORE::SaveMonthStat - month stat write failed for user '%s'\n", login.c_str());
1057     return -1;
1058     }
1059
1060 for (size_t i = 0; i < DIR_NUM; i++)
1061     {
1062     char dirName[3];
1063     snprintf(dirName, 3, "U%llu", (unsigned long long)i);
1064     s.WriteInt(dirName, stat.monthUp[i]); // Classic
1065     s2.WriteInt(dirName, stat.monthUp[i]); // New
1066     snprintf(dirName, 3, "D%llu", (unsigned long long)i);
1067     s.WriteInt(dirName, stat.monthDown[i]); // Classic
1068     s2.WriteInt(dirName, stat.monthDown[i]); // New
1069     }
1070
1071 // Classic
1072 s.WriteDouble("cash", stat.cash);
1073
1074 // New
1075 s2.WriteDouble("Cash", stat.cash);
1076 s2.WriteDouble("FreeMb", stat.freeMb);
1077 s2.WriteDouble("LastCashAdd", stat.lastCashAdd);
1078 s2.WriteInt("LastCashAddTime", stat.lastCashAddTime);
1079 s2.WriteInt("PassiveTime", stat.passiveTime);
1080 s2.WriteInt("LastActivityTime", stat.lastActivityTime);
1081
1082 return 0;
1083 }
1084 //-----------------------------------------------------------------------------*/
1085 int FILES_STORE::AddAdmin(const std::string & login) const
1086 {
1087 std::string fileName;
1088 strprintf(&fileName, "%s/%s.adm", storeSettings.GetAdminsDir().c_str(), login.c_str());
1089
1090 if (Touch(fileName))
1091     {
1092     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1093     errorStr = "Cannot create file " + fileName;
1094     printfd(__FILE__, "FILES_STORE::AddAdmin - failed to add admin '%s'\n", login.c_str());
1095     return -1;
1096     }
1097
1098 return 0;
1099 }
1100 //-----------------------------------------------------------------------------*/
1101 int FILES_STORE::DelAdmin(const std::string & login) const
1102 {
1103 std::string fileName;
1104 strprintf(&fileName, "%s/%s.adm", storeSettings.GetAdminsDir().c_str(), login.c_str());
1105 if (unlink(fileName.c_str()))
1106     {
1107     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1108     errorStr = "unlink failed. Message: '";
1109     errorStr += strerror(errno);
1110     errorStr += "'";
1111     printfd(__FILE__, "FILES_STORE::DelAdmin - unlink failed. Message: '%s'\n", strerror(errno));
1112     }
1113 return 0;
1114 }
1115 //-----------------------------------------------------------------------------*/
1116 int FILES_STORE::SaveAdmin(const ADMIN_CONF & ac) const
1117 {
1118 char passwordE[2 * ADM_PASSWD_LEN + 2];
1119 char pass[ADM_PASSWD_LEN + 1];
1120 char adminPass[ADM_PASSWD_LEN + 1];
1121
1122 std::string fileName;
1123
1124 strprintf(&fileName, "%s/%s.adm", storeSettings.GetAdminsDir().c_str(), ac.login.c_str());
1125
1126     {
1127     CONFIGFILE cf(fileName, true);
1128
1129     int e = cf.Error();
1130
1131     if (e)
1132         {
1133         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1134         errorStr = "Cannot write admin " + ac.login + ". " + fileName;
1135         printfd(__FILE__, "FILES_STORE::SaveAdmin - failed to save admin '%s'\n", ac.login.c_str());
1136         return -1;
1137         }
1138
1139     memset(pass, 0, sizeof(pass));
1140     memset(adminPass, 0, sizeof(adminPass));
1141
1142     BLOWFISH_CTX ctx;
1143     EnDecodeInit(adm_enc_passwd, strlen(adm_enc_passwd), &ctx);
1144
1145     strncpy(adminPass, ac.password.c_str(), ADM_PASSWD_LEN);
1146     adminPass[ADM_PASSWD_LEN - 1] = 0;
1147
1148     for (int i = 0; i < ADM_PASSWD_LEN/8; i++)
1149         {
1150         EncodeString(pass + 8*i, adminPass + 8*i, &ctx);
1151         }
1152
1153     pass[ADM_PASSWD_LEN - 1] = 0;
1154     Encode12(passwordE, pass, ADM_PASSWD_LEN);
1155
1156     cf.WriteString("password", passwordE);
1157     cf.WriteInt("ChgConf",     ac.priv.userConf);
1158     cf.WriteInt("ChgPassword", ac.priv.userPasswd);
1159     cf.WriteInt("ChgStat",     ac.priv.userStat);
1160     cf.WriteInt("ChgCash",     ac.priv.userCash);
1161     cf.WriteInt("UsrAddDel",   ac.priv.userAddDel);
1162     cf.WriteInt("ChgTariff",   ac.priv.tariffChg);
1163     cf.WriteInt("ChgAdmin",    ac.priv.adminChg);
1164     cf.WriteInt("ChgService",  ac.priv.serviceChg);
1165     cf.WriteInt("ChgCorp",     ac.priv.corpChg);
1166     }
1167
1168 return 0;
1169 }
1170 //-----------------------------------------------------------------------------
1171 int FILES_STORE::RestoreAdmin(ADMIN_CONF * ac, const std::string & login) const
1172 {
1173 std::string fileName;
1174 strprintf(&fileName, "%s/%s.adm", storeSettings.GetAdminsDir().c_str(), login.c_str());
1175 CONFIGFILE cf(fileName);
1176 char pass[ADM_PASSWD_LEN + 1];
1177 char password[ADM_PASSWD_LEN + 1];
1178 char passwordE[2 * ADM_PASSWD_LEN + 2];
1179 BLOWFISH_CTX ctx;
1180
1181 std::string p;
1182
1183 if (cf.Error())
1184     {
1185     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1186     errorStr = "Cannot open " + fileName;
1187     printfd(__FILE__, "FILES_STORE::RestoreAdmin - failed to restore admin '%s'\n", ac->login.c_str());
1188     return -1;
1189     }
1190
1191 if (cf.ReadString("password", &p, "*"))
1192     {
1193     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1194     errorStr = "Error in parameter password";
1195     printfd(__FILE__, "FILES_STORE::RestoreAdmin - password read failed for admin '%s'\n", ac->login.c_str());
1196     return -1;
1197     }
1198
1199 memset(passwordE, 0, sizeof(passwordE));
1200 strncpy(passwordE, p.c_str(), 2*ADM_PASSWD_LEN);
1201
1202 memset(pass, 0, sizeof(pass));
1203
1204 if (passwordE[0] != 0)
1205     {
1206     Decode21(pass, passwordE);
1207     EnDecodeInit(adm_enc_passwd, strlen(adm_enc_passwd), &ctx);
1208
1209     for (int i = 0; i < ADM_PASSWD_LEN/8; i++)
1210         {
1211         DecodeString(password + 8*i, pass + 8*i, &ctx);
1212         }
1213     }
1214 else
1215     {
1216     password[0] = 0;
1217     }
1218
1219 ac->password = password;
1220
1221 uint16_t a;
1222
1223 if (cf.ReadUShortInt("ChgConf", &a, 0) == 0)
1224     ac->priv.userConf = a;
1225 else
1226     {
1227     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1228     errorStr = "Error in parameter ChgConf";
1229     printfd(__FILE__, "FILES_STORE::RestoreAdmin - chgconf read failed for admin '%s'\n", ac->login.c_str());
1230     return -1;
1231     }
1232
1233 if (cf.ReadUShortInt("ChgPassword", &a, 0) == 0)
1234     ac->priv.userPasswd = a;
1235 else
1236     {
1237     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1238     errorStr = "Error in parameter ChgPassword";
1239     printfd(__FILE__, "FILES_STORE::RestoreAdmin - chgpassword read failed for admin '%s'\n", ac->login.c_str());
1240     return -1;
1241     }
1242
1243 if (cf.ReadUShortInt("ChgStat", &a, 0) == 0)
1244     ac->priv.userStat = a;
1245 else
1246     {
1247     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1248     errorStr = "Error in parameter ChgStat";
1249     printfd(__FILE__, "FILES_STORE::RestoreAdmin - chgstat read failed for admin '%s'\n", ac->login.c_str());
1250     return -1;
1251     }
1252
1253 if (cf.ReadUShortInt("ChgCash", &a, 0) == 0)
1254     ac->priv.userCash = a;
1255 else
1256     {
1257     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1258     errorStr = "Error in parameter ChgCash";
1259     printfd(__FILE__, "FILES_STORE::RestoreAdmin - chgcash read failed for admin '%s'\n", ac->login.c_str());
1260     return -1;
1261     }
1262
1263 if (cf.ReadUShortInt("UsrAddDel", &a, 0) == 0)
1264     ac->priv.userAddDel = a;
1265 else
1266     {
1267     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1268     errorStr = "Error in parameter UsrAddDel";
1269     printfd(__FILE__, "FILES_STORE::RestoreAdmin - usradddel read failed for admin '%s'\n", ac->login.c_str());
1270     return -1;
1271     }
1272
1273 if (cf.ReadUShortInt("ChgAdmin", &a, 0) == 0)
1274     ac->priv.adminChg = a;
1275 else
1276     {
1277     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1278     errorStr = "Error in parameter ChgAdmin";
1279     printfd(__FILE__, "FILES_STORE::RestoreAdmin - chgadmin read failed for admin '%s'\n", ac->login.c_str());
1280     return -1;
1281     }
1282
1283 if (cf.ReadUShortInt("ChgTariff", &a, 0) == 0)
1284     ac->priv.tariffChg = a;
1285 else
1286     {
1287     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1288     errorStr = "Error in parameter ChgTariff";
1289     printfd(__FILE__, "FILES_STORE::RestoreAdmin - chgtariff read failed for admin '%s'\n", ac->login.c_str());
1290     return -1;
1291     }
1292
1293 if (cf.ReadUShortInt("ChgService", &a, 0) == 0)
1294     ac->priv.serviceChg = a;
1295 else
1296     ac->priv.serviceChg = 0;
1297
1298 if (cf.ReadUShortInt("ChgCorp", &a, 0) == 0)
1299     ac->priv.corpChg = a;
1300 else
1301     ac->priv.corpChg = 0;
1302
1303 return 0;
1304 }
1305 //-----------------------------------------------------------------------------
1306 int FILES_STORE::AddTariff(const std::string & name) const
1307 {
1308 std::string fileName;
1309 strprintf(&fileName, "%s/%s.tf", storeSettings.GetTariffsDir().c_str(), name.c_str());
1310 if (Touch(fileName))
1311     {
1312     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1313     errorStr = "Cannot create file " + fileName;
1314     printfd(__FILE__, "FILES_STORE::AddTariff - failed to add tariff '%s'\n", name.c_str());
1315     return -1;
1316     }
1317 return 0;
1318 }
1319 //-----------------------------------------------------------------------------
1320 int FILES_STORE::DelTariff(const std::string & name) const
1321 {
1322 std::string fileName;
1323 strprintf(&fileName, "%s/%s.tf", storeSettings.GetTariffsDir().c_str(), name.c_str());
1324 if (unlink(fileName.c_str()))
1325     {
1326     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1327     errorStr = "unlink failed. Message: '";
1328     errorStr += strerror(errno);
1329     errorStr += "'";
1330     printfd(__FILE__, "FILES_STORE::DelTariff - unlink failed. Message: '%s'\n", strerror(errno));
1331     }
1332 return 0;
1333 }
1334 //-----------------------------------------------------------------------------
1335 int FILES_STORE::RestoreTariff(TARIFF_DATA * td, const std::string & tariffName) const
1336 {
1337 std::string fileName = storeSettings.GetTariffsDir() + "/" + tariffName + ".tf";
1338 CONFIGFILE conf(fileName);
1339 std::string str;
1340 td->tariffConf.name = tariffName;
1341
1342 if (conf.Error() != 0)
1343     {
1344     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1345     errorStr = "Cannot read file " + fileName;
1346     printfd(__FILE__, "FILES_STORE::RestoreTariff - failed to read tariff '%s'\n", tariffName.c_str());
1347     return -1;
1348     }
1349
1350 std::string param;
1351 for (int i = 0; i<DIR_NUM; i++)
1352     {
1353     strprintf(&param, "Time%d", i);
1354     if (conf.ReadString(param, &str, "00:00-00:00") < 0)
1355         {
1356         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1357         errorStr = "Cannot read tariff " + tariffName + ". Parameter " + param;
1358         printfd(__FILE__, "FILES_STORE::RestoreTariff - time%d read failed for tariff '%s'\n", i, tariffName.c_str());
1359         return -1;
1360         }
1361
1362     ParseTariffTimeStr(str.c_str(),
1363                        td->dirPrice[i].hDay,
1364                        td->dirPrice[i].mDay,
1365                        td->dirPrice[i].hNight,
1366                        td->dirPrice[i].mNight);
1367
1368     strprintf(&param, "PriceDayA%d", i);
1369     if (conf.ReadDouble(param, &td->dirPrice[i].priceDayA, 0.0) < 0)
1370         {
1371         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1372         errorStr = "Cannot read tariff " + tariffName + ". Parameter " + param;
1373         printfd(__FILE__, "FILES_STORE::RestoreTariff - pricedaya read failed for tariff '%s'\n", tariffName.c_str());
1374         return -1;
1375         }
1376     td->dirPrice[i].priceDayA /= (1024*1024);
1377
1378     strprintf(&param, "PriceDayB%d", i);
1379     if (conf.ReadDouble(param, &td->dirPrice[i].priceDayB, 0.0) < 0)
1380         {
1381         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1382         errorStr = "Cannot read tariff " + tariffName + ". Parameter " + param;
1383         printfd(__FILE__, "FILES_STORE::RestoreTariff - pricedayb read failed for tariff '%s'\n", tariffName.c_str());
1384         return -1;
1385         }
1386     td->dirPrice[i].priceDayB /= (1024*1024);
1387
1388     strprintf(&param, "PriceNightA%d", i);
1389     if (conf.ReadDouble(param, &td->dirPrice[i].priceNightA, 0.0) < 0)
1390         {
1391         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1392         errorStr = "Cannot read tariff " + tariffName + ". Parameter " + param;
1393         printfd(__FILE__, "FILES_STORE::RestoreTariff - pricenighta read failed for tariff '%s'\n", tariffName.c_str());
1394         return -1;
1395         }
1396     td->dirPrice[i].priceNightA /= (1024*1024);
1397
1398     strprintf(&param, "PriceNightB%d", i);
1399     if (conf.ReadDouble(param, &td->dirPrice[i].priceNightB, 0.0) < 0)
1400         {
1401         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1402         errorStr = "Cannot read tariff " + tariffName + ". Parameter " + param;
1403         printfd(__FILE__, "FILES_STORE::RestoreTariff - pricenightb read failed for tariff '%s'\n", tariffName.c_str());
1404         return -1;
1405         }
1406     td->dirPrice[i].priceNightB /= (1024*1024);
1407
1408     strprintf(&param, "Threshold%d", i);
1409     if (conf.ReadInt(param, &td->dirPrice[i].threshold, 0) < 0)
1410         {
1411         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1412         errorStr = "Cannot read tariff " + tariffName + ". Parameter " + param;
1413         printfd(__FILE__, "FILES_STORE::RestoreTariff - threshold read failed for tariff '%s'\n", tariffName.c_str());
1414         return -1;
1415         }
1416
1417     strprintf(&param, "SinglePrice%d", i);
1418     if (conf.ReadInt(param, &td->dirPrice[i].singlePrice, 0) < 0)
1419         {
1420         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1421         errorStr = "Cannot read tariff " + tariffName + ". Parameter " + param;
1422         printfd(__FILE__, "FILES_STORE::RestoreTariff - singleprice read failed for tariff '%s'\n", tariffName.c_str());
1423         return -1;
1424         }
1425
1426     strprintf(&param, "NoDiscount%d", i);
1427     if (conf.ReadInt(param, &td->dirPrice[i].noDiscount, 0) < 0)
1428         {
1429         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1430         errorStr = "Cannot read tariff " + tariffName + ". Parameter " + param;
1431         printfd(__FILE__, "FILES_STORE::RestoreTariff - nodiscount read failed for tariff '%s'\n", tariffName.c_str());
1432         return -1;
1433         }
1434     }
1435
1436 if (conf.ReadDouble("Fee", &td->tariffConf.fee, 0) < 0)
1437     {
1438     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1439     errorStr = "Cannot read tariff " + tariffName + ". Parameter Fee";
1440     printfd(__FILE__, "FILES_STORE::RestoreTariff - fee read failed for tariff '%s'\n", tariffName.c_str());
1441     return -1;
1442     }
1443
1444 if (conf.ReadDouble("Free", &td->tariffConf.free, 0) < 0)
1445     {
1446     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1447     errorStr = "Cannot read tariff " + tariffName + ". Parameter Free";
1448     printfd(__FILE__, "FILES_STORE::RestoreTariff - free read failed for tariff '%s'\n", tariffName.c_str());
1449     return -1;
1450     }
1451
1452 if (conf.ReadDouble("PassiveCost", &td->tariffConf.passiveCost, 0) < 0)
1453     {
1454     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1455     errorStr = "Cannot read tariff " + tariffName + ". Parameter PassiveCost";
1456     printfd(__FILE__, "FILES_STORE::RestoreTariff - passivecost read failed for tariff '%s'\n", tariffName.c_str());
1457     return -1;
1458     }
1459
1460 if (conf.ReadString("TraffType", &str, "") < 0)
1461     {
1462     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1463     errorStr = "Cannot read tariff " + tariffName + ". Parameter TraffType";
1464     printfd(__FILE__, "FILES_STORE::RestoreTariff - trafftype read failed for tariff '%s'\n", tariffName.c_str());
1465     return -1;
1466     }
1467
1468 if (!strcasecmp(str.c_str(), "up"))
1469     td->tariffConf.traffType = TRAFF_UP;
1470 else
1471     if (!strcasecmp(str.c_str(), "down"))
1472         td->tariffConf.traffType = TRAFF_DOWN;
1473     else
1474         if (!strcasecmp(str.c_str(), "up+down"))
1475             td->tariffConf.traffType = TRAFF_UP_DOWN;
1476         else
1477             if (!strcasecmp(str.c_str(), "max"))
1478                 td->tariffConf.traffType = TRAFF_MAX;
1479             else
1480                 {
1481                 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1482                 errorStr = "Cannot read tariff " + tariffName + ". Parameter TraffType incorrect";
1483                 printfd(__FILE__, "FILES_STORE::RestoreTariff - invalid trafftype for tariff '%s'\n", tariffName.c_str());
1484                 return -1;
1485                 }
1486 return 0;
1487 }
1488 //-----------------------------------------------------------------------------
1489 int FILES_STORE::SaveTariff(const TARIFF_DATA & td, const std::string & tariffName) const
1490 {
1491 std::string fileName = storeSettings.GetTariffsDir() + "/" + tariffName + ".tf";
1492
1493     {
1494     CONFIGFILE cf(fileName, true);
1495
1496     int e = cf.Error();
1497
1498     if (e)
1499         {
1500         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1501         errorStr = "Error writing tariff " + tariffName;
1502         printfd(__FILE__, "FILES_STORE::RestoreTariff - failed to save tariff '%s'\n", tariffName.c_str());
1503         return e;
1504         }
1505
1506     std::string param;
1507     for (int i = 0; i < DIR_NUM; i++)
1508         {
1509         strprintf(&param, "PriceDayA%d", i);
1510         cf.WriteDouble(param, td.dirPrice[i].priceDayA * pt_mega);
1511
1512         strprintf(&param, "PriceDayB%d", i);
1513         cf.WriteDouble(param, td.dirPrice[i].priceDayB * pt_mega);
1514
1515         strprintf(&param, "PriceNightA%d", i);
1516         cf.WriteDouble(param, td.dirPrice[i].priceNightA * pt_mega);
1517
1518         strprintf(&param, "PriceNightB%d", i);
1519         cf.WriteDouble(param, td.dirPrice[i].priceNightB * pt_mega);
1520
1521         strprintf(&param, "Threshold%d", i);
1522         cf.WriteInt(param, td.dirPrice[i].threshold);
1523
1524         std::string s;
1525         strprintf(&param, "Time%d", i);
1526
1527         strprintf(&s, "%0d:%0d-%0d:%0d",
1528                 td.dirPrice[i].hDay,
1529                 td.dirPrice[i].mDay,
1530                 td.dirPrice[i].hNight,
1531                 td.dirPrice[i].mNight);
1532
1533         cf.WriteString(param, s);
1534
1535         strprintf(&param, "NoDiscount%d", i);
1536         cf.WriteInt(param, td.dirPrice[i].noDiscount);
1537
1538         strprintf(&param, "SinglePrice%d", i);
1539         cf.WriteInt(param, td.dirPrice[i].singlePrice);
1540         }
1541
1542     cf.WriteDouble("PassiveCost", td.tariffConf.passiveCost);
1543     cf.WriteDouble("Fee", td.tariffConf.fee);
1544     cf.WriteDouble("Free", td.tariffConf.free);
1545
1546     switch (td.tariffConf.traffType)
1547         {
1548         case TRAFF_UP:
1549             cf.WriteString("TraffType", "up");
1550             break;
1551         case TRAFF_DOWN:
1552             cf.WriteString("TraffType", "down");
1553             break;
1554         case TRAFF_UP_DOWN:
1555             cf.WriteString("TraffType", "up+down");
1556             break;
1557         case TRAFF_MAX:
1558             cf.WriteString("TraffType", "max");
1559             break;
1560         }
1561     }
1562
1563 return 0;
1564 }
1565 //-----------------------------------------------------------------------------
1566 int FILES_STORE::WriteDetailedStat(const std::map<IP_DIR_PAIR, STAT_NODE> & statTree,
1567                                    time_t lastStat,
1568                                    const std::string & login) const
1569 {
1570 char fn[FN_STR_LEN];
1571 char dn[FN_STR_LEN];
1572 FILE * statFile;
1573 time_t t;
1574 tm * lt;
1575
1576 t = time(NULL);
1577
1578 snprintf(dn, FN_STR_LEN, "%s/%s/detail_stat", storeSettings.GetUsersDir().c_str(), login.c_str());
1579 if (access(dn, F_OK) != 0)
1580     {
1581     if (mkdir(dn, 0700) != 0)
1582         {
1583         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1584         errorStr = "Directory \'" + std::string(dn) + "\' cannot be created.";
1585         printfd(__FILE__, "FILES_STORE::WriteDetailStat - mkdir failed. Message: '%s'\n", strerror(errno));
1586         return -1;
1587         }
1588     }
1589
1590 int e = chown(dn, storeSettings.GetStatUID(), storeSettings.GetStatGID());
1591 e += chmod(dn, storeSettings.GetStatModeDir());
1592
1593 if (e)
1594     {
1595     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1596     printfd(__FILE__, "FILES_STORE::WriteDetailStat - chmod/chown failed for user '%s'. Error: '%s'\n", login.c_str(), strerror(errno));
1597     }
1598
1599 lt = localtime(&t);
1600
1601 if (lt->tm_hour == 0 && lt->tm_min <= 5)
1602     {
1603     t -= 3600 * 24;
1604     lt = localtime(&t);
1605     }
1606
1607 snprintf(dn, FN_STR_LEN, "%s/%s/detail_stat/%d",
1608          storeSettings.GetUsersDir().c_str(),
1609          login.c_str(),
1610          lt->tm_year+1900);
1611
1612 if (access(dn, F_OK) != 0)
1613     {
1614     if (mkdir(dn, 0700) != 0)
1615         {
1616         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1617         errorStr = "Directory \'" + std::string(dn) + "\' cannot be created.";
1618         printfd(__FILE__, "FILES_STORE::WriteDetailStat - mkdir failed. Message: '%s'\n", strerror(errno));
1619         return -1;
1620         }
1621     }
1622
1623 e = chown(dn, storeSettings.GetStatUID(), storeSettings.GetStatGID());
1624 e += chmod(dn, storeSettings.GetStatModeDir());
1625
1626 if (e)
1627     {
1628     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1629     printfd(__FILE__, "FILES_STORE::WriteDetailStat - chmod/chown failed for user '%s'. Error: '%s'\n", login.c_str(), strerror(errno));
1630     }
1631
1632 snprintf(dn, FN_STR_LEN, "%s/%s/detail_stat/%d/%s%d", 
1633          storeSettings.GetUsersDir().c_str(),
1634          login.c_str(),
1635          lt->tm_year+1900,
1636          lt->tm_mon+1 < 10 ? "0" : "",
1637          lt->tm_mon+1);
1638 if (access(dn, F_OK) != 0)
1639     {
1640     if (mkdir(dn, 0700) != 0)
1641         {
1642         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1643         errorStr = "Directory \'" + std::string(dn) + "\' cannot be created.";
1644         printfd(__FILE__, "FILES_STORE::WriteDetailStat - mkdir failed. Message: '%s'\n", strerror(errno));
1645         return -1;
1646         }
1647     }
1648
1649 e = chown(dn, storeSettings.GetStatUID(), storeSettings.GetStatGID());
1650 e += chmod(dn, storeSettings.GetStatModeDir());
1651
1652 if (e)
1653     {
1654     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1655     printfd(__FILE__, "FILES_STORE::WriteDetailStat - chmod/chown failed for user '%s'. Error: '%s'\n", login.c_str(), strerror(errno));
1656     }
1657
1658 snprintf(fn, FN_STR_LEN, "%s/%s%d", dn, lt->tm_mday < 10 ? "0" : "", lt->tm_mday);
1659
1660 statFile = fopen (fn, "at");
1661
1662 if (!statFile)
1663     {
1664     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1665     errorStr = "File \'" + std::string(fn) + "\' cannot be written.";
1666     printfd(__FILE__, "FILES_STORE::WriteDetailStat - fopen failed. Message: '%s'\n", strerror(errno));
1667     return -1;
1668     }
1669
1670 struct tm * lt1;
1671 struct tm * lt2;
1672
1673 lt1 = localtime(&lastStat);
1674
1675 int h1, m1, s1;
1676 int h2, m2, s2;
1677
1678 h1 = lt1->tm_hour;
1679 m1 = lt1->tm_min;
1680 s1 = lt1->tm_sec;
1681
1682 lt2 = localtime(&t);
1683
1684 h2 = lt2->tm_hour;
1685 m2 = lt2->tm_min;
1686 s2 = lt2->tm_sec;
1687
1688 if (fprintf(statFile, "-> %02d.%02d.%02d - %02d.%02d.%02d\n",
1689             h1, m1, s1, h2, m2, s2) < 0)
1690     {
1691     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1692     errorStr = std::string("fprint failed. Message: '") + strerror(errno) + "'";
1693     printfd(__FILE__, "FILES_STORE::WriteDetailStat - fprintf failed. Message: '%s'\n", strerror(errno));
1694     fclose(statFile);
1695     return -1;
1696     }
1697
1698 std::map<IP_DIR_PAIR, STAT_NODE>::const_iterator stIter;
1699 stIter = statTree.begin();
1700
1701 while (stIter != statTree.end())
1702     {
1703     std::string u, d;
1704     x2str(stIter->second.up, u);
1705     x2str(stIter->second.down, d);
1706     #ifdef TRAFF_STAT_WITH_PORTS
1707     if (fprintf(statFile, "%17s:%hu\t%15d\t%15s\t%15s\t%f\n",
1708                 inet_ntostring(stIter->first.ip).c_str(),
1709                 stIter->first.port,
1710                 stIter->first.dir,
1711                 d.c_str(),
1712                 u.c_str(),
1713                 stIter->second.cash) < 0)
1714         {
1715         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1716         errorStr = "fprint failed. Message: '";
1717         errorStr += strerror(errno);
1718         errorStr += "'";
1719         printfd(__FILE__, "FILES_STORE::WriteDetailStat - fprintf failed. Message: '%s'\n", strerror(errno));
1720         fclose(statFile);
1721         return -1;
1722         }
1723     #else
1724     if (fprintf(statFile, "%17s\t%15d\t%15s\t%15s\t%f\n",
1725                 inet_ntostring(stIter->first.ip).c_str(),
1726                 stIter->first.dir,
1727                 d.c_str(),
1728                 u.c_str(),
1729                 stIter->second.cash) < 0)
1730         {
1731         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1732         errorStr = std::string("fprint failed. Message: '");
1733         errorStr += strerror(errno);
1734         errorStr += "'";
1735         printfd(__FILE__, "FILES_STORE::WriteDetailStat - fprintf failed. Message: '%s'\n", strerror(errno));
1736         fclose(statFile);
1737         return -1;
1738         }
1739     #endif
1740
1741     ++stIter;
1742     }
1743
1744 fclose(statFile);
1745
1746 e = chown(fn, storeSettings.GetStatUID(), storeSettings.GetStatGID());
1747 e += chmod(fn, storeSettings.GetStatMode());
1748
1749 if (e)
1750     {
1751     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1752     printfd(__FILE__, "FILES_STORE::WriteDetailStat - chmod/chown failed for user '%s'. Error: '%s'\n", login.c_str(), strerror(errno));
1753     }
1754
1755 return 0;
1756 }
1757 //-----------------------------------------------------------------------------
1758 int FILES_STORE::AddMessage(STG_MSG * msg, const std::string & login) const
1759 {
1760 std::string fn;
1761 std::string dn;
1762 struct timeval tv;
1763
1764 strprintf(&dn, "%s/%s/messages", storeSettings.GetUsersDir().c_str(), login.c_str());
1765 if (access(dn.c_str(), F_OK) != 0)
1766     {
1767     if (mkdir(dn.c_str(), 0700) != 0)
1768         {
1769         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1770         errorStr = "Directory \'";
1771         errorStr += dn;
1772         errorStr += "\' cannot be created.";
1773         printfd(__FILE__, "FILES_STORE::AddMessage - mkdir failed. Message: '%s'\n", strerror(errno));
1774         return -1;
1775         }
1776     }
1777
1778 chmod(dn.c_str(), storeSettings.GetConfModeDir());
1779
1780 gettimeofday(&tv, NULL);
1781
1782 msg->header.id = ((long long)tv.tv_sec) * 1000000 + ((long long)tv.tv_usec);
1783 strprintf(&fn, "%s/%lld", dn.c_str(), msg->header.id);
1784
1785 if (Touch(fn))
1786     {
1787     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1788     errorStr = "File \'";
1789     errorStr += fn;
1790     errorStr += "\' cannot be writen.";
1791     printfd(__FILE__, "FILES_STORE::AddMessage - fopen failed. Message: '%s'\n", strerror(errno));
1792     return -1;
1793     }
1794
1795 return EditMessage(*msg, login);
1796 }
1797 //-----------------------------------------------------------------------------
1798 int FILES_STORE::EditMessage(const STG_MSG & msg, const std::string & login) const
1799 {
1800 std::string fileName;
1801
1802 FILE * msgFile;
1803 strprintf(&fileName, "%s/%s/messages/%lld", storeSettings.GetUsersDir().c_str(), login.c_str(), msg.header.id);
1804
1805 if (access(fileName.c_str(), F_OK) != 0)
1806     {
1807     std::string idstr;
1808     x2str(msg.header.id, idstr);
1809     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1810     errorStr = "Message for user \'";
1811     errorStr += login + "\' with ID \'";
1812     errorStr += idstr + "\' does not exist.";
1813     printfd(__FILE__, "FILES_STORE::EditMessage - %s\n", errorStr.c_str());
1814     return -1;
1815     }
1816
1817 Touch(fileName + ".new");
1818
1819 msgFile = fopen((fileName + ".new").c_str(), "wt");
1820 if (!msgFile)
1821     {
1822     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1823     errorStr = "File \'" + fileName + "\' cannot be writen.";
1824     printfd(__FILE__, "FILES_STORE::EditMessage - fopen failed. Message: '%s'\n", strerror(errno));
1825     return -1;
1826     }
1827
1828 bool res = true;
1829 res &= (fprintf(msgFile, "%d\n", msg.header.type) >= 0);
1830 res &= (fprintf(msgFile, "%u\n", msg.header.lastSendTime) >= 0);
1831 res &= (fprintf(msgFile, "%u\n", msg.header.creationTime) >= 0);
1832 res &= (fprintf(msgFile, "%u\n", msg.header.showTime) >= 0);
1833 res &= (fprintf(msgFile, "%d\n", msg.header.repeat) >= 0);
1834 res &= (fprintf(msgFile, "%u\n", msg.header.repeatPeriod) >= 0);
1835 res &= (fprintf(msgFile, "%s", msg.text.c_str()) >= 0);
1836
1837 if (!res)
1838     {
1839     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1840     errorStr = std::string("fprintf failed. Message: '") + strerror(errno) + "'";
1841     printfd(__FILE__, "FILES_STORE::EditMessage - fprintf failed. Message: '%s'\n", strerror(errno));
1842     fclose(msgFile);
1843     return -1;
1844     }
1845
1846 fclose(msgFile);
1847
1848 chmod((fileName + ".new").c_str(), storeSettings.GetConfMode());
1849
1850 if (rename((fileName + ".new").c_str(), fileName.c_str()) < 0)
1851     {
1852     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1853     errorStr = "Error moving dir from " + fileName + ".new to " + fileName;
1854     printfd(__FILE__, "FILES_STORE::SaveTariff - rename failed. Message: '%s'\n", strerror(errno));
1855     return -1;
1856     }
1857
1858 return 0;
1859 }
1860 //-----------------------------------------------------------------------------
1861 int FILES_STORE::GetMessage(uint64_t id, STG_MSG * msg, const std::string & login) const
1862 {
1863 std::string fn;
1864 strprintf(&fn, "%s/%s/messages/%lld", storeSettings.GetUsersDir().c_str(), login.c_str(), id);
1865 msg->header.id = id;
1866 return ReadMessage(fn, &msg->header, &msg->text);
1867 }
1868 //-----------------------------------------------------------------------------
1869 int FILES_STORE::DelMessage(uint64_t id, const std::string & login) const
1870 {
1871 std::string fn;
1872 strprintf(&fn, "%s/%s/messages/%lld", storeSettings.GetUsersDir().c_str(), login.c_str(), id);
1873
1874 return unlink(fn.c_str());
1875 }
1876 //-----------------------------------------------------------------------------
1877 int FILES_STORE::GetMessageHdrs(std::vector<STG_MSG_HDR> * hdrsList, const std::string & login) const
1878 {
1879 std::string dn(storeSettings.GetUsersDir() + "/" + login + "/messages/");
1880
1881 if (access(dn.c_str(), F_OK) != 0)
1882     {
1883     return 0;
1884     }
1885
1886 std::vector<std::string> messages;
1887 GetFileList(&messages, dn, S_IFREG, "");
1888
1889 for (unsigned i = 0; i < messages.size(); i++)
1890     {
1891     unsigned long long id = 0;
1892
1893     if (str2x(messages[i].c_str(), id))
1894         {
1895         if (unlink((dn + messages[i]).c_str()))
1896             {
1897             STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1898             errorStr = std::string("unlink failed. Message: '") + strerror(errno) + "'";
1899             printfd(__FILE__, "FILES_STORE::GetMessageHdrs - unlink failed. Message: '%s'\n", strerror(errno));
1900             return -1;
1901             }
1902         continue;
1903         }
1904
1905     STG_MSG_HDR hdr;
1906     if (ReadMessage(dn + messages[i], &hdr, NULL))
1907         {
1908         return -1;
1909         }
1910
1911     if (hdr.repeat < 0)
1912         {
1913         if (unlink((dn + messages[i]).c_str()))
1914             {
1915             STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1916             errorStr = std::string("unlink failed. Message: '") + strerror(errno) + "'";
1917             printfd(__FILE__, "FILES_STORE::GetMessageHdrs - unlink failed. Message: '%s'\n", strerror(errno));
1918             return -1;
1919             }
1920         continue;
1921         }
1922
1923     hdr.id = id;
1924     hdrsList->push_back(hdr);
1925     }
1926 return 0;
1927 }
1928 //-----------------------------------------------------------------------------
1929 int FILES_STORE::ReadMessage(const std::string & fileName,
1930                              STG_MSG_HDR * hdr,
1931                              std::string * text) const
1932 {
1933 FILE * msgFile;
1934 msgFile = fopen(fileName.c_str(), "rt");
1935 if (!msgFile)
1936     {
1937     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1938     errorStr = "File \'";
1939     errorStr += fileName;
1940     errorStr += "\' cannot be openned.";
1941     printfd(__FILE__, "FILES_STORE::ReadMessage - fopen failed. Message: '%s'\n", strerror(errno));
1942     return -1;
1943     }
1944 char p[20];
1945 unsigned * d[6];
1946 d[0] = &hdr->type;
1947 d[1] = &hdr->lastSendTime;
1948 d[2] = &hdr->creationTime;
1949 d[3] = &hdr->showTime;
1950 d[4] = (unsigned*)(&hdr->repeat);
1951 d[5] = &hdr->repeatPeriod;
1952
1953 memset(p, 0, sizeof(p));
1954
1955 for (int pos = 0; pos < 6; pos++)
1956     {
1957     if (fgets(p, sizeof(p) - 1, msgFile) == NULL) {
1958         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1959         errorStr = "Cannot read file \'";
1960         errorStr += fileName;
1961         errorStr += "\'. Missing data.";
1962         printfd(__FILE__, "FILES_STORE::ReadMessage - cannot read file (missing data)\n");
1963         printfd(__FILE__, "FILES_STORE::ReadMessage - position: %d\n", pos);
1964         fclose(msgFile);
1965         return -1;
1966     }
1967
1968     char * ep;
1969     ep = strrchr(p, '\r');
1970     if (ep) *ep = 0;
1971     ep = strrchr(p, '\n');
1972     if (ep) *ep = 0;
1973
1974     if (feof(msgFile))
1975         {
1976         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1977         errorStr = "Cannot read file \'";
1978         errorStr += fileName;
1979         errorStr += "\'. Missing data.";
1980         printfd(__FILE__, "FILES_STORE::ReadMessage - cannot read file (feof)\n");
1981         printfd(__FILE__, "FILES_STORE::ReadMessage - position: %d\n", pos);
1982         fclose(msgFile);
1983         return -1;
1984         }
1985
1986     if (str2x(p, *(d[pos])))
1987         {
1988         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1989         errorStr = "Cannot read file \'";
1990         errorStr += fileName;
1991         errorStr += "\'. Incorrect value. \'";
1992         errorStr += p;
1993         errorStr += "\'";
1994         printfd(__FILE__, "FILES_STORE::ReadMessage - incorrect value\n");
1995         fclose(msgFile);
1996         return -1;
1997         }
1998     }
1999
2000 char txt[2048];
2001 memset(txt, 0, sizeof(txt));
2002 if (text)
2003     {
2004     text->erase(text->begin(), text->end());
2005     while (!feof(msgFile))
2006         {
2007         txt[0] = 0;
2008         if (fgets(txt, sizeof(txt) - 1, msgFile) == NULL) {
2009             break;
2010         }
2011
2012         (*text) += txt;
2013         }
2014     }
2015 fclose(msgFile);
2016 return 0;
2017 }
2018 //-----------------------------------------------------------------------------
2019 int FILES_STORE::Touch(const std::string & path) const
2020 {
2021 FILE * f = fopen(path.c_str(), "wb");
2022 if (f)
2023     {
2024     fclose(f);
2025     return 0;
2026     }
2027 return -1;
2028 }
2029 //-----------------------------------------------------------------------------
2030 int GetFileList(std::vector<std::string> * fileList, const std::string & directory, mode_t mode, const std::string & ext)
2031 {
2032 DIR * d = opendir(directory.c_str());
2033
2034 if (!d)
2035     {
2036     printfd(__FILE__, "GetFileList - Failed to open dir '%s': '%s'\n", directory.c_str(), strerror(errno));
2037     return -1;
2038     }
2039
2040 dirent * entry;
2041 while ((entry = readdir(d)))
2042     {
2043     if (!(strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..")))
2044         continue;
2045
2046     std::string str = directory + "/" + std::string(entry->d_name);
2047
2048     struct stat st;
2049     if (stat(str.c_str(), &st))
2050         continue;
2051
2052     if (!(st.st_mode & mode)) // Filter by mode
2053         continue;
2054
2055     if (!ext.empty())
2056         {
2057         // Check extension
2058         size_t d_nameLen = strlen(entry->d_name);
2059         if (d_nameLen <= ext.size())
2060             continue;
2061
2062         if (ext == entry->d_name + (d_nameLen - ext.size()))
2063             {
2064             entry->d_name[d_nameLen - ext.size()] = 0;
2065             fileList->push_back(entry->d_name);
2066             }
2067         }
2068     else
2069         {
2070         fileList->push_back(entry->d_name);
2071         }
2072     }
2073
2074 closedir(d);
2075
2076 return 0;
2077 }
2078 //-----------------------------------------------------------------------------