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