]> git.stg.codes - stg.git/blob - projects/sgconf/common_sg.cpp
e407a7165c6e560c1a85fb528b28e285d5de8930
[stg.git] / projects / sgconf / common_sg.cpp
1 /*
2  *    This program is free software; you can redistribute it and/or modify
3  *    it under the terms of the GNU General Public License as published by
4  *    the Free Software Foundation; either version 2 of the License, or
5  *    (at your option) any later version.
6  *
7  *    This program is distributed in the hope that it will be useful,
8  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
9  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  *    GNU General Public License for more details.
11  *
12  *    You should have received a copy of the GNU General Public License
13  *    along with this program; if not, write to the Free Software
14  *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
15  */
16
17 /*
18  *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
19  */
20
21  /*
22  $Author: faust $
23  $Revision: 1.12 $
24  $Date: 2009/06/08 10:02:28 $
25  */
26
27
28 #include "sg_error_codes.h"
29 #include "common_sg.h"
30 #include "version_sg.h"
31
32 #include "stg/common.h"
33
34 #include <iostream>
35 #include <vector>
36
37 #include <cstdio>
38 #include <cstring>
39 #include <cstdlib>
40 #include <cerrno>
41 #include <clocale>
42
43 #include <langinfo.h>
44 #include <iconv.h>
45
46 using namespace STG;
47
48 const int usageConf = 0;
49 const int usageInfo = 1;
50
51 const int TO_KOI8 = 0;
52 const int FROM_KOI8 = 1;
53 //-----------------------------------------------------------------------------
54 struct ResultData
55 {
56     bool result;
57     std::string reason;
58 };
59 //-----------------------------------------------------------------------------
60 struct GetUserData
61 {
62     GetUserData(REQUEST & req, bool res) : request(req), result(res) {}
63     REQUEST & request;
64     bool result;
65     std::string reason;
66 };
67 //---------------------------------------------------------------------------
68 struct HelpParams
69 {
70     std::string setActionName;
71     std::string getActionName;
72     std::string valueName;
73     std::string valueParam;
74 };
75 //---------------------------------------------------------------------------
76 void Usage(int usageType)
77 {
78 printf("Sgconf version: %s\n\n", VERSION_SG);
79
80 char action[4];
81 if (usageType == usageConf)
82     strcpy(action, "set");
83 else
84     strcpy(action, "get");
85
86 printf("To add or to set cash use:\n");
87 printf("sgconf set -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> -c <add_cash[:log message]>\n");
88 printf("sgconf set -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> -v <set_cash[:log message]>\n");
89 printf("To get cash use:\n");
90 printf("sgconf get -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> -c\n\n");
91
92 HelpParams hp[] =
93 {
94     {"set tariff",              "get tariff",           "-t",   "<tariff:now|delayed>"},
95     {"set credit",              "get credit",           "-r",   "<credit>"},
96     {"set credit expire",       "get credit expire",    "-E",   "<credit_expire_date>"},
97     {"set password",            "get password",         "-o",   "<new_password>"},
98     {"set prepaid traffic",     "get prepaid traffic",  "-e",   "<prepaid>"},
99     {"set IP-addresses",        "get IP-addresses",     "-I",   "<*|ip_addr[,ip_addr...]>"},
100     {"set name",                "get name",             "-A",   "<name>"},
101     {"set note",                "get note",             "-N",   "<note>"},
102     {"set street address",      "get street address",   "-D",   "<address>"},
103     {"set email",               "get email",            "-L",   "<email>"},
104     {"set phone",               "get phone",            "-P",   "<phone>"},
105     {"set group",               "get group",            "-G",   "<group>"},
106     {"set/unset down",          "get down",             "-d",   "<0/1>"},
107     {"set/unset \'passive\'",   "get \'passive\'",      "-i",   "<0/1>"},
108     {"set/unset \'disableDetailStat\'",   "get \'disableDetailStat\'",      "--disable-stat",   "<0/1>"},
109     {"set/unset \'alwaysOnline\'",   "get \'alwaysOnline\'",      "--always-online",   "<0/1>"},
110 };
111
112 for (unsigned i = 0; i < sizeof(hp) / sizeof(HelpParams); i++)
113     {
114     printf("To %s use:\n", hp[i].setActionName.c_str());
115     printf("sgconf set -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> %s %s\n",
116            hp[i].valueName.c_str(), hp[i].valueParam.c_str());
117     printf("To %s use:\n", hp[i].getActionName.c_str());
118     printf("sgconf get -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> %s\n\n",
119            hp[i].valueName.c_str());
120     }
121
122 printf("To set user\'s upload traffic value use:\n");
123 printf("sgconf set -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> --u0 <traff> [--u1<traff> ...]\n");
124 printf("To get user\'s upload traffic value use:\n");
125 printf("sgconf get -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> --u0 [--u1 ...]\n\n");
126
127 printf("To set user\'s download traffic value use:\n");
128 printf("sgconf set -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> --d0 <traff> [--d1<traff> ...]\n");
129 printf("To get user\'s download traffic value use:\n");
130 printf("sgconf get -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> --d0 [--d1 ...]\n\n");
131
132 printf("To set userdata<0...9> use:\n");
133 printf("sgconf set -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> --ud0 <userdata> [--ud1<userdata> ...]\n");
134 printf("To get userdata<0...9> use:\n");
135 printf("sgconf get -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> --ud0 [--ud1 ...]\n\n");
136
137 printf("To get user's authorizers list use:\n");
138 printf("sgconf get -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> --authorized-by\n\n");
139
140 printf("To send message use:\n");
141 printf("sgconf set -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> -m <message>\n\n");
142
143 printf("To create user use:\n");
144 printf("sgconf set -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> -n\n\n");
145
146 printf("To delete user use:\n");
147 printf("sgconf set -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> -l\n\n");
148 }
149 //---------------------------------------------------------------------------
150 void UsageConf()
151 {
152 Usage(usageConf);
153 }
154 //---------------------------------------------------------------------------
155 void UsageInfo()
156 {
157 Usage(usageInfo);
158 }
159 //---------------------------------------------------------------------------
160 int CheckLogin(const char * login)
161 {
162 for (int i = 0; i < (int)strlen(login); i++)
163     {
164     if (!(( login[i] >= 'a' && login[i] <= 'z')
165         || (login[i] >= 'A' && login[i] <= 'Z')
166         || (login[i] >= '0' && login[i] <= '9')
167         ||  login[i] == '.'
168         ||  login[i] == '_'
169         ||  login[i] == '-'))
170         {
171         return 1;
172         }
173     }
174 return 0;
175 }
176 //-----------------------------------------------------------------------------
177 short int ParseServerPort(const char * p)
178 {
179 int port;
180 if (str2x(p, port) != 0)
181     {
182     printf("Incorrect server port %s\n", p);
183     exit(NETWORK_ERR_CODE);
184     }
185 return (short)port;
186 }
187 //-----------------------------------------------------------------------------
188 char * ParseAdminLogin(char * adm)
189 {
190 if (CheckLogin(adm))
191     {
192     printf("Incorrect admin login %s\n", adm);
193     exit(PARAMETER_PARSING_ERR_CODE);
194     }
195 return adm;
196 }
197 //-----------------------------------------------------------------------------
198 char * ParsePassword(char * pass)
199 {
200 if (strlen(pass) >= ADM_PASSWD_LEN)
201     {
202     printf("Password too big %s\n", pass);
203     exit(PARAMETER_PARSING_ERR_CODE);
204     }
205
206 return pass;
207 }
208 //-----------------------------------------------------------------------------
209 char * ParseUser(char * usr)
210 {
211 if (CheckLogin(usr))
212     {
213     printf("Incorrect user login %s\n", usr);
214     exit(PARAMETER_PARSING_ERR_CODE);
215     }
216 return usr;
217 }
218 //-----------------------------------------------------------------------------
219 void ConvertKOI8(const std::string & src, std::string * dst, int encType)
220 {
221 iconv_t cd;
222 char * ob = new char[src.size() * 2 + 1];
223 char * ib = new char[src.size() + 1];
224
225 strcpy(ib, src.c_str());
226
227 char * outbuf = ob;
228 char * inbuf = ib;
229
230 setlocale(LC_ALL, "");
231
232 char charsetF[100];
233 char charsetT[100];
234
235 if (encType == TO_KOI8)
236     {
237     strcpy(charsetF, nl_langinfo(CODESET));
238     strcpy(charsetT, "koi8-ru");
239     }
240 else
241     {
242     strcpy(charsetT, nl_langinfo(CODESET));
243     strcpy(charsetF, "koi8-ru");
244     }
245
246 size_t nconv = 1;
247
248 size_t insize = strlen(ib);
249 size_t outsize = insize * 2 + 1;
250
251 insize = src.size();
252
253 cd = iconv_open(charsetT, charsetF);
254 if (cd == (iconv_t) -1)
255     {
256     if (errno != EINVAL)
257         printf("error iconv_open\n");
258     else
259         {
260         printf("Warning: iconv from %s to %s failed\n", charsetF, charsetT);
261         *dst = src;
262         return;
263         }
264
265     exit(ICONV_ERR_CODE);
266     }
267
268 #if defined(FREE_BSD) || defined(FREE_BSD5)
269 nconv = iconv(cd, (const char **)&inbuf, &insize, &outbuf, &outsize);
270 #else
271 nconv = iconv(cd, &inbuf, &insize, &outbuf, &outsize);
272 #endif
273 //printf("charsetT=%s charsetF=%s\n", charsetT, charsetF);
274 //printf("ib=%s ob=%s\n", ib, ob);
275 //printf("nconv=%d outsize=%d\n", nconv, outsize);
276 if (nconv == (size_t) -1)
277     {
278     if (errno != EINVAL)
279         {
280         printf("iconv error\n");
281         exit(ICONV_ERR_CODE);
282         }
283     }
284
285 *outbuf = L'\0';
286
287 iconv_close(cd);
288 *dst = ob;
289
290 delete[] ob;
291 delete[] ib;
292 }
293 //-----------------------------------------------------------------------------
294 void ConvertFromKOI8(const std::string & src, std::string * dst)
295 {
296 ConvertKOI8(src, dst, FROM_KOI8);
297 }
298 //-----------------------------------------------------------------------------
299 void ResultCallback(bool result, const std::string & reason, void * d)
300 {
301 ResultData * data = static_cast<ResultData *>(d);
302 data->result = result;
303 data->reason = reason;
304 }
305 //-----------------------------------------------------------------------------
306 void RecvAuthByData(bool result, const std::string & reason,
307                     const AUTH_BY::INFO & list, void * d)
308 {
309 ResultData * data = static_cast<ResultData *>(d);
310 data->result = result;
311 data->reason = reason;
312
313 if (!result)
314     return;
315
316 for (std::vector<std::string>::const_iterator it = list.begin(); it != list.end(); ++it)
317     std::cout << *it << "\n";
318
319 std::cout << std::endl;
320 }
321 //-----------------------------------------------------------------------------
322 struct StringReqParams
323 {
324     std::string name;
325     RESETABLE<std::string> reqParam;
326     const std::string * value;
327 };
328 //-----------------------------------------------------------------------------
329 void GetUserCallback(bool result, const std::string& reason, const GET_USER::INFO & info, void * d)
330 {
331 GetUserData * data = static_cast<GetUserData *>(d);
332 data->result = false;
333 data->reason = reason;
334
335 if (!result)
336     return;
337
338 if (info.login == "")
339     {
340     data->result = false;
341     data->reason = "Invalid login.";
342     return;
343     }
344
345 if (!data->request.cash.empty())
346     cout << "cash = " << info.cash << endl;
347
348 if (!data->request.credit.empty())
349     cout << "credit = " << info.credit << endl;
350
351 if (!data->request.creditExpire.empty())
352     {
353     char buf[32];
354     struct tm brokenTime;
355     time_t tt = info.creditExpire;
356
357     brokenTime.tm_wday = 0;
358     brokenTime.tm_yday = 0;
359     brokenTime.tm_isdst = 0;
360     brokenTime.tm_hour = 0;
361     brokenTime.tm_min = 0;
362     brokenTime.tm_sec = 0;
363
364     gmtime_r(&tt, &brokenTime);
365
366     strftime(buf, 32, "%Y-%m-%d", &brokenTime);
367
368     cout << "creditExpire = " << buf << endl;
369     }
370
371 if (!data->request.down.empty())
372     cout << "down = " << info.down << endl;
373
374 if (!data->request.passive.empty())
375     cout << "passive = " << info.passive << endl;
376
377 if (!data->request.disableDetailStat.empty())
378     cout << "disableDetailStat = " << info.disableDetailStat << endl;
379
380 if (!data->request.alwaysOnline.empty())
381     cout << "alwaysOnline = " << info.alwaysOnline << endl;
382
383 if (!data->request.prepaidTraff.empty())
384     cout << "prepaidTraff = " << info.prepaidTraff << endl;
385
386 for (int i = 0; i < DIR_NUM; i++)
387     {
388     if (!data->request.sessionUpload[i].empty())
389         cout << "session upload for dir " << i << " = " << info.stat.su[i] << endl;
390     if (!data->request.sessionDownload[i].empty())
391         cout << "session download for dir " << i << "=" << info.stat.sd[i] << endl;
392     }
393
394 for (int i = 0; i < DIR_NUM; i++)
395     {
396     if (!data->request.monthUpload[i].empty())
397         cout << "month upload for dir " << i << " = " << info.stat.mu[i] << endl;
398     if (!data->request.monthDownload[i].empty())
399         cout << "month download for dir " << i << " = " << info.stat.md[i] << endl;
400     }
401
402 for (int i = 0; i < USERDATA_NUM; i++)
403     {
404     if (!data->request.userData[i].empty())
405         {
406         std::string str;
407         ConvertFromKOI8(info.userData[i], &str);
408         cout << "user data " << i << " = " << str << endl;
409         }
410     }
411
412 StringReqParams strReqParams[] =
413 {
414     {"note",     data->request.note,        &info.note},
415     {"name",     data->request.name,        &info.name},
416     {"address",  data->request.address,     &info.address},
417     {"email",    data->request.email,       &info.email},
418     {"phone",    data->request.phone,       &info.phone},
419     {"group",    data->request.group,       &info.group},
420     {"tariff",   data->request.tariff,      &info.tariff},
421     {"password", data->request.usrPasswd,   &info.password},
422     {"ip",       data->request.ips,         &info.ips} // IP-address of user
423 };
424 for (unsigned i = 0; i < sizeof(strReqParams) / sizeof(StringReqParams); i++)
425     {
426     if (!strReqParams[i].reqParam.empty())
427         {
428         string str;
429         ConvertFromKOI8(*strReqParams[i].value, &str);
430         cout << strReqParams[i].name << " = " << str << endl;
431         }
432     }
433 data->result = true;
434 }
435 //-----------------------------------------------------------------------------
436 bool ProcessSetUser(const std::string & server,
437                     int port,
438                     const std::string & login,
439                     const std::string & password,
440                     const std::string & user,
441                     const USER_CONF_RES & conf,
442                     const USER_STAT_RES & stat)
443 {
444 SERVCONF sc(server, port, login, password);
445
446 ResultData data;
447 int res = sc.ChgUser(user, conf, stat, ResultCallback, &data);
448
449 if (res == st_ok && data.result)
450     {
451     printf("Ok\n");
452     return false;
453     }
454
455 printf("Error\n");
456 if (res != st_ok)
457     printf("%s\n", sc.GetStrError().c_str());
458 else
459     printf("%s\n", data.reason.c_str());
460 return true;
461 }
462 //-----------------------------------------------------------------------------
463 bool ProcessSendMessage(const std::string & server, uint16_t port,
464                         const std::string & login, const std::string & password,
465                         const std::string & user, const std::string & text)
466 {
467 SERVCONF sc(server, port, login, password);
468
469 ResultData data;
470 int res = sc.SendMessage(user, text, ResultCallback, &data);
471
472 if (res == st_ok && data.result)
473     {
474     printf("Ok\n");
475     return true;
476     }
477
478 printf("Error\n");
479 if (res != st_ok)
480     printf("%s\n", sc.GetStrError().c_str());
481 else
482     printf("%s\n", data.reason.c_str());
483 return false;
484 }
485 //-----------------------------------------------------------------------------
486 bool ProcessGetUser(const std::string &server,
487                     int port,
488                     const std::string &admLogin,
489                     const std::string &admPasswd,
490                     const std::string &login,
491                     REQUEST & request)
492 {
493 SERVCONF sc(server, port, admLogin, admPasswd);
494
495 GetUserData data(request, false);
496 bool res = (sc.GetUser(login.c_str(), GetUserCallback, &data) == st_ok);
497
498 if (res && data.result)
499     {
500     printf("Ok\n");
501     return true;
502     }
503
504 printf("Error\n");
505 if (!res)
506     printf("%s\n", sc.GetStrError().c_str());
507 else
508     printf("%s\n", data.reason.c_str());
509 return false;
510 }
511 //-----------------------------------------------------------------------------
512 bool ProcessAuthBy(const std::string &server,
513                    int port,
514                    const std::string &admLogin,
515                    const std::string &admPasswd,
516                    const std::string &login)
517 {
518 SERVCONF sc(server, port, admLogin, admPasswd);
519
520 ResultData data;
521 bool res = (sc.AuthBy(login.c_str(), RecvAuthByData, &data) == st_ok);
522
523 if (res && data.result)
524     {
525     printf("Ok\n");
526     return true;
527     }
528
529 printf("Error\n");
530 if (!res)
531     printf("%s\n", sc.GetStrError().c_str());
532 else
533     printf("%s\n", data.reason.c_str());
534 return false;
535 }
536 //-----------------------------------------------------------------------------