]> git.stg.codes - stg.git/blob - stargazer/plugins/configuration/sgconfig/conn.cpp
Port to CMake, get rid of os_int.h.
[stg.git] / stargazer / plugins / configuration / sgconfig / conn.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 : Maxim Mamontov <faust@stargazer.dp.ua>
19  */
20
21 #include "conn.h"
22
23 #include "stg/admins.h"
24 #include "stg/admin.h"
25 #include "stg/logger.h"
26 #include "stg/blowfish.h"
27 #include "stg/bfstream.h"
28 #include "stg/common.h"
29
30 #include <cassert>
31 #include <cstring>
32 #include <cerrno>
33
34 #include <unistd.h>
35 #include <sys/socket.h>
36
37 using STG::Conn;
38
39 const char Conn::STG_HEADER[] = "SG04";
40 const char Conn::OK_HEADER[] = "OKHD";
41 const char Conn::ERR_HEADER[] = "ERHD";
42 const char Conn::OK_LOGIN[] = "OKLG";
43 const char Conn::ERR_LOGIN[] = "ERLG";
44 const char Conn::OK_LOGINS[] = "OKLS";
45 const char Conn::ERR_LOGINS[] = "ERLS";
46
47 Conn::Conn(const BASE_PARSER::REGISTRY & registry,
48            ADMINS & admins, int sock, const sockaddr_in& addr,
49            PLUGIN_LOGGER & logger)
50     : m_registry(registry),
51       m_admins(admins),
52       m_admin(NULL),
53       m_sock(sock),
54       m_addr(addr),
55       m_keepAlive(false),
56       m_parser(NULL),
57       m_xmlParser(XML_ParserCreate(NULL)),
58       m_state(HEADER),
59       m_buffer(m_header),
60       m_bufferSize(sizeof(m_header)),
61       m_stream(NULL),
62       m_logger(logger),
63 #ifdef DUMPCRYPTO
64       m_dataState(false, *this),
65       m_dumper(endpoint())
66 #else
67       m_dataState(false, *this)
68 #endif
69 {
70     if (m_xmlParser == NULL)
71         throw Error("Failed to create XML parser.");
72
73     XML_ParserReset(m_xmlParser, NULL);
74     XML_SetElementHandler(m_xmlParser, ParseXMLStart, ParseXMLEnd);
75     XML_SetUserData(m_xmlParser, this);
76 }
77
78 Conn::~Conn()
79 {
80     shutdown(m_sock, SHUT_RDWR);
81     close(m_sock);
82
83     XML_ParserFree(m_xmlParser);
84
85     delete m_stream;
86     delete m_parser;
87 }
88
89 bool Conn::Read()
90 {
91     ssize_t res = read(m_sock, m_buffer, m_bufferSize);
92     if (res < 0)
93     {
94         m_state = ERROR;
95         Log(__FILE__, "Failed to read data from " + endpoint() + ". Reason: '" + strerror(errno) + "'");
96         return false;
97     }
98     if (res == 0 && m_state != DATA) // EOF is ok for data.
99     {
100         m_state = ERROR;
101         Log(__FILE__, "Failed to read data from " + endpoint() + ". Unexpected EOF.");
102         return false;
103     }
104 #ifdef DUMPCRYPTO
105     m_dumper.write(m_buffer, res);
106 #endif
107     m_bufferSize -= res;
108     m_buffer = static_cast<char*>(m_buffer) + res;
109     return HandleBuffer(res);
110 }
111
112 bool Conn::WriteAnswer(const void* buffer, size_t size)
113 {
114     ssize_t res = write(m_sock, buffer, size);
115     if (res < 0)
116     {
117         m_state = ERROR;
118         Log(__FILE__, "Failed to write data to " + endpoint() + ". Reason: '" + strerror(errno) + "'.");
119         return false;
120     }
121     return true;
122 }
123
124 BASE_PARSER * Conn::GetParser(const std::string & tag) const
125 {
126     BASE_PARSER::REGISTRY::const_iterator it = m_registry.find(ToLower(tag));
127     if (it == m_registry.end())
128         return NULL;
129     return it->second->create(*m_admin);
130 }
131
132 bool Conn::HandleBuffer(size_t size)
133 {
134     if (m_state == DATA)
135         return HandleData(size);
136
137     if (m_bufferSize > 0)
138         return true;
139
140     switch (m_state)
141     {
142         case HEADER: return HandleHeader();
143         case LOGIN: return HandleLogin();
144         case CRYPTO_LOGIN: return HandleCryptoLogin();
145         default: return true;
146     }
147
148     return true;
149 }
150
151 bool Conn::HandleHeader()
152 {
153     if (strncmp(m_header, STG_HEADER, sizeof(m_header)) != 0)
154     {
155         Log(__FILE__, "Received invalid header from " + endpoint() + ".");
156         WriteAnswer(ERR_HEADER, sizeof(ERR_HEADER) - 1); // Without \0
157         m_state = ERROR;
158         return false;
159     }
160     m_state = LOGIN;
161     m_buffer = m_login;
162     m_bufferSize = sizeof(m_login);
163     return WriteAnswer(OK_HEADER, sizeof(OK_HEADER) - 1); // Without \0
164 }
165
166 bool Conn::HandleLogin()
167 {
168     if (m_admins.Find(m_login, &m_admin)) // ADMINS::Find returns true on error.
169     {
170         std::string login(m_login, strnlen(m_login, sizeof(m_login)));
171         Log(__FILE__, "Received invalid login '" + ToPrintable(login) + "' from " + endpoint() + ".");
172         WriteAnswer(ERR_LOGIN, sizeof(ERR_LOGIN) - 1); // Without \0
173         m_state = ERROR;
174         return false;
175     }
176     m_admin->SetIP(IP());
177     m_state = CRYPTO_LOGIN;
178     m_buffer = m_cryptoLogin;
179     m_bufferSize = sizeof(m_cryptoLogin);
180     return WriteAnswer(OK_LOGIN, sizeof(OK_LOGIN) - 1); // Without \0
181 }
182
183 bool Conn::HandleCryptoLogin()
184 {
185     char login[ADM_LOGIN_LEN + 1];
186     BLOWFISH_CTX ctx;
187     InitContext(m_admin->GetPassword().c_str(), ADM_PASSWD_LEN, &ctx);
188     DecryptString(login, m_cryptoLogin, ADM_LOGIN_LEN, &ctx);
189
190     if (strncmp(m_login, login, sizeof(login)) != 0)
191     {
192         Log(__FILE__, "Attempt to connect with wrong password from " + m_admin->GetLogin() + "@" + endpoint() + ".");
193         WriteAnswer(ERR_LOGINS, sizeof(ERR_LOGINS) - 1); // Without \0
194         m_state = ERROR;
195         return false;
196     }
197
198     m_state = DATA;
199     m_buffer = m_data;
200     m_bufferSize = sizeof(m_data);
201     m_stream = new STG::DECRYPT_STREAM(m_admin->GetPassword(), DataCallback, &m_dataState);
202     return WriteAnswer(OK_LOGINS, sizeof(OK_LOGINS) - 1); // Without \0
203 }
204
205 bool Conn::HandleData(size_t size)
206 {
207     m_stream->Put(m_data, size, size == 0 || memchr(m_data, 0, size) != NULL);
208     m_buffer = m_data;
209     return m_stream->IsOk();
210 }
211
212 bool Conn::DataCallback(const void * block, size_t size, void * data)
213 {
214     assert(data != NULL);
215     DataState& state = *static_cast<DataState *>(data);
216
217     const char * xml = static_cast<const char *>(block);
218     size_t length = strnlen(xml, size);
219
220     state.final = state.final || length < size || size == 0;
221
222     if (XML_Parse(state.conn.m_xmlParser, xml, length, state.final) == XML_STATUS_ERROR)
223     {
224         state.conn.Log(__FILE__, "Received invalid XML from " + state.conn.m_admin->GetLogin() + "@" + state.conn.endpoint() + ".");
225         printfd(__FILE__, "XML parse error at line %d, %d: %s. Is final: %d\n",
226                   static_cast<int>(XML_GetCurrentLineNumber(state.conn.m_xmlParser)),
227                   static_cast<int>(XML_GetCurrentColumnNumber(state.conn.m_xmlParser)),
228                   XML_ErrorString(XML_GetErrorCode(state.conn.m_xmlParser)), (int)state.final);
229         printfd(__FILE__, "Data block: '%s' of size %d\n", xml, length);
230         state.conn.m_state = ERROR;
231         return false;
232     }
233
234     if (state.final)
235     {
236         if (!state.conn.WriteResponse())
237         {
238             state.conn.Log(__FILE__, "Failed to write response to " + state.conn.m_admin->GetLogin() + "@" + state.conn.endpoint() + ".");
239             state.conn.m_state = ERROR;
240             return false;
241         }
242         state.conn.m_state = DONE;
243     }
244
245     return true;
246 }
247
248 void Conn::ParseXMLStart(void * data, const char * el, const char ** attr)
249 {
250     assert(data != NULL);
251     Conn & conn = *static_cast<Conn *>(data);
252
253     if (conn.m_parser == NULL)
254         conn.m_parser = conn.GetParser(el);
255
256     if (conn.m_parser == NULL)
257     {
258         conn.Log(__FILE__, "Received unknown command '" + std::string(el) + "' from " + conn.m_admin->GetLogin() + "@" + conn.endpoint() + ".");
259         conn.m_state = ERROR;
260         return;
261     }
262
263     conn.m_parser->Start(data, el, attr);
264 }
265
266 void Conn::ParseXMLEnd(void * data, const char * el)
267 {
268     assert(data != NULL);
269     Conn & conn = *static_cast<Conn *>(data);
270
271     if (conn.m_parser == NULL)
272     {
273         // No need to log it.
274         conn.m_state = ERROR;
275         return;
276     }
277
278     conn.m_parser->End(data, el);
279 }
280
281 bool Conn::WriteResponse()
282 {
283     STG::ENCRYPT_STREAM stream(m_admin->GetPassword(), WriteCallback, this);
284     std::string answer;
285     if (m_parser != NULL)
286         answer = m_parser->GetAnswer();
287     else
288         answer = "<Error result=\"Unknown command.\"/>";
289     delete m_parser;
290     m_parser = NULL;
291     printfd(__FILE__, "Writing %d bytes of answer.\n", answer.length());
292     stream.Put(answer.c_str(), answer.length() + 1 /* including \0 */, true /* final */);
293     return stream.IsOk();
294 }
295
296 bool Conn::WriteCallback(const void * block, size_t size, void * data)
297 {
298     assert(data != NULL);
299     Conn & conn = *static_cast<Conn *>(data);
300     return WriteAll(conn.m_sock, block, size);;
301 }
302
303 void Conn::Log(const char * file, const std::string & message)
304 {
305     printfd(file, "%s\n", message.c_str());
306     m_logger(message);
307 }