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"
31 #include "stg/user_conf.h"
32 #include "stg/user_stat.h"
33 #include "stg/common.h"
54 typedef typename T::value_type type;
58 struct ARRAY_TYPE<T[]>
63 template <typename T, size_t N>
64 struct ARRAY_TYPE<T[N]>
70 struct nullary_function
72 typedef T result_type;
76 class binder0 : public nullary_function<typename F::result_type>
79 binder0(const F & func, const typename F::argument_type & arg)
80 : m_func(func), m_arg(arg) {}
81 typename F::result_type operator()() const { return m_func(m_arg); }
84 typename F::argument_type m_arg;
89 binder0<F> bind0(const F & func, const typename F::argument_type & arg)
91 return binder0<F>(func, arg);
94 template <typename C, typename A, typename R>
95 class METHOD1_ADAPTER : public std::unary_function<A, R>
98 METHOD1_ADAPTER(R (C::* func)(A), C & obj) : m_func(func), m_obj(obj) {}
99 R operator()(A arg) { return (m_obj.*m_func)(arg); }
105 template <typename C, typename A, typename R>
106 class CONST_METHOD1_ADAPTER : public std::unary_function<A, R>
109 CONST_METHOD1_ADAPTER(R (C::* func)(A) const, C & obj) : m_func(func), m_obj(obj) {}
110 R operator()(A arg) const { return (m_obj.*m_func)(arg); }
112 R (C::* m_func)(A) const;
116 template <typename C, typename A, typename R>
117 METHOD1_ADAPTER<C, A, R> Method1Adapt(R (C::* func)(A), C & obj)
119 return METHOD1_ADAPTER<C, A, R>(func, obj);
122 template <typename C, typename A, typename R>
123 CONST_METHOD1_ADAPTER<C, A, R> Method1Adapt(R (C::* func)(A) const, C & obj)
125 return CONST_METHOD1_ADAPTER<C, A, R>(func, obj);
128 template <typename T>
129 bool SetArrayItem(T & array, const char * index, const typename ARRAY_TYPE<T>::type & value)
132 if (str2x(index, pos))
138 void RawXMLCallback(bool result, const std::string & reason, const std::string & response, void * /*data*/)
142 std::cerr << "Failed to get raw XML response. Reason: '" << reason << "'." << std::endl;
145 SGCONF::PrintXML(response);
150 void UsageImpl(bool full);
151 void UsageConnection();
152 void UsageAdmins(bool full);
153 void UsageTariffs(bool full);
154 void UsageUsers(bool full);
155 void UsageServices(bool full);
156 void UsageCorporations(bool full);
160 void ReadUserConfigFile(SGCONF::OPTION_BLOCK & block)
162 std::vector<std::string> paths;
163 const char * configHome = getenv("XDG_CONFIG_HOME");
164 if (configHome == NULL)
166 const char * home = getenv("HOME");
169 paths.push_back(std::string(home) + "/.config/sgconf/sgconf.conf");
170 paths.push_back(std::string(home) + "/.sgconf/sgconf.conf");
173 paths.push_back(std::string(configHome) + "/sgconf/sgconf.conf");
174 for (std::vector<std::string>::const_iterator it = paths.begin(); it != paths.end(); ++it)
175 if (access(it->c_str(), R_OK) == 0)
177 block.ParseFile(*it);
182 } // namespace anonymous
187 class CONFIG_ACTION : public ACTION
190 CONFIG_ACTION(SGCONF::CONFIG & config,
191 const std::string & paramDescription)
193 m_description(paramDescription)
196 virtual ACTION * Clone() const { return new CONFIG_ACTION(*this); }
198 virtual std::string ParamDescription() const { return m_description; }
199 virtual std::string DefaultDescription() const { return ""; }
200 virtual OPTION_BLOCK & Suboptions() { return m_suboptions; }
201 virtual PARSER_STATE Parse(int argc, char ** argv);
204 SGCONF::CONFIG & m_config;
205 std::string m_description;
206 OPTION_BLOCK m_suboptions;
208 void ParseCredentials(const std::string & credentials);
209 void ParseHostAndPort(const std::string & hostAndPort);
212 typedef bool (* API_FUNCTION) (const SGCONF::CONFIG &,
214 const std::map<std::string, std::string> &);
219 COMMAND(API_FUNCTION funPtr,
220 const std::string & arg,
221 const std::map<std::string, std::string> & options)
226 bool Execute(const SGCONF::CONFIG & config) const
228 return m_funPtr(config, m_arg, m_options);
232 API_FUNCTION m_funPtr;
234 std::map<std::string, std::string> m_options;
240 void Add(API_FUNCTION funPtr,
241 const std::string & arg,
242 const std::map<std::string, std::string> & options) { m_commands.push_back(COMMAND(funPtr, arg, options)); }
243 bool Execute(const SGCONF::CONFIG & config) const
245 std::list<COMMAND>::const_iterator it(m_commands.begin());
247 while (it != m_commands.end() && res)
249 res = res && it->Execute(config);
255 std::list<COMMAND> m_commands;
258 class API_ACTION : public ACTION
261 API_ACTION(COMMANDS & commands,
262 const std::string & paramDescription,
264 const OPTION_BLOCK& suboptions,
266 : m_commands(commands),
267 m_description(paramDescription),
268 m_argument(needArgument ? "1" : ""), // Hack
269 m_suboptions(suboptions),
272 API_ACTION(COMMANDS & commands,
273 const std::string & paramDescription,
276 : m_commands(commands),
277 m_description(paramDescription),
278 m_argument(needArgument ? "1" : ""), // Hack
282 virtual ACTION * Clone() const { return new API_ACTION(*this); }
284 virtual std::string ParamDescription() const { return m_description; }
285 virtual std::string DefaultDescription() const { return ""; }
286 virtual OPTION_BLOCK & Suboptions() { return m_suboptions; }
287 virtual PARSER_STATE Parse(int argc, char ** argv)
289 PARSER_STATE state(false, argc, argv);
290 if (!m_argument.empty())
295 throw ERROR("Missing argument.");
300 m_suboptions.Parse(state.argc, state.argv);
301 m_commands.Add(m_funPtr, m_argument, m_params);
306 COMMANDS & m_commands;
307 std::string m_description;
308 std::string m_argument;
309 OPTION_BLOCK m_suboptions;
310 std::map<std::string, std::string> m_params;
311 API_FUNCTION m_funPtr;
314 PARSER_STATE CONFIG_ACTION::Parse(int argc, char ** argv)
319 throw ERROR("Missing argument.");
320 char * pos = strchr(*argv, '@');
323 ParseCredentials(std::string(*argv, pos));
324 ParseHostAndPort(std::string(pos + 1));
328 ParseHostAndPort(std::string(*argv));
330 return PARSER_STATE(false, --argc, ++argv);
333 void CONFIG_ACTION::ParseCredentials(const std::string & credentials)
335 std::string::size_type pos = credentials.find_first_of(':');
336 if (pos != std::string::npos)
338 m_config.userName = credentials.substr(0, pos);
339 m_config.userPass = credentials.substr(pos + 1);
343 m_config.userName = credentials;
347 void CONFIG_ACTION::ParseHostAndPort(const std::string & hostAndPort)
349 std::string::size_type pos = hostAndPort.find_first_of(':');
350 if (pos != std::string::npos)
352 m_config.server = hostAndPort.substr(0, pos);
354 if (str2x(hostAndPort.substr(pos + 1), port))
355 throw ERROR("Invalid port value: '" + hostAndPort.substr(pos + 1) + "'");
356 m_config.port = port;
360 m_config.server = hostAndPort;
365 CONFIG_ACTION * MakeParamAction(SGCONF::CONFIG & config,
366 const std::string & paramDescription)
368 return new CONFIG_ACTION(config, paramDescription);
372 ACTION * MakeAPIAction(COMMANDS & commands,
373 const std::string & paramDescription,
377 return new API_ACTION(commands, paramDescription, needArgument, funPtr);
380 bool RawXMLFunction(const SGCONF::CONFIG & config,
381 const std::string & arg,
382 const std::map<std::string, std::string> & /*options*/)
384 STG::SERVCONF proto(config.server.data(),
386 config.userName.data(),
387 config.userPass.data());
388 return proto.RawXML(arg, RawXMLCallback, NULL) == STG::st_ok;
391 } // namespace SGCONF
395 struct option long_options_get[] = {
396 {"server", 1, 0, 's'}, //Server
397 {"port", 1, 0, 'p'}, //Port
398 {"admin", 1, 0, 'a'}, //Admin
399 {"admin_pass", 1, 0, 'w'}, //passWord
400 {"user", 1, 0, 'u'}, //User
401 {"addcash", 0, 0, 'c'}, //Add Cash
402 //{"setcash", 0, 0, 'v'}, //Set Cash
403 {"credit", 0, 0, 'r'}, //cRedit
404 {"tariff", 0, 0, 't'}, //Tariff
405 {"message", 0, 0, 'm'}, //message
406 {"password", 0, 0, 'o'}, //password
407 {"down", 0, 0, 'd'}, //down
408 {"passive", 0, 0, 'i'}, //passive
409 {"disable-stat",0, 0, 'S'}, //disable detail stat
410 {"always-online",0, 0, 'O'}, //always online
411 {"session-upload", 1, 0, 500}, //SU0
412 {"session-download", 1, 0, 501}, //SD0
413 {"month-upload", 1, 0, 502}, //MU0
414 {"month-download", 1, 0, 503}, //MD0
416 {"user-data", 1, 0, 700}, //UserData0
418 {"prepaid", 0, 0, 'e'}, //prepaid traff
419 {"create", 0, 0, 'n'}, //create
420 {"delete", 0, 0, 'l'}, //delete
422 {"note", 0, 0, 'N'}, //Note
423 {"name", 0, 0, 'A'}, //nAme
424 {"address", 0, 0, 'D'}, //aDdress
425 {"email", 0, 0, 'L'}, //emaiL
426 {"phone", 0, 0, 'P'}, //phone
427 {"group", 0, 0, 'G'}, //Group
428 {"ip", 0, 0, 'I'}, //IP-address of user
429 {"authorized-by",0, 0, 800}, //always online
433 struct option long_options_set[] = {
434 {"server", 1, 0, 's'}, //Server
435 {"port", 1, 0, 'p'}, //Port
436 {"admin", 1, 0, 'a'}, //Admin
437 {"admin_pass", 1, 0, 'w'}, //passWord
438 {"user", 1, 0, 'u'}, //User
439 {"addcash", 1, 0, 'c'}, //Add Cash
440 {"setcash", 1, 0, 'v'}, //Set Cash
441 {"credit", 1, 0, 'r'}, //cRedit
442 {"tariff", 1, 0, 't'}, //Tariff
443 {"message", 1, 0, 'm'}, //message
444 {"password", 1, 0, 'o'}, //password
445 {"down", 1, 0, 'd'}, //down
446 {"passive", 1, 0, 'i'}, //passive
447 {"disable-stat",1, 0, 'S'}, //disable detail stat
448 {"always-online",1, 0, 'O'}, //always online
449 {"session-upload", 1, 0, 500}, //U0
450 {"session-download", 1, 0, 501}, //U1
451 {"month-upload", 1, 0, 502}, //U2
452 {"month-download", 1, 0, 503}, //U3
454 {"user-data", 1, 0, 700}, //UserData
456 {"prepaid", 1, 0, 'e'}, //prepaid traff
457 {"create", 1, 0, 'n'}, //create
458 {"delete", 1, 0, 'l'}, //delete
460 {"note", 1, 0, 'N'}, //Note
461 {"name", 1, 0, 'A'}, //nAme
462 {"address", 1, 0, 'D'}, //aDdress
463 {"email", 1, 0, 'L'}, //emaiL
464 {"phone", 1, 0, 'P'}, //phone
465 {"group", 1, 0, 'G'}, //Group
466 {"ip", 0, 0, 'I'}, //IP-address of user
470 //-----------------------------------------------------------------------------
471 CASH_INFO ParseCash(const char * str)
473 //-c 123.45:log message
474 std::string cashString;
476 const char * pos = strchr(str, ':');
479 cashString.append(str, pos);
480 message.append(pos + 1);
486 if (strtodouble2(cashString, cash) != 0)
488 printf("Incorrect cash value %s\n", str);
489 exit(PARAMETER_PARSING_ERR_CODE);
492 return CASH_INFO(cash, message);
494 //-----------------------------------------------------------------------------
495 double ParseCredit(const char * c)
498 if (strtodouble2(c, credit) != 0)
500 printf("Incorrect credit value %s\n", c);
501 exit(PARAMETER_PARSING_ERR_CODE);
506 //-----------------------------------------------------------------------------
507 double ParsePrepaidTraffic(const char * c)
510 if (strtodouble2(c, credit) != 0)
512 printf("Incorrect prepaid traffic value %s\n", c);
513 exit(PARAMETER_PARSING_ERR_CODE);
518 //-----------------------------------------------------------------------------
519 int64_t ParseTraff(const char * c)
522 if (str2x(c, traff) != 0)
524 printf("Incorrect credit value %s\n", c);
525 exit(PARAMETER_PARSING_ERR_CODE);
530 //-----------------------------------------------------------------------------
531 bool ParseDownPassive(const char * dp)
533 if (!(dp[1] == 0 && (dp[0] == '1' || dp[0] == '0')))
535 printf("Incorrect value %s\n", dp);
536 exit(PARAMETER_PARSING_ERR_CODE);
541 //-----------------------------------------------------------------------------
542 void ParseTariff(const char * str, RESETABLE<std::string> & tariffName, RESETABLE<std::string> & nextTariff)
544 const char * pos = strchr(str, ':');
547 std::string tariff(str, pos);
548 if (strcmp(pos + 1, "now") == 0)
550 else if (strcmp(pos + 1, "delayed") == 0)
554 printf("Incorrect tariff value '%s'. Should be '<tariff>', '<tariff>:now' or '<tariff>:delayed'.\n", str);
555 exit(PARAMETER_PARSING_ERR_CODE);
561 //-----------------------------------------------------------------------------
562 time_t ParseCreditExpire(const char * str)
564 struct tm brokenTime;
566 brokenTime.tm_wday = 0;
567 brokenTime.tm_yday = 0;
568 brokenTime.tm_isdst = 0;
569 brokenTime.tm_hour = 0;
570 brokenTime.tm_min = 0;
571 brokenTime.tm_sec = 0;
573 stg_strptime(str, "%Y-%m-%d", &brokenTime);
575 return stg_timegm(&brokenTime);
577 //-----------------------------------------------------------------------------
578 void ParseAnyString(const char * c, string * msg, const char * enc)
581 char * ob = new char[strlen(c) + 1];
582 char * ib = new char[strlen(c) + 1];
589 setlocale(LC_ALL, "");
592 strncpy(charsetF, nl_langinfo(CODESET), 255);
594 const char * charsetT = enc;
598 size_t insize = strlen(ib);
599 size_t outsize = strlen(ib);
603 cd = iconv_open(charsetT, charsetF);
604 if (cd == (iconv_t) -1)
608 printf("Warning: iconv from %s to %s failed\n", charsetF, charsetT);
613 printf("error iconv_open\n");
615 exit(ICONV_ERR_CODE);
618 #if defined(FREE_BSD) || defined(FREE_BSD5)
619 nconv = iconv (cd, (const char**)&inbuf, &insize, &outbuf, &outsize);
621 nconv = iconv (cd, &inbuf, &insize, &outbuf, &outsize);
623 //printf("nconv=%d outsize=%d\n", nconv, outsize);
624 if (nconv == (size_t) -1)
628 printf("iconv error\n");
629 exit(ICONV_ERR_CODE);
641 //-----------------------------------------------------------------------------
642 void CreateRequestSet(REQUEST * req, char * r)
644 const int strLen = 10024;
646 memset(str, 0, strLen);
650 if (!req->usrMsg.empty())
653 Encode12str(msg, req->usrMsg.data());
654 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());
655 //sprintf(str, "<message login=\"%s\" priority=\"0\" text=\"%s\"/>\n", req->login, msg);
662 sprintf(str, "<DelUser login=\"%s\"/>", req->login.const_data().c_str());
670 sprintf(str, "<AddUser> <login value=\"%s\"/> </AddUser>", req->login.const_data().c_str());
676 strcat(r, "<SetUser>\n");
677 sprintf(str, "<login value=\"%s\"/>\n", req->login.const_data().c_str());
679 if (!req->credit.empty())
681 sprintf(str, "<credit value=\"%f\"/>\n", req->credit.const_data());
685 if (!req->creditExpire.empty())
687 sprintf(str, "<creditExpire value=\"%ld\"/>\n", req->creditExpire.const_data());
691 if (!req->prepaidTraff.empty())
693 sprintf(str, "<FreeMb value=\"%f\"/>\n", req->prepaidTraff.const_data());
697 if (!req->cash.empty())
700 Encode12str(msg, req->message);
701 sprintf(str, "<cash add=\"%f\" msg=\"%s\"/>\n", req->cash.const_data(), msg.c_str());
705 if (!req->setCash.empty())
708 Encode12str(msg, req->message);
709 sprintf(str, "<cash set=\"%f\" msg=\"%s\"/>\n", req->setCash.const_data(), msg.c_str());
713 if (!req->usrPasswd.empty())
715 sprintf(str, "<password value=\"%s\" />\n", req->usrPasswd.const_data().c_str());
719 if (!req->down.empty())
721 sprintf(str, "<down value=\"%d\" />\n", req->down.const_data());
725 if (!req->passive.empty())
727 sprintf(str, "<passive value=\"%d\" />\n", req->passive.const_data());
731 if (!req->disableDetailStat.empty())
733 sprintf(str, "<disableDetailStat value=\"%d\" />\n", req->disableDetailStat.const_data());
737 if (!req->alwaysOnline.empty())
739 sprintf(str, "<aonline value=\"%d\" />\n", req->alwaysOnline.const_data());
743 // IP-address of user
744 if (!req->ips.empty())
746 sprintf(str, "<ip value=\"%s\" />\n", req->ips.const_data().c_str());
750 int uPresent = false;
751 int dPresent = false;
752 for (int i = 0; i < DIR_NUM; i++)
754 if (!req->monthUpload[i].empty())
756 if (!uPresent && !dPresent)
758 sprintf(str, "<traff ");
764 ss << req->monthUpload[i].const_data();
765 //sprintf(str, "MU%d=\"%lld\" ", i, req->u[i].const_data());
766 sprintf(str, "MU%d=\"%s\" ", i, ss.str().c_str());
769 if (!req->monthDownload[i].empty())
771 if (!uPresent && !dPresent)
773 sprintf(str, "<traff ");
779 ss << req->monthDownload[i].const_data();
780 sprintf(str, "MD%d=\"%s\" ", i, ss.str().c_str());
783 if (!req->sessionUpload[i].empty())
785 if (!uPresent && !dPresent)
787 sprintf(str, "<traff ");
793 ss << req->sessionUpload[i].const_data();
794 //sprintf(str, "MU%d=\"%lld\" ", i, req->u[i].const_data());
795 sprintf(str, "MU%d=\"%s\" ", i, ss.str().c_str());
798 if (!req->sessionDownload[i].empty())
800 if (!uPresent && !dPresent)
802 sprintf(str, "<traff ");
808 ss << req->sessionDownload[i].const_data();
809 sprintf(str, "MD%d=\"%s\" ", i, ss.str().c_str());
813 if (uPresent || dPresent)
820 if (!req->tariff.empty())
822 switch (req->chgTariff)
825 sprintf(str, "<tariff now=\"%s\"/>\n", req->tariff.const_data().c_str());
829 sprintf(str, "<tariff recalc=\"%s\"/>\n", req->tariff.const_data().c_str());
833 sprintf(str, "<tariff delayed=\"%s\"/>\n", req->tariff.const_data().c_str());
840 if (!req->note.empty())
843 Encode12str(note, req->note.data());
844 sprintf(str, "<note value=\"%s\"/>", note.c_str());
848 if (!req->name.empty())
851 Encode12str(name, req->name.data());
852 sprintf(str, "<name value=\"%s\"/>", name.c_str());
856 if (!req->address.empty())
859 Encode12str(address, req->address.data());
860 sprintf(str, "<address value=\"%s\"/>", address.c_str());
864 if (!req->email.empty())
867 Encode12str(email, req->email.data());
868 sprintf(str, "<email value=\"%s\"/>", email.c_str());
872 if (!req->phone.empty())
875 Encode12str(phone, req->phone.data());
876 sprintf(str, "<phone value=\"%s\"/>", phone.c_str());
880 if (!req->group.empty())
883 Encode12str(group, req->group.data());
884 sprintf(str, "<group value=\"%s\"/>", group.c_str());
888 for (int i = 0; i < USERDATA_NUM; i++)
890 if (!req->userData[i].empty())
893 Encode12str(ud, req->userData[i].data());
894 sprintf(str, "<userdata%d value=\"%s\"/>", i, ud.c_str());
899 strcat(r, "</SetUser>\n");
901 //-----------------------------------------------------------------------------
902 int CheckParameters(REQUEST * req)
909 bool a = !req->admLogin.empty()
910 && !req->admPasswd.empty()
911 && !req->server.empty()
912 && !req->port.empty()
913 && !req->login.empty();
915 bool b = !req->cash.empty()
916 || !req->setCash.empty()
917 || !req->credit.empty()
918 || !req->prepaidTraff.empty()
919 || !req->tariff.empty()
920 || !req->usrMsg.empty()
921 || !req->usrPasswd.empty()
923 || !req->note.empty()
924 || !req->name.empty()
925 || !req->address.empty()
926 || !req->email.empty()
927 || !req->phone.empty()
928 || !req->group.empty()
929 || !req->ips.empty() // IP-address of user
935 for (int i = 0; i < DIR_NUM; i++)
937 if (req->sessionUpload[i].empty())
944 for (int i = 0; i < DIR_NUM; i++)
946 if (req->sessionDownload[i].empty())
953 for (int i = 0; i < DIR_NUM; i++)
955 if (req->monthUpload[i].empty())
962 for (int i = 0; i < DIR_NUM; i++)
964 if (req->monthDownload[i].empty())
971 for (int i = 0; i < DIR_NUM; i++)
973 if (req->userData[i].empty())
981 //printf("a=%d, b=%d, u=%d, d=%d ud=%d\n", a, b, u, d, ud);
982 return a && (b || su || sd || mu || md || ud);
984 //-----------------------------------------------------------------------------
985 int CheckParametersGet(REQUEST * req)
987 return CheckParameters(req);
989 //-----------------------------------------------------------------------------
990 int CheckParametersSet(REQUEST * req)
992 return CheckParameters(req);
994 //-----------------------------------------------------------------------------
995 bool mainGet(int argc, char **argv)
999 RESETABLE<string> t1;
1000 int missedOptionArg = false;
1002 const char * short_options_get = "s:p:a:w:u:crtmodieNADLPGISOE";
1003 int option_index = -1;
1008 c = getopt_long(argc, argv, short_options_get, long_options_get, &option_index);
1015 req.server = optarg;
1019 req.port = ParseServerPort(optarg);
1024 req.admLogin = ParseAdminLogin(optarg);
1027 case 'w': //admin password
1028 req.admPasswd = ParsePassword(optarg);
1031 case 'o': //change user password
1032 req.usrPasswd = " ";
1036 req.login = ParseUser(optarg);
1039 case 'c': //get cash
1047 case 'E': //credit expire
1048 req.creditExpire = 1;
1063 case 'e': //Prepaid Traffic
1064 req.prepaidTraff = 1;
1091 case 'I': //IP-address of user
1095 case 'S': //Detail stat status
1096 req.disableDetailStat = " ";
1099 case 'O': //Always online status
1100 req.alwaysOnline = " ";
1104 SetArrayItem(req.sessionUpload, optarg, 1);
1105 //req.sessionUpload[optarg] = 1;
1108 SetArrayItem(req.sessionDownload, optarg, 1);
1109 //req.sessionDownload[optarg] = 1;
1112 SetArrayItem(req.monthUpload, optarg, 1);
1113 //req.monthUpload[optarg] = 1;
1116 SetArrayItem(req.monthDownload, optarg, 1);
1117 //req.monthDownload[optarg] = 1;
1120 case 700: //UserData
1121 SetArrayItem(req.userData, optarg, std::string(" "));
1122 //req.userData[optarg] = " ";
1131 missedOptionArg = true;
1135 printf ("?? getopt returned character code 0%o ??\n", c);
1141 printf ("non-option ARGV-elements: ");
1142 while (optind < argc)
1143 printf ("%s ", argv[optind++]);
1145 exit(PARAMETER_PARSING_ERR_CODE);
1148 if (missedOptionArg || !CheckParametersGet(&req))
1150 //printf("Parameter needed\n");
1152 exit(PARAMETER_PARSING_ERR_CODE);
1156 return ProcessAuthBy(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data());
1158 return ProcessGetUser(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data(), req);
1160 //-----------------------------------------------------------------------------
1161 bool mainSet(int argc, char **argv)
1166 bool isMessage = false;
1169 RESETABLE<string> t1;
1171 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:";
1173 int missedOptionArg = false;
1179 int option_index = -1;
1181 c = getopt_long(argc, argv, short_options_set, long_options_set, &option_index);
1189 req.server = optarg;
1193 req.port = ParseServerPort(optarg);
1198 req.admLogin = ParseAdminLogin(optarg);
1201 case 'w': //admin password
1202 req.admPasswd = ParsePassword(optarg);
1205 case 'o': //change user password
1206 conf.password = ParsePassword(optarg);
1210 req.login = ParseUser(optarg);
1213 case 'c': //add cash
1214 stat.cashAdd = ParseCash(optarg);
1217 case 'v': //set cash
1218 stat.cashSet = ParseCash(optarg);
1222 conf.credit = ParseCredit(optarg);
1225 case 'E': //credit expire
1226 conf.creditExpire = ParseCreditExpire(optarg);
1230 conf.disabled = ParseDownPassive(optarg);
1234 conf.passive = ParseDownPassive(optarg);
1238 ParseTariff(optarg, conf.tariffName, conf.nextTariff);
1242 ParseAnyString(optarg, &str);
1247 case 'e': //Prepaid Traffic
1248 stat.freeMb = ParsePrepaidTraffic(optarg);
1251 case 'n': //Create User
1252 req.createUser = true;
1255 case 'l': //Delete User
1256 req.deleteUser = true;
1260 ParseAnyString(optarg, &str, "koi8-ru");
1265 ParseAnyString(optarg, &str, "koi8-ru");
1266 conf.realName = str;
1270 ParseAnyString(optarg, &str, "koi8-ru");
1275 ParseAnyString(optarg, &str, "koi8-ru");
1280 ParseAnyString(optarg, &str);
1285 ParseAnyString(optarg, &str, "koi8-ru");
1289 case 'I': //IP-address of user
1290 ParseAnyString(optarg, &str);
1291 conf.ips = StrToIPS(str);
1295 conf.disabledDetailStat = ParseDownPassive(optarg);
1299 conf.alwaysOnline = ParseDownPassive(optarg);
1303 SetArrayItem(stat.sessionUp, optarg, ParseTraff(argv[optind++]));
1306 SetArrayItem(stat.sessionDown, optarg, ParseTraff(argv[optind++]));
1309 SetArrayItem(stat.monthUp, optarg, ParseTraff(argv[optind++]));
1312 SetArrayItem(stat.monthDown, optarg, ParseTraff(argv[optind++]));
1315 case 700: //UserData
1316 ParseAnyString(argv[optind++], &str);
1317 SetArrayItem(conf.userdata, optarg, str);
1321 missedOptionArg = true;
1325 missedOptionArg = true;
1329 printf("?? getopt returned character code 0%o ??\n", c);
1335 printf ("non-option ARGV-elements: ");
1336 while (optind < argc)
1337 printf ("%s ", argv[optind++]);
1339 exit(PARAMETER_PARSING_ERR_CODE);
1342 if (missedOptionArg || !CheckParametersSet(&req))
1344 //printf("Parameter needed\n");
1346 exit(PARAMETER_PARSING_ERR_CODE);
1349 const int rLen = 20000;
1351 memset(rstr, 0, rLen);
1354 return ProcessSendMessage(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data(), req.usrMsg.data());
1356 return ProcessSetUser(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data(), conf, stat);
1358 //-----------------------------------------------------------------------------
1359 int main(int argc, char **argv)
1361 SGCONF::CONFIG config;
1362 SGCONF::COMMANDS commands;
1364 SGCONF::OPTION_BLOCKS blocks;
1365 blocks.Add("General options")
1366 .Add("c", "config", SGCONF::MakeParamAction(config.configFile, std::string("~/.config/stg/sgconf.conf"), "<config file>"), "override default config file")
1367 .Add("h", "help", SGCONF::MakeFunc0Action(bind0(Method1Adapt(&SGCONF::OPTION_BLOCKS::Help, blocks), 0)), "\t\tshow this help and exit")
1368 .Add("help-all", SGCONF::MakeFunc0Action(UsageAll), "\t\tshow full help and exit")
1369 .Add("v", "version", SGCONF::MakeFunc0Action(Version), "\t\tshow version information and exit");
1370 SGCONF::OPTION_BLOCK & block = blocks.Add("Connection options")
1371 .Add("s", "server", SGCONF::MakeParamAction(config.server, std::string("localhost"), "<address>"), "\t\thost to connect")
1372 .Add("p", "port", SGCONF::MakeParamAction(config.port, uint16_t(5555), "<port>"), "\t\tport to connect")
1373 .Add("u", "username", SGCONF::MakeParamAction(config.userName, std::string("admin"), "<username>"), "\tadministrative login")
1374 .Add("w", "userpass", SGCONF::MakeParamAction(config.userPass, "<password>"), "\tpassword for the administrative login")
1375 .Add("a", "address", SGCONF::MakeParamAction(config, "<connection string>"), "connection params as a single string in format: <login>:<password>@<host>:<port>");
1376 blocks.Add("Raw XML")
1377 .Add("r", "raw", SGCONF::MakeAPIAction(commands, "<xml>", true, SGCONF::RawXMLFunction), "\tmake raw XML request");
1378 /*blocks.Add("Admins management options")
1379 .Add("get-admins", SGCONF::MakeConfAction())
1380 .Add("get-admin", SGCONF::MakeConfAction())
1381 .Add("add-admin", SGCONF::MakeConfAction())
1382 .Add("del-admin", SGCONF::MakeConfAction())
1383 .Add("chg-admin", SGCONF::MakeConfAction());*/
1386 SGCONF::PARSER_STATE state(false, argc, argv);
1390 state = blocks.Parse(--argc, ++argv); // Skipping self name
1392 catch (const SGCONF::OPTION::ERROR& ex)
1394 std::cerr << ex.what() << "\n";
1403 std::cerr << "Unknown option: '" << *state.argv << "'\n";
1409 SGCONF::CONFIG configOverride(config);
1411 if (config.configFile.empty())
1413 const char * mainConfigFile = "/etc/sgconf/sgconf.conf";
1414 if (access(mainConfigFile, R_OK) == 0)
1415 block.ParseFile(mainConfigFile);
1416 ReadUserConfigFile(block);
1420 block.ParseFile(config.configFile.data());
1423 config = configOverride;
1425 catch (const std::exception& ex)
1427 std::cerr << ex.what() << "\n";
1431 std::cerr << "Config: " << config.Serialize() << std::endl;
1432 return commands.Execute(config) ? 0 : -1;
1445 exit(PARAMETER_PARSING_ERR_CODE);
1448 if (strcmp(argv[1], "get") == 0)
1451 return mainGet(argc - 1, argv + 1);
1453 else if (strcmp(argv[1], "set") == 0)
1456 if (mainSet(argc - 1, argv + 1) )
1463 exit(PARAMETER_PARSING_ERR_CODE);
1465 return UNKNOWN_ERR_CODE;*/
1467 //-----------------------------------------------------------------------------
1482 void UsageImpl(bool full)
1484 std::cout << "sgconf is the Stargazer management utility.\n\n"
1486 << "\tsgconf [options]\n\n"
1487 << "General options:\n"
1488 << "\t-c, --config <config file>\t\toverride default config file (default: \"~/.config/stg/sgconf.conf\")\n"
1489 << "\t-h, --help\t\t\t\tshow this help and exit\n"
1490 << "\t--help-all\t\t\t\tshow full help and exit\n"
1491 << "\t-v, --version\t\t\t\tshow version information and exit\n\n";
1496 UsageServices(full);
1497 UsageCorporations(full);
1499 //-----------------------------------------------------------------------------
1500 void UsageConnection()
1502 std::cout << "Connection options:\n"
1503 << "\t-s, --server <address>\t\t\thost to connect (ip or domain name, default: \"localhost\")\n"
1504 << "\t-p, --port <port>\t\t\tport to connect (default: \"5555\")\n"
1505 << "\t-u, --username <username>\t\tadministrative login (default: \"admin\")\n"
1506 << "\t-w, --userpass <password>\t\tpassword for administrative login\n"
1507 << "\t-a, --address <connection string>\tconnection params as a single string in format: <login>:<password>@<host>:<port>\n\n";
1509 //-----------------------------------------------------------------------------
1510 void UsageAdmins(bool full)
1512 std::cout << "Admins management options:\n"
1513 << "\t--get-admins\t\t\t\tget a list of admins (subsequent options will define what to show)\n";
1515 std::cout << "\t\t--login\t\t\t\tshow admin's login\n"
1516 << "\t\t--priv\t\t\t\tshow admin's priviledges\n\n";
1517 std::cout << "\t--get-admin\t\t\t\tget the information about admin\n";
1519 std::cout << "\t\t--login <login>\t\t\tlogin of the admin to show\n"
1520 << "\t\t--priv\t\t\t\tshow admin's priviledges\n\n";
1521 std::cout << "\t--add-admin\t\t\t\tadd a new admin\n";
1523 std::cout << "\t\t--login <login>\t\t\tlogin of the admin to add\n"
1524 << "\t\t--password <password>\t\tpassword of the admin to add\n"
1525 << "\t\t--priv <priv number>\t\tpriviledges of the admin to add\n\n";
1526 std::cout << "\t--del-admin\t\t\t\tdelete an existing admin\n";
1528 std::cout << "\t\t--login <login>\t\t\tlogin of the admin to delete\n\n";
1529 std::cout << "\t--chg-admin\t\t\t\tchange an existing admin\n";
1531 std::cout << "\t\t--login <login>\t\t\tlogin of the admin to change\n"
1532 << "\t\t--priv <priv number>\t\tnew priviledges\n\n";
1534 //-----------------------------------------------------------------------------
1535 void UsageTariffs(bool full)
1537 std::cout << "Tariffs management options:\n"
1538 << "\t--get-tariffs\t\t\t\tget a list of tariffs (subsequent options will define what to show)\n";
1540 std::cout << "\t\t--name\t\t\t\tshow tariff's name\n"
1541 << "\t\t--fee\t\t\t\tshow tariff's fee\n"
1542 << "\t\t--free\t\t\t\tshow tariff's prepaid traffic in terms of cost\n"
1543 << "\t\t--passive-cost\t\t\tshow tariff's cost of \"freeze\"\n"
1544 << "\t\t--traff-type\t\t\tshow what type of traffix will be accounted by the tariff\n"
1545 << "\t\t--dirs\t\t\t\tshow tarification rules for directions\n\n";
1546 std::cout << "\t--get-tariff\t\t\t\tget the information about tariff\n";
1548 std::cout << "\t\t--name <name>\t\t\tname of the tariff to show\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--add-tariff\t\t\t\tadd a new tariff\n";
1556 std::cout << "\t\t--name <name>\t\t\tname of the tariff to add\n"
1557 << "\t\t--fee <fee>\t\t\tstariff's fee\n"
1558 << "\t\t--free <free>\t\t\ttariff's prepaid traffic in terms of cost\n"
1559 << "\t\t--passive-cost <cost>\t\ttariff's cost of \"freeze\"\n"
1560 << "\t\t--traff-type <type>\t\twhat type of traffi will be accounted by the tariff\n"
1561 << "\t\t--times <times>\t\t\tslash-separated list of \"day\" time-spans (in form \"hh:mm-hh:mm\") for each direction\n"
1562 << "\t\t--prices-day-a <prices>\t\tslash-separated list of prices for \"day\" traffic before threshold for each direction\n"
1563 << "\t\t--prices-night-a <prices>\tslash-separated list of prices for \"night\" traffic before threshold for each direction\n"
1564 << "\t\t--prices-day-b <prices>\t\tslash-separated list of prices for \"day\" traffic after threshold for each direction\n"
1565 << "\t\t--prices-night-b <prices>\tslash-separated list of prices for \"night\" traffic after threshold for each direction\n"
1566 << "\t\t--single-prices <yes|no>\tslash-separated list of \"single price\" flags for each direction\n"
1567 << "\t\t--no-discounts <yes|no>\t\tslash-separated list of \"no discount\" flags for each direction\n"
1568 << "\t\t--thresholds <thresholds>\tslash-separated list of thresholds (in Mb) for each direction\n\n";
1569 std::cout << "\t--del-tariff\t\t\t\tdelete an existing tariff\n";
1571 std::cout << "\t\t--name <name>\t\t\tname of the tariff to delete\n\n";
1572 std::cout << "\t--chg-tariff\t\t\t\tchange an existing tariff\n";
1574 std::cout << "\t\t--name <name>\t\t\tname of the tariff to change\n"
1575 << "\t\t--fee <fee>\t\t\tstariff's fee\n"
1576 << "\t\t--free <free>\t\t\ttariff's prepaid traffic in terms of cost\n"
1577 << "\t\t--passive-cost <cost>\t\ttariff's cost of \"freeze\"\n"
1578 << "\t\t--traff-type <type>\t\twhat type of traffix will be accounted by the tariff\n"
1579 << "\t\t--dir <N>\t\t\tnumber of direction data to change\n"
1580 << "\t\t\t--time <time>\t\t\"day\" time-span (in form \"hh:mm-hh:mm\")\n"
1581 << "\t\t\t--price-day-a <price>\tprice for \"day\" traffic before threshold\n"
1582 << "\t\t\t--price-night-a <price>\tprice for \"night\" traffic before threshold\n"
1583 << "\t\t\t--price-day-b <price>\tprice for \"day\" traffic after threshold\n"
1584 << "\t\t\t--price-night-b <price>\tprice for \"night\" traffic after threshold\n"
1585 << "\t\t\t--single-price <yes|no>\t\"single price\" flag\n"
1586 << "\t\t\t--no-discount <yes|no>\t\"no discount\" flag\n"
1587 << "\t\t\t--threshold <threshold>\tthreshold (in Mb)\n\n";
1589 //-----------------------------------------------------------------------------
1590 void UsageUsers(bool full)
1592 std::cout << "Users management options:\n"
1593 << "\t--get-users\t\t\t\tget a list of users (subsequent options will define what to show)\n";
1595 std::cout << "\n\n";
1596 std::cout << "\t--get-user\t\t\t\tget the information about user\n";
1598 std::cout << "\n\n";
1599 std::cout << "\t--add-user\t\t\t\tadd a new user\n";
1601 std::cout << "\n\n";
1602 std::cout << "\t--del-user\t\t\t\tdelete an existing user\n";
1604 std::cout << "\n\n";
1605 std::cout << "\t--chg-user\t\t\t\tchange an existing user\n";
1607 std::cout << "\n\n";
1608 std::cout << "\t--check-user\t\t\t\tcheck credentials is valid\n";
1610 std::cout << "\n\n";
1611 std::cout << "\t--send-message\t\t\t\tsend a message to a user\n";
1613 std::cout << "\n\n";
1615 //-----------------------------------------------------------------------------
1616 void UsageServices(bool full)
1618 std::cout << "Services management options:\n"
1619 << "\t--get-services\t\t\t\tget a list of services (subsequent options will define what to show)\n";
1621 std::cout << "\t\t--name\t\t\t\tshow service's name\n"
1622 << "\t\t--comment\t\t\tshow a comment to the service\n"
1623 << "\t\t--cost\t\t\t\tshow service's cost\n"
1624 << "\t\t--pay-day\t\t\tshow service's pay day\n\n";
1625 std::cout << "\t--get-service\t\t\t\tget the information about service\n";
1627 std::cout << "\t\t--name <name>\t\t\tname of the service to show\n"
1628 << "\t\t--comment\t\t\tshow a comment to the service\n"
1629 << "\t\t--cost\t\t\t\tshow service's cost\n"
1630 << "\t\t--pay-day\t\t\tshow service's pay day\n\n";
1631 std::cout << "\t--add-service\t\t\t\tadd a new service\n";
1633 std::cout << "\t\t--name <name>\t\t\tname of the service to add\n"
1634 << "\t\t--comment <comment>\t\ta comment to the service\n"
1635 << "\t\t--cost <cost>\t\t\tservice's cost\n"
1636 << "\t\t--pay-day <day>\t\t\tservice's pay day\n\n";
1637 std::cout << "\t--del-service\t\t\t\tdelete an existing service\n";
1639 std::cout << "\t\t--name <name>\t\t\tname of the service to delete\n\n";
1640 std::cout << "\t--chg-service\t\t\t\tchange an existing service\n";
1642 std::cout << "\t\t--name <name>\t\t\tname of the service to change\n"
1643 << "\t\t--comment <comment>\t\ta comment to the service\n"
1644 << "\t\t--cost <cost>\t\t\tservice's cost\n"
1645 << "\t\t--pay-day <day>\t\t\tservice's pay day\n\n";
1647 //-----------------------------------------------------------------------------
1648 void UsageCorporations(bool full)
1650 std::cout << "Corporations management options:\n"
1651 << "\t--get-corporations\t\t\tget a list of corporations (subsequent options will define what to show)\n";
1653 std::cout << "\t\t--name\t\t\t\tshow corporation's name\n"
1654 << "\t\t--cash\t\t\t\tshow corporation's cash\n\n";
1655 std::cout << "\t--get-corp\t\t\t\tget the information about corporation\n";
1657 std::cout << "\t\t--name <name>\t\t\tname of the corporation to show\n"
1658 << "\t\t--cash\t\t\t\tshow corporation's cash\n\n";
1659 std::cout << "\t--add-corp\t\t\t\tadd a new corporation\n";
1661 std::cout << "\t\t--name <name>\t\t\tname of the corporation to add\n"
1662 << "\t\t--cash <cash>\t\t\tinitial corporation's cash (default: \"0\")\n\n";
1663 std::cout << "\t--del-corp\t\t\t\tdelete an existing corporation\n";
1665 std::cout << "\t\t--name <name>\t\t\tname of the corporation to delete\n\n";
1666 std::cout << "\t--chg-corp\t\t\t\tchange an existing corporation\n";
1668 std::cout << "\t\t--name <name>\t\t\tname of the corporation to change\n"
1669 << "\t\t--add-cash <amount>[:<message>]\tadd cash to the corporation's account and optional comment message\n"
1670 << "\t\t--set-cash <cash>[:<message>]\tnew corporation's cash and optional comment message\n\n";
1675 std::cout << "sgconf, version: 2.0.0-alpha.\n";
1678 } // namespace anonymous