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"
33 #include "stg/user_conf.h"
34 #include "stg/user_stat.h"
35 #include "stg/common.h"
56 typedef typename T::value_type type;
60 struct ARRAY_TYPE<T[]>
65 template <typename T, size_t N>
66 struct ARRAY_TYPE<T[N]>
72 struct nullary_function
74 typedef T result_type;
78 class binder0 : public nullary_function<typename F::result_type>
81 binder0(const F & func, const typename F::argument_type & arg)
82 : m_func(func), m_arg(arg) {}
83 typename F::result_type operator()() const { return m_func(m_arg); }
86 typename F::argument_type m_arg;
91 binder0<F> bind0(const F & func, const typename F::argument_type & arg)
93 return binder0<F>(func, arg);
96 template <typename C, typename A, typename R>
97 class METHOD1_ADAPTER : public std::unary_function<A, R>
100 METHOD1_ADAPTER(R (C::* func)(A), C & obj) : m_func(func), m_obj(obj) {}
101 R operator()(A arg) { return (m_obj.*m_func)(arg); }
107 template <typename C, typename A, typename R>
108 class CONST_METHOD1_ADAPTER : public std::unary_function<A, R>
111 CONST_METHOD1_ADAPTER(R (C::* func)(A) const, C & obj) : m_func(func), m_obj(obj) {}
112 R operator()(A arg) const { return (m_obj.*m_func)(arg); }
114 R (C::* m_func)(A) const;
118 template <typename C, typename A, typename R>
119 METHOD1_ADAPTER<C, A, R> Method1Adapt(R (C::* func)(A), C & obj)
121 return METHOD1_ADAPTER<C, A, R>(func, obj);
124 template <typename C, typename A, typename R>
125 CONST_METHOD1_ADAPTER<C, A, R> Method1Adapt(R (C::* func)(A) const, C & obj)
127 return CONST_METHOD1_ADAPTER<C, A, R>(func, obj);
130 template <typename T>
131 bool SetArrayItem(T & array, const char * index, const typename ARRAY_TYPE<T>::type & value)
134 if (str2x(index, pos))
140 void RawXMLCallback(bool result, const std::string & reason, const std::string & response, void * /*data*/)
144 std::cerr << "Failed to get raw XML response. Reason: '" << reason << "'." << std::endl;
147 SGCONF::PrintXML(response);
152 void UsageImpl(bool full);
153 void UsageConnection();
154 void UsageAdmins(bool full);
155 void UsageTariffs(bool full);
156 void UsageUsers(bool full);
157 void UsageServices(bool full);
158 void UsageCorporations(bool full);
162 void ReadUserConfigFile(SGCONF::OPTION_BLOCK & block)
164 std::vector<std::string> paths;
165 const char * configHome = getenv("XDG_CONFIG_HOME");
166 if (configHome == NULL)
168 const char * home = getenv("HOME");
171 paths.push_back(std::string(home) + "/.config/sgconf/sgconf.conf");
172 paths.push_back(std::string(home) + "/.sgconf/sgconf.conf");
175 paths.push_back(std::string(configHome) + "/sgconf/sgconf.conf");
176 for (std::vector<std::string>::const_iterator it = paths.begin(); it != paths.end(); ++it)
177 if (access(it->c_str(), R_OK) == 0)
179 block.ParseFile(*it);
184 } // namespace anonymous
189 class CONFIG_ACTION : public ACTION
192 CONFIG_ACTION(SGCONF::CONFIG & config,
193 const std::string & paramDescription)
195 m_description(paramDescription)
198 virtual ACTION * Clone() const { return new CONFIG_ACTION(*this); }
200 virtual std::string ParamDescription() const { return m_description; }
201 virtual std::string DefaultDescription() const { return ""; }
202 virtual OPTION_BLOCK & Suboptions() { return m_suboptions; }
203 virtual PARSER_STATE Parse(int argc, char ** argv);
206 SGCONF::CONFIG & m_config;
207 std::string m_description;
208 OPTION_BLOCK m_suboptions;
210 void ParseCredentials(const std::string & credentials);
211 void ParseHostAndPort(const std::string & hostAndPort);
214 typedef bool (* API_FUNCTION) (const SGCONF::CONFIG &,
216 const std::map<std::string, std::string> &);
221 COMMAND(API_FUNCTION funPtr,
222 const std::string & arg,
223 const std::map<std::string, std::string> & options)
228 bool Execute(const SGCONF::CONFIG & config) const
230 return m_funPtr(config, m_arg, m_options);
234 API_FUNCTION m_funPtr;
236 std::map<std::string, std::string> m_options;
242 void Add(API_FUNCTION funPtr,
243 const std::string & arg,
244 const std::map<std::string, std::string> & options) { m_commands.push_back(COMMAND(funPtr, arg, options)); }
245 bool Execute(const SGCONF::CONFIG & config) const
247 std::list<COMMAND>::const_iterator it(m_commands.begin());
249 while (it != m_commands.end() && res)
251 res = res && it->Execute(config);
257 std::list<COMMAND> m_commands;
260 class API_ACTION : public ACTION
263 API_ACTION(COMMANDS & commands,
264 const std::string & paramDescription,
266 const OPTION_BLOCK& suboptions,
268 : m_commands(commands),
269 m_description(paramDescription),
270 m_argument(needArgument ? "1" : ""), // Hack
271 m_suboptions(suboptions),
274 API_ACTION(COMMANDS & commands,
275 const std::string & paramDescription,
278 : m_commands(commands),
279 m_description(paramDescription),
280 m_argument(needArgument ? "1" : ""), // Hack
284 virtual ACTION * Clone() const { return new API_ACTION(*this); }
286 virtual std::string ParamDescription() const { return m_description; }
287 virtual std::string DefaultDescription() const { return ""; }
288 virtual OPTION_BLOCK & Suboptions() { return m_suboptions; }
289 virtual PARSER_STATE Parse(int argc, char ** argv)
291 PARSER_STATE state(false, argc, argv);
292 if (!m_argument.empty())
297 throw ERROR("Missing argument.");
302 m_suboptions.Parse(state.argc, state.argv);
303 m_commands.Add(m_funPtr, m_argument, m_params);
308 COMMANDS & m_commands;
309 std::string m_description;
310 std::string m_argument;
311 OPTION_BLOCK m_suboptions;
312 std::map<std::string, std::string> m_params;
313 API_FUNCTION m_funPtr;
316 PARSER_STATE CONFIG_ACTION::Parse(int argc, char ** argv)
321 throw ERROR("Missing argument.");
322 char * pos = strchr(*argv, '@');
325 ParseCredentials(std::string(*argv, pos));
326 ParseHostAndPort(std::string(pos + 1));
330 ParseHostAndPort(std::string(*argv));
332 return PARSER_STATE(false, --argc, ++argv);
335 void CONFIG_ACTION::ParseCredentials(const std::string & credentials)
337 std::string::size_type pos = credentials.find_first_of(':');
338 if (pos != std::string::npos)
340 m_config.userName = credentials.substr(0, pos);
341 m_config.userPass = credentials.substr(pos + 1);
345 m_config.userName = credentials;
349 void CONFIG_ACTION::ParseHostAndPort(const std::string & hostAndPort)
351 std::string::size_type pos = hostAndPort.find_first_of(':');
352 if (pos != std::string::npos)
354 m_config.server = hostAndPort.substr(0, pos);
356 if (str2x(hostAndPort.substr(pos + 1), port))
357 throw ERROR("Invalid port value: '" + hostAndPort.substr(pos + 1) + "'");
358 m_config.port = port;
362 m_config.server = hostAndPort;
367 CONFIG_ACTION * MakeParamAction(SGCONF::CONFIG & config,
368 const std::string & paramDescription)
370 return new CONFIG_ACTION(config, paramDescription);
374 ACTION * MakeAPIAction(COMMANDS & commands,
375 const std::string & paramDescription,
379 return new API_ACTION(commands, paramDescription, needArgument, funPtr);
383 ACTION * MakeAPIAction(COMMANDS & commands,
386 return new API_ACTION(commands, "", false, funPtr);
389 bool RawXMLFunction(const SGCONF::CONFIG & config,
390 const std::string & arg,
391 const std::map<std::string, std::string> & /*options*/)
393 STG::SERVCONF proto(config.server.data(),
395 config.userName.data(),
396 config.userPass.data());
397 return proto.RawXML(arg, RawXMLCallback, NULL) == STG::st_ok;
400 } // namespace SGCONF
404 struct option long_options_get[] = {
405 {"server", 1, 0, 's'}, //Server
406 {"port", 1, 0, 'p'}, //Port
407 {"admin", 1, 0, 'a'}, //Admin
408 {"admin_pass", 1, 0, 'w'}, //passWord
409 {"user", 1, 0, 'u'}, //User
410 {"addcash", 0, 0, 'c'}, //Add Cash
411 //{"setcash", 0, 0, 'v'}, //Set Cash
412 {"credit", 0, 0, 'r'}, //cRedit
413 {"tariff", 0, 0, 't'}, //Tariff
414 {"message", 0, 0, 'm'}, //message
415 {"password", 0, 0, 'o'}, //password
416 {"down", 0, 0, 'd'}, //down
417 {"passive", 0, 0, 'i'}, //passive
418 {"disable-stat",0, 0, 'S'}, //disable detail stat
419 {"always-online",0, 0, 'O'}, //always online
420 {"session-upload", 1, 0, 500}, //SU0
421 {"session-download", 1, 0, 501}, //SD0
422 {"month-upload", 1, 0, 502}, //MU0
423 {"month-download", 1, 0, 503}, //MD0
425 {"user-data", 1, 0, 700}, //UserData0
427 {"prepaid", 0, 0, 'e'}, //prepaid traff
428 {"create", 0, 0, 'n'}, //create
429 {"delete", 0, 0, 'l'}, //delete
431 {"note", 0, 0, 'N'}, //Note
432 {"name", 0, 0, 'A'}, //nAme
433 {"address", 0, 0, 'D'}, //aDdress
434 {"email", 0, 0, 'L'}, //emaiL
435 {"phone", 0, 0, 'P'}, //phone
436 {"group", 0, 0, 'G'}, //Group
437 {"ip", 0, 0, 'I'}, //IP-address of user
438 {"authorized-by",0, 0, 800}, //always online
442 struct option long_options_set[] = {
443 {"server", 1, 0, 's'}, //Server
444 {"port", 1, 0, 'p'}, //Port
445 {"admin", 1, 0, 'a'}, //Admin
446 {"admin_pass", 1, 0, 'w'}, //passWord
447 {"user", 1, 0, 'u'}, //User
448 {"addcash", 1, 0, 'c'}, //Add Cash
449 {"setcash", 1, 0, 'v'}, //Set Cash
450 {"credit", 1, 0, 'r'}, //cRedit
451 {"tariff", 1, 0, 't'}, //Tariff
452 {"message", 1, 0, 'm'}, //message
453 {"password", 1, 0, 'o'}, //password
454 {"down", 1, 0, 'd'}, //down
455 {"passive", 1, 0, 'i'}, //passive
456 {"disable-stat",1, 0, 'S'}, //disable detail stat
457 {"always-online",1, 0, 'O'}, //always online
458 {"session-upload", 1, 0, 500}, //U0
459 {"session-download", 1, 0, 501}, //U1
460 {"month-upload", 1, 0, 502}, //U2
461 {"month-download", 1, 0, 503}, //U3
463 {"user-data", 1, 0, 700}, //UserData
465 {"prepaid", 1, 0, 'e'}, //prepaid traff
466 {"create", 1, 0, 'n'}, //create
467 {"delete", 1, 0, 'l'}, //delete
469 {"note", 1, 0, 'N'}, //Note
470 {"name", 1, 0, 'A'}, //nAme
471 {"address", 1, 0, 'D'}, //aDdress
472 {"email", 1, 0, 'L'}, //emaiL
473 {"phone", 1, 0, 'P'}, //phone
474 {"group", 1, 0, 'G'}, //Group
475 {"ip", 0, 0, 'I'}, //IP-address of user
479 //-----------------------------------------------------------------------------
480 CASH_INFO ParseCash(const char * str)
482 //-c 123.45:log message
483 std::string cashString;
485 const char * pos = strchr(str, ':');
488 cashString.append(str, pos);
489 message.append(pos + 1);
495 if (strtodouble2(cashString, cash) != 0)
497 printf("Incorrect cash value %s\n", str);
498 exit(PARAMETER_PARSING_ERR_CODE);
501 return CASH_INFO(cash, message);
503 //-----------------------------------------------------------------------------
504 double ParseCredit(const char * c)
507 if (strtodouble2(c, credit) != 0)
509 printf("Incorrect credit value %s\n", c);
510 exit(PARAMETER_PARSING_ERR_CODE);
515 //-----------------------------------------------------------------------------
516 double ParsePrepaidTraffic(const char * c)
519 if (strtodouble2(c, credit) != 0)
521 printf("Incorrect prepaid traffic value %s\n", c);
522 exit(PARAMETER_PARSING_ERR_CODE);
527 //-----------------------------------------------------------------------------
528 int64_t ParseTraff(const char * c)
531 if (str2x(c, traff) != 0)
533 printf("Incorrect credit value %s\n", c);
534 exit(PARAMETER_PARSING_ERR_CODE);
539 //-----------------------------------------------------------------------------
540 bool ParseDownPassive(const char * dp)
542 if (!(dp[1] == 0 && (dp[0] == '1' || dp[0] == '0')))
544 printf("Incorrect value %s\n", dp);
545 exit(PARAMETER_PARSING_ERR_CODE);
550 //-----------------------------------------------------------------------------
551 void ParseTariff(const char * str, RESETABLE<std::string> & tariffName, RESETABLE<std::string> & nextTariff)
553 const char * pos = strchr(str, ':');
556 std::string tariff(str, pos);
557 if (strcmp(pos + 1, "now") == 0)
559 else if (strcmp(pos + 1, "delayed") == 0)
563 printf("Incorrect tariff value '%s'. Should be '<tariff>', '<tariff>:now' or '<tariff>:delayed'.\n", str);
564 exit(PARAMETER_PARSING_ERR_CODE);
570 //-----------------------------------------------------------------------------
571 time_t ParseCreditExpire(const char * str)
573 struct tm brokenTime;
575 brokenTime.tm_wday = 0;
576 brokenTime.tm_yday = 0;
577 brokenTime.tm_isdst = 0;
578 brokenTime.tm_hour = 0;
579 brokenTime.tm_min = 0;
580 brokenTime.tm_sec = 0;
582 stg_strptime(str, "%Y-%m-%d", &brokenTime);
584 return stg_timegm(&brokenTime);
586 //-----------------------------------------------------------------------------
587 void ParseAnyString(const char * c, string * msg, const char * enc)
590 char * ob = new char[strlen(c) + 1];
591 char * ib = new char[strlen(c) + 1];
598 setlocale(LC_ALL, "");
601 strncpy(charsetF, nl_langinfo(CODESET), 255);
603 const char * charsetT = enc;
607 size_t insize = strlen(ib);
608 size_t outsize = strlen(ib);
612 cd = iconv_open(charsetT, charsetF);
613 if (cd == (iconv_t) -1)
617 printf("Warning: iconv from %s to %s failed\n", charsetF, charsetT);
622 printf("error iconv_open\n");
624 exit(ICONV_ERR_CODE);
627 #if defined(FREE_BSD) || defined(FREE_BSD5)
628 nconv = iconv (cd, (const char**)&inbuf, &insize, &outbuf, &outsize);
630 nconv = iconv (cd, &inbuf, &insize, &outbuf, &outsize);
632 //printf("nconv=%d outsize=%d\n", nconv, outsize);
633 if (nconv == (size_t) -1)
637 printf("iconv error\n");
638 exit(ICONV_ERR_CODE);
650 //-----------------------------------------------------------------------------
651 void CreateRequestSet(REQUEST * req, char * r)
653 const int strLen = 10024;
655 memset(str, 0, strLen);
659 if (!req->usrMsg.empty())
662 Encode12str(msg, req->usrMsg.data());
663 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());
664 //sprintf(str, "<message login=\"%s\" priority=\"0\" text=\"%s\"/>\n", req->login, msg);
671 sprintf(str, "<DelUser login=\"%s\"/>", req->login.const_data().c_str());
679 sprintf(str, "<AddUser> <login value=\"%s\"/> </AddUser>", req->login.const_data().c_str());
685 strcat(r, "<SetUser>\n");
686 sprintf(str, "<login value=\"%s\"/>\n", req->login.const_data().c_str());
688 if (!req->credit.empty())
690 sprintf(str, "<credit value=\"%f\"/>\n", req->credit.const_data());
694 if (!req->creditExpire.empty())
696 sprintf(str, "<creditExpire value=\"%ld\"/>\n", req->creditExpire.const_data());
700 if (!req->prepaidTraff.empty())
702 sprintf(str, "<FreeMb value=\"%f\"/>\n", req->prepaidTraff.const_data());
706 if (!req->cash.empty())
709 Encode12str(msg, req->message);
710 sprintf(str, "<cash add=\"%f\" msg=\"%s\"/>\n", req->cash.const_data(), msg.c_str());
714 if (!req->setCash.empty())
717 Encode12str(msg, req->message);
718 sprintf(str, "<cash set=\"%f\" msg=\"%s\"/>\n", req->setCash.const_data(), msg.c_str());
722 if (!req->usrPasswd.empty())
724 sprintf(str, "<password value=\"%s\" />\n", req->usrPasswd.const_data().c_str());
728 if (!req->down.empty())
730 sprintf(str, "<down value=\"%d\" />\n", req->down.const_data());
734 if (!req->passive.empty())
736 sprintf(str, "<passive value=\"%d\" />\n", req->passive.const_data());
740 if (!req->disableDetailStat.empty())
742 sprintf(str, "<disableDetailStat value=\"%d\" />\n", req->disableDetailStat.const_data());
746 if (!req->alwaysOnline.empty())
748 sprintf(str, "<aonline value=\"%d\" />\n", req->alwaysOnline.const_data());
752 // IP-address of user
753 if (!req->ips.empty())
755 sprintf(str, "<ip value=\"%s\" />\n", req->ips.const_data().c_str());
759 int uPresent = false;
760 int dPresent = false;
761 for (int i = 0; i < DIR_NUM; i++)
763 if (!req->monthUpload[i].empty())
765 if (!uPresent && !dPresent)
767 sprintf(str, "<traff ");
773 ss << req->monthUpload[i].const_data();
774 //sprintf(str, "MU%d=\"%lld\" ", i, req->u[i].const_data());
775 sprintf(str, "MU%d=\"%s\" ", i, ss.str().c_str());
778 if (!req->monthDownload[i].empty())
780 if (!uPresent && !dPresent)
782 sprintf(str, "<traff ");
788 ss << req->monthDownload[i].const_data();
789 sprintf(str, "MD%d=\"%s\" ", i, ss.str().c_str());
792 if (!req->sessionUpload[i].empty())
794 if (!uPresent && !dPresent)
796 sprintf(str, "<traff ");
802 ss << req->sessionUpload[i].const_data();
803 //sprintf(str, "MU%d=\"%lld\" ", i, req->u[i].const_data());
804 sprintf(str, "MU%d=\"%s\" ", i, ss.str().c_str());
807 if (!req->sessionDownload[i].empty())
809 if (!uPresent && !dPresent)
811 sprintf(str, "<traff ");
817 ss << req->sessionDownload[i].const_data();
818 sprintf(str, "MD%d=\"%s\" ", i, ss.str().c_str());
822 if (uPresent || dPresent)
829 if (!req->tariff.empty())
831 switch (req->chgTariff)
834 sprintf(str, "<tariff now=\"%s\"/>\n", req->tariff.const_data().c_str());
838 sprintf(str, "<tariff recalc=\"%s\"/>\n", req->tariff.const_data().c_str());
842 sprintf(str, "<tariff delayed=\"%s\"/>\n", req->tariff.const_data().c_str());
849 if (!req->note.empty())
852 Encode12str(note, req->note.data());
853 sprintf(str, "<note value=\"%s\"/>", note.c_str());
857 if (!req->name.empty())
860 Encode12str(name, req->name.data());
861 sprintf(str, "<name value=\"%s\"/>", name.c_str());
865 if (!req->address.empty())
868 Encode12str(address, req->address.data());
869 sprintf(str, "<address value=\"%s\"/>", address.c_str());
873 if (!req->email.empty())
876 Encode12str(email, req->email.data());
877 sprintf(str, "<email value=\"%s\"/>", email.c_str());
881 if (!req->phone.empty())
884 Encode12str(phone, req->phone.data());
885 sprintf(str, "<phone value=\"%s\"/>", phone.c_str());
889 if (!req->group.empty())
892 Encode12str(group, req->group.data());
893 sprintf(str, "<group value=\"%s\"/>", group.c_str());
897 for (int i = 0; i < USERDATA_NUM; i++)
899 if (!req->userData[i].empty())
902 Encode12str(ud, req->userData[i].data());
903 sprintf(str, "<userdata%d value=\"%s\"/>", i, ud.c_str());
908 strcat(r, "</SetUser>\n");
910 //-----------------------------------------------------------------------------
911 int CheckParameters(REQUEST * req)
918 bool a = !req->admLogin.empty()
919 && !req->admPasswd.empty()
920 && !req->server.empty()
921 && !req->port.empty()
922 && !req->login.empty();
924 bool b = !req->cash.empty()
925 || !req->setCash.empty()
926 || !req->credit.empty()
927 || !req->prepaidTraff.empty()
928 || !req->tariff.empty()
929 || !req->usrMsg.empty()
930 || !req->usrPasswd.empty()
932 || !req->note.empty()
933 || !req->name.empty()
934 || !req->address.empty()
935 || !req->email.empty()
936 || !req->phone.empty()
937 || !req->group.empty()
938 || !req->ips.empty() // IP-address of user
944 for (int i = 0; i < DIR_NUM; i++)
946 if (req->sessionUpload[i].empty())
953 for (int i = 0; i < DIR_NUM; i++)
955 if (req->sessionDownload[i].empty())
962 for (int i = 0; i < DIR_NUM; i++)
964 if (req->monthUpload[i].empty())
971 for (int i = 0; i < DIR_NUM; i++)
973 if (req->monthDownload[i].empty())
980 for (int i = 0; i < DIR_NUM; i++)
982 if (req->userData[i].empty())
990 //printf("a=%d, b=%d, u=%d, d=%d ud=%d\n", a, b, u, d, ud);
991 return a && (b || su || sd || mu || md || ud);
993 //-----------------------------------------------------------------------------
994 int CheckParametersGet(REQUEST * req)
996 return CheckParameters(req);
998 //-----------------------------------------------------------------------------
999 int CheckParametersSet(REQUEST * req)
1001 return CheckParameters(req);
1003 //-----------------------------------------------------------------------------
1004 bool mainGet(int argc, char **argv)
1008 RESETABLE<string> t1;
1009 int missedOptionArg = false;
1011 const char * short_options_get = "s:p:a:w:u:crtmodieNADLPGISOE";
1012 int option_index = -1;
1017 c = getopt_long(argc, argv, short_options_get, long_options_get, &option_index);
1024 req.server = optarg;
1028 req.port = ParseServerPort(optarg);
1033 req.admLogin = ParseAdminLogin(optarg);
1036 case 'w': //admin password
1037 req.admPasswd = ParsePassword(optarg);
1040 case 'o': //change user password
1041 req.usrPasswd = " ";
1045 req.login = ParseUser(optarg);
1048 case 'c': //get cash
1056 case 'E': //credit expire
1057 req.creditExpire = 1;
1072 case 'e': //Prepaid Traffic
1073 req.prepaidTraff = 1;
1100 case 'I': //IP-address of user
1104 case 'S': //Detail stat status
1105 req.disableDetailStat = " ";
1108 case 'O': //Always online status
1109 req.alwaysOnline = " ";
1113 SetArrayItem(req.sessionUpload, optarg, 1);
1114 //req.sessionUpload[optarg] = 1;
1117 SetArrayItem(req.sessionDownload, optarg, 1);
1118 //req.sessionDownload[optarg] = 1;
1121 SetArrayItem(req.monthUpload, optarg, 1);
1122 //req.monthUpload[optarg] = 1;
1125 SetArrayItem(req.monthDownload, optarg, 1);
1126 //req.monthDownload[optarg] = 1;
1129 case 700: //UserData
1130 SetArrayItem(req.userData, optarg, std::string(" "));
1131 //req.userData[optarg] = " ";
1140 missedOptionArg = true;
1144 printf ("?? getopt returned character code 0%o ??\n", c);
1150 printf ("non-option ARGV-elements: ");
1151 while (optind < argc)
1152 printf ("%s ", argv[optind++]);
1154 exit(PARAMETER_PARSING_ERR_CODE);
1157 if (missedOptionArg || !CheckParametersGet(&req))
1159 //printf("Parameter needed\n");
1161 exit(PARAMETER_PARSING_ERR_CODE);
1165 return ProcessAuthBy(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data());
1167 return ProcessGetUser(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data(), req);
1169 //-----------------------------------------------------------------------------
1170 bool mainSet(int argc, char **argv)
1175 bool isMessage = false;
1178 RESETABLE<string> t1;
1180 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:";
1182 int missedOptionArg = false;
1188 int option_index = -1;
1190 c = getopt_long(argc, argv, short_options_set, long_options_set, &option_index);
1198 req.server = optarg;
1202 req.port = ParseServerPort(optarg);
1207 req.admLogin = ParseAdminLogin(optarg);
1210 case 'w': //admin password
1211 req.admPasswd = ParsePassword(optarg);
1214 case 'o': //change user password
1215 conf.password = ParsePassword(optarg);
1219 req.login = ParseUser(optarg);
1222 case 'c': //add cash
1223 stat.cashAdd = ParseCash(optarg);
1226 case 'v': //set cash
1227 stat.cashSet = ParseCash(optarg);
1231 conf.credit = ParseCredit(optarg);
1234 case 'E': //credit expire
1235 conf.creditExpire = ParseCreditExpire(optarg);
1239 conf.disabled = ParseDownPassive(optarg);
1243 conf.passive = ParseDownPassive(optarg);
1247 ParseTariff(optarg, conf.tariffName, conf.nextTariff);
1251 ParseAnyString(optarg, &str);
1256 case 'e': //Prepaid Traffic
1257 stat.freeMb = ParsePrepaidTraffic(optarg);
1260 case 'n': //Create User
1261 req.createUser = true;
1264 case 'l': //Delete User
1265 req.deleteUser = true;
1269 ParseAnyString(optarg, &str, "koi8-ru");
1274 ParseAnyString(optarg, &str, "koi8-ru");
1275 conf.realName = str;
1279 ParseAnyString(optarg, &str, "koi8-ru");
1284 ParseAnyString(optarg, &str, "koi8-ru");
1289 ParseAnyString(optarg, &str);
1294 ParseAnyString(optarg, &str, "koi8-ru");
1298 case 'I': //IP-address of user
1299 ParseAnyString(optarg, &str);
1300 conf.ips = StrToIPS(str);
1304 conf.disabledDetailStat = ParseDownPassive(optarg);
1308 conf.alwaysOnline = ParseDownPassive(optarg);
1312 SetArrayItem(stat.sessionUp, optarg, ParseTraff(argv[optind++]));
1315 SetArrayItem(stat.sessionDown, optarg, ParseTraff(argv[optind++]));
1318 SetArrayItem(stat.monthUp, optarg, ParseTraff(argv[optind++]));
1321 SetArrayItem(stat.monthDown, optarg, ParseTraff(argv[optind++]));
1324 case 700: //UserData
1325 ParseAnyString(argv[optind++], &str);
1326 SetArrayItem(conf.userdata, optarg, str);
1330 missedOptionArg = true;
1334 missedOptionArg = true;
1338 printf("?? getopt returned character code 0%o ??\n", c);
1344 printf ("non-option ARGV-elements: ");
1345 while (optind < argc)
1346 printf ("%s ", argv[optind++]);
1348 exit(PARAMETER_PARSING_ERR_CODE);
1351 if (missedOptionArg || !CheckParametersSet(&req))
1353 //printf("Parameter needed\n");
1355 exit(PARAMETER_PARSING_ERR_CODE);
1358 const int rLen = 20000;
1360 memset(rstr, 0, rLen);
1363 return ProcessSendMessage(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data(), req.usrMsg.data());
1365 return ProcessSetUser(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data(), conf, stat);
1367 //-----------------------------------------------------------------------------
1368 int main(int argc, char **argv)
1370 SGCONF::CONFIG config;
1371 SGCONF::COMMANDS commands;
1373 SGCONF::OPTION_BLOCKS blocks;
1374 blocks.Add("General options")
1375 .Add("c", "config", SGCONF::MakeParamAction(config.configFile, std::string("~/.config/stg/sgconf.conf"), "<config file>"), "override default config file")
1376 .Add("h", "help", SGCONF::MakeFunc0Action(bind0(Method1Adapt(&SGCONF::OPTION_BLOCKS::Help, blocks), 0)), "\t\tshow this help and exit")
1377 .Add("help-all", SGCONF::MakeFunc0Action(UsageAll), "\t\tshow full help and exit")
1378 .Add("v", "version", SGCONF::MakeFunc0Action(Version), "\t\tshow version information and exit");
1379 SGCONF::OPTION_BLOCK & block = blocks.Add("Connection options")
1380 .Add("s", "server", SGCONF::MakeParamAction(config.server, std::string("localhost"), "<address>"), "\t\thost to connect")
1381 .Add("p", "port", SGCONF::MakeParamAction(config.port, uint16_t(5555), "<port>"), "\t\tport to connect")
1382 .Add("u", "username", SGCONF::MakeParamAction(config.userName, std::string("admin"), "<username>"), "\tadministrative login")
1383 .Add("w", "userpass", SGCONF::MakeParamAction(config.userPass, "<password>"), "\tpassword for the administrative login")
1384 .Add("a", "address", SGCONF::MakeParamAction(config, "<connection string>"), "connection params as a single string in format: <login>:<password>@<host>:<port>");
1385 blocks.Add("Raw XML")
1386 .Add("r", "raw", SGCONF::MakeAPIAction(commands, "<xml>", true, SGCONF::RawXMLFunction), "\tmake raw XML request");
1387 blocks.Add("Admin management options")
1388 .Add("get-admins", SGCONF::MakeAPIAction(commands, SGCONF::GetAdminsFunction), "\tget admin list")
1389 .Add("get-admin", SGCONF::MakeAPIAction(commands, "<login>", true, SGCONF::GetAdminFunction), "\tget admin")
1390 .Add("add-admin", SGCONF::MakeAPIAction(commands, "<login>", true, SGCONF::AddAdminFunction), "\tadd admin")
1391 .Add("del-admin", SGCONF::MakeAPIAction(commands, "<login>", true, SGCONF::DelAdminFunction), "\tdel admin")
1392 .Add("chg-admin", SGCONF::MakeAPIAction(commands, "<login>", true, SGCONF::ChgAdminFunction), "\tchange admin");
1393 blocks.Add("Tariff management options")
1394 .Add("get-tariffs", SGCONF::MakeAPIAction(commands, SGCONF::GetTariffsFunction), "\tget tariff list")
1395 .Add("get-tariff", SGCONF::MakeAPIAction(commands, "<name>", true, SGCONF::GetTariffFunction), "\tget tariff")
1396 .Add("add-tariff", SGCONF::MakeAPIAction(commands, "<name>", true, SGCONF::AddTariffFunction), "\tadd tariff")
1397 .Add("del-tariff", SGCONF::MakeAPIAction(commands, "<name>", true, SGCONF::DelTariffFunction), "\tdel tariff")
1398 .Add("chg-tariff", SGCONF::MakeAPIAction(commands, "<name>", true, SGCONF::ChgTariffFunction), "\tchange tariff");
1401 SGCONF::PARSER_STATE state(false, argc, argv);
1405 state = blocks.Parse(--argc, ++argv); // Skipping self name
1407 catch (const SGCONF::OPTION::ERROR& ex)
1409 std::cerr << ex.what() << "\n";
1418 std::cerr << "Unknown option: '" << *state.argv << "'\n";
1424 SGCONF::CONFIG configOverride(config);
1426 if (config.configFile.empty())
1428 const char * mainConfigFile = "/etc/sgconf/sgconf.conf";
1429 if (access(mainConfigFile, R_OK) == 0)
1430 block.ParseFile(mainConfigFile);
1431 ReadUserConfigFile(block);
1435 block.ParseFile(config.configFile.data());
1438 config = configOverride;
1440 catch (const std::exception& ex)
1442 std::cerr << ex.what() << "\n";
1446 std::cerr << "Config: " << config.Serialize() << std::endl;
1447 return commands.Execute(config) ? 0 : -1;
1460 exit(PARAMETER_PARSING_ERR_CODE);
1463 if (strcmp(argv[1], "get") == 0)
1466 return mainGet(argc - 1, argv + 1);
1468 else if (strcmp(argv[1], "set") == 0)
1471 if (mainSet(argc - 1, argv + 1) )
1478 exit(PARAMETER_PARSING_ERR_CODE);
1480 return UNKNOWN_ERR_CODE;*/
1482 //-----------------------------------------------------------------------------
1497 void UsageImpl(bool full)
1499 std::cout << "sgconf is the Stargazer management utility.\n\n"
1501 << "\tsgconf [options]\n\n"
1502 << "General options:\n"
1503 << "\t-c, --config <config file>\t\toverride default config file (default: \"~/.config/stg/sgconf.conf\")\n"
1504 << "\t-h, --help\t\t\t\tshow this help and exit\n"
1505 << "\t--help-all\t\t\t\tshow full help and exit\n"
1506 << "\t-v, --version\t\t\t\tshow version information and exit\n\n";
1511 UsageServices(full);
1512 UsageCorporations(full);
1514 //-----------------------------------------------------------------------------
1515 void UsageConnection()
1517 std::cout << "Connection options:\n"
1518 << "\t-s, --server <address>\t\t\thost to connect (ip or domain name, default: \"localhost\")\n"
1519 << "\t-p, --port <port>\t\t\tport to connect (default: \"5555\")\n"
1520 << "\t-u, --username <username>\t\tadministrative login (default: \"admin\")\n"
1521 << "\t-w, --userpass <password>\t\tpassword for administrative login\n"
1522 << "\t-a, --address <connection string>\tconnection params as a single string in format: <login>:<password>@<host>:<port>\n\n";
1524 //-----------------------------------------------------------------------------
1525 void UsageAdmins(bool full)
1527 std::cout << "Admins management options:\n"
1528 << "\t--get-admins\t\t\t\tget a list of admins (subsequent options will define what to show)\n";
1530 std::cout << "\t\t--login\t\t\t\tshow admin's login\n"
1531 << "\t\t--priv\t\t\t\tshow admin's priviledges\n\n";
1532 std::cout << "\t--get-admin\t\t\t\tget the information about admin\n";
1534 std::cout << "\t\t--login <login>\t\t\tlogin of the admin to show\n"
1535 << "\t\t--priv\t\t\t\tshow admin's priviledges\n\n";
1536 std::cout << "\t--add-admin\t\t\t\tadd a new admin\n";
1538 std::cout << "\t\t--login <login>\t\t\tlogin of the admin to add\n"
1539 << "\t\t--password <password>\t\tpassword of the admin to add\n"
1540 << "\t\t--priv <priv number>\t\tpriviledges of the admin to add\n\n";
1541 std::cout << "\t--del-admin\t\t\t\tdelete an existing admin\n";
1543 std::cout << "\t\t--login <login>\t\t\tlogin of the admin to delete\n\n";
1544 std::cout << "\t--chg-admin\t\t\t\tchange an existing admin\n";
1546 std::cout << "\t\t--login <login>\t\t\tlogin of the admin to change\n"
1547 << "\t\t--priv <priv number>\t\tnew priviledges\n\n";
1549 //-----------------------------------------------------------------------------
1550 void UsageTariffs(bool full)
1552 std::cout << "Tariffs management options:\n"
1553 << "\t--get-tariffs\t\t\t\tget a list of tariffs (subsequent options will define what to show)\n";
1555 std::cout << "\t\t--name\t\t\t\tshow tariff's name\n"
1556 << "\t\t--fee\t\t\t\tshow tariff's fee\n"
1557 << "\t\t--free\t\t\t\tshow tariff's prepaid traffic in terms of cost\n"
1558 << "\t\t--passive-cost\t\t\tshow tariff's cost of \"freeze\"\n"
1559 << "\t\t--traff-type\t\t\tshow what type of traffix will be accounted by the tariff\n"
1560 << "\t\t--dirs\t\t\t\tshow tarification rules for directions\n\n";
1561 std::cout << "\t--get-tariff\t\t\t\tget the information about tariff\n";
1563 std::cout << "\t\t--name <name>\t\t\tname of the tariff to show\n"
1564 << "\t\t--fee\t\t\t\tshow tariff's fee\n"
1565 << "\t\t--free\t\t\t\tshow tariff's prepaid traffic in terms of cost\n"
1566 << "\t\t--passive-cost\t\t\tshow tariff's cost of \"freeze\"\n"
1567 << "\t\t--traff-type\t\t\tshow what type of traffix will be accounted by the tariff\n"
1568 << "\t\t--dirs\t\t\t\tshow tarification rules for directions\n\n";
1569 std::cout << "\t--add-tariff\t\t\t\tadd a new tariff\n";
1571 std::cout << "\t\t--name <name>\t\t\tname of the tariff to add\n"
1572 << "\t\t--fee <fee>\t\t\tstariff's fee\n"
1573 << "\t\t--free <free>\t\t\ttariff's prepaid traffic in terms of cost\n"
1574 << "\t\t--passive-cost <cost>\t\ttariff's cost of \"freeze\"\n"
1575 << "\t\t--traff-type <type>\t\twhat type of traffi will be accounted by the tariff\n"
1576 << "\t\t--times <times>\t\t\tslash-separated list of \"day\" time-spans (in form \"hh:mm-hh:mm\") for each direction\n"
1577 << "\t\t--prices-day-a <prices>\t\tslash-separated list of prices for \"day\" traffic before threshold for each direction\n"
1578 << "\t\t--prices-night-a <prices>\tslash-separated list of prices for \"night\" traffic before threshold for each direction\n"
1579 << "\t\t--prices-day-b <prices>\t\tslash-separated list of prices for \"day\" traffic after threshold for each direction\n"
1580 << "\t\t--prices-night-b <prices>\tslash-separated list of prices for \"night\" traffic after threshold for each direction\n"
1581 << "\t\t--single-prices <yes|no>\tslash-separated list of \"single price\" flags for each direction\n"
1582 << "\t\t--no-discounts <yes|no>\t\tslash-separated list of \"no discount\" flags for each direction\n"
1583 << "\t\t--thresholds <thresholds>\tslash-separated list of thresholds (in Mb) for each direction\n\n";
1584 std::cout << "\t--del-tariff\t\t\t\tdelete an existing tariff\n";
1586 std::cout << "\t\t--name <name>\t\t\tname of the tariff to delete\n\n";
1587 std::cout << "\t--chg-tariff\t\t\t\tchange an existing tariff\n";
1589 std::cout << "\t\t--name <name>\t\t\tname of the tariff to change\n"
1590 << "\t\t--fee <fee>\t\t\tstariff's fee\n"
1591 << "\t\t--free <free>\t\t\ttariff's prepaid traffic in terms of cost\n"
1592 << "\t\t--passive-cost <cost>\t\ttariff's cost of \"freeze\"\n"
1593 << "\t\t--traff-type <type>\t\twhat type of traffix will be accounted by the tariff\n"
1594 << "\t\t--dir <N>\t\t\tnumber of direction data to change\n"
1595 << "\t\t\t--time <time>\t\t\"day\" time-span (in form \"hh:mm-hh:mm\")\n"
1596 << "\t\t\t--price-day-a <price>\tprice for \"day\" traffic before threshold\n"
1597 << "\t\t\t--price-night-a <price>\tprice for \"night\" traffic before threshold\n"
1598 << "\t\t\t--price-day-b <price>\tprice for \"day\" traffic after threshold\n"
1599 << "\t\t\t--price-night-b <price>\tprice for \"night\" traffic after threshold\n"
1600 << "\t\t\t--single-price <yes|no>\t\"single price\" flag\n"
1601 << "\t\t\t--no-discount <yes|no>\t\"no discount\" flag\n"
1602 << "\t\t\t--threshold <threshold>\tthreshold (in Mb)\n\n";
1604 //-----------------------------------------------------------------------------
1605 void UsageUsers(bool full)
1607 std::cout << "Users management options:\n"
1608 << "\t--get-users\t\t\t\tget a list of users (subsequent options will define what to show)\n";
1610 std::cout << "\n\n";
1611 std::cout << "\t--get-user\t\t\t\tget the information about user\n";
1613 std::cout << "\n\n";
1614 std::cout << "\t--add-user\t\t\t\tadd a new user\n";
1616 std::cout << "\n\n";
1617 std::cout << "\t--del-user\t\t\t\tdelete an existing user\n";
1619 std::cout << "\n\n";
1620 std::cout << "\t--chg-user\t\t\t\tchange an existing user\n";
1622 std::cout << "\n\n";
1623 std::cout << "\t--check-user\t\t\t\tcheck credentials is valid\n";
1625 std::cout << "\n\n";
1626 std::cout << "\t--send-message\t\t\t\tsend a message to a user\n";
1628 std::cout << "\n\n";
1630 //-----------------------------------------------------------------------------
1631 void UsageServices(bool full)
1633 std::cout << "Services management options:\n"
1634 << "\t--get-services\t\t\t\tget a list of services (subsequent options will define what to show)\n";
1636 std::cout << "\t\t--name\t\t\t\tshow service's name\n"
1637 << "\t\t--comment\t\t\tshow a comment to the service\n"
1638 << "\t\t--cost\t\t\t\tshow service's cost\n"
1639 << "\t\t--pay-day\t\t\tshow service's pay day\n\n";
1640 std::cout << "\t--get-service\t\t\t\tget the information about service\n";
1642 std::cout << "\t\t--name <name>\t\t\tname of the service to show\n"
1643 << "\t\t--comment\t\t\tshow a comment to the service\n"
1644 << "\t\t--cost\t\t\t\tshow service's cost\n"
1645 << "\t\t--pay-day\t\t\tshow service's pay day\n\n";
1646 std::cout << "\t--add-service\t\t\t\tadd a new service\n";
1648 std::cout << "\t\t--name <name>\t\t\tname of the service to add\n"
1649 << "\t\t--comment <comment>\t\ta comment to the service\n"
1650 << "\t\t--cost <cost>\t\t\tservice's cost\n"
1651 << "\t\t--pay-day <day>\t\t\tservice's pay day\n\n";
1652 std::cout << "\t--del-service\t\t\t\tdelete an existing service\n";
1654 std::cout << "\t\t--name <name>\t\t\tname of the service to delete\n\n";
1655 std::cout << "\t--chg-service\t\t\t\tchange an existing service\n";
1657 std::cout << "\t\t--name <name>\t\t\tname of the service to change\n"
1658 << "\t\t--comment <comment>\t\ta comment to the service\n"
1659 << "\t\t--cost <cost>\t\t\tservice's cost\n"
1660 << "\t\t--pay-day <day>\t\t\tservice's pay day\n\n";
1662 //-----------------------------------------------------------------------------
1663 void UsageCorporations(bool full)
1665 std::cout << "Corporations management options:\n"
1666 << "\t--get-corporations\t\t\tget a list of corporations (subsequent options will define what to show)\n";
1668 std::cout << "\t\t--name\t\t\t\tshow corporation's name\n"
1669 << "\t\t--cash\t\t\t\tshow corporation's cash\n\n";
1670 std::cout << "\t--get-corp\t\t\t\tget the information about corporation\n";
1672 std::cout << "\t\t--name <name>\t\t\tname of the corporation to show\n"
1673 << "\t\t--cash\t\t\t\tshow corporation's cash\n\n";
1674 std::cout << "\t--add-corp\t\t\t\tadd a new corporation\n";
1676 std::cout << "\t\t--name <name>\t\t\tname of the corporation to add\n"
1677 << "\t\t--cash <cash>\t\t\tinitial corporation's cash (default: \"0\")\n\n";
1678 std::cout << "\t--del-corp\t\t\t\tdelete an existing corporation\n";
1680 std::cout << "\t\t--name <name>\t\t\tname of the corporation to delete\n\n";
1681 std::cout << "\t--chg-corp\t\t\t\tchange an existing corporation\n";
1683 std::cout << "\t\t--name <name>\t\t\tname of the corporation to change\n"
1684 << "\t\t--add-cash <amount>[:<message>]\tadd cash to the corporation's account and optional comment message\n"
1685 << "\t\t--set-cash <cash>[:<message>]\tnew corporation's cash and optional comment message\n\n";
1690 std::cout << "sgconf, version: 2.0.0-alpha.\n";
1693 } // namespace anonymous