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