]> git.stg.codes - stg.git/blob - projects/stargazer/plugins/store/files/file_store.cpp
Service and corporation permissions added
[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     cf.WriteInt("ChgService",  ac.priv.serviceChg);
1284     cf.WriteInt("ChgCorp",     ac.priv.corpChg);
1285     }
1286
1287 return 0;
1288 }
1289 //-----------------------------------------------------------------------------
1290 int FILES_STORE::RestoreAdmin(ADMIN_CONF * ac, const string & login) const
1291 {
1292 string fileName;
1293 strprintf(&fileName, "%s/%s.adm", storeSettings.GetAdminsDir().c_str(), login.c_str());
1294 CONFIGFILE cf(fileName);
1295 char pass[ADM_PASSWD_LEN + 1];
1296 char password[ADM_PASSWD_LEN + 1];
1297 char passwordE[2 * ADM_PASSWD_LEN + 2];
1298 BLOWFISH_CTX ctx;
1299
1300 string p;
1301
1302 if (cf.Error())
1303     {
1304     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1305     errorStr = "Cannot open " + fileName;
1306     printfd(__FILE__, "FILES_STORE::RestoreAdmin - failed to restore admin '%s'\n", ac->login.c_str());
1307     return -1;
1308     }
1309
1310 int a;
1311
1312 if (cf.ReadString("password", &p, "*"))
1313     {
1314     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1315     errorStr = "Error in parameter password";
1316     printfd(__FILE__, "FILES_STORE::RestoreAdmin - password read failed for admin '%s'\n", ac->login.c_str());
1317     return -1;
1318     }
1319
1320 memset(passwordE, 0, sizeof(passwordE));
1321 strncpy(passwordE, p.c_str(), 2*ADM_PASSWD_LEN);
1322
1323 memset(pass, 0, sizeof(pass));
1324
1325 if (passwordE[0] != 0)
1326     {
1327     Decode21(pass, passwordE);
1328     EnDecodeInit(adm_enc_passwd, strlen(adm_enc_passwd), &ctx);
1329
1330     for (int i = 0; i < ADM_PASSWD_LEN/8; i++)
1331         {
1332         DecodeString(password + 8*i, pass + 8*i, &ctx);
1333         }
1334     }
1335 else
1336     {
1337     password[0] = 0;
1338     }
1339
1340 ac->password = password;
1341
1342 if (cf.ReadInt("ChgConf", &a, 0) == 0)
1343     ac->priv.userConf = a;
1344 else
1345     {
1346     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1347     errorStr = "Error in parameter ChgConf";
1348     printfd(__FILE__, "FILES_STORE::RestoreAdmin - chgconf read failed for admin '%s'\n", ac->login.c_str());
1349     return -1;
1350     }
1351
1352 if (cf.ReadInt("ChgPassword", &a, 0) == 0)
1353     ac->priv.userPasswd = a;
1354 else
1355     {
1356     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1357     errorStr = "Error in parameter ChgPassword";
1358     printfd(__FILE__, "FILES_STORE::RestoreAdmin - chgpassword read failed for admin '%s'\n", ac->login.c_str());
1359     return -1;
1360     }
1361
1362 if (cf.ReadInt("ChgStat", &a, 0) == 0)
1363     ac->priv.userStat = a;
1364 else
1365     {
1366     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1367     errorStr = "Error in parameter ChgStat";
1368     printfd(__FILE__, "FILES_STORE::RestoreAdmin - chgstat read failed for admin '%s'\n", ac->login.c_str());
1369     return -1;
1370     }
1371
1372 if (cf.ReadInt("ChgCash", &a, 0) == 0)
1373     ac->priv.userCash = a;
1374 else
1375     {
1376     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1377     errorStr = "Error in parameter ChgCash";
1378     printfd(__FILE__, "FILES_STORE::RestoreAdmin - chgcash read failed for admin '%s'\n", ac->login.c_str());
1379     return -1;
1380     }
1381
1382 if (cf.ReadInt("UsrAddDel", &a, 0) == 0)
1383     ac->priv.userAddDel = a;
1384 else
1385     {
1386     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1387     errorStr = "Error in parameter UsrAddDel";
1388     printfd(__FILE__, "FILES_STORE::RestoreAdmin - usradddel read failed for admin '%s'\n", ac->login.c_str());
1389     return -1;
1390     }
1391
1392 if (cf.ReadInt("ChgAdmin", &a, 0) == 0)
1393     ac->priv.adminChg = a;
1394 else
1395     {
1396     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1397     errorStr = "Error in parameter ChgAdmin";
1398     printfd(__FILE__, "FILES_STORE::RestoreAdmin - chgadmin read failed for admin '%s'\n", ac->login.c_str());
1399     return -1;
1400     }
1401
1402 if (cf.ReadInt("ChgTariff", &a, 0) == 0)
1403     ac->priv.tariffChg = a;
1404 else
1405     {
1406     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1407     errorStr = "Error in parameter ChgTariff";
1408     printfd(__FILE__, "FILES_STORE::RestoreAdmin - chgtariff read failed for admin '%s'\n", ac->login.c_str());
1409     return -1;
1410     }
1411
1412 if (cf.ReadInt("ChgService", &a, 0) == 0)
1413     ac->priv.serviceChg = a;
1414 else
1415     ac->priv.serviceChg = 0;
1416
1417 if (cf.ReadInt("ChgCorp", &a, 0) == 0)
1418     ac->priv.corpChg = a;
1419 else
1420     ac->priv.corpChg = 0;
1421
1422 return 0;
1423 }
1424 //-----------------------------------------------------------------------------
1425 int FILES_STORE::AddTariff(const string & name) const
1426 {
1427 string fileName;
1428 strprintf(&fileName, "%s/%s.tf", storeSettings.GetTariffsDir().c_str(), name.c_str());
1429 if (Touch(fileName))
1430     {
1431     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1432     errorStr = "Cannot create file " + fileName;
1433     printfd(__FILE__, "FILES_STORE::AddTariff - failed to add tariff '%s'\n", name.c_str());
1434     return -1;
1435     }
1436 return 0;
1437 }
1438 //-----------------------------------------------------------------------------
1439 int FILES_STORE::DelTariff(const string & name) const
1440 {
1441 string fileName;
1442 strprintf(&fileName, "%s/%s.tf", storeSettings.GetTariffsDir().c_str(), name.c_str());
1443 if (unlink(fileName.c_str()))
1444     {
1445     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1446     errorStr = "unlink failed. Message: '";
1447     errorStr += strerror(errno);
1448     errorStr += "'";
1449     printfd(__FILE__, "FILES_STORE::DelTariff - unlink failed. Message: '%s'\n", strerror(errno));
1450     }
1451 return 0;
1452 }
1453 //-----------------------------------------------------------------------------
1454 int FILES_STORE::RestoreTariff(TARIFF_DATA * td, const string & tariffName) const
1455 {
1456 string fileName = storeSettings.GetTariffsDir() + "/" + tariffName + ".tf";
1457 CONFIGFILE conf(fileName);
1458 string str;
1459 td->tariffConf.name = tariffName;
1460
1461 if (conf.Error() != 0)
1462     {
1463     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1464     errorStr = "Cannot read file " + fileName;
1465     printfd(__FILE__, "FILES_STORE::RestoreTariff - failed to read tariff '%s'\n", tariffName.c_str());
1466     return -1;
1467     }
1468
1469 string param;
1470 for (int i = 0; i<DIR_NUM; i++)
1471     {
1472     strprintf(&param, "Time%d", i);
1473     if (conf.ReadString(param, &str, "00:00-00:00") < 0)
1474         {
1475         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1476         errorStr = "Cannot read tariff " + tariffName + ". Parameter " + param;
1477         printfd(__FILE__, "FILES_STORE::RestoreTariff - time%d read failed for tariff '%s'\n", i, tariffName.c_str());
1478         return -1;
1479         }
1480
1481     ParseTariffTimeStr(str.c_str(),
1482                        td->dirPrice[i].hDay,
1483                        td->dirPrice[i].mDay,
1484                        td->dirPrice[i].hNight,
1485                        td->dirPrice[i].mNight);
1486
1487     strprintf(&param, "PriceDayA%d", i);
1488     if (conf.ReadDouble(param, &td->dirPrice[i].priceDayA, 0.0) < 0)
1489         {
1490         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1491         errorStr = "Cannot read tariff " + tariffName + ". Parameter " + param;
1492         printfd(__FILE__, "FILES_STORE::RestoreTariff - pricedaya read failed for tariff '%s'\n", tariffName.c_str());
1493         return -1;
1494         }
1495     td->dirPrice[i].priceDayA /= (1024*1024);
1496
1497     strprintf(&param, "PriceDayB%d", i);
1498     if (conf.ReadDouble(param, &td->dirPrice[i].priceDayB, 0.0) < 0)
1499         {
1500         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1501         errorStr = "Cannot read tariff " + tariffName + ". Parameter " + param;
1502         printfd(__FILE__, "FILES_STORE::RestoreTariff - pricedayb read failed for tariff '%s'\n", tariffName.c_str());
1503         return -1;
1504         }
1505     td->dirPrice[i].priceDayB /= (1024*1024);
1506
1507     strprintf(&param, "PriceNightA%d", i);
1508     if (conf.ReadDouble(param, &td->dirPrice[i].priceNightA, 0.0) < 0)
1509         {
1510         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1511         errorStr = "Cannot read tariff " + tariffName + ". Parameter " + param;
1512         printfd(__FILE__, "FILES_STORE::RestoreTariff - pricenighta read failed for tariff '%s'\n", tariffName.c_str());
1513         return -1;
1514         }
1515     td->dirPrice[i].priceNightA /= (1024*1024);
1516
1517     strprintf(&param, "PriceNightB%d", i);
1518     if (conf.ReadDouble(param, &td->dirPrice[i].priceNightB, 0.0) < 0)
1519         {
1520         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1521         errorStr = "Cannot read tariff " + tariffName + ". Parameter " + param;
1522         printfd(__FILE__, "FILES_STORE::RestoreTariff - pricenightb read failed for tariff '%s'\n", tariffName.c_str());
1523         return -1;
1524         }
1525     td->dirPrice[i].priceNightB /= (1024*1024);
1526
1527     strprintf(&param, "Threshold%d", i);
1528     if (conf.ReadInt(param, &td->dirPrice[i].threshold, 0) < 0)
1529         {
1530         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1531         errorStr = "Cannot read tariff " + tariffName + ". Parameter " + param;
1532         printfd(__FILE__, "FILES_STORE::RestoreTariff - threshold read failed for tariff '%s'\n", tariffName.c_str());
1533         return -1;
1534         }
1535
1536     strprintf(&param, "SinglePrice%d", i);
1537     if (conf.ReadInt(param, &td->dirPrice[i].singlePrice, 0) < 0)
1538         {
1539         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1540         errorStr = "Cannot read tariff " + tariffName + ". Parameter " + param;
1541         printfd(__FILE__, "FILES_STORE::RestoreTariff - singleprice read failed for tariff '%s'\n", tariffName.c_str());
1542         return -1;
1543         }
1544
1545     strprintf(&param, "NoDiscount%d", i);
1546     if (conf.ReadInt(param, &td->dirPrice[i].noDiscount, 0) < 0)
1547         {
1548         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1549         errorStr = "Cannot read tariff " + tariffName + ". Parameter " + param;
1550         printfd(__FILE__, "FILES_STORE::RestoreTariff - nodiscount read failed for tariff '%s'\n", tariffName.c_str());
1551         return -1;
1552         }
1553     }
1554
1555 if (conf.ReadDouble("Fee", &td->tariffConf.fee, 0) < 0)
1556     {
1557     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1558     errorStr = "Cannot read tariff " + tariffName + ". Parameter Fee";
1559     printfd(__FILE__, "FILES_STORE::RestoreTariff - fee read failed for tariff '%s'\n", tariffName.c_str());
1560     return -1;
1561     }
1562
1563 if (conf.ReadDouble("Free", &td->tariffConf.free, 0) < 0)
1564     {
1565     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1566     errorStr = "Cannot read tariff " + tariffName + ". Parameter Free";
1567     printfd(__FILE__, "FILES_STORE::RestoreTariff - free read failed for tariff '%s'\n", tariffName.c_str());
1568     return -1;
1569     }
1570
1571 if (conf.ReadDouble("PassiveCost", &td->tariffConf.passiveCost, 0) < 0)
1572     {
1573     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1574     errorStr = "Cannot read tariff " + tariffName + ". Parameter PassiveCost";
1575     printfd(__FILE__, "FILES_STORE::RestoreTariff - passivecost read failed for tariff '%s'\n", tariffName.c_str());
1576     return -1;
1577     }
1578
1579 if (conf.ReadString("TraffType", &str, "") < 0)
1580     {
1581     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1582     errorStr = "Cannot read tariff " + tariffName + ". Parameter TraffType";
1583     printfd(__FILE__, "FILES_STORE::RestoreTariff - trafftype read failed for tariff '%s'\n", tariffName.c_str());
1584     return -1;
1585     }
1586
1587 if (!strcasecmp(str.c_str(), "up"))
1588     td->tariffConf.traffType = TRAFF_UP;
1589 else
1590     if (!strcasecmp(str.c_str(), "down"))
1591         td->tariffConf.traffType = TRAFF_DOWN;
1592     else
1593         if (!strcasecmp(str.c_str(), "up+down"))
1594             td->tariffConf.traffType = TRAFF_UP_DOWN;
1595         else
1596             if (!strcasecmp(str.c_str(), "max"))
1597                 td->tariffConf.traffType = TRAFF_MAX;
1598             else
1599                 {
1600                 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1601                 errorStr = "Cannot read tariff " + tariffName + ". Parameter TraffType incorrect";
1602                 printfd(__FILE__, "FILES_STORE::RestoreTariff - invalid trafftype for tariff '%s'\n", tariffName.c_str());
1603                 return -1;
1604                 }
1605 return 0;
1606 }
1607 //-----------------------------------------------------------------------------
1608 int FILES_STORE::SaveTariff(const TARIFF_DATA & td, const string & tariffName) const
1609 {
1610 string fileName = storeSettings.GetTariffsDir() + "/" + tariffName + ".tf";
1611
1612     {
1613     CONFIGFILE cf(fileName, true);
1614
1615     int e = cf.Error();
1616
1617     if (e)
1618         {
1619         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1620         errorStr = "Error writing tariff " + tariffName;
1621         printfd(__FILE__, "FILES_STORE::RestoreTariff - failed to save tariff '%s'\n", tariffName.c_str());
1622         return e;
1623         }
1624
1625     string param;
1626     for (int i = 0; i < DIR_NUM; i++)
1627         {
1628         strprintf(&param, "PriceDayA%d", i);
1629         cf.WriteDouble(param, td.dirPrice[i].priceDayA * pt_mega);
1630
1631         strprintf(&param, "PriceDayB%d", i);
1632         cf.WriteDouble(param, td.dirPrice[i].priceDayB * pt_mega);
1633
1634         strprintf(&param, "PriceNightA%d", i);
1635         cf.WriteDouble(param, td.dirPrice[i].priceNightA * pt_mega);
1636
1637         strprintf(&param, "PriceNightB%d", i);
1638         cf.WriteDouble(param, td.dirPrice[i].priceNightB * pt_mega);
1639
1640         strprintf(&param, "Threshold%d", i);
1641         cf.WriteInt(param, td.dirPrice[i].threshold);
1642
1643         string s;
1644         strprintf(&param, "Time%d", i);
1645
1646         strprintf(&s, "%0d:%0d-%0d:%0d",
1647                 td.dirPrice[i].hDay,
1648                 td.dirPrice[i].mDay,
1649                 td.dirPrice[i].hNight,
1650                 td.dirPrice[i].mNight);
1651
1652         cf.WriteString(param, s);
1653
1654         strprintf(&param, "NoDiscount%d", i);
1655         cf.WriteInt(param, td.dirPrice[i].noDiscount);
1656
1657         strprintf(&param, "SinglePrice%d", i);
1658         cf.WriteInt(param, td.dirPrice[i].singlePrice);
1659         }
1660
1661     cf.WriteDouble("PassiveCost", td.tariffConf.passiveCost);
1662     cf.WriteDouble("Fee", td.tariffConf.fee);
1663     cf.WriteDouble("Free", td.tariffConf.free);
1664
1665     switch (td.tariffConf.traffType)
1666         {
1667         case TRAFF_UP:
1668             cf.WriteString("TraffType", "up");
1669             break;
1670         case TRAFF_DOWN:
1671             cf.WriteString("TraffType", "down");
1672             break;
1673         case TRAFF_UP_DOWN:
1674             cf.WriteString("TraffType", "up+down");
1675             break;
1676         case TRAFF_MAX:
1677             cf.WriteString("TraffType", "max");
1678             break;
1679         }
1680     }
1681
1682 return 0;
1683 }
1684 //-----------------------------------------------------------------------------
1685 int FILES_STORE::WriteDetailedStat(const map<IP_DIR_PAIR, STAT_NODE> & statTree,
1686                                    time_t lastStat,
1687                                    const string & login) const
1688 {
1689 char fn[FN_STR_LEN];
1690 char dn[FN_STR_LEN];
1691 FILE * statFile;
1692 time_t t;
1693 tm * lt;
1694
1695 t = time(NULL);
1696
1697 snprintf(dn, FN_STR_LEN, "%s/%s/detail_stat", storeSettings.GetUsersDir().c_str(), login.c_str());
1698 if (access(dn, F_OK) != 0)
1699     {
1700     if (mkdir(dn, 0700) != 0)
1701         {
1702         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1703         errorStr = "Directory \'" + string(dn) + "\' cannot be created.";
1704         printfd(__FILE__, "FILES_STORE::WriteDetailStat - mkdir failed. Message: '%s'\n", strerror(errno));
1705         return -1;
1706         }
1707     }
1708
1709 int e = chown(dn, storeSettings.GetStatUID(), storeSettings.GetStatGID());
1710 e += chmod(dn, storeSettings.GetStatModeDir());
1711
1712 if (e)
1713     {
1714     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1715     printfd(__FILE__, "FILES_STORE::WriteDetailStat - chmod/chown failed for user '%s'. Error: '%s'\n", login.c_str(), strerror(errno));
1716     }
1717
1718 lt = localtime(&t);
1719
1720 if (lt->tm_hour == 0 && lt->tm_min <= 5)
1721     {
1722     t -= 3600 * 24;
1723     lt = localtime(&t);
1724     }
1725
1726 snprintf(dn, FN_STR_LEN, "%s/%s/detail_stat/%d",
1727          storeSettings.GetUsersDir().c_str(),
1728          login.c_str(),
1729          lt->tm_year+1900);
1730
1731 if (access(dn, F_OK) != 0)
1732     {
1733     if (mkdir(dn, 0700) != 0)
1734         {
1735         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1736         errorStr = "Directory \'" + string(dn) + "\' cannot be created.";
1737         printfd(__FILE__, "FILES_STORE::WriteDetailStat - mkdir failed. Message: '%s'\n", strerror(errno));
1738         return -1;
1739         }
1740     }
1741
1742 e = chown(dn, storeSettings.GetStatUID(), storeSettings.GetStatGID());
1743 e += chmod(dn, storeSettings.GetStatModeDir());
1744
1745 if (e)
1746     {
1747     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1748     printfd(__FILE__, "FILES_STORE::WriteDetailStat - chmod/chown failed for user '%s'. Error: '%s'\n", login.c_str(), strerror(errno));
1749     }
1750
1751 snprintf(dn, FN_STR_LEN, "%s/%s/detail_stat/%d/%s%d", 
1752          storeSettings.GetUsersDir().c_str(),
1753          login.c_str(),
1754          lt->tm_year+1900,
1755          lt->tm_mon+1 < 10 ? "0" : "",
1756          lt->tm_mon+1);
1757 if (access(dn, F_OK) != 0)
1758     {
1759     if (mkdir(dn, 0700) != 0)
1760         {
1761         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1762         errorStr = "Directory \'" + string(dn) + "\' cannot be created.";
1763         printfd(__FILE__, "FILES_STORE::WriteDetailStat - mkdir failed. Message: '%s'\n", strerror(errno));
1764         return -1;
1765         }
1766     }
1767
1768 e = chown(dn, storeSettings.GetStatUID(), storeSettings.GetStatGID());
1769 e += chmod(dn, storeSettings.GetStatModeDir());
1770
1771 if (e)
1772     {
1773     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1774     printfd(__FILE__, "FILES_STORE::WriteDetailStat - chmod/chown failed for user '%s'. Error: '%s'\n", login.c_str(), strerror(errno));
1775     }
1776
1777 snprintf(fn, FN_STR_LEN, "%s/%s%d", dn, lt->tm_mday < 10 ? "0" : "", lt->tm_mday);
1778
1779 statFile = fopen (fn, "at");
1780
1781 if (!statFile)
1782     {
1783     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1784     errorStr = "File \'" + string(fn) + "\' cannot be written.";
1785     printfd(__FILE__, "FILES_STORE::WriteDetailStat - fopen failed. Message: '%s'\n", strerror(errno));
1786     return -1;
1787     }
1788
1789 struct tm * lt1;
1790 struct tm * lt2;
1791
1792 lt1 = localtime(&lastStat);
1793
1794 int h1, m1, s1;
1795 int h2, m2, s2;
1796
1797 h1 = lt1->tm_hour;
1798 m1 = lt1->tm_min;
1799 s1 = lt1->tm_sec;
1800
1801 lt2 = localtime(&t);
1802
1803 h2 = lt2->tm_hour;
1804 m2 = lt2->tm_min;
1805 s2 = lt2->tm_sec;
1806
1807 if (fprintf(statFile, "-> %02d.%02d.%02d - %02d.%02d.%02d\n",
1808             h1, m1, s1, h2, m2, s2) < 0)
1809     {
1810     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1811     errorStr = string("fprint failed. Message: '") + strerror(errno) + "'";
1812     printfd(__FILE__, "FILES_STORE::WriteDetailStat - fprintf failed. Message: '%s'\n", strerror(errno));
1813     fclose(statFile);
1814     return -1;
1815     }
1816
1817 map<IP_DIR_PAIR, STAT_NODE>::const_iterator stIter;
1818 stIter = statTree.begin();
1819
1820 while (stIter != statTree.end())
1821     {
1822     string u, d;
1823     x2str(stIter->second.up, u);
1824     x2str(stIter->second.down, d);
1825     #ifdef TRAFF_STAT_WITH_PORTS
1826     if (fprintf(statFile, "%17s:%hu\t%15d\t%15s\t%15s\t%f\n",
1827                 inet_ntostring(stIter->first.ip).c_str(),
1828                 stIter->first.port,
1829                 stIter->first.dir,
1830                 d.c_str(),
1831                 u.c_str(),
1832                 stIter->second.cash) < 0)
1833         {
1834         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1835         errorStr = "fprint failed. Message: '";
1836         errorStr += strerror(errno);
1837         errorStr += "'";
1838         printfd(__FILE__, "FILES_STORE::WriteDetailStat - fprintf failed. Message: '%s'\n", strerror(errno));
1839         fclose(statFile);
1840         return -1;
1841         }
1842     #else
1843     if (fprintf(statFile, "%17s\t%15d\t%15s\t%15s\t%f\n",
1844                 inet_ntostring(stIter->first.ip).c_str(),
1845                 stIter->first.dir,
1846                 d.c_str(),
1847                 u.c_str(),
1848                 stIter->second.cash) < 0)
1849         {
1850         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1851         errorStr = string("fprint failed. Message: '");
1852         errorStr += strerror(errno);
1853         errorStr += "'";
1854         printfd(__FILE__, "FILES_STORE::WriteDetailStat - fprintf failed. Message: '%s'\n", strerror(errno));
1855         fclose(statFile);
1856         return -1;
1857         }
1858     #endif
1859
1860     ++stIter;
1861     }
1862
1863 fclose(statFile);
1864
1865 e = chown(fn, storeSettings.GetStatUID(), storeSettings.GetStatGID());
1866 e += chmod(fn, storeSettings.GetStatMode());
1867
1868 if (e)
1869     {
1870     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1871     printfd(__FILE__, "FILES_STORE::WriteDetailStat - chmod/chown failed for user '%s'. Error: '%s'\n", login.c_str(), strerror(errno));
1872     }
1873
1874 return 0;
1875 }
1876 //-----------------------------------------------------------------------------
1877 int FILES_STORE::AddMessage(STG_MSG * msg, const string & login) const
1878 {
1879 //ðÒÏ×ÅÒÉÔØ ÅÓÔØ ÌÉ ÄÉÒÅËÔÏÒÉÑ ÄÌÑ ÓÏÏÂÝÅÎÉÊ. åÓÌÉ ÎÅÔ - ÓÏÚÄÁÔØ.
1880 //úÁÔÅÍ ÐÏÌÏÖÉÔØ ÓÏÏÂÝÅÎÉÅ Ó ÉÍÅÎÅÍ ÆÁÊÌÁ - ×ÒÅÍÅÎÎOÊ ÍÅÔËÏÊ. úÁÐÉÓÁÔØ ÔÕÄÁ
1881 //ÔÅËÓÔ É ÐÒÉÏÒÉÔÅÔ.
1882
1883 string fn;
1884 string dn;
1885 struct timeval tv;
1886
1887 strprintf(&dn, "%s/%s/messages", storeSettings.GetUsersDir().c_str(), login.c_str());
1888 if (access(dn.c_str(), F_OK) != 0)
1889     {
1890     if (mkdir(dn.c_str(), 0700) != 0)
1891         {
1892         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1893         errorStr = "Directory \'";
1894         errorStr += dn;
1895         errorStr += "\' cannot be created.";
1896         printfd(__FILE__, "FILES_STORE::AddMessage - mkdir failed. Message: '%s'\n", strerror(errno));
1897         return -1;
1898         }
1899     }
1900
1901 chmod(dn.c_str(), storeSettings.GetConfModeDir());
1902
1903 gettimeofday(&tv, NULL);
1904
1905 msg->header.id = ((long long)tv.tv_sec) * 1000000 + ((long long)tv.tv_usec);
1906 strprintf(&fn, "%s/%lld", dn.c_str(), msg->header.id);
1907
1908 if (Touch(fn))
1909     {
1910     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1911     errorStr = "File \'";
1912     errorStr += fn;
1913     errorStr += "\' cannot be writen.";
1914     printfd(__FILE__, "FILES_STORE::AddMessage - fopen failed. Message: '%s'\n", strerror(errno));
1915     return -1;
1916     }
1917
1918 return EditMessage(*msg, login);
1919 }
1920 //-----------------------------------------------------------------------------
1921 int FILES_STORE::EditMessage(const STG_MSG & msg, const string & login) const
1922 {
1923 //ðÒÏ×ÅÒÉÔØ ÅÓÌÔØ ÌÉ ÄÉÒÅËÔÏÒÉÑ ÄÌÑ ÓÏÏÂÝÅÎÉÊ. åÓÌÉ ÎÅÔ - ÓÏÚÄÁÔØ.
1924 //úÁÔÅÍ ÐÏÌÏÖÉÔØ ÓÏÏÂÝÅÎÉÅ Ó ÉÍÅÎÅÍ ÆÁÊÌÁ - ×ÒÅÍÅÎÎOÊ ÍÅÔËÏÊ. úÁÐÉÓÁÔØ ÔÕÄÁ
1925 //ÔÅËÓÔ É ÐÒÉÏÒÉÔÅÔ.
1926
1927 string fileName;
1928
1929 FILE * msgFile;
1930 strprintf(&fileName, "%s/%s/messages/%lld", storeSettings.GetUsersDir().c_str(), login.c_str(), msg.header.id);
1931
1932 if (access(fileName.c_str(), F_OK) != 0)
1933     {
1934     string idstr;
1935     x2str(msg.header.id, idstr);
1936     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1937     errorStr = "Message for user \'";
1938     errorStr += login + "\' with ID \'";
1939     errorStr += idstr + "\' does not exist.";
1940     printfd(__FILE__, "FILES_STORE::EditMessage - %s\n", errorStr.c_str());
1941     return -1;
1942     }
1943
1944 Touch(fileName + ".new");
1945
1946 msgFile = fopen((fileName + ".new").c_str(), "wt");
1947 if (!msgFile)
1948     {
1949     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1950     errorStr = "File \'" + fileName + "\' cannot be writen.";
1951     printfd(__FILE__, "FILES_STORE::EditMessage - fopen failed. Message: '%s'\n", strerror(errno));
1952     return -1;
1953     }
1954
1955 bool res = true;
1956 res &= (fprintf(msgFile, "%d\n", msg.header.type) >= 0);
1957 res &= (fprintf(msgFile, "%u\n", msg.header.lastSendTime) >= 0);
1958 res &= (fprintf(msgFile, "%u\n", msg.header.creationTime) >= 0);
1959 res &= (fprintf(msgFile, "%u\n", msg.header.showTime) >= 0);
1960 res &= (fprintf(msgFile, "%d\n", msg.header.repeat) >= 0);
1961 res &= (fprintf(msgFile, "%u\n", msg.header.repeatPeriod) >= 0);
1962 res &= (fprintf(msgFile, "%s", msg.text.c_str()) >= 0);
1963
1964 if (!res)
1965     {
1966     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1967     errorStr = string("fprintf failed. Message: '") + strerror(errno) + "'";
1968     printfd(__FILE__, "FILES_STORE::EditMessage - fprintf failed. Message: '%s'\n", strerror(errno));
1969     fclose(msgFile);
1970     return -1;
1971     }
1972
1973 fclose(msgFile);
1974
1975 chmod((fileName + ".new").c_str(), storeSettings.GetConfMode());
1976
1977 if (rename((fileName + ".new").c_str(), fileName.c_str()) < 0)
1978     {
1979     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
1980     errorStr = "Error moving dir from " + fileName + ".new to " + fileName;
1981     printfd(__FILE__, "FILES_STORE::SaveTariff - rename failed. Message: '%s'\n", strerror(errno));
1982     return -1;
1983     }
1984
1985 return 0;
1986 }
1987 //-----------------------------------------------------------------------------
1988 int FILES_STORE::GetMessage(uint64_t id, STG_MSG * msg, const string & login) const
1989 {
1990 string fn;
1991 strprintf(&fn, "%s/%s/messages/%lld", storeSettings.GetUsersDir().c_str(), login.c_str(), id);
1992 msg->header.id = id;
1993 return ReadMessage(fn, &msg->header, &msg->text);
1994 }
1995 //-----------------------------------------------------------------------------
1996 int FILES_STORE::DelMessage(uint64_t id, const string & login) const
1997 {
1998 string fn;
1999 strprintf(&fn, "%s/%s/messages/%lld", storeSettings.GetUsersDir().c_str(), login.c_str(), id);
2000
2001 return unlink(fn.c_str());
2002 }
2003 //-----------------------------------------------------------------------------
2004 int FILES_STORE::GetMessageHdrs(vector<STG_MSG_HDR> * hdrsList, const string & login) const
2005 {
2006 string dn(storeSettings.GetUsersDir() + "/" + login + "/messages/");
2007
2008 //hdrsList->resize(messages.size());
2009
2010 if (access(dn.c_str(), F_OK) != 0)
2011     {
2012     return 0;
2013     }
2014
2015 vector<string> messages;
2016 GetFileList(&messages, dn, S_IFREG, "");
2017
2018 for (unsigned i = 0; i < messages.size(); i++)
2019     {
2020     unsigned long long id = 0;
2021
2022     if (str2x(messages[i].c_str(), id))
2023         {
2024         if (unlink((dn + messages[i]).c_str()))
2025             {
2026             STG_LOCKER lock(&mutex, __FILE__, __LINE__);
2027             errorStr = string("unlink failed. Message: '") + strerror(errno) + "'";
2028             printfd(__FILE__, "FILES_STORE::GetMessageHdrs - unlink failed. Message: '%s'\n", strerror(errno));
2029             return -1;
2030             }
2031         continue;
2032         }
2033
2034     STG_MSG_HDR hdr;
2035     if (ReadMessage(dn + messages[i], &hdr, NULL))
2036         {
2037         return -1;
2038         }
2039
2040     if (hdr.repeat < 0)
2041         {
2042         if (unlink((dn + messages[i]).c_str()))
2043             {
2044             STG_LOCKER lock(&mutex, __FILE__, __LINE__);
2045             errorStr = string("unlink failed. Message: '") + strerror(errno) + "'";
2046             printfd(__FILE__, "FILES_STORE::GetMessageHdrs - unlink failed. Message: '%s'\n", strerror(errno));
2047             return -1;
2048             }
2049         continue;
2050         }
2051
2052     hdr.id = id;
2053     hdrsList->push_back(hdr);
2054     }
2055 return 0;
2056 }
2057 //-----------------------------------------------------------------------------
2058 int FILES_STORE::ReadMessage(const string & fileName,
2059                              STG_MSG_HDR * hdr,
2060                              string * text) const
2061 {
2062 FILE * msgFile;
2063 msgFile = fopen(fileName.c_str(), "rt");
2064 if (!msgFile)
2065     {
2066     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
2067     errorStr = "File \'";
2068     errorStr += fileName;
2069     errorStr += "\' cannot be openned.";
2070     printfd(__FILE__, "FILES_STORE::ReadMessage - fopen failed. Message: '%s'\n", strerror(errno));
2071     return -1;
2072     }
2073 char p[20];
2074 unsigned * d[6];
2075 d[0] = &hdr->type;
2076 d[1] = &hdr->lastSendTime;
2077 d[2] = &hdr->creationTime;
2078 d[3] = &hdr->showTime;
2079 d[4] = (unsigned*)(&hdr->repeat);
2080 d[5] = &hdr->repeatPeriod;
2081
2082 memset(p, 0, sizeof(p));
2083
2084 for (int pos = 0; pos < 6; pos++)
2085     {
2086     if (fgets(p, sizeof(p) - 1, msgFile) == NULL) {
2087         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
2088         errorStr = "Cannot read file \'";
2089         errorStr += fileName;
2090         errorStr += "\'. Missing data.";
2091         printfd(__FILE__, "FILES_STORE::ReadMessage - cannot read file (missing data)\n");
2092         printfd(__FILE__, "FILES_STORE::ReadMessage - position: %d\n", pos);
2093         fclose(msgFile);
2094         return -1;
2095     }
2096
2097     char * ep;
2098     ep = strrchr(p, '\r');
2099     if (ep) *ep = 0;
2100     ep = strrchr(p, '\n');
2101     if (ep) *ep = 0;
2102
2103     if (feof(msgFile))
2104         {
2105         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
2106         errorStr = "Cannot read file \'";
2107         errorStr += fileName;
2108         errorStr += "\'. Missing data.";
2109         printfd(__FILE__, "FILES_STORE::ReadMessage - cannot read file (feof)\n");
2110         printfd(__FILE__, "FILES_STORE::ReadMessage - position: %d\n", pos);
2111         fclose(msgFile);
2112         return -1;
2113         }
2114
2115     if (str2x(p, *(d[pos])))
2116         {
2117         STG_LOCKER lock(&mutex, __FILE__, __LINE__);
2118         errorStr = "Cannot read file \'";
2119         errorStr += fileName;
2120         errorStr += "\'. Incorrect value. \'";
2121         errorStr += p;
2122         errorStr += "\'";
2123         printfd(__FILE__, "FILES_STORE::ReadMessage - incorrect value\n");
2124         fclose(msgFile);
2125         return -1;
2126         }
2127     }
2128
2129 char txt[2048];
2130 memset(txt, 0, sizeof(txt));
2131 if (text)
2132     {
2133     text->erase(text->begin(), text->end());
2134     while (!feof(msgFile))
2135         {
2136         txt[0] = 0;
2137         if (fgets(txt, sizeof(txt) - 1, msgFile) == NULL) {
2138             break;
2139         }
2140
2141         (*text) += txt;
2142         }
2143     }
2144 fclose(msgFile);
2145 return 0;
2146 }
2147 //-----------------------------------------------------------------------------
2148 int FILES_STORE::Touch(const std::string & path) const
2149 {
2150 FILE * f = fopen(path.c_str(), "wb");
2151 if (f)
2152     {
2153     fclose(f);
2154     return 0;
2155     }
2156 return -1;
2157 }
2158 //-----------------------------------------------------------------------------
2159 int GetFileList(vector<string> * fileList, const string & directory, mode_t mode, const string & ext)
2160 {
2161 // æÕÎËÃÉÑ ÐÒÏÓÍÁÔÒÉ×ÁÅÔ ÓÏÄÅÒÖÉÍÏÅ ÄÉÒÅËÔÏÒÉÉ
2162
2163 DIR * d = opendir(directory.c_str());
2164
2165 if (!d)
2166     {
2167     printfd(__FILE__, "GetFileList - Failed to open dir '%s': '%s'\n", directory.c_str(), strerror(errno));
2168     return -1;
2169     }
2170
2171 dirent * entry;
2172 while ((entry = readdir(d)))
2173     {
2174     if (!(strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..")))
2175         continue;
2176
2177     string str = directory + "/" + string(entry->d_name);
2178
2179     struct stat st;
2180     if (stat(str.c_str(), &st))
2181         continue;
2182
2183     if (!(st.st_mode & mode)) // Filter by mode
2184         continue;
2185
2186     if (!ext.empty())
2187         {
2188         // Check extension
2189         size_t d_nameLen = strlen(entry->d_name);
2190         if (d_nameLen <= ext.size())
2191             continue;
2192
2193         if (ext == entry->d_name + (d_nameLen - ext.size()))
2194             {
2195             entry->d_name[d_nameLen - ext.size()] = 0;
2196             fileList->push_back(entry->d_name);
2197             }
2198         }
2199     else
2200         {
2201         fileList->push_back(entry->d_name);
2202         }
2203     }
2204
2205 closedir(d);
2206
2207 return 0;
2208 }
2209 //-----------------------------------------------------------------------------