]> git.stg.codes - stg.git/blob - projects/sgconf/common_sg.cpp
Allowed to use dot in entity name.
[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 send message use:\n");
126 printf("sgconf set -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> -m <message>\n\n");
127
128 printf("To create user use:\n");
129 printf("sgconf set -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> -n\n\n");
130
131 printf("To delete user use:\n");
132 printf("sgconf set -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> -l\n\n");
133 }
134 //---------------------------------------------------------------------------
135 void UsageConf()
136 {
137 Usage(usageConf);
138 }
139 //---------------------------------------------------------------------------
140 void UsageInfo()
141 {
142 Usage(usageInfo);
143 }
144 //---------------------------------------------------------------------------
145 int CheckLogin(const char * login)
146 {
147 for (int i = 0; i < (int)strlen(login); i++)
148     {
149     if (!(( login[i] >= 'a' && login[i] <= 'z')
150         || (login[i] >= 'A' && login[i] <= 'Z')
151         || (login[i] >= '0' && login[i] <= '9')
152         ||  login[i] == '.'
153         ||  login[i] == '_'
154         ||  login[i] == '-'))
155         {
156         return 1;
157         }
158     }
159 return 0;
160 }
161 //-----------------------------------------------------------------------------
162 short int ParseServerPort(const char * p)
163 {
164 int port;
165 if (str2x(p, port) != 0)
166     {
167     printf("Incorresct server port %s\n", p);
168     exit(NETWORK_ERR_CODE);
169     }
170 return (short)port;
171 }
172 //-----------------------------------------------------------------------------
173 char * ParseAdminLogin(char * adm)
174 {
175 if (CheckLogin(adm))
176     {
177     printf("Incorresct admin login %s\n", adm);
178     exit(PARAMETER_PARSING_ERR_CODE);
179     }
180 return adm;
181 }
182 //-----------------------------------------------------------------------------
183 char * ParsePassword(char * pass)
184 {
185 if (strlen(pass) >= ADM_PASSWD_LEN)
186     {
187     printf("Password too big %s\n", pass);
188     exit(PARAMETER_PARSING_ERR_CODE);
189     }
190
191 return pass;
192 }
193 //-----------------------------------------------------------------------------
194 char * ParseUser(char * usr)
195 {
196 if (CheckLogin(usr))
197     {
198     printf("Incorresct user login %s\n", usr);
199     exit(PARAMETER_PARSING_ERR_CODE);
200     }
201 return usr;
202 }
203 //-----------------------------------------------------------------------------
204 void ConvertKOI8(const string & src, string * dst, int encType)
205 {
206 iconv_t cd;
207 char * ob = new char[src.size() * 2 + 1];
208 char * ib = new char[src.size() + 1];
209
210 strcpy(ib, src.c_str());
211
212 char * outbuf = ob;
213 char * inbuf = ib;
214
215 setlocale(LC_ALL, "");
216
217 char charsetF[100];
218 char charsetT[100];
219
220 if (encType == TO_KOI8)
221     {
222     strcpy(charsetF, nl_langinfo(CODESET));
223     strcpy(charsetT, "koi8-ru");
224     }
225 else
226     {
227     strcpy(charsetT, nl_langinfo(CODESET));
228     strcpy(charsetF, "koi8-ru");
229     }
230
231 size_t nconv = 1;
232
233 size_t insize = strlen(ib);
234 size_t outsize = insize * 2 + 1;
235
236 insize = src.size();
237
238 cd = iconv_open(charsetT, charsetF);
239 if (cd == (iconv_t) -1)
240     {
241     if (errno != EINVAL)
242         printf("error iconv_open\n");
243     else
244         {
245         printf("Warning: iconv from %s to %s failed\n", charsetF, charsetT);
246         *dst = src;
247         return;
248         }
249
250     exit(ICONV_ERR_CODE);
251     }
252
253 #if defined(FREE_BSD) || defined(FREE_BSD5)
254 nconv = iconv(cd, (const char **)&inbuf, &insize, &outbuf, &outsize);
255 #else
256 nconv = iconv(cd, &inbuf, &insize, &outbuf, &outsize);
257 #endif
258 //printf("charsetT=%s charsetF=%s\n", charsetT, charsetF);
259 //printf("ib=%s ob=%s\n", ib, ob);
260 //printf("nconv=%d outsize=%d\n", nconv, outsize);
261 if (nconv == (size_t) -1)
262     {
263     if (errno != EINVAL)
264         {
265         printf("iconv error\n");
266         exit(ICONV_ERR_CODE);
267         }
268     }
269
270 *outbuf = L'\0';
271
272 iconv_close(cd);
273 *dst = ob;
274
275 delete[] ob;
276 delete[] ib;
277 }
278 //-----------------------------------------------------------------------------
279 void ConvertFromKOI8(const string & src, string * dst)
280 {
281 ConvertKOI8(src, dst, FROM_KOI8);
282 }
283 //-----------------------------------------------------------------------------
284 void ConvertToKOI8(const string & src, string * dst)
285 {
286 ConvertKOI8(src, dst, TO_KOI8);
287 }
288 //-----------------------------------------------------------------------------
289 int RecvSetUserAnswer(const char * ans, void * d)
290 {
291 GetUserCbData * gucbd;
292 gucbd = (GetUserCbData *)d;
293
294 bool * result = gucbd->result;
295
296 //REQUEST * req = (REQUEST *)gucbd->data;
297
298 //printf("ans=%s\n", ans);
299 if (strcasecmp("Ok", ans) == 0)
300     *result = true;
301 else
302     *result = false;
303
304 return 0;
305 }
306 //-----------------------------------------------------------------------------
307 struct StringReqParams
308 {
309     string name;
310     RESETABLE<string> reqParam;
311     string * value;
312 };
313 //-----------------------------------------------------------------------------
314 void RecvUserData(USERDATA * ud, void * d)
315 {
316 GetUserCbData * gucbd;
317 gucbd = (GetUserCbData *)d;
318
319 bool * result = gucbd->result;
320
321 REQUEST * req = (REQUEST *)gucbd->data;
322
323 if (ud->login == "")
324     {
325     *result = false;
326     return;
327     }
328
329 if (!req->cash.res_empty())
330     cout << "cash=" << ud->cash << endl;
331
332 if (!req->credit.res_empty())
333     cout << "credit=" << ud->credit << endl;
334
335 if (!req->creditExpire.res_empty())
336     {
337     char buf[32];
338     struct tm brokenTime;
339     time_t tt = ud->creditExpire;
340
341     brokenTime.tm_wday = 0;
342     brokenTime.tm_yday = 0;
343     brokenTime.tm_isdst = 0;
344     brokenTime.tm_hour = 0;
345     brokenTime.tm_min = 0;
346     brokenTime.tm_sec = 0;
347
348     gmtime_r(&tt, &brokenTime);
349
350     strftime(buf, 32, "%Y-%m-%d", &brokenTime);
351
352     cout << "creditExpire=" << buf << endl;
353     }
354
355 if (!req->down.res_empty())
356     cout << "down=" << ud->down << endl;
357
358 if (!req->passive.res_empty())
359     cout << "passive=" << ud->passive << endl;
360
361 if (!req->disableDetailStat.res_empty())
362     cout << "disableDetailStat=" << ud->disableDetailStat << endl;
363
364 if (!req->alwaysOnline.res_empty())
365     cout << "alwaysOnline=" << ud->alwaysOnline << endl;
366
367 if (!req->prepaidTraff.res_empty())
368     cout << "prepaidTraff=" << ud->prepaidTraff << endl;
369
370 for (int i = 0; i < DIR_NUM; i++)
371     {
372     if (!req->u[i].res_empty())
373         cout << "u" << i << "=" << ud->stat.mu[i] << endl;
374     if (!req->d[i].res_empty())
375         cout << "d" << i << "=" << ud->stat.md[i] << endl;
376     }
377
378 for (int i = 0; i < USERDATA_NUM; i++)
379     {
380     if (!req->ud[i].res_empty())
381         {
382         string str;
383         ConvertFromKOI8(ud->userData[i], &str);
384         cout << "userdata" << i << "=" << str << endl;
385         }
386     }
387
388 StringReqParams strReqParams[] =
389 {
390     {"note",     req->note,        &ud->note},
391     {"name",     req->name,        &ud->name},
392     {"address",  req->address,     &ud->address},
393     {"email",    req->email,       &ud->email},
394     {"phone",    req->phone,       &ud->phone},
395     {"group",    req->group,       &ud->group},
396     {"tariff",   req->tariff,      &ud->tariff},
397     {"password", req->usrPasswd,   &ud->password},
398     {"ip",       req->ips,         &ud->ips}    // IP-address of user
399 };
400 for (unsigned i = 0; i < sizeof(strReqParams) / sizeof(StringReqParams); i++)
401     {
402     if (!strReqParams[i].reqParam.res_empty())
403         {
404         string str;
405         ConvertFromKOI8(*strReqParams[i].value, &str);
406         cout << strReqParams[i].name << "=" << str << endl;
407         }
408     }
409 *result = true;
410 }
411 //-----------------------------------------------------------------------------
412 int ProcessSetUser(const std::string &server,
413                    int port,
414                    const std::string &admLogin,
415                    const std::string &admPasswd,
416                    const std::string &str,
417                    void * data,
418                    bool isMessage)
419 {
420 SERVCONF sc;
421
422 bool result = false;
423
424
425 sc.SetServer(server.c_str());  // õÓÔÁÎÁ×ÌÉ×ÁÅÍ ÉÍÑ ÓÅÒ×ÅÒÁ Ó ËÏÔÏÒÇÏ ÚÁÂÉÒÁÔØ ÉÎÆÕ
426 sc.SetPort(port);           // ÁÄÍÉÎÓËÉÊ ÐÏÒÔ ÓÅÒ×ÅÒÁÐÏÒÔ
427 sc.SetAdmLogin(admLogin.c_str());    // ÷ÙÓÔÁ×ÌÑÅÍ ÌÏÇÉΠɠÐÁÒÏÌØ ÁÄÍÉÎÁ
428 sc.SetAdmPassword(admPasswd.c_str());
429
430 // TODO Good variable name :)
431 GetUserCbData gucbd;
432
433 gucbd.data = data;
434 gucbd.result = &result;
435
436 if (isMessage)
437     {
438     sc.SetSendMessageCb(RecvSetUserAnswer, &gucbd);
439     sc.MsgUser(str.c_str());
440     }
441 else
442     {
443     sc.SetChgUserCb(RecvSetUserAnswer, &gucbd);
444     sc.ChgUser(str.c_str());
445     }
446
447 if (result)
448     {
449     printf("Ok\n");
450     return 0;
451     }
452 else
453     {
454     printf("Error\n");
455     return -1;
456     }
457
458 return 0;
459 }
460 //-----------------------------------------------------------------------------
461 int ProcessGetUser(const std::string &server,
462                    int port,
463                    const std::string &admLogin,
464                    const std::string &admPasswd,
465                    const std::string &login,
466                    void * data)
467 {
468 SERVCONF sc;
469
470 bool result = false;
471
472 sc.SetServer(server.c_str());  // õÓÔÁÎÁ×ÌÉ×ÁÅÍ ÉÍÑ ÓÅÒ×ÅÒÁ Ó ËÏÔÏÒÇÏ ÚÁÂÉÒÁÔØ ÉÎÆÕ
473 sc.SetPort(port);           // ÁÄÍÉÎÓËÉÊ ÐÏÒÔ ÓÅÒ×ÅÒÁÐÏÒÔ
474 sc.SetAdmLogin(admLogin.c_str());    // ÷ÙÓÔÁ×ÌÑÅÍ ÌÏÇÉΠɠÐÁÒÏÌØ ÁÄÍÉÎÁ
475 sc.SetAdmPassword(admPasswd.c_str());
476
477 // TODO Good variable name :)
478 GetUserCbData gucbd;
479
480 gucbd.data = data;
481 gucbd.result = &result;
482
483 sc.SetGetUserDataRecvCb(RecvUserData, &gucbd);
484 sc.GetUser(login.c_str());
485
486 if (result)
487     {
488     printf("Ok\n");
489     return 0;
490     }
491 else
492     {
493     printf("Error\n");
494     return -1;
495     }
496
497 return 0;
498 }
499 //-----------------------------------------------------------------------------