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