]> git.stg.codes - stg.git/blob - projects/stargazer/plugins/configuration/sgconfig/rsconf.cpp
Log errors from plugins to server log.
[stg.git] / projects / stargazer / plugins / configuration / sgconfig / rsconf.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 *
19 *    DESCRIPTION: æÁÊÌ Ó ÏÓÎÏ×ÎÙÍÉ ÆÕÎËÃÉÑÍÉ ÄÌÑ ÓÅÔÅ×ÏÇÏ ÏÂÍÅÎÁ ÄÁÎÎÙÍÉ
20 *    Ó ÍÅÎÅÄÖÅÒÏÍ ËÌÉÅÎÔÏ×. ðÒÉÅÍ, ÐÅÒÅÄÁÞÁ É ÛÉÆÒÏ×ÁÎÉÅ ÓÏÏÂÝÅÎÉÊ.
21 *
22 *    AUTHOR: Boris Mikhailenko <stg34@stargazer.dp.ua>
23 *
24 *    $Revision: 1.24 $
25 *    $Date: 2010/10/04 20:24:54 $
26 *
27 *******************************************************************/
28
29 #include <unistd.h> // close
30
31 #include <cerrno>
32 #include <csignal>
33 #include <cstdio> // snprintf
34
35 #include "stg/blowfish.h"
36 #include "configproto.h"
37
38 #ifndef ENODATA
39 // FreeBSD 4.* - suxx
40 #define ENODATA -1
41 #endif
42
43 enum CONF_STATE
44     {
45     confHdr,
46     confLogin,
47     confLoginCipher,
48     confData
49     };
50
51 enum
52     {
53     ans_ok = 0,
54     ans_err
55     };
56
57 //-----------------------------------------------------------------------------
58 int CONFIGPROTO::Prepare()
59 {
60 list<string> ansList; //óÀÄÁ ÂÕÄÅÔ ÐÏÍÅÝÅΠÏÔ×ÅÔ ÄÌÑ ÍÅÎÅÄÖÅÒÁ ËÌÉÅÎÔÏ×
61 int res;
62 struct sockaddr_in listenAddr;
63
64 sigset_t sigmask, oldmask;
65 sigemptyset(&sigmask);
66 sigaddset(&sigmask, SIGINT);
67 sigaddset(&sigmask, SIGTERM);
68 sigaddset(&sigmask, SIGUSR1);
69 sigaddset(&sigmask, SIGHUP);
70 pthread_sigmask(SIG_BLOCK, &sigmask, &oldmask);
71
72 listenSocket = socket(PF_INET, SOCK_STREAM, 0);
73
74 if (listenSocket < 0)
75     {
76     errorStr = "Create NET_CONFIGURATOR socket failed.";
77     logger("Cannot create a socket: %s", strerror(errno));
78     return -1;
79     }
80
81 listenAddr.sin_family = PF_INET;
82 listenAddr.sin_port = htons(port);
83 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
84
85 int lng = 1;
86
87 if (0 != setsockopt(listenSocket, SOL_SOCKET, SO_REUSEADDR, &lng, 4))
88     {
89     errorStr = "Setsockopt failed. " + string(strerror(errno));
90     logger("setsockopt error: %s", strerror(errno));
91     return -1;
92     }
93
94 res = bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr));
95
96 if (res == -1)
97     {
98     errorStr = "Bind admin socket failed";
99     logger("Cannot bind the socket: %s", strerror(errno));
100     return -1;
101     }
102
103 res = listen(listenSocket, 0);
104 if (res == -1)
105     {
106     errorStr = "Listen admin socket failed";
107     logger("Cannot listen the socket: %s", strerror(errno));
108     return -1;
109     }
110
111 errorStr = "";
112 nonstop = true;
113 return 0;
114 }
115 //-----------------------------------------------------------------------------
116 int CONFIGPROTO::Stop()
117 {
118 nonstop = false;
119 close(listenSocket);
120 //TODO: Idiotism
121 int                 sock;
122 struct sockaddr_in  addr;
123 socklen_t           addrLen;
124 addr.sin_family = PF_INET;
125 addr.sin_port = htons(port);
126 addr.sin_addr.s_addr = inet_addr("127.0.0.1");
127
128 addrLen = sizeof(addr);
129 sock = socket(PF_INET, SOCK_STREAM, 0);
130 connect(sock, (sockaddr*)&addr, addrLen);
131 close(sock);
132 //Idiotism end
133 return 0;
134 }
135 //-----------------------------------------------------------------------------
136 void CONFIGPROTO::Run()
137 {
138 state = confHdr;
139
140 while (nonstop)
141     {
142     state = confHdr;
143     struct sockaddr_in outerAddr;
144     socklen_t outerAddrLen(sizeof(outerAddr));
145     int outerSocket = accept(listenSocket,
146                              (struct sockaddr*)(&outerAddr),
147                              &outerAddrLen);
148
149     if (!nonstop)
150         {
151         break;
152         }
153
154     if (outerSocket < 0)
155         {
156         logger("accept error: %s", strerror(errno));
157         printfd(__FILE__, "accept failed\n");
158         continue;
159         }
160
161     adminIP = *(unsigned int*)&(outerAddr.sin_addr);
162
163     if (state == confHdr)
164         {
165         if (RecvHdr(outerSocket) < 0)
166             {
167             close(outerSocket);
168             continue;
169             }
170         if (state == confLogin)
171             {
172             if (SendHdrAnswer(outerSocket, ans_ok) < 0)
173                 {
174                 close(outerSocket);
175                 continue;
176                 }
177             if (RecvLogin(outerSocket) < 0)
178                 {
179                 close(outerSocket);
180                 continue;
181                 }
182             if (state == confLoginCipher)
183                 {
184                 if (SendLoginAnswer(outerSocket) < 0)
185                     {
186                     close(outerSocket);
187                     continue;
188                     }
189                 if (RecvLoginS(outerSocket) < 0)
190                     {
191                     close(outerSocket);
192                     continue;
193                     }
194                 if (state == confData)
195                     {
196                     if (SendLoginSAnswer(outerSocket, ans_ok) < 0)
197                         {
198                         close(outerSocket);
199                         continue;
200                         }
201                     if (RecvData(outerSocket) < 0)
202                         {
203                         close(outerSocket);
204                         continue;
205                         }
206                     state = confHdr;
207                     }
208                 else
209                     {
210                     if (SendLoginSAnswer(outerSocket, ans_err) < 0)
211                         {
212                         close(outerSocket);
213                         continue;
214                         }
215                     WriteLogAccessFailed(adminIP);
216                     }
217                 }
218             else
219                 {
220                 WriteLogAccessFailed(adminIP);
221                 }
222             }
223         else
224             {
225             WriteLogAccessFailed(adminIP);
226             if (SendHdrAnswer(outerSocket, ans_err) < 0)
227                 {
228                 close(outerSocket);
229                 continue;
230                 }
231             }
232         }
233     else
234         {
235         WriteLogAccessFailed(adminIP);
236         }
237     printfd(__FILE__, "Successfull connection from %s\n", inet_ntostring(outerAddr.sin_addr.s_addr).c_str());
238     close(outerSocket);
239     }
240 }
241 //-----------------------------------------------------------------------------
242 int CONFIGPROTO::RecvHdr(int sock)
243 {
244 char buf[sizeof(STG_HEADER)];
245 memset(buf, 0, sizeof(STG_HEADER));
246 size_t stgHdrLen = sizeof(STG_HEADER) - 1; // Without 0-char
247 size_t pos = 0;
248 while (pos < stgHdrLen)
249     {
250     if (!WaitPackets(sock))
251         {
252         state = confHdr;
253         SendError("Bad request");
254         return -1;
255         }
256     int ret = recv(sock, &buf[pos], stgHdrLen - pos, 0);
257     if (ret <= 0)
258         {
259         if (ret < 0)
260             logger("recv error: %s", strerror(errno));
261         state = confHdr;
262         return -1;
263         }
264     pos += ret;
265     }
266
267 if (0 == strncmp(buf, STG_HEADER, strlen(STG_HEADER)))
268     {
269     state = confLogin;
270     return 0;
271     }
272 else
273     {
274     SendError("Bad request");
275     }
276
277 state = confHdr;
278 return -1;
279 }
280 //-----------------------------------------------------------------------------
281 int CONFIGPROTO::SendHdrAnswer(int sock, int err)
282 {
283 if (err)
284     {
285     if (send(sock, ERR_HEADER, sizeof(ERR_HEADER) - 1, 0) < 0)
286         {
287         logger("send error: %s", strerror(errno));
288         return -1;
289         }
290     }
291 else
292     {
293     if (send(sock, OK_HEADER, sizeof(OK_HEADER) - 1, 0) < 0)
294         {
295         logger("send error: %s", strerror(errno));
296         return -1;
297         }
298     }
299
300 return 0;
301 }
302 //-----------------------------------------------------------------------------
303 int CONFIGPROTO::RecvLogin(int sock)
304 {
305 char login[ADM_LOGIN_LEN + 1];
306
307 memset(login, 0, ADM_LOGIN_LEN + 1);
308
309 size_t pos = 0;
310 while (pos < ADM_LOGIN_LEN) {
311     if (!WaitPackets(sock))
312         {
313         state = confHdr;
314         return ENODATA;
315         }
316
317     int ret = recv(sock, &login[pos], ADM_LOGIN_LEN - pos, 0);
318
319     if (ret <= 0)
320         {
321         // Error in network
322         logger("recv error: %s", strerror(errno));
323         state = confHdr;
324         return ENODATA;
325         }
326
327     pos += ret;
328 }
329
330 if (admins->Find(login, &currAdmin))
331     {
332     // Admin not found
333     state = confHdr;
334     return ENODATA;
335     }
336
337 currAdmin->SetIP(adminIP);
338 adminLogin = login;
339 state = confLoginCipher;
340 return 0;
341 }
342 //-----------------------------------------------------------------------------
343 int CONFIGPROTO::SendLoginAnswer(int sock)
344 {
345 if (send(sock, OK_LOGIN, sizeof(OK_LOGIN) - 1, 0) < 0)
346     {
347     logger("Send OK_LOGIN error in SendLoginAnswer.");
348     return -1;
349     }
350 return 0;
351 }
352 //-----------------------------------------------------------------------------
353 int CONFIGPROTO::RecvLoginS(int sock)
354 {
355 char loginS[ADM_LOGIN_LEN + 1];
356 memset(loginS, 0, ADM_LOGIN_LEN + 1);
357
358 size_t pos = 0;
359 while (pos < ADM_LOGIN_LEN)
360     {
361     if (!WaitPackets(sock))
362         {
363         state = confHdr;
364         return ENODATA;
365         }
366
367     int ret = recv(sock, &loginS[pos], ADM_LOGIN_LEN - pos, 0);
368
369     if (ret <= 0)
370         {
371         // Network error
372         printfd(__FILE__, "recv error: '%s'\n", strerror(errno));
373         logger("recv error: %s", strerror(errno));
374         state = confHdr;
375         return ENODATA;
376         }
377
378     pos += ret;
379     }
380
381 if (currAdmin->GetLogin().empty())
382     {
383     state = confHdr;
384     return ENODATA;
385     }
386
387 BLOWFISH_CTX ctx;
388 EnDecodeInit(currAdmin->GetPassword().c_str(), ADM_PASSWD_LEN, &ctx);
389
390 char login[ADM_LOGIN_LEN + 1];
391 for (size_t i = 0; i < ADM_LOGIN_LEN / 8; i++)
392     {
393     DecodeString(login + i * 8, loginS + i * 8, &ctx);
394     }
395
396 if (currAdmin == admins->GetNoAdmin())
397     {
398     // If there are no admins registered in the system - give access with any password
399     state = confData;
400     return 0;
401     }
402
403 if (strncmp(currAdmin->GetLogin().c_str(), login, ADM_LOGIN_LEN) != 0)
404     {
405     state = confHdr;
406     return ENODATA;
407     }
408
409 state = confData;
410 return 0;
411 }
412 //-----------------------------------------------------------------------------
413 int CONFIGPROTO::SendLoginSAnswer(int sock, int err)
414 {
415 if (err)
416     {
417     if (send(sock, ERR_LOGINS, sizeof(ERR_LOGINS) - 1, 0) < 0)
418         {
419         logger("send error: %s", strerror(errno));
420         return -1;
421         }
422     }
423 else
424     {
425     if (send(sock, OK_LOGINS, sizeof(OK_LOGINS) - 1, 0) < 0)
426         {
427         logger("send error: %s", strerror(errno));
428         return -1;
429         }
430     }
431 return 0;
432 }
433 //-----------------------------------------------------------------------------
434 int CONFIGPROTO::RecvData(int sock)
435 {
436 requestList.clear();
437 BLOWFISH_CTX ctx;
438
439 EnDecodeInit(currAdmin->GetPassword().c_str(), ADM_PASSWD_LEN, &ctx);
440
441 while (1)
442     {
443     bool done = false;
444     char bufferS[8];
445     size_t pos = 0;
446     while (pos < sizeof(bufferS))
447         {
448         if (!WaitPackets(sock))
449             {
450             done = true;
451             break;
452             }
453
454         int ret = recv(sock, &bufferS[pos], sizeof(bufferS) - pos, 0);
455         if (ret < 0)
456             {
457             // Network error
458             logger("recv error: %s", strerror(errno));
459             printfd(__FILE__, "recv error: '%s'\n", strerror(errno));
460             return -1;
461             }
462
463         if (ret == 0)
464             {
465             done = true;
466             break;
467             }
468
469         pos += ret;
470         }
471
472     char buffer[8];
473     buffer[7] = 0;
474
475     DecodeString(buffer, bufferS, &ctx);
476     requestList.push_back(std::string(buffer, pos));
477
478     if (done || memchr(buffer, 0, pos) != NULL)
479         {
480         // End of data
481         if (ParseCommand())
482             {
483             SendError("Bad command");
484             }
485         return SendDataAnswer(sock);
486         }
487     }
488 return 0;
489 }
490 //-----------------------------------------------------------------------------
491 int CONFIGPROTO::SendDataAnswer(int sock)
492 {
493 list<string>::iterator li;
494 li = answerList.begin();
495
496 BLOWFISH_CTX ctx;
497
498 char buff[8];
499 char buffS[8];
500 int n = 0;
501 int k = 0;
502
503 EnDecodeInit(currAdmin->GetPassword().c_str(), ADM_PASSWD_LEN, &ctx);
504
505 while (li != answerList.end())
506     {
507     while ((*li).c_str()[k])
508         {
509         buff[n % 8] = (*li).c_str()[k];
510         n++;
511         k++;
512
513         if (n % 8 == 0)
514             {
515             EncodeString(buffS, buff, &ctx);
516             int ret = send(sock, buffS, 8, 0);
517             if (ret < 0)
518                 {
519                 return -1;
520                 }
521             }
522         }
523     k = 0;// new node
524     ++li;
525     }
526
527 if (answerList.empty()) {
528     return 0;
529 }
530
531 buff[n % 8] = 0;
532 EncodeString(buffS, buff, &ctx);
533
534 answerList.clear();
535
536 return send(sock, buffS, 8, 0);
537 }
538 //-----------------------------------------------------------------------------
539 void CONFIGPROTO::SendError(const char * text)
540 {
541 char s[255];
542 answerList.clear();
543 snprintf(s, 255, "<Error value=\"%s\"/>", text);
544 answerList.push_back(s);
545 }
546 //-----------------------------------------------------------------------------
547 void CONFIGPROTO::WriteLogAccessFailed(uint32_t ip)
548 {
549 logger("Admin's connection failed. IP %s", inet_ntostring(ip).c_str());
550 }
551 //-----------------------------------------------------------------------------