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