]> git.stg.codes - stg.git/blob - libs/srvconf/netunit.cpp
Fight CLang warnings.
[stg.git] / libs / srvconf / netunit.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 #include "netunit.h"
22
23 #include "stg/servconf_types.h"
24 #include "stg/common.h"
25 #include "stg/blowfish.h"
26 #include "stg/bfstream.h"
27
28 #include <algorithm> // std::min
29
30 #include <cerrno>
31 #include <cstring>
32 #include <cassert>
33
34 #include <netdb.h>
35 #include <arpa/inet.h>
36 #include <unistd.h>
37
38 #include <sys/types.h>
39 #include <sys/socket.h>
40 #include <netinet/in.h>
41
42 const char STG_HEADER[] = "SG04";
43 const char OK_HEADER[]  = "OKHD";
44 const char ERR_HEADER[] = "ERHD";
45 const char OK_LOGIN[]   = "OKLG";
46 const char ERR_LOGIN[]  = "ERLG";
47 const char OK_LOGINS[]  = "OKLS";
48 const char ERR_LOGINS[] = "ERLS";
49
50 using namespace STG;
51
52 namespace
53 {
54
55 struct ReadState
56 {
57     bool last;
58     NetTransact::Callback callback;
59     void* callbackData;
60     NetTransact* nt;
61 };
62
63 }
64
65 //---------------------------------------------------------------------------
66
67 const char SEND_DATA_ERROR[]          = "Error sending data.";
68 const char RECV_DATA_ANSWER_ERROR[]   = "Error receiving data answer.";
69 const char UNKNOWN_ERROR[]            = "Unknown error";
70 const char CONNECT_FAILED[]           = "Failed to connect.";
71 const char BIND_FAILED[]              = "Failed to bind.";
72 const char INCORRECT_LOGIN[]          = "Incorrect login.";
73 const char INCORRECT_HEADER[]         = "Incorrect header.";
74 const char SEND_LOGIN_ERROR[]         = "Error sending login.";
75 const char RECV_LOGIN_ANSWER_ERROR[]  = "Error receiving login answer.";
76 const char CREATE_SOCKET_ERROR[]      = "Failed to create socket.";
77 const char SEND_HEADER_ERROR[]        = "Error sending header.";
78 const char RECV_HEADER_ANSWER_ERROR[] = "Error receiving header answer.";
79
80 //---------------------------------------------------------------------------
81 NetTransact::NetTransact(const std::string& s, uint16_t p,
82                          const std::string& l, const std::string& pwd)
83     : m_server(s),
84       m_port(p),
85       m_localPort(0),
86       m_login(l),
87       m_password(pwd),
88       m_sock(-1)
89 {
90 }
91 //---------------------------------------------------------------------------
92 NetTransact::NetTransact(const std::string& s, uint16_t p,
93                          const std::string& la, uint16_t lp,
94                          const std::string& l, const std::string& pwd)
95     : m_server(s),
96       m_port(p),
97       m_localAddress(la),
98       m_localPort(lp),
99       m_login(l),
100       m_password(pwd),
101       m_sock(-1)
102 {
103 }
104 //---------------------------------------------------------------------------
105 NetTransact::~NetTransact()
106 {
107     Disconnect();
108 }
109 //---------------------------------------------------------------------------
110 int NetTransact::Connect()
111 {
112     m_sock = socket(PF_INET, SOCK_STREAM, 0);
113     if (m_sock < 0)
114     {
115         m_errorMsg = CREATE_SOCKET_ERROR;
116         return st_conn_fail;
117     }
118
119     if (!m_localAddress.empty())
120     {
121         if (m_localPort == 0)
122             m_localPort = m_port;
123
124         uint32_t ip = inet_addr(m_localAddress.c_str());
125
126         if (ip == INADDR_NONE)
127         {
128             auto phe = gethostbyname(m_localAddress.c_str());
129             if (phe == NULL)
130             {
131                 m_errorMsg = "Can not reslove '" + m_localAddress + "'";
132                 return st_dns_err;
133             }
134
135             struct hostent he;
136             memcpy(&he, phe, sizeof(he));
137             ip = *reinterpret_cast<uint32_t*>(he.h_addr_list[0]);
138         }
139
140         struct sockaddr_in localAddr;
141         memset(&localAddr, 0, sizeof(localAddr));
142         localAddr.sin_family = AF_INET;
143         localAddr.sin_port = htons(m_localPort);
144         localAddr.sin_addr.s_addr = ip;
145
146         if (bind(m_sock, reinterpret_cast<sockaddr*>(&localAddr), sizeof(localAddr)) < 0)
147         {
148             m_errorMsg = BIND_FAILED;
149             return st_conn_fail;
150         }
151     }
152
153     struct sockaddr_in outerAddr;
154     memset(&outerAddr, 0, sizeof(outerAddr));
155
156     uint32_t ip = inet_addr(m_server.c_str());
157
158     if (ip == INADDR_NONE)
159     {
160         auto phe = gethostbyname(m_server.c_str());
161         if (phe == NULL)
162         {
163             m_errorMsg = "Can not reslove '" + m_server + "'";
164             return st_dns_err;
165         }
166
167         struct hostent he;
168         memcpy(&he, phe, sizeof(he));
169         ip = *reinterpret_cast<uint32_t*>(he.h_addr_list[0]);
170     }
171
172     outerAddr.sin_family = AF_INET;
173     outerAddr.sin_port = htons(m_port);
174     outerAddr.sin_addr.s_addr = ip;
175
176     if (connect(m_sock, reinterpret_cast<sockaddr *>(&outerAddr), sizeof(outerAddr)) < 0)
177     {
178         m_errorMsg = CONNECT_FAILED;
179         return st_conn_fail;
180     }
181
182     return st_ok;
183 }
184 //---------------------------------------------------------------------------
185 void NetTransact::Disconnect()
186 {
187     if (m_sock != -1)
188     {
189         shutdown(m_sock, SHUT_RDWR);
190         close(m_sock);
191         m_sock = -1;
192     }
193 }
194 //---------------------------------------------------------------------------
195 int NetTransact::Transact(const std::string& request, Callback callback, void* data)
196 {
197     int ret;
198     if ((ret = TxHeader()) != st_ok)
199         return ret;
200
201     if ((ret = RxHeaderAnswer()) != st_ok)
202         return ret;
203
204     if ((ret = TxLogin()) != st_ok)
205         return ret;
206
207     if ((ret = RxLoginAnswer()) != st_ok)
208         return ret;
209
210     if ((ret = TxLoginS()) != st_ok)
211         return ret;
212
213     if ((ret = RxLoginSAnswer()) != st_ok)
214         return ret;
215
216     if ((ret = TxData(request)) != st_ok)
217         return ret;
218
219     if ((ret = RxDataAnswer(callback, data)) != st_ok)
220         return ret;
221
222     return st_ok;
223 }
224 //---------------------------------------------------------------------------
225 int NetTransact::TxHeader()
226 {
227     if (!WriteAll(m_sock, STG_HEADER, strlen(STG_HEADER)))
228     {
229         m_errorMsg = SEND_HEADER_ERROR;
230         return st_send_fail;
231     }
232
233     return st_ok;
234 }
235 //---------------------------------------------------------------------------
236 int NetTransact::RxHeaderAnswer()
237 {
238     char buffer[sizeof(STG_HEADER) + 1];
239
240     if (!ReadAll(m_sock, buffer, strlen(OK_HEADER)))
241     {
242         m_errorMsg = RECV_HEADER_ANSWER_ERROR;
243         return st_recv_fail;
244     }
245
246     if (strncmp(OK_HEADER, buffer, strlen(OK_HEADER)) == 0)
247         return st_ok;
248
249     if (strncmp(ERR_HEADER, buffer, strlen(ERR_HEADER)) == 0)
250     {
251         m_errorMsg = INCORRECT_HEADER;
252         return st_header_err;
253     }
254
255     m_errorMsg = UNKNOWN_ERROR;
256     return st_unknown_err;
257 }
258 //---------------------------------------------------------------------------
259 int NetTransact::TxLogin()
260 {
261     char loginZ[ADM_LOGIN_LEN + 1];
262     memset(loginZ, 0, ADM_LOGIN_LEN + 1);
263     strncpy(loginZ, m_login.c_str(), ADM_LOGIN_LEN);
264
265     if (!WriteAll(m_sock, loginZ, ADM_LOGIN_LEN))
266     {
267         m_errorMsg = SEND_LOGIN_ERROR;
268         return st_send_fail;
269     }
270
271     return st_ok;
272 }
273 //---------------------------------------------------------------------------
274 int NetTransact::RxLoginAnswer()
275 {
276     char buffer[sizeof(OK_LOGIN) + 1];
277
278     if (!ReadAll(m_sock, buffer, strlen(OK_LOGIN)))
279     {
280         m_errorMsg = RECV_LOGIN_ANSWER_ERROR;
281         return st_recv_fail;
282     }
283
284     if (strncmp(OK_LOGIN, buffer, strlen(OK_LOGIN)) == 0)
285         return st_ok;
286
287     if (strncmp(ERR_LOGIN, buffer, strlen(ERR_LOGIN)) == 0)
288     {
289         m_errorMsg = INCORRECT_LOGIN;
290         return st_login_err;
291     }
292
293     m_errorMsg = UNKNOWN_ERROR;
294     return st_unknown_err;
295 }
296 //---------------------------------------------------------------------------
297 int NetTransact::TxLoginS()
298 {
299     char loginZ[ADM_LOGIN_LEN + 1];
300     memset(loginZ, 0, ADM_LOGIN_LEN + 1);
301
302     BLOWFISH_CTX ctx;
303     InitContext(m_password.c_str(), PASSWD_LEN, &ctx);
304     EncryptString(loginZ, m_login.c_str(), std::min<size_t>(m_login.length() + 1, ADM_LOGIN_LEN), &ctx);
305     if (!WriteAll(m_sock, loginZ, ADM_LOGIN_LEN))
306     {
307         m_errorMsg = SEND_LOGIN_ERROR;
308         return st_send_fail;
309     }
310
311     return st_ok;
312 }
313 //---------------------------------------------------------------------------
314 int NetTransact::RxLoginSAnswer()
315 {
316     char buffer[sizeof(OK_LOGINS) + 1];
317
318     if (!ReadAll(m_sock, buffer, strlen(OK_LOGINS)))
319     {
320         m_errorMsg = RECV_LOGIN_ANSWER_ERROR;
321         return st_recv_fail;
322     }
323
324     if (strncmp(OK_LOGINS, buffer, strlen(OK_LOGINS)) == 0)
325         return st_ok;
326
327     if (strncmp(ERR_LOGINS, buffer, strlen(ERR_LOGINS)) == 0)
328     {
329         m_errorMsg = INCORRECT_LOGIN;
330         return st_logins_err;
331     }
332
333     m_errorMsg = UNKNOWN_ERROR;
334     return st_unknown_err;
335 }
336 //---------------------------------------------------------------------------
337 int NetTransact::TxData(const std::string& text)
338 {
339     STG::ENCRYPT_STREAM stream(m_password, TxCrypto, this);
340     stream.Put(text.c_str(), text.length() + 1, true);
341     if (!stream.IsOk())
342     {
343         m_errorMsg = SEND_DATA_ERROR;
344         return st_send_fail;
345     }
346
347     return st_ok;
348 }
349 //---------------------------------------------------------------------------
350 int NetTransact::RxDataAnswer(Callback callback, void* data)
351 {
352     ReadState state = {false, callback, data, this};
353     STG::DECRYPT_STREAM stream(m_password, RxCrypto, &state);
354     while (!state.last)
355     {
356         char buffer[1024];
357         ssize_t res = read(m_sock, buffer, sizeof(buffer));
358         if (res < 0)
359         {
360             m_errorMsg = RECV_DATA_ANSWER_ERROR;
361             return st_recv_fail;
362         }
363         stream.Put(buffer, res, res == 0);
364         if (!stream.IsOk())
365             return st_xml_parse_error;
366     }
367
368     return st_ok;
369 }
370 //---------------------------------------------------------------------------
371 bool NetTransact::TxCrypto(const void* block, size_t size, void* data)
372 {
373     assert(data != NULL);
374     auto& nt = *static_cast<NetTransact*>(data);
375     if (!WriteAll(nt.m_sock, block, size))
376         return false;
377     return true;
378 }
379 //---------------------------------------------------------------------------
380 bool NetTransact::RxCrypto(const void* block, size_t size, void* data)
381 {
382     assert(data != NULL);
383     auto& state = *static_cast<ReadState *>(data);
384
385     const char* buffer = static_cast<const char *>(block);
386     for (size_t pos = 0; pos < size; ++pos)
387         if (buffer[pos] == 0)
388         {
389             state.last = true;
390             size = pos; // Adjust string size
391         }
392
393     if (state.callback)
394         if (!state.callback(std::string(buffer, size), state.last, state.callbackData))
395             return false;
396
397     return true;
398 }