]> git.stg.codes - stg.git/blob - libs/srvconf/netunit.cpp
Port to CMake, get rid of os_int.h.
[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 final;
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     : server(s),
84       port(p),
85       localPort(0),
86       login(l),
87       password(pwd),
88       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     : server(s),
96       port(p),
97       localAddress(la),
98       localPort(lp),
99       login(l),
100       password(pwd),
101       sock(-1)
102 {
103 }
104 //---------------------------------------------------------------------------
105 NETTRANSACT::~NETTRANSACT()
106 {
107 Disconnect();
108 }
109 //---------------------------------------------------------------------------
110 int NETTRANSACT::Connect()
111 {
112 sock = socket(PF_INET, SOCK_STREAM, 0);
113 if (sock < 0)
114     {
115     errorMsg = CREATE_SOCKET_ERROR;
116     return st_conn_fail;
117     }
118
119 if (!localAddress.empty())
120     {
121     if (localPort == 0)
122         localPort = port;
123
124     unsigned long ip = inet_addr(localAddress.c_str());
125
126     if (ip == INADDR_NONE)
127         {
128         struct hostent * phe = gethostbyname(localAddress.c_str());
129         if (phe == NULL)
130             {
131             errorMsg = "Can not reslove '" + localAddress + "'";
132             return st_dns_err;
133             }
134
135         struct hostent he;
136         memcpy(&he, phe, sizeof(he));
137         ip = *((long *)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(localPort);
144     localAddr.sin_addr.s_addr = ip;
145
146     if (bind(sock, (struct sockaddr *)&localAddr, sizeof(localAddr)) < 0)
147         {
148         errorMsg = BIND_FAILED;
149         return st_conn_fail;
150         }
151     }
152
153 struct sockaddr_in outerAddr;
154 memset(&outerAddr, 0, sizeof(outerAddr));
155
156 unsigned long ip = inet_addr(server.c_str());
157
158 if (ip == INADDR_NONE)
159     {
160     struct hostent * phe = gethostbyname(server.c_str());
161     if (phe == NULL)
162         {
163         errorMsg = "Can not reslove '" + server + "'";
164         return st_dns_err;
165         }
166
167     struct hostent he;
168     memcpy(&he, phe, sizeof(he));
169     ip = *((long *)he.h_addr_list[0]);
170     }
171
172 outerAddr.sin_family = AF_INET;
173 outerAddr.sin_port = htons(port);
174 outerAddr.sin_addr.s_addr = ip;
175
176 if (connect(sock, (struct sockaddr *)&outerAddr, sizeof(outerAddr)) < 0)
177     {
178     errorMsg = CONNECT_FAILED;
179     return st_conn_fail;
180     }
181
182 return st_ok;
183 }
184 //---------------------------------------------------------------------------
185 void NETTRANSACT::Disconnect()
186 {
187 if (sock != -1)
188     {
189     shutdown(sock, SHUT_RDWR);
190     close(sock);
191     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(sock, STG_HEADER, strlen(STG_HEADER)))
228     {
229     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(sock, buffer, strlen(OK_HEADER)))
241     {
242     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     errorMsg = INCORRECT_HEADER;
252     return st_header_err;
253     }
254 else
255     {
256     errorMsg = UNKNOWN_ERROR;
257     return st_unknown_err;
258     }
259 }
260 //---------------------------------------------------------------------------
261 int NETTRANSACT::TxLogin()
262 {
263 char loginZ[ADM_LOGIN_LEN + 1];
264 memset(loginZ, 0, ADM_LOGIN_LEN + 1);
265 strncpy(loginZ, login.c_str(), ADM_LOGIN_LEN);
266
267 if (!WriteAll(sock, loginZ, ADM_LOGIN_LEN))
268     {
269     errorMsg = SEND_LOGIN_ERROR;
270     return st_send_fail;
271     }
272
273 return st_ok;
274 }
275 //---------------------------------------------------------------------------
276 int NETTRANSACT::RxLoginAnswer()
277 {
278 char buffer[sizeof(OK_LOGIN) + 1];
279
280 if (!ReadAll(sock, buffer, strlen(OK_LOGIN)))
281     {
282     errorMsg = RECV_LOGIN_ANSWER_ERROR;
283     return st_recv_fail;
284     }
285
286 if (strncmp(OK_LOGIN, buffer, strlen(OK_LOGIN)) == 0)
287     return st_ok;
288
289 if (strncmp(ERR_LOGIN, buffer, strlen(ERR_LOGIN)) == 0)
290     {
291     errorMsg = INCORRECT_LOGIN;
292     return st_login_err;
293     }
294 else
295     {
296     errorMsg = UNKNOWN_ERROR;
297     return st_unknown_err;
298     }
299 }
300 //---------------------------------------------------------------------------
301 int NETTRANSACT::TxLoginS()
302 {
303 char loginZ[ADM_LOGIN_LEN + 1];
304 memset(loginZ, 0, ADM_LOGIN_LEN + 1);
305
306 BLOWFISH_CTX ctx;
307 InitContext(password.c_str(), PASSWD_LEN, &ctx);
308 EncryptString(loginZ, login.c_str(), std::min<size_t>(login.length() + 1, ADM_LOGIN_LEN), &ctx);
309 if (!WriteAll(sock, loginZ, ADM_LOGIN_LEN))
310     {
311     errorMsg = SEND_LOGIN_ERROR;
312     return st_send_fail;
313     }
314
315 return st_ok;
316 }
317 //---------------------------------------------------------------------------
318 int NETTRANSACT::RxLoginSAnswer()
319 {
320 char buffer[sizeof(OK_LOGINS) + 1];
321
322 if (!ReadAll(sock, buffer, strlen(OK_LOGINS)))
323     {
324     errorMsg = RECV_LOGIN_ANSWER_ERROR;
325     return st_recv_fail;
326     }
327
328 if (strncmp(OK_LOGINS, buffer, strlen(OK_LOGINS)) == 0)
329     return st_ok;
330
331 if (strncmp(ERR_LOGINS, buffer, strlen(ERR_LOGINS)) == 0)
332     {
333     errorMsg = INCORRECT_LOGIN;
334     return st_logins_err;
335     }
336 else
337     {
338     errorMsg = UNKNOWN_ERROR;
339     return st_unknown_err;
340     }
341 }
342 //---------------------------------------------------------------------------
343 int NETTRANSACT::TxData(const std::string & text)
344 {
345 STG::ENCRYPT_STREAM stream(password, TxCrypto, this);
346 stream.Put(text.c_str(), text.length() + 1, true);
347 if (!stream.IsOk())
348     {
349     errorMsg = SEND_DATA_ERROR;
350     return st_send_fail;
351     }
352
353 return st_ok;
354 }
355 //---------------------------------------------------------------------------
356 int NETTRANSACT::RxDataAnswer(CALLBACK callback, void * data)
357 {
358 ReadState state = {false, callback, data, this};
359 STG::DECRYPT_STREAM stream(password, RxCrypto, &state);
360 while (!state.final)
361     {
362     char buffer[1024];
363     ssize_t res = read(sock, buffer, sizeof(buffer));
364     if (res < 0)
365         {
366         errorMsg = RECV_DATA_ANSWER_ERROR;
367         return st_recv_fail;
368         }
369     stream.Put(buffer, res, res == 0);
370     if (!stream.IsOk())
371         return st_xml_parse_error;
372     }
373
374 return st_ok;
375 }
376 //---------------------------------------------------------------------------
377 bool NETTRANSACT::TxCrypto(const void * block, size_t size, void * data)
378 {
379 assert(data != NULL);
380 NETTRANSACT & nt = *static_cast<NETTRANSACT *>(data);
381 if (!WriteAll(nt.sock, block, size))
382     return false;
383 return true;
384 }
385 //---------------------------------------------------------------------------
386 bool NETTRANSACT::RxCrypto(const void * block, size_t size, void * data)
387 {
388 assert(data != NULL);
389 ReadState & state = *static_cast<ReadState *>(data);
390
391 const char * buffer = static_cast<const char *>(block);
392 for (size_t pos = 0; pos < size; ++pos)
393     if (buffer[pos] == 0)
394         {
395         state.final = true;
396         size = pos; // Adjust string size
397         }
398
399 if (state.callback)
400     if (!state.callback(std::string(buffer, size), state.final, state.callbackData))
401         return false;
402
403 return true;
404 }