]> git.stg.codes - stg.git/blob - projects/sgconf/main.cpp
Merge branch 'master' of gitorious.org:stg/stg
[stg.git] / projects / sgconf / main.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  *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
20  */
21
22 #include "request.h"
23 #include "common_sg.h"
24 #include "sg_error_codes.h"
25
26 #include "options.h"
27 #include "actions.h"
28 #include "config.h"
29
30 #include "stg/user_conf.h"
31 #include "stg/user_stat.h"
32 #include "stg/common.h"
33
34 #include <cerrno>
35 #include <clocale>
36 #include <cstdio>
37 #include <cstdlib>
38 #include <cstring>
39 #include <string>
40 #include <sstream>
41
42 #include <unistd.h>
43 #include <getopt.h>
44 #include <iconv.h>
45 #include <langinfo.h>
46
47 namespace
48 {
49
50 template <typename T>
51 struct ARRAY_TYPE
52 {
53 typedef typename T::value_type type;
54 };
55
56 template <typename T>
57 struct ARRAY_TYPE<T[]>
58 {
59 typedef T type;
60 };
61
62 template <typename T, size_t N>
63 struct ARRAY_TYPE<T[N]>
64 {
65 typedef T type;
66 };
67
68 template <typename T>
69 bool SetArrayItem(T & array, const char * index, const typename ARRAY_TYPE<T>::type & value)
70 {
71 size_t pos = 0;
72 if (str2x(index, pos))
73     return false;
74 array[pos] = value;
75 return true;
76 }
77
78 void Usage();
79 void UsageAll();
80 void UsageImpl(bool full);
81 void UsageConnection();
82 void UsageAdmins(bool full);
83 void UsageTariffs(bool full);
84 void UsageUsers(bool full);
85 void UsageServices(bool full);
86 void UsageCorporations(bool full);
87
88 void Version();
89
90 } // namespace anonymous
91
92 namespace SGCONF
93 {
94
95 class CONFIG_ACTION: public ACTION
96 {
97     public:
98         CONFIG_ACTION(CONFIG & config,
99                       const std::string & paramDescription)
100             : m_config(config),
101               m_description(paramDescription)
102         {}
103
104         virtual std::string ParamDescription() const { return m_description; }
105         virtual std::string DefaultDescription() const { return ""; }
106         virtual OPTION_BLOCK & Suboptions() { return m_suboptions; }
107         virtual PARSER_STATE Parse(int argc, char ** argv);
108
109     private:
110         CONFIG & m_config;
111         std::string m_description;
112         OPTION_BLOCK m_suboptions;
113
114         void ParseCredentials(const std::string & credentials);
115         void ParseHostAndPort(const std::string & hostAndPort);
116 };
117
118 PARSER_STATE CONFIG_ACTION::Parse(int argc, char ** argv)
119 {
120 char * pos = strchr(*argv, '@');
121 if (pos != NULL)
122     {
123     ParseCredentials(std::string(*argv, pos));
124     ParseHostAndPort(std::string(pos + 1));
125     }
126 else
127     {
128     ParseHostAndPort(std::string(*argv));
129     }
130 return PARSER_STATE(false, --argc, ++argv);
131 }
132
133 void CONFIG_ACTION::ParseCredentials(const std::string & credentials)
134 {
135 std::string::size_type pos = credentials.find_first_of(':');
136 if (pos != std::string::npos)
137     {
138     m_config.userName = credentials.substr(0, pos);
139     m_config.userPass = credentials.substr(pos + 1);
140     }
141 else
142     {
143     m_config.userName = credentials;
144     }
145 }
146
147 void CONFIG_ACTION::ParseHostAndPort(const std::string & hostAndPort)
148 {
149 std::string::size_type pos = hostAndPort.find_first_of(':');
150 if (pos != std::string::npos)
151     {
152     m_config.server = hostAndPort.substr(0, pos);
153     uint16_t port = 0;
154     if (str2x(hostAndPort.substr(pos + 1), port))
155         throw ERROR("Invalid port value: '" + hostAndPort.substr(pos + 1) + "'");
156     m_config.port = port;
157     }
158 else
159     {
160     m_config.server = hostAndPort;
161     }
162 }
163
164 inline
165 CONFIG_ACTION * MakeParamAction(CONFIG & config,
166                                 const std::string & paramDescription)
167 {
168 return new CONFIG_ACTION(config, paramDescription);
169 }
170
171 } // namespace SGCONF
172
173 time_t stgTime;
174
175 struct option long_options_get[] = {
176 {"server",      1, 0, 's'},  //Server
177 {"port",        1, 0, 'p'},  //Port
178 {"admin",       1, 0, 'a'},  //Admin
179 {"admin_pass",  1, 0, 'w'},  //passWord
180 {"user",        1, 0, 'u'},  //User
181 {"addcash",     0, 0, 'c'},  //Add Cash
182 //{"setcash",     0, 0, 'v'},  //Set Cash
183 {"credit",      0, 0, 'r'},  //cRedit
184 {"tariff",      0, 0, 't'},  //Tariff
185 {"message",     0, 0, 'm'},  //message
186 {"password",    0, 0, 'o'},  //password
187 {"down",        0, 0, 'd'},  //down
188 {"passive",     0, 0, 'i'},  //passive
189 {"disable-stat",0, 0, 'S'},  //disable detail stat
190 {"always-online",0, 0, 'O'}, //always online
191 {"session-upload",   1, 0, 500},  //SU0
192 {"session-download", 1, 0, 501},  //SD0
193 {"month-upload",     1, 0, 502},  //MU0
194 {"month-download",   1, 0, 503},  //MD0
195
196 {"user-data",   1, 0, 700},  //UserData0
197
198 {"prepaid",     0, 0, 'e'},  //prepaid traff
199 {"create",      0, 0, 'n'},  //create
200 {"delete",      0, 0, 'l'},  //delete
201
202 {"note",        0, 0, 'N'},  //Note
203 {"name",        0, 0, 'A'},  //nAme
204 {"address",     0, 0, 'D'},  //aDdress
205 {"email",       0, 0, 'L'},  //emaiL
206 {"phone",       0, 0, 'P'},  //phone
207 {"group",       0, 0, 'G'},  //Group
208 {"ip",          0, 0, 'I'},  //IP-address of user
209 {"authorized-by",0, 0, 800}, //always online
210
211 {0, 0, 0, 0}};
212
213 struct option long_options_set[] = {
214 {"server",      1, 0, 's'},  //Server
215 {"port",        1, 0, 'p'},  //Port
216 {"admin",       1, 0, 'a'},  //Admin
217 {"admin_pass",  1, 0, 'w'},  //passWord
218 {"user",        1, 0, 'u'},  //User
219 {"addcash",     1, 0, 'c'},  //Add Cash
220 {"setcash",     1, 0, 'v'},  //Set Cash
221 {"credit",      1, 0, 'r'},  //cRedit
222 {"tariff",      1, 0, 't'},  //Tariff
223 {"message",     1, 0, 'm'},  //message
224 {"password",    1, 0, 'o'},  //password
225 {"down",        1, 0, 'd'},  //down
226 {"passive",     1, 0, 'i'},  //passive
227 {"disable-stat",1, 0, 'S'},  //disable detail stat
228 {"always-online",1, 0, 'O'},  //always online
229 {"session-upload",   1, 0, 500},  //U0
230 {"session-download", 1, 0, 501},  //U1
231 {"month-upload",     1, 0, 502},  //U2
232 {"month-download",   1, 0, 503},  //U3
233
234 {"user-data",        1, 0, 700},  //UserData
235
236 {"prepaid",     1, 0, 'e'},  //prepaid traff
237 {"create",      1, 0, 'n'},  //create
238 {"delete",      1, 0, 'l'},  //delete
239
240 {"note",        1, 0, 'N'},  //Note
241 {"name",        1, 0, 'A'},  //nAme
242 {"address",     1, 0, 'D'},  //aDdress
243 {"email",       1, 0, 'L'},  //emaiL
244 {"phone",       1, 0, 'P'},  //phone
245 {"group",       1, 0, 'G'},  //Group
246 {"ip",          0, 0, 'I'},  //IP-address of user
247
248 {0, 0, 0, 0}};
249
250 //-----------------------------------------------------------------------------
251 CASH_INFO ParseCash(const char * str)
252 {
253 //-c 123.45:log message
254 std::string cashString;
255 std::string message;
256 const char * pos = strchr(str, ':');
257 if (pos != NULL)
258     {
259     cashString.append(str, pos);
260     message.append(pos + 1);
261     }
262 else
263     cashString = str;
264
265 double cash = 0;
266 if (strtodouble2(cashString, cash) != 0)
267     {
268     printf("Incorrect cash value %s\n", str);
269     exit(PARAMETER_PARSING_ERR_CODE);
270     }
271
272 return CASH_INFO(cash, message);
273 }
274 //-----------------------------------------------------------------------------
275 double ParseCredit(const char * c)
276 {
277 double credit;
278 if (strtodouble2(c, credit) != 0)
279     {
280     printf("Incorrect credit value %s\n", c);
281     exit(PARAMETER_PARSING_ERR_CODE);
282     }
283
284 return credit;
285 }
286 //-----------------------------------------------------------------------------
287 double ParsePrepaidTraffic(const char * c)
288 {
289 double credit;
290 if (strtodouble2(c, credit) != 0)
291     {
292     printf("Incorrect prepaid traffic value %s\n", c);
293     exit(PARAMETER_PARSING_ERR_CODE);
294     }
295
296 return credit;
297 }
298 //-----------------------------------------------------------------------------
299 int64_t ParseTraff(const char * c)
300 {
301 int64_t traff;
302 if (str2x(c, traff) != 0)
303     {
304     printf("Incorrect credit value %s\n", c);
305     exit(PARAMETER_PARSING_ERR_CODE);
306     }
307
308 return traff;
309 }
310 //-----------------------------------------------------------------------------
311 bool ParseDownPassive(const char * dp)
312 {
313 if (!(dp[1] == 0 && (dp[0] == '1' || dp[0] == '0')))
314     {
315     printf("Incorrect value %s\n", dp);
316     exit(PARAMETER_PARSING_ERR_CODE);
317     }
318
319 return dp[0] - '0';
320 }
321 //-----------------------------------------------------------------------------
322 void ParseTariff(const char * str, RESETABLE<std::string> & tariffName, RESETABLE<std::string> & nextTariff)
323 {
324 const char * pos = strchr(str, ':');
325 if (pos != NULL)
326     {
327     std::string tariff(str, pos);
328     if (strcmp(pos + 1, "now") == 0)
329         tariffName = tariff;
330     else if (strcmp(pos + 1, "delayed") == 0)
331         nextTariff = tariff;
332     else
333         {
334         printf("Incorrect tariff value '%s'. Should be '<tariff>', '<tariff>:now' or '<tariff>:delayed'.\n", str);
335         exit(PARAMETER_PARSING_ERR_CODE);
336         }
337     }
338 else
339     tariffName = str;
340 }
341 //-----------------------------------------------------------------------------
342 time_t ParseCreditExpire(const char * str)
343 {
344 struct tm brokenTime;
345
346 brokenTime.tm_wday = 0;
347 brokenTime.tm_yday = 0;
348 brokenTime.tm_isdst = 0;
349 brokenTime.tm_hour = 0;
350 brokenTime.tm_min = 0;
351 brokenTime.tm_sec = 0;
352
353 stg_strptime(str, "%Y-%m-%d", &brokenTime);
354
355 return stg_timegm(&brokenTime);
356 }
357 //-----------------------------------------------------------------------------
358 void ParseAnyString(const char * c, string * msg, const char * enc)
359 {
360 iconv_t cd;
361 char * ob = new char[strlen(c) + 1];
362 char * ib = new char[strlen(c) + 1];
363
364 strcpy(ib, c);
365
366 char * outbuf = ob;
367 char * inbuf = ib;
368
369 setlocale(LC_ALL, "");
370
371 char charsetF[255];
372 strncpy(charsetF, nl_langinfo(CODESET), 255);
373
374 const char * charsetT = enc;
375
376 size_t nconv = 1;
377
378 size_t insize = strlen(ib);
379 size_t outsize = strlen(ib);
380
381 insize = strlen(c);
382
383 cd = iconv_open(charsetT, charsetF);
384 if (cd == (iconv_t) -1)
385     {
386     if (errno == EINVAL)
387         {
388         printf("Warning: iconv from %s to %s failed\n", charsetF, charsetT);
389         *msg = c;
390         return;
391         }
392     else
393         printf("error iconv_open\n");
394
395     exit(ICONV_ERR_CODE);
396     }
397
398 #if defined(FREE_BSD) || defined(FREE_BSD5)
399 nconv = iconv (cd, (const char**)&inbuf, &insize, &outbuf, &outsize);
400 #else
401 nconv = iconv (cd, &inbuf, &insize, &outbuf, &outsize);
402 #endif
403 //printf("nconv=%d outsize=%d\n", nconv, outsize);
404 if (nconv == (size_t) -1)
405     {
406     if (errno != EINVAL)
407         {
408         printf("iconv error\n");
409         exit(ICONV_ERR_CODE);
410         }
411     }
412
413 *outbuf = L'\0';
414
415 iconv_close(cd);
416 *msg = ob;
417
418 delete[] ob;
419 delete[] ib;
420 }
421 //-----------------------------------------------------------------------------
422 void CreateRequestSet(REQUEST * req, char * r)
423 {
424 const int strLen = 10024;
425 char str[strLen];
426 memset(str, 0, strLen);
427
428 r[0] = 0;
429
430 if (!req->usrMsg.empty())
431     {
432     string msg;
433     Encode12str(msg, req->usrMsg.data());
434     sprintf(str, "<Message login=\"%s\" msgver=\"1\" msgtype=\"1\" repeat=\"0\" repeatperiod=\"0\" showtime=\"0\" text=\"%s\"/>", req->login.const_data().c_str(), msg.c_str());
435     //sprintf(str, "<message login=\"%s\" priority=\"0\" text=\"%s\"/>\n", req->login, msg);
436     strcat(r, str);
437     return;
438     }
439
440 if (req->deleteUser)
441     {
442     sprintf(str, "<DelUser login=\"%s\"/>", req->login.const_data().c_str());
443     strcat(r, str);
444     //printf("%s\n", r);
445     return;
446     }
447
448 if (req->createUser)
449     {
450     sprintf(str, "<AddUser> <login value=\"%s\"/> </AddUser>", req->login.const_data().c_str());
451     strcat(r, str);
452     //printf("%s\n", r);
453     return;
454     }
455
456 strcat(r, "<SetUser>\n");
457 sprintf(str, "<login value=\"%s\"/>\n", req->login.const_data().c_str());
458 strcat(r, str);
459 if (!req->credit.empty())
460     {
461     sprintf(str, "<credit value=\"%f\"/>\n", req->credit.const_data());
462     strcat(r, str);
463     }
464
465 if (!req->creditExpire.empty())
466     {
467     sprintf(str, "<creditExpire value=\"%ld\"/>\n", req->creditExpire.const_data());
468     strcat(r, str);
469     }
470
471 if (!req->prepaidTraff.empty())
472     {
473     sprintf(str, "<FreeMb value=\"%f\"/>\n", req->prepaidTraff.const_data());
474     strcat(r, str);
475     }
476
477 if (!req->cash.empty())
478     {
479     string msg;
480     Encode12str(msg, req->message);
481     sprintf(str, "<cash add=\"%f\" msg=\"%s\"/>\n", req->cash.const_data(), msg.c_str());
482     strcat(r, str);
483     }
484
485 if (!req->setCash.empty())
486     {
487     string msg;
488     Encode12str(msg, req->message);
489     sprintf(str, "<cash set=\"%f\" msg=\"%s\"/>\n", req->setCash.const_data(), msg.c_str());
490     strcat(r, str);
491     }
492
493 if (!req->usrPasswd.empty())
494     {
495     sprintf(str, "<password value=\"%s\" />\n", req->usrPasswd.const_data().c_str());
496     strcat(r, str);
497     }
498
499 if (!req->down.empty())
500     {
501     sprintf(str, "<down value=\"%d\" />\n", req->down.const_data());
502     strcat(r, str);
503     }
504
505 if (!req->passive.empty())
506     {
507     sprintf(str, "<passive value=\"%d\" />\n", req->passive.const_data());
508     strcat(r, str);
509     }
510
511 if (!req->disableDetailStat.empty())
512     {
513     sprintf(str, "<disableDetailStat value=\"%d\" />\n", req->disableDetailStat.const_data());
514     strcat(r, str);
515     }
516
517 if (!req->alwaysOnline.empty())
518     {
519     sprintf(str, "<aonline value=\"%d\" />\n", req->alwaysOnline.const_data());
520     strcat(r, str);
521     }
522
523 // IP-address of user
524 if (!req->ips.empty())
525     {
526     sprintf(str, "<ip value=\"%s\" />\n", req->ips.const_data().c_str());
527     strcat(r, str);
528     }
529
530 int uPresent = false;
531 int dPresent = false;
532 for (int i = 0; i < DIR_NUM; i++)
533     {
534     if (!req->monthUpload[i].empty())
535         {
536         if (!uPresent && !dPresent)
537             {
538             sprintf(str, "<traff ");
539             strcat(r, str);
540             uPresent = true;
541             }
542
543         stringstream ss;
544         ss << req->monthUpload[i].const_data();
545         //sprintf(str, "MU%d=\"%lld\" ", i, req->u[i].const_data());
546         sprintf(str, "MU%d=\"%s\" ", i, ss.str().c_str());
547         strcat(r, str);
548         }
549     if (!req->monthDownload[i].empty())
550         {
551         if (!uPresent && !dPresent)
552             {
553             sprintf(str, "<traff ");
554             strcat(r, str);
555             dPresent = true;
556             }
557
558         stringstream ss;
559         ss << req->monthDownload[i].const_data();
560         sprintf(str, "MD%d=\"%s\" ", i, ss.str().c_str());
561         strcat(r, str);
562         }
563     if (!req->sessionUpload[i].empty())
564         {
565         if (!uPresent && !dPresent)
566             {
567             sprintf(str, "<traff ");
568             strcat(r, str);
569             uPresent = true;
570             }
571
572         stringstream ss;
573         ss << req->sessionUpload[i].const_data();
574         //sprintf(str, "MU%d=\"%lld\" ", i, req->u[i].const_data());
575         sprintf(str, "MU%d=\"%s\" ", i, ss.str().c_str());
576         strcat(r, str);
577         }
578     if (!req->sessionDownload[i].empty())
579         {
580         if (!uPresent && !dPresent)
581             {
582             sprintf(str, "<traff ");
583             strcat(r, str);
584             dPresent = true;
585             }
586
587         stringstream ss;
588         ss << req->sessionDownload[i].const_data();
589         sprintf(str, "MD%d=\"%s\" ", i, ss.str().c_str());
590         strcat(r, str);
591         }
592     }
593 if (uPresent || dPresent)
594     {
595     strcat(r, "/>");
596     }
597
598 //printf("%s\n", r);
599
600 if (!req->tariff.empty())
601     {
602     switch (req->chgTariff)
603         {
604         case TARIFF_NOW:
605             sprintf(str, "<tariff now=\"%s\"/>\n", req->tariff.const_data().c_str());
606             strcat(r, str);
607             break;
608         case TARIFF_REC:
609             sprintf(str, "<tariff recalc=\"%s\"/>\n", req->tariff.const_data().c_str());
610             strcat(r, str);
611             break;
612         case TARIFF_DEL:
613             sprintf(str, "<tariff delayed=\"%s\"/>\n", req->tariff.const_data().c_str());
614             strcat(r, str);
615             break;
616         }
617
618     }
619
620 if (!req->note.empty())
621     {
622     string note;
623     Encode12str(note, req->note.data());
624     sprintf(str, "<note value=\"%s\"/>", note.c_str());
625     strcat(r, str);
626     }
627
628 if (!req->name.empty())
629     {
630     string name;
631     Encode12str(name, req->name.data());
632     sprintf(str, "<name value=\"%s\"/>", name.c_str());
633     strcat(r, str);
634     }
635
636 if (!req->address.empty())
637     {
638     string address;
639     Encode12str(address, req->address.data());
640     sprintf(str, "<address value=\"%s\"/>", address.c_str());
641     strcat(r, str);
642     }
643
644 if (!req->email.empty())
645     {
646     string email;
647     Encode12str(email, req->email.data());
648     sprintf(str, "<email value=\"%s\"/>", email.c_str());
649     strcat(r, str);
650     }
651
652 if (!req->phone.empty())
653     {
654     string phone;
655     Encode12str(phone, req->phone.data());
656     sprintf(str, "<phone value=\"%s\"/>", phone.c_str());
657     strcat(r, str);
658     }
659
660 if (!req->group.empty())
661     {
662     string group;
663     Encode12str(group, req->group.data());
664     sprintf(str, "<group value=\"%s\"/>", group.c_str());
665     strcat(r, str);
666     }
667
668 for (int i = 0; i < USERDATA_NUM; i++)
669     {
670     if (!req->userData[i].empty())
671         {
672         string ud;
673         Encode12str(ud, req->userData[i].data());
674         sprintf(str, "<userdata%d value=\"%s\"/>", i, ud.c_str());
675         strcat(r, str);
676         }
677     }
678
679 strcat(r, "</SetUser>\n");
680 }
681 //-----------------------------------------------------------------------------
682 int CheckParameters(REQUEST * req)
683 {
684 bool su = false;
685 bool sd = false;
686 bool mu = false;
687 bool md = false;
688 bool ud = false;
689 bool a = !req->admLogin.empty()
690     && !req->admPasswd.empty()
691     && !req->server.empty()
692     && !req->port.empty()
693     && !req->login.empty();
694
695 bool b = !req->cash.empty()
696     || !req->setCash.empty()
697     || !req->credit.empty()
698     || !req->prepaidTraff.empty()
699     || !req->tariff.empty()
700     || !req->usrMsg.empty()
701     || !req->usrPasswd.empty()
702
703     || !req->note.empty()
704     || !req->name.empty()
705     || !req->address.empty()
706     || !req->email.empty()
707     || !req->phone.empty()
708     || !req->group.empty()
709     || !req->ips.empty() // IP-address of user
710
711     || !req->createUser
712     || !req->deleteUser;
713
714
715 for (int i = 0; i < DIR_NUM; i++)
716     {
717     if (req->sessionUpload[i].empty())
718         {
719         su = true;
720         break;
721         }
722     }
723
724 for (int i = 0; i < DIR_NUM; i++)
725     {
726     if (req->sessionDownload[i].empty())
727         {
728         sd = true;
729         break;
730         }
731     }
732
733 for (int i = 0; i < DIR_NUM; i++)
734     {
735     if (req->monthUpload[i].empty())
736         {
737         mu = true;
738         break;
739         }
740     }
741
742 for (int i = 0; i < DIR_NUM; i++)
743     {
744     if (req->monthDownload[i].empty())
745         {
746         md = true;
747         break;
748         }
749     }
750
751 for (int i = 0; i < DIR_NUM; i++)
752     {
753     if (req->userData[i].empty())
754         {
755         ud = true;
756         break;
757         }
758     }
759
760
761 //printf("a=%d, b=%d, u=%d, d=%d ud=%d\n", a, b, u, d, ud);
762 return a && (b || su || sd || mu || md || ud);
763 }
764 //-----------------------------------------------------------------------------
765 int CheckParametersGet(REQUEST * req)
766 {
767 return CheckParameters(req);
768 }
769 //-----------------------------------------------------------------------------
770 int CheckParametersSet(REQUEST * req)
771 {
772 return CheckParameters(req);
773 }
774 //-----------------------------------------------------------------------------
775 bool mainGet(int argc, char **argv)
776 {
777 int c;
778 REQUEST req;
779 RESETABLE<string>   t1;
780 int missedOptionArg = false;
781
782 const char * short_options_get = "s:p:a:w:u:crtmodieNADLPGISOE";
783 int option_index = -1;
784
785 while (1)
786     {
787     option_index = -1;
788     c = getopt_long(argc, argv, short_options_get, long_options_get, &option_index);
789     if (c == -1)
790         break;
791
792     switch (c)
793         {
794         case 's': //server
795             req.server = optarg;
796             break;
797
798         case 'p': //port
799             req.port = ParseServerPort(optarg);
800             //req.portReq = 1;
801             break;
802
803         case 'a': //admin
804             req.admLogin = ParseAdminLogin(optarg);
805             break;
806
807         case 'w': //admin password
808             req.admPasswd = ParsePassword(optarg);
809             break;
810
811         case 'o': //change user password
812             req.usrPasswd = " ";
813             break;
814
815         case 'u': //user
816             req.login = ParseUser(optarg);
817             break;
818
819         case 'c': //get cash
820             req.cash = 1;
821             break;
822
823         case 'r': //credit
824             req.credit = 1;
825             break;
826
827         case 'E': //credit expire
828             req.creditExpire = 1;
829             break;
830
831         case 'd': //down
832             req.down = 1;
833             break;
834
835         case 'i': //passive
836             req.passive = 1;
837             break;
838
839         case 't': //tariff
840             req.tariff = " ";
841             break;
842
843         case 'e': //Prepaid Traffic
844             req.prepaidTraff = 1;
845             break;
846
847         case 'N': //Note
848             req.note = " ";
849             break;
850
851         case 'A': //nAme
852             req.name = " ";
853             break;
854
855         case 'D': //aDdress
856             req.address =" ";
857             break;
858
859         case 'L': //emaiL
860             req.email = " ";
861             break;
862
863         case 'P': //phone
864             req.phone = " ";
865             break;
866
867         case 'G': //Group
868             req.group = " ";
869             break;
870
871         case 'I': //IP-address of user
872             req.ips = " ";
873             break;
874
875         case 'S': //Detail stat status
876             req.disableDetailStat = " ";
877             break;
878
879         case 'O': //Always online status
880             req.alwaysOnline = " ";
881             break;
882
883         case 500: //U
884             SetArrayItem(req.sessionUpload, optarg, 1);
885             //req.sessionUpload[optarg] = 1;
886             break;
887         case 501:
888             SetArrayItem(req.sessionDownload, optarg, 1);
889             //req.sessionDownload[optarg] = 1;
890             break;
891         case 502:
892             SetArrayItem(req.monthUpload, optarg, 1);
893             //req.monthUpload[optarg] = 1;
894             break;
895         case 503:
896             SetArrayItem(req.monthDownload, optarg, 1);
897             //req.monthDownload[optarg] = 1;
898             break;
899
900         case 700: //UserData
901             SetArrayItem(req.userData, optarg, std::string(" "));
902             //req.userData[optarg] = " ";
903             break;
904
905         case 800:
906             req.authBy = true;
907             break;
908
909         case '?':
910         case ':':
911             missedOptionArg = true;
912             break;
913
914         default:
915             printf ("?? getopt returned character code 0%o ??\n", c);
916         }
917     }
918
919 if (optind < argc)
920     {
921     printf ("non-option ARGV-elements: ");
922     while (optind < argc)
923         printf ("%s ", argv[optind++]);
924     UsageInfo();
925     exit(PARAMETER_PARSING_ERR_CODE);
926     }
927
928 if (missedOptionArg || !CheckParametersGet(&req))
929     {
930     //printf("Parameter needed\n");
931     UsageInfo();
932     exit(PARAMETER_PARSING_ERR_CODE);
933     }
934
935 if (req.authBy)
936     return ProcessAuthBy(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data());
937 else
938     return ProcessGetUser(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data(), req);
939 }
940 //-----------------------------------------------------------------------------
941 bool mainSet(int argc, char **argv)
942 {
943 string str;
944
945 int c;
946 bool isMessage = false;
947 REQUEST req;
948
949 RESETABLE<string>   t1;
950
951 const char * short_options_set = "s:p:a:w:u:c:r:t:m:o:d:i:e:v:nlN:A:D:L:P:G:I:S:O:E:";
952
953 int missedOptionArg = false;
954
955 USER_CONF_RES conf;
956 USER_STAT_RES stat;
957 while (1)
958     {
959     int option_index = -1;
960
961     c = getopt_long(argc, argv, short_options_set, long_options_set, &option_index);
962
963     if (c == -1)
964         break;
965
966     switch (c)
967         {
968         case 's': //server
969             req.server = optarg;
970             break;
971
972         case 'p': //port
973             req.port = ParseServerPort(optarg);
974             //req.portReq = 1;
975             break;
976
977         case 'a': //admin
978             req.admLogin = ParseAdminLogin(optarg);
979             break;
980
981         case 'w': //admin password
982             req.admPasswd = ParsePassword(optarg);
983             break;
984
985         case 'o': //change user password
986             conf.password = ParsePassword(optarg);
987             break;
988
989         case 'u': //user
990             req.login = ParseUser(optarg);
991             break;
992
993         case 'c': //add cash
994             stat.cashAdd = ParseCash(optarg);
995             break;
996
997         case 'v': //set cash
998             stat.cashSet = ParseCash(optarg);
999             break;
1000
1001         case 'r': //credit
1002             conf.credit = ParseCredit(optarg);
1003             break;
1004
1005         case 'E': //credit expire
1006             conf.creditExpire = ParseCreditExpire(optarg);
1007             break;
1008
1009         case 'd': //down
1010             conf.disabled = ParseDownPassive(optarg);
1011             break;
1012
1013         case 'i': //passive
1014             conf.passive = ParseDownPassive(optarg);
1015             break;
1016
1017         case 't': //tariff
1018             ParseTariff(optarg, conf.tariffName, conf.nextTariff);
1019             break;
1020
1021         case 'm': //message
1022             ParseAnyString(optarg, &str);
1023             req.usrMsg = str;
1024             isMessage = true;
1025             break;
1026
1027         case 'e': //Prepaid Traffic
1028             stat.freeMb = ParsePrepaidTraffic(optarg);
1029             break;
1030
1031         case 'n': //Create User
1032             req.createUser = true;
1033             break;
1034
1035         case 'l': //Delete User
1036             req.deleteUser = true;
1037             break;
1038
1039         case 'N': //Note
1040             ParseAnyString(optarg, &str, "koi8-ru");
1041             conf.note = str;
1042             break;
1043
1044         case 'A': //nAme
1045             ParseAnyString(optarg, &str, "koi8-ru");
1046             conf.realName = str;
1047             break;
1048
1049         case 'D': //aDdress
1050             ParseAnyString(optarg, &str, "koi8-ru");
1051             conf.address = str;
1052             break;
1053
1054         case 'L': //emaiL
1055             ParseAnyString(optarg, &str, "koi8-ru");
1056             conf.email = str;
1057             break;
1058
1059         case 'P': //phone
1060             ParseAnyString(optarg, &str);
1061             conf.phone = str;
1062             break;
1063
1064         case 'G': //Group
1065             ParseAnyString(optarg, &str, "koi8-ru");
1066             conf.group = str;
1067             break;
1068
1069         case 'I': //IP-address of user
1070             ParseAnyString(optarg, &str);
1071             conf.ips = StrToIPS(str);
1072             break;
1073
1074         case 'S':
1075             conf.disabledDetailStat = ParseDownPassive(optarg);
1076             break;
1077
1078         case 'O':
1079             conf.alwaysOnline = ParseDownPassive(optarg);
1080             break;
1081
1082         case 500: //U
1083             SetArrayItem(stat.sessionUp, optarg, ParseTraff(argv[optind++]));
1084             break;
1085         case 501:
1086             SetArrayItem(stat.sessionDown, optarg, ParseTraff(argv[optind++]));
1087             break;
1088         case 502:
1089             SetArrayItem(stat.monthUp, optarg, ParseTraff(argv[optind++]));
1090             break;
1091         case 503:
1092             SetArrayItem(stat.monthDown, optarg, ParseTraff(argv[optind++]));
1093             break;
1094
1095         case 700: //UserData
1096             ParseAnyString(argv[optind++], &str);
1097             SetArrayItem(conf.userdata, optarg, str);
1098             break;
1099
1100         case '?':
1101             missedOptionArg = true;
1102             break;
1103
1104         case ':':
1105             missedOptionArg = true;
1106             break;
1107
1108         default:
1109             printf("?? getopt returned character code 0%o ??\n", c);
1110         }
1111     }
1112
1113 if (optind < argc)
1114     {
1115     printf ("non-option ARGV-elements: ");
1116     while (optind < argc)
1117         printf ("%s ", argv[optind++]);
1118     UsageConf();
1119     exit(PARAMETER_PARSING_ERR_CODE);
1120     }
1121
1122 if (missedOptionArg || !CheckParametersSet(&req))
1123     {
1124     //printf("Parameter needed\n");
1125     UsageConf();
1126     exit(PARAMETER_PARSING_ERR_CODE);
1127     }
1128
1129 const int rLen = 20000;
1130 char rstr[rLen];
1131 memset(rstr, 0, rLen);
1132
1133 if (isMessage)
1134     return ProcessSendMessage(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data(), req.usrMsg.data());
1135
1136 return ProcessSetUser(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data(), conf, stat);
1137 }
1138 //-----------------------------------------------------------------------------
1139 int main(int argc, char **argv)
1140 {
1141 UsageAll();
1142 exit(0);
1143
1144 SGCONF::CONFIG config;
1145
1146 SGCONF::OPTION_BLOCK generalOptions;
1147 generalOptions.Add("c", "config", SGCONF::MakeParamAction(config.configFile, std::string("~/.config/stg/sgconf.conf"), "<config file>"), "override default config file");
1148 generalOptions.Add("h", "help", SGCONF::MakeFunc0Action(Usage), "show this help and exit");
1149 generalOptions.Add("help-all", SGCONF::MakeFunc0Action(UsageAll), "show full help and exit");
1150 generalOptions.Add("v", "version", SGCONF::MakeFunc0Action(Version), "show version information and exit");
1151
1152 SGCONF::OPTION_BLOCK connOptions;
1153 connOptions.Add("s", "server", SGCONF::MakeParamAction(config.server, std::string("localhost"), "<address>"), "host to connect");
1154 connOptions.Add("p", "port", SGCONF::MakeParamAction(config.port, uint16_t(5555), "<port>"), "port to connect");
1155 connOptions.Add("u", "username", SGCONF::MakeParamAction(config.userName, std::string("admin"), "<username>"), "administrative login");
1156 connOptions.Add("w", "userpass", SGCONF::MakeParamAction(config.userPass, "<password>"), "password for the administrative login");
1157 connOptions.Add("a", "address", SGCONF::MakeParamAction(config, "<connection string>"), "connection params as a single string in format: <login>:<password>@<host>:<port>");
1158
1159 if (argc < 2)
1160     {
1161     Usage();
1162     return 1;
1163     }
1164
1165 if (argc <= 2)
1166     {
1167     UsageConf();
1168     exit(PARAMETER_PARSING_ERR_CODE);
1169     }
1170
1171 if (strcmp(argv[1], "get") == 0)
1172     {
1173     //printf("get\n");
1174     return mainGet(argc - 1, argv + 1);
1175     }
1176 else if (strcmp(argv[1], "set") == 0)
1177     {
1178     //printf("set\n");
1179     if (mainSet(argc - 1, argv + 1) )
1180         return 0;
1181     return -1;
1182     }
1183 else
1184     {
1185     UsageConf();
1186     exit(PARAMETER_PARSING_ERR_CODE);
1187     }
1188 return UNKNOWN_ERR_CODE;
1189 }
1190 //-----------------------------------------------------------------------------
1191
1192 namespace
1193 {
1194
1195 void Usage()
1196 {
1197 UsageImpl(false);
1198 }
1199
1200 void UsageAll()
1201 {
1202 UsageImpl(true);
1203 }
1204
1205 void UsageImpl(bool full)
1206 {
1207 std::cout << "sgconf is the Stargazer management utility.\n\n"
1208           << "Usage:\n"
1209           << "\tsgconf [options]\n\n"
1210           << "General options:\n"
1211           << "\t-c, --config <config file>\t\toverride default config file (default: \"~/.config/stg/sgconf.conf\")\n"
1212           << "\t-h, --help\t\t\t\tshow this help and exit\n"
1213           << "\t--help-all\t\t\t\tshow full help and exit\n"
1214           << "\t-v, --version\t\t\t\tshow version information and exit\n\n";
1215 UsageConnection();
1216 UsageAdmins(full);
1217 UsageTariffs(full);
1218 UsageUsers(full);
1219 UsageServices(full);
1220 UsageCorporations(full);
1221 }
1222 //-----------------------------------------------------------------------------
1223 void UsageConnection()
1224 {
1225 std::cout << "Connection options:\n"
1226           << "\t-s, --server <address>\t\t\thost to connect (ip or domain name, default: \"localhost\")\n"
1227           << "\t-p, --port <port>\t\t\tport to connect (default: \"5555\")\n"
1228           << "\t-u, --username <username>\t\tadministrative login (default: \"admin\")\n"
1229           << "\t-w, --userpass <password>\t\tpassword for administrative login\n"
1230           << "\t-a, --address <connection string>\tconnection params as a single string in format: <login>:<password>@<host>:<port>\n\n";
1231 }
1232 //-----------------------------------------------------------------------------
1233 void UsageAdmins(bool full)
1234 {
1235 std::cout << "Admins management options:\n"
1236           << "\t--get-admins\t\t\t\tget a list of admins (subsequent options will define what to show)\n";
1237 if (full)
1238     std::cout << "\t\t--login\t\t\t\tshow admin's login\n"
1239               << "\t\t--priv\t\t\t\tshow admin's priviledges\n\n";
1240 std::cout << "\t--get-admin\t\t\t\tget the information about admin\n";
1241 if (full)
1242     std::cout << "\t\t--login <login>\t\t\tlogin of the admin to show\n"
1243               << "\t\t--priv\t\t\t\tshow admin's priviledges\n\n";
1244 std::cout << "\t--add-admin\t\t\t\tadd a new admin\n";
1245 if (full)
1246     std::cout << "\t\t--login <login>\t\t\tlogin of the admin to add\n"
1247               << "\t\t--password <password>\t\tpassword of the admin to add\n"
1248               << "\t\t--priv <priv number>\t\tpriviledges of the admin to add\n\n";
1249 std::cout << "\t--del-admin\t\t\t\tdelete an existing admin\n";
1250 if (full)
1251     std::cout << "\t\t--login <login>\t\t\tlogin of the admin to delete\n\n";
1252 std::cout << "\t--chg-admin\t\t\t\tchange an existing admin\n";
1253 if (full)
1254     std::cout << "\t\t--login <login>\t\t\tlogin of the admin to change\n"
1255               << "\t\t--priv <priv number>\t\tnew priviledges\n\n";
1256 }
1257 //-----------------------------------------------------------------------------
1258 void UsageTariffs(bool full)
1259 {
1260 std::cout << "Tariffs management options:\n"
1261           << "\t--get-tariffs\t\t\t\tget a list of tariffs (subsequent options will define what to show)\n";
1262 if (full)
1263     std::cout << "\t\t--name\t\t\t\tshow tariff's name\n"
1264               << "\t\t--fee\t\t\t\tshow tariff's fee\n"
1265               << "\t\t--free\t\t\t\tshow tariff's prepaid traffic in terms of cost\n"
1266               << "\t\t--passive-cost\t\t\tshow tariff's cost of \"freeze\"\n"
1267               << "\t\t--traff-type\t\t\tshow what type of traffix will be accounted by the tariff\n"
1268               << "\t\t--dirs\t\t\t\tshow tarification rules for directions\n\n";
1269 std::cout << "\t--get-tariff\t\t\t\tget the information about tariff\n";
1270 if (full)
1271     std::cout << "\t\t--name <name>\t\t\tname of the tariff to show\n"
1272               << "\t\t--fee\t\t\t\tshow tariff's fee\n"
1273               << "\t\t--free\t\t\t\tshow tariff's prepaid traffic in terms of cost\n"
1274               << "\t\t--passive-cost\t\t\tshow tariff's cost of \"freeze\"\n"
1275               << "\t\t--traff-type\t\t\tshow what type of traffix will be accounted by the tariff\n"
1276               << "\t\t--dirs\t\t\t\tshow tarification rules for directions\n\n";
1277 std::cout << "\t--add-tariff\t\t\t\tadd a new tariff\n";
1278 if (full)
1279     std::cout << "\t\t--name <name>\t\t\tname of the tariff to add\n"
1280               << "\t\t--fee <fee>\t\t\tstariff's fee\n"
1281               << "\t\t--free <free>\t\t\ttariff's prepaid traffic in terms of cost\n"
1282               << "\t\t--passive-cost <cost>\t\ttariff's cost of \"freeze\"\n"
1283               << "\t\t--traff-type <type>\t\twhat type of traffi will be accounted by the tariff\n"
1284               << "\t\t--times <times>\t\t\tslash-separated list of \"day\" time-spans (in form \"hh:mm-hh:mm\") for each direction\n"
1285               << "\t\t--prices-day-a <prices>\t\tslash-separated list of prices for \"day\" traffic before threshold for each direction\n"
1286               << "\t\t--prices-night-a <prices>\tslash-separated list of prices for \"night\" traffic before threshold for each direction\n"
1287               << "\t\t--prices-day-b <prices>\t\tslash-separated list of prices for \"day\" traffic after threshold for each direction\n"
1288               << "\t\t--prices-night-b <prices>\tslash-separated list of prices for \"night\" traffic after threshold for each direction\n"
1289               << "\t\t--single-prices <yes|no>\tslash-separated list of \"single price\" flags for each direction\n"
1290               << "\t\t--no-discounts <yes|no>\t\tslash-separated list of \"no discount\" flags for each direction\n"
1291               << "\t\t--thresholds <thresholds>\tslash-separated list of thresholds (in Mb) for each direction\n\n";
1292 std::cout << "\t--del-tariff\t\t\t\tdelete an existing tariff\n";
1293 if (full)
1294     std::cout << "\t\t--name <name>\t\t\tname of the tariff to delete\n\n";
1295 std::cout << "\t--chg-tariff\t\t\t\tchange an existing tariff\n";
1296 if (full)
1297     std::cout << "\t\t--name <name>\t\t\tname of the tariff to change\n"
1298               << "\t\t--fee <fee>\t\t\tstariff's fee\n"
1299               << "\t\t--free <free>\t\t\ttariff's prepaid traffic in terms of cost\n"
1300               << "\t\t--passive-cost <cost>\t\ttariff's cost of \"freeze\"\n"
1301               << "\t\t--traff-type <type>\t\twhat type of traffix will be accounted by the tariff\n"
1302               << "\t\t--dir <N>\t\t\tnumber of direction data to change\n"
1303               << "\t\t\t--time <time>\t\t\"day\" time-span (in form \"hh:mm-hh:mm\")\n"
1304               << "\t\t\t--price-day-a <price>\tprice for \"day\" traffic before threshold\n"
1305               << "\t\t\t--price-night-a <price>\tprice for \"night\" traffic before threshold\n"
1306               << "\t\t\t--price-day-b <price>\tprice for \"day\" traffic after threshold\n"
1307               << "\t\t\t--price-night-b <price>\tprice for \"night\" traffic after threshold\n"
1308               << "\t\t\t--single-price <yes|no>\t\"single price\" flag\n"
1309               << "\t\t\t--no-discount <yes|no>\t\"no discount\" flag\n"
1310               << "\t\t\t--threshold <threshold>\tthreshold (in Mb)\n\n";
1311 }
1312 //-----------------------------------------------------------------------------
1313 void UsageUsers(bool full)
1314 {
1315 std::cout << "Users management options:\n"
1316           << "\t--get-users\t\t\t\tget a list of users (subsequent options will define what to show)\n";
1317 if (full)
1318     std::cout << "\n\n";
1319 std::cout << "\t--get-user\t\t\t\tget the information about user\n";
1320 if (full)
1321     std::cout << "\n\n";
1322 std::cout << "\t--add-user\t\t\t\tadd a new user\n";
1323 if (full)
1324     std::cout << "\n\n";
1325 std::cout << "\t--del-user\t\t\t\tdelete an existing user\n";
1326 if (full)
1327     std::cout << "\n\n";
1328 std::cout << "\t--chg-user\t\t\t\tchange an existing user\n";
1329 if (full)
1330     std::cout << "\n\n";
1331 std::cout << "\t--check-user\t\t\t\tcheck credentials is valid\n";
1332 if (full)
1333     std::cout << "\n\n";
1334 std::cout << "\t--send-message\t\t\t\tsend a message to a user\n";
1335 if (full)
1336     std::cout << "\n\n";
1337 }
1338 //-----------------------------------------------------------------------------
1339 void UsageServices(bool full)
1340 {
1341 std::cout << "Services management options:\n"
1342           << "\t--get-services\t\t\t\tget a list of services (subsequent options will define what to show)\n";
1343 if (full)
1344     std::cout << "\t\t--name\t\t\t\tshow service's name\n"
1345               << "\t\t--comment\t\t\tshow a comment to the service\n"
1346               << "\t\t--cost\t\t\t\tshow service's cost\n"
1347               << "\t\t--pay-day\t\t\tshow service's pay day\n\n";
1348 std::cout << "\t--get-service\t\t\t\tget the information about service\n";
1349 if (full)
1350     std::cout << "\t\t--name <name>\t\t\tname of the service to show\n"
1351               << "\t\t--comment\t\t\tshow a comment to the service\n"
1352               << "\t\t--cost\t\t\t\tshow service's cost\n"
1353               << "\t\t--pay-day\t\t\tshow service's pay day\n\n";
1354 std::cout << "\t--add-service\t\t\t\tadd a new service\n";
1355 if (full)
1356     std::cout << "\t\t--name <name>\t\t\tname of the service to add\n"
1357               << "\t\t--comment <comment>\t\ta comment to the service\n"
1358               << "\t\t--cost <cost>\t\t\tservice's cost\n"
1359               << "\t\t--pay-day <day>\t\t\tservice's pay day\n\n";
1360 std::cout << "\t--del-service\t\t\t\tdelete an existing service\n";
1361 if (full)
1362     std::cout << "\t\t--name <name>\t\t\tname of the service to delete\n\n";
1363 std::cout << "\t--chg-service\t\t\t\tchange an existing service\n";
1364 if (full)
1365     std::cout << "\t\t--name <name>\t\t\tname of the service to change\n"
1366               << "\t\t--comment <comment>\t\ta comment to the service\n"
1367               << "\t\t--cost <cost>\t\t\tservice's cost\n"
1368               << "\t\t--pay-day <day>\t\t\tservice's pay day\n\n";
1369 }
1370 //-----------------------------------------------------------------------------
1371 void UsageCorporations(bool full)
1372 {
1373 std::cout << "Corporations management options:\n"
1374           << "\t--get-corporations\t\t\tget a list of corporations (subsequent options will define what to show)\n";
1375 if (full)
1376     std::cout << "\t\t--name\t\t\t\tshow corporation's name\n"
1377               << "\t\t--cash\t\t\t\tshow corporation's cash\n\n";
1378 std::cout << "\t--get-corp\t\t\t\tget the information about corporation\n";
1379 if (full)
1380     std::cout << "\t\t--name <name>\t\t\tname of the corporation to show\n"
1381               << "\t\t--cash\t\t\t\tshow corporation's cash\n\n";
1382 std::cout << "\t--add-corp\t\t\t\tadd a new corporation\n";
1383 if (full)
1384     std::cout << "\t\t--name <name>\t\t\tname of the corporation to add\n"
1385               << "\t\t--cash <cash>\t\t\tinitial corporation's cash (default: \"0\")\n\n";
1386 std::cout << "\t--del-corp\t\t\t\tdelete an existing corporation\n";
1387 if (full)
1388     std::cout << "\t\t--name <name>\t\t\tname of the corporation to delete\n\n";
1389 std::cout << "\t--chg-corp\t\t\t\tchange an existing corporation\n";
1390 if (full)
1391     std::cout << "\t\t--name <name>\t\t\tname of the corporation to change\n"
1392               << "\t\t--add-cash <amount>[:<message>]\tadd cash to the corporation's account and optional comment message\n"
1393               << "\t\t--set-cash <cash>[:<message>]\tnew corporation's cash and optional comment message\n\n";
1394 }
1395
1396 void Version()
1397 {
1398 std::cout << "sgconf, version: 2.0.0-alpha.\n";
1399 }
1400
1401 } // namespace anonymous