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