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