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.
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.
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
18 * Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
19 * Author : Maxim Mamontov <faust@stargazer.dp.ua>
23 #include "common_sg.h"
24 #include "sg_error_codes.h"
32 #include "stg/user_conf.h"
33 #include "stg/user_stat.h"
34 #include "stg/common.h"
55 typedef typename T::value_type type;
59 struct ARRAY_TYPE<T[]>
64 template <typename T, size_t N>
65 struct ARRAY_TYPE<T[N]>
71 struct nullary_function
73 typedef T result_type;
77 class binder0 : public nullary_function<typename F::result_type>
80 binder0(const F & func, const typename F::argument_type & arg)
81 : m_func(func), m_arg(arg) {}
82 typename F::result_type operator()() const { return m_func(m_arg); }
85 typename F::argument_type m_arg;
90 binder0<F> bind0(const F & func, const typename F::argument_type & arg)
92 return binder0<F>(func, arg);
95 template <typename C, typename A, typename R>
96 class METHOD1_ADAPTER : public std::unary_function<A, R>
99 METHOD1_ADAPTER(R (C::* func)(A), C & obj) : m_func(func), m_obj(obj) {}
100 R operator()(A arg) { return (m_obj.*m_func)(arg); }
106 template <typename C, typename A, typename R>
107 class CONST_METHOD1_ADAPTER : public std::unary_function<A, R>
110 CONST_METHOD1_ADAPTER(R (C::* func)(A) const, C & obj) : m_func(func), m_obj(obj) {}
111 R operator()(A arg) const { return (m_obj.*m_func)(arg); }
113 R (C::* m_func)(A) const;
117 template <typename C, typename A, typename R>
118 METHOD1_ADAPTER<C, A, R> Method1Adapt(R (C::* func)(A), C & obj)
120 return METHOD1_ADAPTER<C, A, R>(func, obj);
123 template <typename C, typename A, typename R>
124 CONST_METHOD1_ADAPTER<C, A, R> Method1Adapt(R (C::* func)(A) const, C & obj)
126 return CONST_METHOD1_ADAPTER<C, A, R>(func, obj);
129 template <typename T>
130 bool SetArrayItem(T & array, const char * index, const typename ARRAY_TYPE<T>::type & value)
133 if (str2x(index, pos))
139 void RawXMLCallback(bool result, const std::string & reason, const std::string & response, void * /*data*/)
143 std::cerr << "Failed to get raw XML response. Reason: '" << reason << "'." << std::endl;
146 SGCONF::PrintXML(response);
151 void UsageImpl(bool full);
152 void UsageConnection();
153 void UsageAdmins(bool full);
154 void UsageTariffs(bool full);
155 void UsageUsers(bool full);
156 void UsageServices(bool full);
157 void UsageCorporations(bool full);
161 void ReadUserConfigFile(SGCONF::OPTION_BLOCK & block)
163 std::vector<std::string> paths;
164 const char * configHome = getenv("XDG_CONFIG_HOME");
165 if (configHome == NULL)
167 const char * home = getenv("HOME");
170 paths.push_back(std::string(home) + "/.config/sgconf/sgconf.conf");
171 paths.push_back(std::string(home) + "/.sgconf/sgconf.conf");
174 paths.push_back(std::string(configHome) + "/sgconf/sgconf.conf");
175 for (std::vector<std::string>::const_iterator it = paths.begin(); it != paths.end(); ++it)
176 if (access(it->c_str(), R_OK) == 0)
178 block.ParseFile(*it);
183 } // namespace anonymous
188 class CONFIG_ACTION : public ACTION
191 CONFIG_ACTION(SGCONF::CONFIG & config,
192 const std::string & paramDescription)
194 m_description(paramDescription)
197 virtual ACTION * Clone() const { return new CONFIG_ACTION(*this); }
199 virtual std::string ParamDescription() const { return m_description; }
200 virtual std::string DefaultDescription() const { return ""; }
201 virtual OPTION_BLOCK & Suboptions() { return m_suboptions; }
202 virtual PARSER_STATE Parse(int argc, char ** argv);
205 SGCONF::CONFIG & m_config;
206 std::string m_description;
207 OPTION_BLOCK m_suboptions;
209 void ParseCredentials(const std::string & credentials);
210 void ParseHostAndPort(const std::string & hostAndPort);
213 typedef bool (* API_FUNCTION) (const SGCONF::CONFIG &,
215 const std::map<std::string, std::string> &);
220 COMMAND(API_FUNCTION funPtr,
221 const std::string & arg,
222 const std::map<std::string, std::string> & options)
227 bool Execute(const SGCONF::CONFIG & config) const
229 return m_funPtr(config, m_arg, m_options);
233 API_FUNCTION m_funPtr;
235 std::map<std::string, std::string> m_options;
241 void Add(API_FUNCTION funPtr,
242 const std::string & arg,
243 const std::map<std::string, std::string> & options) { m_commands.push_back(COMMAND(funPtr, arg, options)); }
244 bool Execute(const SGCONF::CONFIG & config) const
246 std::list<COMMAND>::const_iterator it(m_commands.begin());
248 while (it != m_commands.end() && res)
250 res = res && it->Execute(config);
256 std::list<COMMAND> m_commands;
259 class API_ACTION : public ACTION
262 API_ACTION(COMMANDS & commands,
263 const std::string & paramDescription,
265 const OPTION_BLOCK& suboptions,
267 : m_commands(commands),
268 m_description(paramDescription),
269 m_argument(needArgument ? "1" : ""), // Hack
270 m_suboptions(suboptions),
273 API_ACTION(COMMANDS & commands,
274 const std::string & paramDescription,
277 : m_commands(commands),
278 m_description(paramDescription),
279 m_argument(needArgument ? "1" : ""), // Hack
283 virtual ACTION * Clone() const { return new API_ACTION(*this); }
285 virtual std::string ParamDescription() const { return m_description; }
286 virtual std::string DefaultDescription() const { return ""; }
287 virtual OPTION_BLOCK & Suboptions() { return m_suboptions; }
288 virtual PARSER_STATE Parse(int argc, char ** argv)
290 PARSER_STATE state(false, argc, argv);
291 if (!m_argument.empty())
296 throw ERROR("Missing argument.");
301 m_suboptions.Parse(state.argc, state.argv);
302 m_commands.Add(m_funPtr, m_argument, m_params);
307 COMMANDS & m_commands;
308 std::string m_description;
309 std::string m_argument;
310 OPTION_BLOCK m_suboptions;
311 std::map<std::string, std::string> m_params;
312 API_FUNCTION m_funPtr;
315 PARSER_STATE CONFIG_ACTION::Parse(int argc, char ** argv)
320 throw ERROR("Missing argument.");
321 char * pos = strchr(*argv, '@');
324 ParseCredentials(std::string(*argv, pos));
325 ParseHostAndPort(std::string(pos + 1));
329 ParseHostAndPort(std::string(*argv));
331 return PARSER_STATE(false, --argc, ++argv);
334 void CONFIG_ACTION::ParseCredentials(const std::string & credentials)
336 std::string::size_type pos = credentials.find_first_of(':');
337 if (pos != std::string::npos)
339 m_config.userName = credentials.substr(0, pos);
340 m_config.userPass = credentials.substr(pos + 1);
344 m_config.userName = credentials;
348 void CONFIG_ACTION::ParseHostAndPort(const std::string & hostAndPort)
350 std::string::size_type pos = hostAndPort.find_first_of(':');
351 if (pos != std::string::npos)
353 m_config.server = hostAndPort.substr(0, pos);
355 if (str2x(hostAndPort.substr(pos + 1), port))
356 throw ERROR("Invalid port value: '" + hostAndPort.substr(pos + 1) + "'");
357 m_config.port = port;
361 m_config.server = hostAndPort;
366 CONFIG_ACTION * MakeParamAction(SGCONF::CONFIG & config,
367 const std::string & paramDescription)
369 return new CONFIG_ACTION(config, paramDescription);
373 ACTION * MakeAPIAction(COMMANDS & commands,
374 const std::string & paramDescription,
378 return new API_ACTION(commands, paramDescription, needArgument, funPtr);
382 ACTION * MakeAPIAction(COMMANDS & commands,
385 return new API_ACTION(commands, "", false, funPtr);
388 bool RawXMLFunction(const SGCONF::CONFIG & config,
389 const std::string & arg,
390 const std::map<std::string, std::string> & /*options*/)
392 STG::SERVCONF proto(config.server.data(),
394 config.userName.data(),
395 config.userPass.data());
396 return proto.RawXML(arg, RawXMLCallback, NULL) == STG::st_ok;
399 } // namespace SGCONF
403 struct option long_options_get[] = {
404 {"server", 1, 0, 's'}, //Server
405 {"port", 1, 0, 'p'}, //Port
406 {"admin", 1, 0, 'a'}, //Admin
407 {"admin_pass", 1, 0, 'w'}, //passWord
408 {"user", 1, 0, 'u'}, //User
409 {"addcash", 0, 0, 'c'}, //Add Cash
410 //{"setcash", 0, 0, 'v'}, //Set Cash
411 {"credit", 0, 0, 'r'}, //cRedit
412 {"tariff", 0, 0, 't'}, //Tariff
413 {"message", 0, 0, 'm'}, //message
414 {"password", 0, 0, 'o'}, //password
415 {"down", 0, 0, 'd'}, //down
416 {"passive", 0, 0, 'i'}, //passive
417 {"disable-stat",0, 0, 'S'}, //disable detail stat
418 {"always-online",0, 0, 'O'}, //always online
419 {"session-upload", 1, 0, 500}, //SU0
420 {"session-download", 1, 0, 501}, //SD0
421 {"month-upload", 1, 0, 502}, //MU0
422 {"month-download", 1, 0, 503}, //MD0
424 {"user-data", 1, 0, 700}, //UserData0
426 {"prepaid", 0, 0, 'e'}, //prepaid traff
427 {"create", 0, 0, 'n'}, //create
428 {"delete", 0, 0, 'l'}, //delete
430 {"note", 0, 0, 'N'}, //Note
431 {"name", 0, 0, 'A'}, //nAme
432 {"address", 0, 0, 'D'}, //aDdress
433 {"email", 0, 0, 'L'}, //emaiL
434 {"phone", 0, 0, 'P'}, //phone
435 {"group", 0, 0, 'G'}, //Group
436 {"ip", 0, 0, 'I'}, //IP-address of user
437 {"authorized-by",0, 0, 800}, //always online
441 struct option long_options_set[] = {
442 {"server", 1, 0, 's'}, //Server
443 {"port", 1, 0, 'p'}, //Port
444 {"admin", 1, 0, 'a'}, //Admin
445 {"admin_pass", 1, 0, 'w'}, //passWord
446 {"user", 1, 0, 'u'}, //User
447 {"addcash", 1, 0, 'c'}, //Add Cash
448 {"setcash", 1, 0, 'v'}, //Set Cash
449 {"credit", 1, 0, 'r'}, //cRedit
450 {"tariff", 1, 0, 't'}, //Tariff
451 {"message", 1, 0, 'm'}, //message
452 {"password", 1, 0, 'o'}, //password
453 {"down", 1, 0, 'd'}, //down
454 {"passive", 1, 0, 'i'}, //passive
455 {"disable-stat",1, 0, 'S'}, //disable detail stat
456 {"always-online",1, 0, 'O'}, //always online
457 {"session-upload", 1, 0, 500}, //U0
458 {"session-download", 1, 0, 501}, //U1
459 {"month-upload", 1, 0, 502}, //U2
460 {"month-download", 1, 0, 503}, //U3
462 {"user-data", 1, 0, 700}, //UserData
464 {"prepaid", 1, 0, 'e'}, //prepaid traff
465 {"create", 1, 0, 'n'}, //create
466 {"delete", 1, 0, 'l'}, //delete
468 {"note", 1, 0, 'N'}, //Note
469 {"name", 1, 0, 'A'}, //nAme
470 {"address", 1, 0, 'D'}, //aDdress
471 {"email", 1, 0, 'L'}, //emaiL
472 {"phone", 1, 0, 'P'}, //phone
473 {"group", 1, 0, 'G'}, //Group
474 {"ip", 0, 0, 'I'}, //IP-address of user
478 //-----------------------------------------------------------------------------
479 CASH_INFO ParseCash(const char * str)
481 //-c 123.45:log message
482 std::string cashString;
484 const char * pos = strchr(str, ':');
487 cashString.append(str, pos);
488 message.append(pos + 1);
494 if (strtodouble2(cashString, cash) != 0)
496 printf("Incorrect cash value %s\n", str);
497 exit(PARAMETER_PARSING_ERR_CODE);
500 return CASH_INFO(cash, message);
502 //-----------------------------------------------------------------------------
503 double ParseCredit(const char * c)
506 if (strtodouble2(c, credit) != 0)
508 printf("Incorrect credit value %s\n", c);
509 exit(PARAMETER_PARSING_ERR_CODE);
514 //-----------------------------------------------------------------------------
515 double ParsePrepaidTraffic(const char * c)
518 if (strtodouble2(c, credit) != 0)
520 printf("Incorrect prepaid traffic value %s\n", c);
521 exit(PARAMETER_PARSING_ERR_CODE);
526 //-----------------------------------------------------------------------------
527 int64_t ParseTraff(const char * c)
530 if (str2x(c, traff) != 0)
532 printf("Incorrect credit value %s\n", c);
533 exit(PARAMETER_PARSING_ERR_CODE);
538 //-----------------------------------------------------------------------------
539 bool ParseDownPassive(const char * dp)
541 if (!(dp[1] == 0 && (dp[0] == '1' || dp[0] == '0')))
543 printf("Incorrect value %s\n", dp);
544 exit(PARAMETER_PARSING_ERR_CODE);
549 //-----------------------------------------------------------------------------
550 void ParseTariff(const char * str, RESETABLE<std::string> & tariffName, RESETABLE<std::string> & nextTariff)
552 const char * pos = strchr(str, ':');
555 std::string tariff(str, pos);
556 if (strcmp(pos + 1, "now") == 0)
558 else if (strcmp(pos + 1, "delayed") == 0)
562 printf("Incorrect tariff value '%s'. Should be '<tariff>', '<tariff>:now' or '<tariff>:delayed'.\n", str);
563 exit(PARAMETER_PARSING_ERR_CODE);
569 //-----------------------------------------------------------------------------
570 time_t ParseCreditExpire(const char * str)
572 struct tm brokenTime;
574 brokenTime.tm_wday = 0;
575 brokenTime.tm_yday = 0;
576 brokenTime.tm_isdst = 0;
577 brokenTime.tm_hour = 0;
578 brokenTime.tm_min = 0;
579 brokenTime.tm_sec = 0;
581 stg_strptime(str, "%Y-%m-%d", &brokenTime);
583 return stg_timegm(&brokenTime);
585 //-----------------------------------------------------------------------------
586 void ParseAnyString(const char * c, string * msg, const char * enc)
589 char * ob = new char[strlen(c) + 1];
590 char * ib = new char[strlen(c) + 1];
597 setlocale(LC_ALL, "");
600 strncpy(charsetF, nl_langinfo(CODESET), 255);
602 const char * charsetT = enc;
606 size_t insize = strlen(ib);
607 size_t outsize = strlen(ib);
611 cd = iconv_open(charsetT, charsetF);
612 if (cd == (iconv_t) -1)
616 printf("Warning: iconv from %s to %s failed\n", charsetF, charsetT);
621 printf("error iconv_open\n");
623 exit(ICONV_ERR_CODE);
626 #if defined(FREE_BSD) || defined(FREE_BSD5)
627 nconv = iconv (cd, (const char**)&inbuf, &insize, &outbuf, &outsize);
629 nconv = iconv (cd, &inbuf, &insize, &outbuf, &outsize);
631 //printf("nconv=%d outsize=%d\n", nconv, outsize);
632 if (nconv == (size_t) -1)
636 printf("iconv error\n");
637 exit(ICONV_ERR_CODE);
649 //-----------------------------------------------------------------------------
650 void CreateRequestSet(REQUEST * req, char * r)
652 const int strLen = 10024;
654 memset(str, 0, strLen);
658 if (!req->usrMsg.empty())
661 Encode12str(msg, req->usrMsg.data());
662 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());
663 //sprintf(str, "<message login=\"%s\" priority=\"0\" text=\"%s\"/>\n", req->login, msg);
670 sprintf(str, "<DelUser login=\"%s\"/>", req->login.const_data().c_str());
678 sprintf(str, "<AddUser> <login value=\"%s\"/> </AddUser>", req->login.const_data().c_str());
684 strcat(r, "<SetUser>\n");
685 sprintf(str, "<login value=\"%s\"/>\n", req->login.const_data().c_str());
687 if (!req->credit.empty())
689 sprintf(str, "<credit value=\"%f\"/>\n", req->credit.const_data());
693 if (!req->creditExpire.empty())
695 sprintf(str, "<creditExpire value=\"%ld\"/>\n", req->creditExpire.const_data());
699 if (!req->prepaidTraff.empty())
701 sprintf(str, "<FreeMb value=\"%f\"/>\n", req->prepaidTraff.const_data());
705 if (!req->cash.empty())
708 Encode12str(msg, req->message);
709 sprintf(str, "<cash add=\"%f\" msg=\"%s\"/>\n", req->cash.const_data(), msg.c_str());
713 if (!req->setCash.empty())
716 Encode12str(msg, req->message);
717 sprintf(str, "<cash set=\"%f\" msg=\"%s\"/>\n", req->setCash.const_data(), msg.c_str());
721 if (!req->usrPasswd.empty())
723 sprintf(str, "<password value=\"%s\" />\n", req->usrPasswd.const_data().c_str());
727 if (!req->down.empty())
729 sprintf(str, "<down value=\"%d\" />\n", req->down.const_data());
733 if (!req->passive.empty())
735 sprintf(str, "<passive value=\"%d\" />\n", req->passive.const_data());
739 if (!req->disableDetailStat.empty())
741 sprintf(str, "<disableDetailStat value=\"%d\" />\n", req->disableDetailStat.const_data());
745 if (!req->alwaysOnline.empty())
747 sprintf(str, "<aonline value=\"%d\" />\n", req->alwaysOnline.const_data());
751 // IP-address of user
752 if (!req->ips.empty())
754 sprintf(str, "<ip value=\"%s\" />\n", req->ips.const_data().c_str());
758 int uPresent = false;
759 int dPresent = false;
760 for (int i = 0; i < DIR_NUM; i++)
762 if (!req->monthUpload[i].empty())
764 if (!uPresent && !dPresent)
766 sprintf(str, "<traff ");
772 ss << req->monthUpload[i].const_data();
773 //sprintf(str, "MU%d=\"%lld\" ", i, req->u[i].const_data());
774 sprintf(str, "MU%d=\"%s\" ", i, ss.str().c_str());
777 if (!req->monthDownload[i].empty())
779 if (!uPresent && !dPresent)
781 sprintf(str, "<traff ");
787 ss << req->monthDownload[i].const_data();
788 sprintf(str, "MD%d=\"%s\" ", i, ss.str().c_str());
791 if (!req->sessionUpload[i].empty())
793 if (!uPresent && !dPresent)
795 sprintf(str, "<traff ");
801 ss << req->sessionUpload[i].const_data();
802 //sprintf(str, "MU%d=\"%lld\" ", i, req->u[i].const_data());
803 sprintf(str, "MU%d=\"%s\" ", i, ss.str().c_str());
806 if (!req->sessionDownload[i].empty())
808 if (!uPresent && !dPresent)
810 sprintf(str, "<traff ");
816 ss << req->sessionDownload[i].const_data();
817 sprintf(str, "MD%d=\"%s\" ", i, ss.str().c_str());
821 if (uPresent || dPresent)
828 if (!req->tariff.empty())
830 switch (req->chgTariff)
833 sprintf(str, "<tariff now=\"%s\"/>\n", req->tariff.const_data().c_str());
837 sprintf(str, "<tariff recalc=\"%s\"/>\n", req->tariff.const_data().c_str());
841 sprintf(str, "<tariff delayed=\"%s\"/>\n", req->tariff.const_data().c_str());
848 if (!req->note.empty())
851 Encode12str(note, req->note.data());
852 sprintf(str, "<note value=\"%s\"/>", note.c_str());
856 if (!req->name.empty())
859 Encode12str(name, req->name.data());
860 sprintf(str, "<name value=\"%s\"/>", name.c_str());
864 if (!req->address.empty())
867 Encode12str(address, req->address.data());
868 sprintf(str, "<address value=\"%s\"/>", address.c_str());
872 if (!req->email.empty())
875 Encode12str(email, req->email.data());
876 sprintf(str, "<email value=\"%s\"/>", email.c_str());
880 if (!req->phone.empty())
883 Encode12str(phone, req->phone.data());
884 sprintf(str, "<phone value=\"%s\"/>", phone.c_str());
888 if (!req->group.empty())
891 Encode12str(group, req->group.data());
892 sprintf(str, "<group value=\"%s\"/>", group.c_str());
896 for (int i = 0; i < USERDATA_NUM; i++)
898 if (!req->userData[i].empty())
901 Encode12str(ud, req->userData[i].data());
902 sprintf(str, "<userdata%d value=\"%s\"/>", i, ud.c_str());
907 strcat(r, "</SetUser>\n");
909 //-----------------------------------------------------------------------------
910 int CheckParameters(REQUEST * req)
917 bool a = !req->admLogin.empty()
918 && !req->admPasswd.empty()
919 && !req->server.empty()
920 && !req->port.empty()
921 && !req->login.empty();
923 bool b = !req->cash.empty()
924 || !req->setCash.empty()
925 || !req->credit.empty()
926 || !req->prepaidTraff.empty()
927 || !req->tariff.empty()
928 || !req->usrMsg.empty()
929 || !req->usrPasswd.empty()
931 || !req->note.empty()
932 || !req->name.empty()
933 || !req->address.empty()
934 || !req->email.empty()
935 || !req->phone.empty()
936 || !req->group.empty()
937 || !req->ips.empty() // IP-address of user
943 for (int i = 0; i < DIR_NUM; i++)
945 if (req->sessionUpload[i].empty())
952 for (int i = 0; i < DIR_NUM; i++)
954 if (req->sessionDownload[i].empty())
961 for (int i = 0; i < DIR_NUM; i++)
963 if (req->monthUpload[i].empty())
970 for (int i = 0; i < DIR_NUM; i++)
972 if (req->monthDownload[i].empty())
979 for (int i = 0; i < DIR_NUM; i++)
981 if (req->userData[i].empty())
989 //printf("a=%d, b=%d, u=%d, d=%d ud=%d\n", a, b, u, d, ud);
990 return a && (b || su || sd || mu || md || ud);
992 //-----------------------------------------------------------------------------
993 int CheckParametersGet(REQUEST * req)
995 return CheckParameters(req);
997 //-----------------------------------------------------------------------------
998 int CheckParametersSet(REQUEST * req)
1000 return CheckParameters(req);
1002 //-----------------------------------------------------------------------------
1003 bool mainGet(int argc, char **argv)
1007 RESETABLE<string> t1;
1008 int missedOptionArg = false;
1010 const char * short_options_get = "s:p:a:w:u:crtmodieNADLPGISOE";
1011 int option_index = -1;
1016 c = getopt_long(argc, argv, short_options_get, long_options_get, &option_index);
1023 req.server = optarg;
1027 req.port = ParseServerPort(optarg);
1032 req.admLogin = ParseAdminLogin(optarg);
1035 case 'w': //admin password
1036 req.admPasswd = ParsePassword(optarg);
1039 case 'o': //change user password
1040 req.usrPasswd = " ";
1044 req.login = ParseUser(optarg);
1047 case 'c': //get cash
1055 case 'E': //credit expire
1056 req.creditExpire = 1;
1071 case 'e': //Prepaid Traffic
1072 req.prepaidTraff = 1;
1099 case 'I': //IP-address of user
1103 case 'S': //Detail stat status
1104 req.disableDetailStat = " ";
1107 case 'O': //Always online status
1108 req.alwaysOnline = " ";
1112 SetArrayItem(req.sessionUpload, optarg, 1);
1113 //req.sessionUpload[optarg] = 1;
1116 SetArrayItem(req.sessionDownload, optarg, 1);
1117 //req.sessionDownload[optarg] = 1;
1120 SetArrayItem(req.monthUpload, optarg, 1);
1121 //req.monthUpload[optarg] = 1;
1124 SetArrayItem(req.monthDownload, optarg, 1);
1125 //req.monthDownload[optarg] = 1;
1128 case 700: //UserData
1129 SetArrayItem(req.userData, optarg, std::string(" "));
1130 //req.userData[optarg] = " ";
1139 missedOptionArg = true;
1143 printf ("?? getopt returned character code 0%o ??\n", c);
1149 printf ("non-option ARGV-elements: ");
1150 while (optind < argc)
1151 printf ("%s ", argv[optind++]);
1153 exit(PARAMETER_PARSING_ERR_CODE);
1156 if (missedOptionArg || !CheckParametersGet(&req))
1158 //printf("Parameter needed\n");
1160 exit(PARAMETER_PARSING_ERR_CODE);
1164 return ProcessAuthBy(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data());
1166 return ProcessGetUser(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data(), req);
1168 //-----------------------------------------------------------------------------
1169 bool mainSet(int argc, char **argv)
1174 bool isMessage = false;
1177 RESETABLE<string> t1;
1179 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:";
1181 int missedOptionArg = false;
1187 int option_index = -1;
1189 c = getopt_long(argc, argv, short_options_set, long_options_set, &option_index);
1197 req.server = optarg;
1201 req.port = ParseServerPort(optarg);
1206 req.admLogin = ParseAdminLogin(optarg);
1209 case 'w': //admin password
1210 req.admPasswd = ParsePassword(optarg);
1213 case 'o': //change user password
1214 conf.password = ParsePassword(optarg);
1218 req.login = ParseUser(optarg);
1221 case 'c': //add cash
1222 stat.cashAdd = ParseCash(optarg);
1225 case 'v': //set cash
1226 stat.cashSet = ParseCash(optarg);
1230 conf.credit = ParseCredit(optarg);
1233 case 'E': //credit expire
1234 conf.creditExpire = ParseCreditExpire(optarg);
1238 conf.disabled = ParseDownPassive(optarg);
1242 conf.passive = ParseDownPassive(optarg);
1246 ParseTariff(optarg, conf.tariffName, conf.nextTariff);
1250 ParseAnyString(optarg, &str);
1255 case 'e': //Prepaid Traffic
1256 stat.freeMb = ParsePrepaidTraffic(optarg);
1259 case 'n': //Create User
1260 req.createUser = true;
1263 case 'l': //Delete User
1264 req.deleteUser = true;
1268 ParseAnyString(optarg, &str, "koi8-ru");
1273 ParseAnyString(optarg, &str, "koi8-ru");
1274 conf.realName = str;
1278 ParseAnyString(optarg, &str, "koi8-ru");
1283 ParseAnyString(optarg, &str, "koi8-ru");
1288 ParseAnyString(optarg, &str);
1293 ParseAnyString(optarg, &str, "koi8-ru");
1297 case 'I': //IP-address of user
1298 ParseAnyString(optarg, &str);
1299 conf.ips = StrToIPS(str);
1303 conf.disabledDetailStat = ParseDownPassive(optarg);
1307 conf.alwaysOnline = ParseDownPassive(optarg);
1311 SetArrayItem(stat.sessionUp, optarg, ParseTraff(argv[optind++]));
1314 SetArrayItem(stat.sessionDown, optarg, ParseTraff(argv[optind++]));
1317 SetArrayItem(stat.monthUp, optarg, ParseTraff(argv[optind++]));
1320 SetArrayItem(stat.monthDown, optarg, ParseTraff(argv[optind++]));
1323 case 700: //UserData
1324 ParseAnyString(argv[optind++], &str);
1325 SetArrayItem(conf.userdata, optarg, str);
1329 missedOptionArg = true;
1333 missedOptionArg = true;
1337 printf("?? getopt returned character code 0%o ??\n", c);
1343 printf ("non-option ARGV-elements: ");
1344 while (optind < argc)
1345 printf ("%s ", argv[optind++]);
1347 exit(PARAMETER_PARSING_ERR_CODE);
1350 if (missedOptionArg || !CheckParametersSet(&req))
1352 //printf("Parameter needed\n");
1354 exit(PARAMETER_PARSING_ERR_CODE);
1357 const int rLen = 20000;
1359 memset(rstr, 0, rLen);
1362 return ProcessSendMessage(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data(), req.usrMsg.data());
1364 return ProcessSetUser(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data(), conf, stat);
1366 //-----------------------------------------------------------------------------
1367 int main(int argc, char **argv)
1369 SGCONF::CONFIG config;
1370 SGCONF::COMMANDS commands;
1372 SGCONF::OPTION_BLOCKS blocks;
1373 blocks.Add("General options")
1374 .Add("c", "config", SGCONF::MakeParamAction(config.configFile, std::string("~/.config/stg/sgconf.conf"), "<config file>"), "override default config file")
1375 .Add("h", "help", SGCONF::MakeFunc0Action(bind0(Method1Adapt(&SGCONF::OPTION_BLOCKS::Help, blocks), 0)), "\t\tshow this help and exit")
1376 .Add("help-all", SGCONF::MakeFunc0Action(UsageAll), "\t\tshow full help and exit")
1377 .Add("v", "version", SGCONF::MakeFunc0Action(Version), "\t\tshow version information and exit");
1378 SGCONF::OPTION_BLOCK & block = blocks.Add("Connection options")
1379 .Add("s", "server", SGCONF::MakeParamAction(config.server, std::string("localhost"), "<address>"), "\t\thost to connect")
1380 .Add("p", "port", SGCONF::MakeParamAction(config.port, uint16_t(5555), "<port>"), "\t\tport to connect")
1381 .Add("u", "username", SGCONF::MakeParamAction(config.userName, std::string("admin"), "<username>"), "\tadministrative login")
1382 .Add("w", "userpass", SGCONF::MakeParamAction(config.userPass, "<password>"), "\tpassword for the administrative login")
1383 .Add("a", "address", SGCONF::MakeParamAction(config, "<connection string>"), "connection params as a single string in format: <login>:<password>@<host>:<port>");
1384 blocks.Add("Raw XML")
1385 .Add("r", "raw", SGCONF::MakeAPIAction(commands, "<xml>", true, SGCONF::RawXMLFunction), "\tmake raw XML request");
1386 blocks.Add("Admins management options")
1387 .Add("get-admins", SGCONF::MakeAPIAction(commands, SGCONF::GetAdminsFunction), "\tget admin list")
1388 .Add("get-admin", SGCONF::MakeAPIAction(commands, "<login>", true, SGCONF::GetAdminFunction), "\tget admin")
1389 .Add("add-admin", SGCONF::MakeAPIAction(commands, "<login>", true, SGCONF::AddAdminFunction), "\tadd admin")
1390 .Add("del-admin", SGCONF::MakeAPIAction(commands, "<login>", true, SGCONF::DelAdminFunction), "\tdel admin")
1391 .Add("chg-admin", SGCONF::MakeAPIAction(commands, "<login>", true, SGCONF::ChgAdminFunction), "\tchange admin");
1394 SGCONF::PARSER_STATE state(false, argc, argv);
1398 state = blocks.Parse(--argc, ++argv); // Skipping self name
1400 catch (const SGCONF::OPTION::ERROR& ex)
1402 std::cerr << ex.what() << "\n";
1411 std::cerr << "Unknown option: '" << *state.argv << "'\n";
1417 SGCONF::CONFIG configOverride(config);
1419 if (config.configFile.empty())
1421 const char * mainConfigFile = "/etc/sgconf/sgconf.conf";
1422 if (access(mainConfigFile, R_OK) == 0)
1423 block.ParseFile(mainConfigFile);
1424 ReadUserConfigFile(block);
1428 block.ParseFile(config.configFile.data());
1431 config = configOverride;
1433 catch (const std::exception& ex)
1435 std::cerr << ex.what() << "\n";
1439 std::cerr << "Config: " << config.Serialize() << std::endl;
1440 return commands.Execute(config) ? 0 : -1;
1453 exit(PARAMETER_PARSING_ERR_CODE);
1456 if (strcmp(argv[1], "get") == 0)
1459 return mainGet(argc - 1, argv + 1);
1461 else if (strcmp(argv[1], "set") == 0)
1464 if (mainSet(argc - 1, argv + 1) )
1471 exit(PARAMETER_PARSING_ERR_CODE);
1473 return UNKNOWN_ERR_CODE;*/
1475 //-----------------------------------------------------------------------------
1490 void UsageImpl(bool full)
1492 std::cout << "sgconf is the Stargazer management utility.\n\n"
1494 << "\tsgconf [options]\n\n"
1495 << "General options:\n"
1496 << "\t-c, --config <config file>\t\toverride default config file (default: \"~/.config/stg/sgconf.conf\")\n"
1497 << "\t-h, --help\t\t\t\tshow this help and exit\n"
1498 << "\t--help-all\t\t\t\tshow full help and exit\n"
1499 << "\t-v, --version\t\t\t\tshow version information and exit\n\n";
1504 UsageServices(full);
1505 UsageCorporations(full);
1507 //-----------------------------------------------------------------------------
1508 void UsageConnection()
1510 std::cout << "Connection options:\n"
1511 << "\t-s, --server <address>\t\t\thost to connect (ip or domain name, default: \"localhost\")\n"
1512 << "\t-p, --port <port>\t\t\tport to connect (default: \"5555\")\n"
1513 << "\t-u, --username <username>\t\tadministrative login (default: \"admin\")\n"
1514 << "\t-w, --userpass <password>\t\tpassword for administrative login\n"
1515 << "\t-a, --address <connection string>\tconnection params as a single string in format: <login>:<password>@<host>:<port>\n\n";
1517 //-----------------------------------------------------------------------------
1518 void UsageAdmins(bool full)
1520 std::cout << "Admins management options:\n"
1521 << "\t--get-admins\t\t\t\tget a list of admins (subsequent options will define what to show)\n";
1523 std::cout << "\t\t--login\t\t\t\tshow admin's login\n"
1524 << "\t\t--priv\t\t\t\tshow admin's priviledges\n\n";
1525 std::cout << "\t--get-admin\t\t\t\tget the information about admin\n";
1527 std::cout << "\t\t--login <login>\t\t\tlogin of the admin to show\n"
1528 << "\t\t--priv\t\t\t\tshow admin's priviledges\n\n";
1529 std::cout << "\t--add-admin\t\t\t\tadd a new admin\n";
1531 std::cout << "\t\t--login <login>\t\t\tlogin of the admin to add\n"
1532 << "\t\t--password <password>\t\tpassword of the admin to add\n"
1533 << "\t\t--priv <priv number>\t\tpriviledges of the admin to add\n\n";
1534 std::cout << "\t--del-admin\t\t\t\tdelete an existing admin\n";
1536 std::cout << "\t\t--login <login>\t\t\tlogin of the admin to delete\n\n";
1537 std::cout << "\t--chg-admin\t\t\t\tchange an existing admin\n";
1539 std::cout << "\t\t--login <login>\t\t\tlogin of the admin to change\n"
1540 << "\t\t--priv <priv number>\t\tnew priviledges\n\n";
1542 //-----------------------------------------------------------------------------
1543 void UsageTariffs(bool full)
1545 std::cout << "Tariffs management options:\n"
1546 << "\t--get-tariffs\t\t\t\tget a list of tariffs (subsequent options will define what to show)\n";
1548 std::cout << "\t\t--name\t\t\t\tshow tariff's name\n"
1549 << "\t\t--fee\t\t\t\tshow tariff's fee\n"
1550 << "\t\t--free\t\t\t\tshow tariff's prepaid traffic in terms of cost\n"
1551 << "\t\t--passive-cost\t\t\tshow tariff's cost of \"freeze\"\n"
1552 << "\t\t--traff-type\t\t\tshow what type of traffix will be accounted by the tariff\n"
1553 << "\t\t--dirs\t\t\t\tshow tarification rules for directions\n\n";
1554 std::cout << "\t--get-tariff\t\t\t\tget the information about tariff\n";
1556 std::cout << "\t\t--name <name>\t\t\tname of the tariff to show\n"
1557 << "\t\t--fee\t\t\t\tshow tariff's fee\n"
1558 << "\t\t--free\t\t\t\tshow tariff's prepaid traffic in terms of cost\n"
1559 << "\t\t--passive-cost\t\t\tshow tariff's cost of \"freeze\"\n"
1560 << "\t\t--traff-type\t\t\tshow what type of traffix will be accounted by the tariff\n"
1561 << "\t\t--dirs\t\t\t\tshow tarification rules for directions\n\n";
1562 std::cout << "\t--add-tariff\t\t\t\tadd a new tariff\n";
1564 std::cout << "\t\t--name <name>\t\t\tname of the tariff to add\n"
1565 << "\t\t--fee <fee>\t\t\tstariff's fee\n"
1566 << "\t\t--free <free>\t\t\ttariff's prepaid traffic in terms of cost\n"
1567 << "\t\t--passive-cost <cost>\t\ttariff's cost of \"freeze\"\n"
1568 << "\t\t--traff-type <type>\t\twhat type of traffi will be accounted by the tariff\n"
1569 << "\t\t--times <times>\t\t\tslash-separated list of \"day\" time-spans (in form \"hh:mm-hh:mm\") for each direction\n"
1570 << "\t\t--prices-day-a <prices>\t\tslash-separated list of prices for \"day\" traffic before threshold for each direction\n"
1571 << "\t\t--prices-night-a <prices>\tslash-separated list of prices for \"night\" traffic before threshold for each direction\n"
1572 << "\t\t--prices-day-b <prices>\t\tslash-separated list of prices for \"day\" traffic after threshold for each direction\n"
1573 << "\t\t--prices-night-b <prices>\tslash-separated list of prices for \"night\" traffic after threshold for each direction\n"
1574 << "\t\t--single-prices <yes|no>\tslash-separated list of \"single price\" flags for each direction\n"
1575 << "\t\t--no-discounts <yes|no>\t\tslash-separated list of \"no discount\" flags for each direction\n"
1576 << "\t\t--thresholds <thresholds>\tslash-separated list of thresholds (in Mb) for each direction\n\n";
1577 std::cout << "\t--del-tariff\t\t\t\tdelete an existing tariff\n";
1579 std::cout << "\t\t--name <name>\t\t\tname of the tariff to delete\n\n";
1580 std::cout << "\t--chg-tariff\t\t\t\tchange an existing tariff\n";
1582 std::cout << "\t\t--name <name>\t\t\tname of the tariff to change\n"
1583 << "\t\t--fee <fee>\t\t\tstariff's fee\n"
1584 << "\t\t--free <free>\t\t\ttariff's prepaid traffic in terms of cost\n"
1585 << "\t\t--passive-cost <cost>\t\ttariff's cost of \"freeze\"\n"
1586 << "\t\t--traff-type <type>\t\twhat type of traffix will be accounted by the tariff\n"
1587 << "\t\t--dir <N>\t\t\tnumber of direction data to change\n"
1588 << "\t\t\t--time <time>\t\t\"day\" time-span (in form \"hh:mm-hh:mm\")\n"
1589 << "\t\t\t--price-day-a <price>\tprice for \"day\" traffic before threshold\n"
1590 << "\t\t\t--price-night-a <price>\tprice for \"night\" traffic before threshold\n"
1591 << "\t\t\t--price-day-b <price>\tprice for \"day\" traffic after threshold\n"
1592 << "\t\t\t--price-night-b <price>\tprice for \"night\" traffic after threshold\n"
1593 << "\t\t\t--single-price <yes|no>\t\"single price\" flag\n"
1594 << "\t\t\t--no-discount <yes|no>\t\"no discount\" flag\n"
1595 << "\t\t\t--threshold <threshold>\tthreshold (in Mb)\n\n";
1597 //-----------------------------------------------------------------------------
1598 void UsageUsers(bool full)
1600 std::cout << "Users management options:\n"
1601 << "\t--get-users\t\t\t\tget a list of users (subsequent options will define what to show)\n";
1603 std::cout << "\n\n";
1604 std::cout << "\t--get-user\t\t\t\tget the information about user\n";
1606 std::cout << "\n\n";
1607 std::cout << "\t--add-user\t\t\t\tadd a new user\n";
1609 std::cout << "\n\n";
1610 std::cout << "\t--del-user\t\t\t\tdelete an existing user\n";
1612 std::cout << "\n\n";
1613 std::cout << "\t--chg-user\t\t\t\tchange an existing user\n";
1615 std::cout << "\n\n";
1616 std::cout << "\t--check-user\t\t\t\tcheck credentials is valid\n";
1618 std::cout << "\n\n";
1619 std::cout << "\t--send-message\t\t\t\tsend a message to a user\n";
1621 std::cout << "\n\n";
1623 //-----------------------------------------------------------------------------
1624 void UsageServices(bool full)
1626 std::cout << "Services management options:\n"
1627 << "\t--get-services\t\t\t\tget a list of services (subsequent options will define what to show)\n";
1629 std::cout << "\t\t--name\t\t\t\tshow service's name\n"
1630 << "\t\t--comment\t\t\tshow a comment to the service\n"
1631 << "\t\t--cost\t\t\t\tshow service's cost\n"
1632 << "\t\t--pay-day\t\t\tshow service's pay day\n\n";
1633 std::cout << "\t--get-service\t\t\t\tget the information about service\n";
1635 std::cout << "\t\t--name <name>\t\t\tname of the service to show\n"
1636 << "\t\t--comment\t\t\tshow a comment to the service\n"
1637 << "\t\t--cost\t\t\t\tshow service's cost\n"
1638 << "\t\t--pay-day\t\t\tshow service's pay day\n\n";
1639 std::cout << "\t--add-service\t\t\t\tadd a new service\n";
1641 std::cout << "\t\t--name <name>\t\t\tname of the service to add\n"
1642 << "\t\t--comment <comment>\t\ta comment to the service\n"
1643 << "\t\t--cost <cost>\t\t\tservice's cost\n"
1644 << "\t\t--pay-day <day>\t\t\tservice's pay day\n\n";
1645 std::cout << "\t--del-service\t\t\t\tdelete an existing service\n";
1647 std::cout << "\t\t--name <name>\t\t\tname of the service to delete\n\n";
1648 std::cout << "\t--chg-service\t\t\t\tchange an existing service\n";
1650 std::cout << "\t\t--name <name>\t\t\tname of the service to change\n"
1651 << "\t\t--comment <comment>\t\ta comment to the service\n"
1652 << "\t\t--cost <cost>\t\t\tservice's cost\n"
1653 << "\t\t--pay-day <day>\t\t\tservice's pay day\n\n";
1655 //-----------------------------------------------------------------------------
1656 void UsageCorporations(bool full)
1658 std::cout << "Corporations management options:\n"
1659 << "\t--get-corporations\t\t\tget a list of corporations (subsequent options will define what to show)\n";
1661 std::cout << "\t\t--name\t\t\t\tshow corporation's name\n"
1662 << "\t\t--cash\t\t\t\tshow corporation's cash\n\n";
1663 std::cout << "\t--get-corp\t\t\t\tget the information about corporation\n";
1665 std::cout << "\t\t--name <name>\t\t\tname of the corporation to show\n"
1666 << "\t\t--cash\t\t\t\tshow corporation's cash\n\n";
1667 std::cout << "\t--add-corp\t\t\t\tadd a new corporation\n";
1669 std::cout << "\t\t--name <name>\t\t\tname of the corporation to add\n"
1670 << "\t\t--cash <cash>\t\t\tinitial corporation's cash (default: \"0\")\n\n";
1671 std::cout << "\t--del-corp\t\t\t\tdelete an existing corporation\n";
1673 std::cout << "\t\t--name <name>\t\t\tname of the corporation to delete\n\n";
1674 std::cout << "\t--chg-corp\t\t\t\tchange an existing corporation\n";
1676 std::cout << "\t\t--name <name>\t\t\tname of the corporation to change\n"
1677 << "\t\t--add-cash <amount>[:<message>]\tadd cash to the corporation's account and optional comment message\n"
1678 << "\t\t--set-cash <cash>[:<message>]\tnew corporation's cash and optional comment message\n\n";
1683 std::cout << "sgconf, version: 2.0.0-alpha.\n";
1686 } // namespace anonymous