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.
 
   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.
 
  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
 
  18  *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
 
  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"
 
  35 #include <sys/socket.h>
 
  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";
 
  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),
 
  57       m_xmlParser(XML_ParserCreate(NULL)),
 
  60       m_bufferSize(sizeof(m_header)),
 
  64       m_dataState(false, *this),
 
  67       m_dataState(false, *this)
 
  70     if (m_xmlParser == NULL)
 
  71         throw Error("Failed to create XML parser.");
 
  73     XML_ParserReset(m_xmlParser, NULL);
 
  74     XML_SetElementHandler(m_xmlParser, ParseXMLStart, ParseXMLEnd);
 
  75     XML_SetUserData(m_xmlParser, this);
 
  80     shutdown(m_sock, SHUT_RDWR);
 
  83     XML_ParserFree(m_xmlParser);
 
  88     ssize_t res = read(m_sock, m_buffer, m_bufferSize);
 
  92         Log(__FILE__, "Failed to read data from " + endpoint() + ". Reason: '" + strerror(errno) + "'");
 
  95     if (res == 0 && m_state != DATA) // EOF is ok for data.
 
  98         Log(__FILE__, "Failed to read data from " + endpoint() + ". Unexpected EOF.");
 
 102     m_dumper.write(m_buffer, res);
 
 105     m_buffer = static_cast<char*>(m_buffer) + res;
 
 106     return HandleBuffer(res);
 
 109 bool Conn::WriteAnswer(const void* buffer, size_t size)
 
 111     ssize_t res = write(m_sock, buffer, size);
 
 115         Log(__FILE__, "Failed to write data to " + endpoint() + ". Reason: '" + strerror(errno) + "'.");
 
 121 BASE_PARSER * Conn::GetParser(const std::string & tag) const
 
 123     BASE_PARSER::REGISTRY::const_iterator it = m_registry.find(ToLower(tag));
 
 124     if (it == m_registry.end())
 
 126     return it->second->create(*m_admin);
 
 129 bool Conn::HandleBuffer(size_t size)
 
 132         return HandleData(size);
 
 134     if (m_bufferSize > 0)
 
 139         case HEADER: return HandleHeader();
 
 140         case LOGIN: return HandleLogin();
 
 141         case CRYPTO_LOGIN: return HandleCryptoLogin();
 
 142         default: return true;
 
 148 bool Conn::HandleHeader()
 
 150     if (strncmp(m_header, STG_HEADER, sizeof(m_header)) != 0)
 
 152         Log(__FILE__, "Received invalid header from " + endpoint() + ".");
 
 153         WriteAnswer(ERR_HEADER, sizeof(ERR_HEADER) - 1); // Without \0
 
 159     m_bufferSize = sizeof(m_login);
 
 160     return WriteAnswer(OK_HEADER, sizeof(OK_HEADER) - 1); // Without \0
 
 163 bool Conn::HandleLogin()
 
 165     if (m_admins.Find(m_login, &m_admin)) // ADMINS::Find returns true on error.
 
 167         std::string login(m_login, strnlen(m_login, sizeof(m_login)));
 
 168         Log(__FILE__, "Received invalid login '" + ToPrintable(login) + "' from " + endpoint() + ".");
 
 169         WriteAnswer(ERR_LOGIN, sizeof(ERR_LOGIN) - 1); // Without \0
 
 173     m_admin->SetIP(IP());
 
 174     m_state = CRYPTO_LOGIN;
 
 175     m_buffer = m_cryptoLogin;
 
 176     m_bufferSize = sizeof(m_cryptoLogin);
 
 177     return WriteAnswer(OK_LOGIN, sizeof(OK_LOGIN) - 1); // Without \0
 
 180 bool Conn::HandleCryptoLogin()
 
 182     char login[ADM_LOGIN_LEN + 1];
 
 184     InitContext(m_admin->GetPassword().c_str(), ADM_PASSWD_LEN, &ctx);
 
 185     DecryptString(login, m_cryptoLogin, ADM_LOGIN_LEN, &ctx);
 
 187     if (strncmp(m_login, login, sizeof(login)) != 0)
 
 189         Log(__FILE__, "Attempt to connect with wrong password from " + m_admin->GetLogin() + "@" + endpoint() + ".");
 
 190         WriteAnswer(ERR_LOGINS, sizeof(ERR_LOGINS) - 1); // Without \0
 
 197     m_bufferSize = sizeof(m_data);
 
 198     m_stream = new STG::DECRYPT_STREAM(m_admin->GetPassword(), DataCallback, &m_dataState);
 
 199     return WriteAnswer(OK_LOGINS, sizeof(OK_LOGINS) - 1); // Without \0
 
 202 bool Conn::HandleData(size_t size)
 
 204     m_stream->Put(m_data, size, size == 0 || memchr(m_data, 0, size) != NULL);
 
 206     return m_stream->IsOk();
 
 209 bool Conn::DataCallback(const void * block, size_t size, void * data)
 
 211     assert(data != NULL);
 
 212     DataState& state = *static_cast<DataState *>(data);
 
 214     const char * xml = static_cast<const char *>(block);
 
 215     size_t length = strnlen(xml, size);
 
 217     state.final = state.final || length < size || size == 0;
 
 219     if (XML_Parse(state.conn.m_xmlParser, xml, length, state.final) == XML_STATUS_ERROR)
 
 221         state.conn.Log(__FILE__, "Received invalid XML from " + state.conn.m_admin->GetLogin() + "@" + state.conn.endpoint() + ".");
 
 222         printfd(__FILE__, "XML parse error at line %d, %d: %s. Is final: %d\n",
 
 223                   static_cast<int>(XML_GetCurrentLineNumber(state.conn.m_xmlParser)),
 
 224                   static_cast<int>(XML_GetCurrentColumnNumber(state.conn.m_xmlParser)),
 
 225                   XML_ErrorString(XML_GetErrorCode(state.conn.m_xmlParser)), (int)state.final);
 
 226         printfd(__FILE__, "Data block: '%s' of size %d\n", xml, length);
 
 227         state.conn.m_state = ERROR;
 
 233         if (!state.conn.WriteResponse())
 
 235             state.conn.Log(__FILE__, "Failed to write response to " + state.conn.m_admin->GetLogin() + "@" + state.conn.endpoint() + ".");
 
 236             state.conn.m_state = ERROR;
 
 239         state.conn.m_state = DONE;
 
 245 void Conn::ParseXMLStart(void * data, const char * el, const char ** attr)
 
 247     assert(data != NULL);
 
 248     Conn & conn = *static_cast<Conn *>(data);
 
 250     if (conn.m_parser == NULL)
 
 251         conn.m_parser = conn.GetParser(el);
 
 253     if (conn.m_parser == NULL)
 
 255         conn.Log(__FILE__, "Received unknown command '" + std::string(el) + "' from " + conn.m_admin->GetLogin() + "@" + conn.endpoint() + ".");
 
 256         conn.m_state = ERROR;
 
 260     conn.m_parser->Start(data, el, attr);
 
 263 void Conn::ParseXMLEnd(void * data, const char * el)
 
 265     assert(data != NULL);
 
 266     Conn & conn = *static_cast<Conn *>(data);
 
 268     if (conn.m_parser == NULL)
 
 270         // No need to log it.
 
 271         conn.m_state = ERROR;
 
 275     conn.m_parser->End(data, el);
 
 278 bool Conn::WriteResponse()
 
 280     STG::ENCRYPT_STREAM stream(m_admin->GetPassword(), WriteCallback, this);
 
 282     if (m_parser != NULL)
 
 283         answer = m_parser->GetAnswer();
 
 285         answer = "<Error result=\"Unknown command.\"/>";
 
 286     printfd(__FILE__, "Writing %d bytes of answer.\n", answer.length());
 
 287     stream.Put(answer.c_str(), answer.length() + 1 /* including \0 */, true /* final */);
 
 288     return stream.IsOk();
 
 291 bool Conn::WriteCallback(const void * block, size_t size, void * data)
 
 293     assert(data != NULL);
 
 294     Conn & conn = *static_cast<Conn *>(data);
 
 295     return WriteAll(conn.m_sock, block, size);;
 
 298 void Conn::Log(const char * file, const std::string & message)
 
 300     printfd(file, "%s\n", message.c_str());