]> git.stg.codes - stg.git/blob - projects/sgconf/common_sg.cpp
Merge branch 'naffanya-dev'
[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 const int usageConf = 0;
47 const int usageInfo = 1;
48
49 const int TO_KOI8 = 0;
50 const int FROM_KOI8 = 1;
51 //-----------------------------------------------------------------------------
52 struct ResultData
53 {
54     bool result;
55     std::string reason;
56 };
57 //-----------------------------------------------------------------------------
58 struct GetUserData
59 {
60     GetUserData(REQUEST & req, bool res) : request(req), result(res) {}
61     REQUEST & request;
62     bool result;
63     std::string reason;
64 };
65 //---------------------------------------------------------------------------
66 struct HelpParams
67 {
68     std::string setActionName;
69     std::string getActionName;
70     std::string valueName;
71     std::string valueParam;
72 };
73 //---------------------------------------------------------------------------
74 void Usage(int usageType)
75 {
76 printf("Sgconf version: %s\n\n", VERSION_SG);
77
78 char action[4];
79 if (usageType == usageConf)
80     strcpy(action, "set");
81 else
82     strcpy(action, "get");
83
84 printf("To add or to set cash use:\n");
85 printf("sgconf set -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> -c <add_cash[:log message]>\n");
86 printf("sgconf set -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> -v <set_cash[:log message]>\n");
87 printf("To get cash use:\n");
88 printf("sgconf get -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> -c\n\n");
89
90 HelpParams hp[] =
91 {
92     {"set tariff",              "get tariff",           "-t",   "<tariff:now|delayed>"},
93     {"set credit",              "get credit",           "-r",   "<credit>"},
94     {"set credit expire",       "get credit expire",    "-E",   "<credit_expire_date>"},
95     {"set password",            "get password",         "-o",   "<new_password>"},
96     {"set prepaid traffic",     "get prepaid traffic",  "-e",   "<prepaid>"},
97     {"set IP-addresses",        "get IP-addresses",     "-I",   "<*|ip_addr[,ip_addr...]>"},
98     {"set name",                "get name",             "-A",   "<name>"},
99     {"set note",                "get note",             "-N",   "<note>"},
100     {"set street address",      "get street address",   "-D",   "<address>"},
101     {"set email",               "get email",            "-L",   "<email>"},
102     {"set phone",               "get phone",            "-P",   "<phone>"},
103     {"set group",               "get group",            "-G",   "<group>"},
104     {"set/unset down",          "get down",             "-d",   "<0/1>"},
105     {"set/unset \'passive\'",   "get \'passive\'",      "-i",   "<0/1>"},
106     {"set/unset \'disableDetailStat\'",   "get \'disableDetailStat\'",      "--disable-stat",   "<0/1>"},
107     {"set/unset \'alwaysOnline\'",   "get \'alwaysOnline\'",      "--always-online",   "<0/1>"},
108 };
109
110 for (unsigned i = 0; i < sizeof(hp) / sizeof(HelpParams); i++)
111     {
112     printf("To %s use:\n", hp[i].setActionName.c_str());
113     printf("sgconf set -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> %s %s\n",
114            hp[i].valueName.c_str(), hp[i].valueParam.c_str());
115     printf("To %s use:\n", hp[i].getActionName.c_str());
116     printf("sgconf get -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> %s\n\n",
117            hp[i].valueName.c_str());
118     }
119
120 printf("To set user\'s upload traffic value use:\n");
121 printf("sgconf set -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> --u0 <traff> [--u1<traff> ...]\n");
122 printf("To get user\'s upload traffic value use:\n");
123 printf("sgconf get -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> --u0 [--u1 ...]\n\n");
124
125 printf("To set user\'s download traffic value use:\n");
126 printf("sgconf set -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> --d0 <traff> [--d1<traff> ...]\n");
127 printf("To get user\'s download traffic value use:\n");
128 printf("sgconf get -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> --d0 [--d1 ...]\n\n");
129
130 printf("To set userdata<0...9> use:\n");
131 printf("sgconf set -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> --ud0 <userdata> [--ud1<userdata> ...]\n");
132 printf("To get userdata<0...9> use:\n");
133 printf("sgconf get -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> --ud0 [--ud1 ...]\n\n");
134
135 printf("To get user's authorizers list use:\n");
136 printf("sgconf get -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> --authorized-by\n\n");
137
138 printf("To send message use:\n");
139 printf("sgconf set -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> -m <message>\n\n");
140
141 printf("To create user use:\n");
142 printf("sgconf set -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> -n\n\n");
143
144 printf("To delete user use:\n");
145 printf("sgconf set -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> -l\n\n");
146 }
147 //---------------------------------------------------------------------------
148 void UsageConf()
149 {
150 Usage(usageConf);
151 }
152 //---------------------------------------------------------------------------
153 void UsageInfo()
154 {
155 Usage(usageInfo);
156 }
157 //---------------------------------------------------------------------------
158 int CheckLogin(const char * login)
159 {
160 for (int i = 0; i < (int)strlen(login); i++)
161     {
162     if (!(( login[i] >= 'a' && login[i] <= 'z')
163         || (login[i] >= 'A' && login[i] <= 'Z')
164         || (login[i] >= '0' && login[i] <= '9')
165         ||  login[i] == '.'
166         ||  login[i] == '_'
167         ||  login[i] == '-'))
168         {
169         return 1;
170         }
171     }
172 return 0;
173 }
174 //-----------------------------------------------------------------------------
175 short int ParseServerPort(const char * p)
176 {
177 int port;
178 if (str2x(p, port) != 0)
179     {
180     printf("Incorrect server port %s\n", p);
181     exit(NETWORK_ERR_CODE);
182     }
183 return (short)port;
184 }
185 //-----------------------------------------------------------------------------
186 char * ParseAdminLogin(char * adm)
187 {
188 if (CheckLogin(adm))
189     {
190     printf("Incorrect admin login %s\n", adm);
191     exit(PARAMETER_PARSING_ERR_CODE);
192     }
193 return adm;
194 }
195 //-----------------------------------------------------------------------------
196 char * ParsePassword(char * pass)
197 {
198 if (strlen(pass) >= ADM_PASSWD_LEN)
199     {
200     printf("Password too big %s\n", pass);
201     exit(PARAMETER_PARSING_ERR_CODE);
202     }
203
204 return pass;
205 }
206 //-----------------------------------------------------------------------------
207 char * ParseUser(char * usr)
208 {
209 if (CheckLogin(usr))
210     {
211     printf("Incorrect user login %s\n", usr);
212     exit(PARAMETER_PARSING_ERR_CODE);
213     }
214 return usr;
215 }
216 //-----------------------------------------------------------------------------
217 void ConvertKOI8(const std::string & src, std::string * dst, int encType)
218 {
219 iconv_t cd;
220 char * ob = new char[src.size() * 2 + 1];
221 char * ib = new char[src.size() + 1];
222
223 strcpy(ib, src.c_str());
224
225 char * outbuf = ob;
226 char * inbuf = ib;
227
228 setlocale(LC_ALL, "");
229
230 char charsetF[100];
231 char charsetT[100];
232
233 if (encType == TO_KOI8)
234     {
235     strcpy(charsetF, nl_langinfo(CODESET));
236     strcpy(charsetT, "koi8-ru");
237     }
238 else
239     {
240     strcpy(charsetT, nl_langinfo(CODESET));
241     strcpy(charsetF, "koi8-ru");
242     }
243
244 size_t nconv = 1;
245
246 size_t insize = strlen(ib);
247 size_t outsize = insize * 2 + 1;
248
249 insize = src.size();
250
251 cd = iconv_open(charsetT, charsetF);
252 if (cd == (iconv_t) -1)
253     {
254     if (errno != EINVAL)
255         printf("error iconv_open\n");
256     else
257         {
258         printf("Warning: iconv from %s to %s failed\n", charsetF, charsetT);
259         *dst = src;
260         return;
261         }
262
263     exit(ICONV_ERR_CODE);
264     }
265
266 #if defined(FREE_BSD) || defined(FREE_BSD5)
267 nconv = iconv(cd, (const char **)&inbuf, &insize, &outbuf, &outsize);
268 #else
269 nconv = iconv(cd, &inbuf, &insize, &outbuf, &outsize);
270 #endif
271 //printf("charsetT=%s charsetF=%s\n", charsetT, charsetF);
272 //printf("ib=%s ob=%s\n", ib, ob);
273 //printf("nconv=%d outsize=%d\n", nconv, outsize);
274 if (nconv == (size_t) -1)
275     {
276     if (errno != EINVAL)
277         {
278         printf("iconv error\n");
279         exit(ICONV_ERR_CODE);
280         }
281     }
282
283 *outbuf = L'\0';
284
285 iconv_close(cd);
286 *dst = ob;
287
288 delete[] ob;
289 delete[] ib;
290 }
291 //-----------------------------------------------------------------------------
292 void ConvertFromKOI8(const std::string & src, std::string * dst)
293 {
294 ConvertKOI8(src, dst, FROM_KOI8);
295 }
296 //-----------------------------------------------------------------------------
297 void SendMessageCallback(bool result, const std::string & reason, void * d)
298 {
299 ResultData * data = static_cast<ResultData *>(d);
300 data->result = result;
301 data->reason = reason;
302 }
303 //-----------------------------------------------------------------------------
304 void RecvSetUserAnswer(bool result, const std::string & reason, void * d)
305 {
306 ResultData * data = static_cast<ResultData *>(d);
307 data->result = result;
308 data->reason = reason;
309 }
310 //-----------------------------------------------------------------------------
311 void RecvAuthByData(bool result, const std::string & reason,
312                     const PARSER_AUTH_BY::INFO & list, void * d)
313 {
314 ResultData * data = static_cast<ResultData *>(d);
315 data->result = result;
316 data->reason = reason;
317
318 if (!result)
319     return;
320
321 for (std::vector<std::string>::const_iterator it = list.begin(); it != list.end(); ++it)
322     std::cout << *it << "\n";
323
324 std::cout << std::endl;
325 }
326 //-----------------------------------------------------------------------------
327 struct StringReqParams
328 {
329     std::string name;
330     RESETABLE<std::string> reqParam;
331     const std::string * value;
332 };
333 //-----------------------------------------------------------------------------
334 void GetUserCallback(bool result, const std::string& reason, const PARSER_GET_USER::INFO & info, void * d)
335 {
336 GetUserData * data = static_cast<GetUserData *>(d);
337 data->result = false;
338 data->reason = reason;
339
340 if (!result)
341     return;
342
343 if (info.login == "")
344     {
345     data->result = false;
346     data->reason = "Invalid login.";
347     return;
348     }
349
350 if (!data->request.cash.res_empty())
351     cout << "cash = " << info.cash << endl;
352
353 if (!data->request.credit.res_empty())
354     cout << "credit = " << info.credit << endl;
355
356 if (!data->request.creditExpire.res_empty())
357     {
358     char buf[32];
359     struct tm brokenTime;
360     time_t tt = info.creditExpire;
361
362     brokenTime.tm_wday = 0;
363     brokenTime.tm_yday = 0;
364     brokenTime.tm_isdst = 0;
365     brokenTime.tm_hour = 0;
366     brokenTime.tm_min = 0;
367     brokenTime.tm_sec = 0;
368
369     gmtime_r(&tt, &brokenTime);
370
371     strftime(buf, 32, "%Y-%m-%d", &brokenTime);
372
373     cout << "creditExpire = " << buf << endl;
374     }
375
376 if (!data->request.down.res_empty())
377     cout << "down = " << info.down << endl;
378
379 if (!data->request.passive.res_empty())
380     cout << "passive = " << info.passive << endl;
381
382 if (!data->request.disableDetailStat.res_empty())
383     cout << "disableDetailStat = " << info.disableDetailStat << endl;
384
385 if (!data->request.alwaysOnline.res_empty())
386     cout << "alwaysOnline = " << info.alwaysOnline << endl;
387
388 if (!data->request.prepaidTraff.res_empty())
389     cout << "prepaidTraff = " << info.prepaidTraff << endl;
390
391 for (int i = 0; i < DIR_NUM; i++)
392     {
393     if (!data->request.sessionUpload[i].res_empty())
394         cout << "session upload for dir " << i << " = " << info.stat.su[i] << endl;
395     if (!data->request.sessionDownload[i].res_empty())
396         cout << "session download for dir " << i << "=" << info.stat.sd[i] << endl;
397     }
398
399 for (int i = 0; i < DIR_NUM; i++)
400     {
401     if (!data->request.monthUpload[i].res_empty())
402         cout << "month upload for dir " << i << " = " << info.stat.mu[i] << endl;
403     if (!data->request.monthDownload[i].res_empty())
404         cout << "month download for dir " << i << " = " << info.stat.md[i] << endl;
405     }
406
407 for (int i = 0; i < USERDATA_NUM; i++)
408     {
409     if (!data->request.userData[i].res_empty())
410         {
411         std::string str;
412         ConvertFromKOI8(info.userData[i], &str);
413         cout << "user data " << i << " = " << str << endl;
414         }
415     }
416
417 StringReqParams strReqParams[] =
418 {
419     {"note",     data->request.note,        &info.note},
420     {"name",     data->request.name,        &info.name},
421     {"address",  data->request.address,     &info.address},
422     {"email",    data->request.email,       &info.email},
423     {"phone",    data->request.phone,       &info.phone},
424     {"group",    data->request.group,       &info.group},
425     {"tariff",   data->request.tariff,      &info.tariff},
426     {"password", data->request.usrPasswd,   &info.password},
427     {"ip",       data->request.ips,         &info.ips} // IP-address of user
428 };
429 for (unsigned i = 0; i < sizeof(strReqParams) / sizeof(StringReqParams); i++)
430     {
431     if (!strReqParams[i].reqParam.res_empty())
432         {
433         string str;
434         ConvertFromKOI8(*strReqParams[i].value, &str);
435         cout << strReqParams[i].name << " = " << str << endl;
436         }
437     }
438 data->result = true;
439 }
440 //-----------------------------------------------------------------------------
441 bool ProcessSetUser(const std::string & server,
442                     int port,
443                     const std::string & admLogin,
444                     const std::string & admPasswd,
445                     const std::string & str)
446 {
447 SERVCONF sc;
448
449 sc.SetServer(server.c_str());
450 sc.SetPort(port);
451 sc.SetAdmLogin(admLogin.c_str());
452 sc.SetAdmPassword(admPasswd.c_str());
453
454 ResultData data;
455 sc.SetChgUserCallback(RecvSetUserAnswer, &data);
456 int res = sc.ChgUser(str.c_str());
457
458 if (res == st_ok && data.result)
459     {
460     printf("Ok\n");
461     return false;
462     }
463
464 printf("Error\n");
465 if (res != st_ok)
466     printf("%s\n", sc.GetStrError().c_str());
467 else
468     printf("%s\n", data.reason.c_str());
469 return true;
470 }
471 //-----------------------------------------------------------------------------
472 bool ProcessSendMessage(const std::string & server, uint16_t port,
473                         const std::string & login, const std::string & password,
474                         const std::string & requestString)
475 {
476 SERVCONF sc;
477
478 sc.SetServer(server.c_str());
479 sc.SetPort(port);
480 sc.SetAdmLogin(login.c_str());
481 sc.SetAdmPassword(password.c_str());
482
483 ResultData data;
484 sc.SetSendMessageCallback(SendMessageCallback, &data);
485 int res = sc.SendMessage(requestString.c_str());
486
487 if (res == st_ok && data.result)
488     {
489     printf("Ok\n");
490     return true;
491     }
492
493 printf("Error\n");
494 if (res != st_ok)
495     printf("%s\n", sc.GetStrError().c_str());
496 else
497     printf("%s\n", data.reason.c_str());
498 return false;
499 }
500 //-----------------------------------------------------------------------------
501 bool ProcessGetUser(const std::string &server,
502                     int port,
503                     const std::string &admLogin,
504                     const std::string &admPasswd,
505                     const std::string &login,
506                     REQUEST & request)
507 {
508 SERVCONF sc;
509
510 sc.SetServer(server.c_str());
511 sc.SetPort(port);
512 sc.SetAdmLogin(admLogin.c_str());
513 sc.SetAdmPassword(admPasswd.c_str());
514
515 GetUserData data(request, false);
516
517 sc.SetGetUserCallback(GetUserCallback, &data);
518 bool res = (sc.GetUser(login.c_str()) == st_ok);
519
520 if (res && data.result)
521     {
522     printf("Ok\n");
523     return true;
524     }
525
526 printf("Error\n");
527 if (!res)
528     printf("%s\n", sc.GetStrError().c_str());
529 else
530     printf("%s\n", data.reason.c_str());
531 return false;
532 }
533 //-----------------------------------------------------------------------------
534 bool ProcessAuthBy(const std::string &server,
535                    int port,
536                    const std::string &admLogin,
537                    const std::string &admPasswd,
538                    const std::string &login)
539 {
540 SERVCONF sc;
541
542 sc.SetServer(server.c_str());
543 sc.SetPort(port);
544 sc.SetAdmLogin(admLogin.c_str());
545 sc.SetAdmPassword(admPasswd.c_str());
546
547 ResultData data;
548 sc.SetAuthByCallback(RecvAuthByData, &data);
549 bool res = (sc.AuthBy(login.c_str()) == st_ok);
550
551 if (res && data.result)
552     {
553     printf("Ok\n");
554     return true;
555     }
556
557 printf("Error\n");
558 if (!res)
559     printf("%s\n", sc.GetStrError().c_str());
560 else
561     printf("%s\n", data.reason.c_str());
562 return false;
563 }
564 //-----------------------------------------------------------------------------