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