1
0

WebAdmin uses the new cNetwork API.

This commit is contained in:
Mattes D 2015-01-24 10:11:34 +01:00
parent 7990d223ea
commit f477b524bb
8 changed files with 242 additions and 208 deletions

View File

@ -38,8 +38,7 @@ cHTTPConnection::~cHTTPConnection()
void cHTTPConnection::SendStatusAndReason(int a_StatusCode, const AString & a_Response) void cHTTPConnection::SendStatusAndReason(int a_StatusCode, const AString & a_Response)
{ {
AppendPrintf(m_OutgoingData, "%d %s\r\nContent-Length: 0\r\n\r\n", a_StatusCode, a_Response.c_str()); SendData(Printf("%d %s\r\nContent-Length: 0\r\n\r\n", a_StatusCode, a_Response.c_str()));
m_HTTPServer.NotifyConnectionWrite(*this);
m_State = wcsRecvHeaders; m_State = wcsRecvHeaders;
} }
@ -49,8 +48,7 @@ void cHTTPConnection::SendStatusAndReason(int a_StatusCode, const AString & a_Re
void cHTTPConnection::SendNeedAuth(const AString & a_Realm) void cHTTPConnection::SendNeedAuth(const AString & a_Realm)
{ {
AppendPrintf(m_OutgoingData, "HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Basic realm=\"%s\"\r\nContent-Length: 0\r\n\r\n", a_Realm.c_str()); SendData(Printf("HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Basic realm=\"%s\"\r\nContent-Length: 0\r\n\r\n", a_Realm.c_str()));
m_HTTPServer.NotifyConnectionWrite(*this);
m_State = wcsRecvHeaders; m_State = wcsRecvHeaders;
} }
@ -61,9 +59,10 @@ void cHTTPConnection::SendNeedAuth(const AString & a_Realm)
void cHTTPConnection::Send(const cHTTPResponse & a_Response) void cHTTPConnection::Send(const cHTTPResponse & a_Response)
{ {
ASSERT(m_State == wcsRecvIdle); ASSERT(m_State == wcsRecvIdle);
a_Response.AppendToData(m_OutgoingData); AString toSend;
a_Response.AppendToData(toSend);
m_State = wcsSendingResp; m_State = wcsSendingResp;
m_HTTPServer.NotifyConnectionWrite(*this); SendData(toSend);
} }
@ -73,10 +72,10 @@ void cHTTPConnection::Send(const cHTTPResponse & a_Response)
void cHTTPConnection::Send(const void * a_Data, size_t a_Size) void cHTTPConnection::Send(const void * a_Data, size_t a_Size)
{ {
ASSERT(m_State == wcsSendingResp); ASSERT(m_State == wcsSendingResp);
AppendPrintf(m_OutgoingData, SIZE_T_FMT_HEX "\r\n", a_Size); // We're sending in Chunked transfer encoding
m_OutgoingData.append((const char *)a_Data, a_Size); SendData(Printf(SIZE_T_FMT_HEX "\r\n", a_Size));
m_OutgoingData.append("\r\n"); SendData(a_Data, a_Size);
m_HTTPServer.NotifyConnectionWrite(*this); SendData("\r\n");
} }
@ -86,9 +85,8 @@ void cHTTPConnection::Send(const void * a_Data, size_t a_Size)
void cHTTPConnection::FinishResponse(void) void cHTTPConnection::FinishResponse(void)
{ {
ASSERT(m_State == wcsSendingResp); ASSERT(m_State == wcsSendingResp);
m_OutgoingData.append("0\r\n\r\n"); SendData("0\r\n\r\n");
m_State = wcsRecvHeaders; m_State = wcsRecvHeaders;
m_HTTPServer.NotifyConnectionWrite(*this);
} }
@ -108,8 +106,7 @@ void cHTTPConnection::AwaitNextRequest(void)
case wcsRecvIdle: case wcsRecvIdle:
{ {
// The client is waiting for a response, send an "Internal server error": // The client is waiting for a response, send an "Internal server error":
m_OutgoingData.append("HTTP/1.1 500 Internal Server Error\r\n\r\n"); SendData("HTTP/1.1 500 Internal Server Error\r\n\r\n");
m_HTTPServer.NotifyConnectionWrite(*this);
m_State = wcsRecvHeaders; m_State = wcsRecvHeaders;
break; break;
} }
@ -117,7 +114,7 @@ void cHTTPConnection::AwaitNextRequest(void)
case wcsSendingResp: case wcsSendingResp:
{ {
// The response headers have been sent, we need to terminate the response body: // The response headers have been sent, we need to terminate the response body:
m_OutgoingData.append("0\r\n\r\n"); SendData("0\r\n\r\n");
m_State = wcsRecvHeaders; m_State = wcsRecvHeaders;
break; break;
} }
@ -140,15 +137,27 @@ void cHTTPConnection::Terminate(void)
{ {
m_HTTPServer.RequestFinished(*this, *m_CurrentRequest); m_HTTPServer.RequestFinished(*this, *m_CurrentRequest);
} }
m_HTTPServer.CloseConnection(*this); m_Link.reset();
} }
bool cHTTPConnection::DataReceived(const char * a_Data, size_t a_Size) void cHTTPConnection::OnLinkCreated(cTCPLinkPtr a_Link)
{ {
ASSERT(m_Link == nullptr);
m_Link = a_Link;
}
void cHTTPConnection::OnReceivedData(const char * a_Data, size_t a_Size)
{
ASSERT(m_Link != nullptr);
switch (m_State) switch (m_State)
{ {
case wcsRecvHeaders: case wcsRecvHeaders:
@ -164,13 +173,14 @@ bool cHTTPConnection::DataReceived(const char * a_Data, size_t a_Size)
delete m_CurrentRequest; delete m_CurrentRequest;
m_CurrentRequest = nullptr; m_CurrentRequest = nullptr;
m_State = wcsInvalid; m_State = wcsInvalid;
m_HTTPServer.CloseConnection(*this); m_Link->Close();
return true; m_Link.reset();
return;
} }
if (m_CurrentRequest->IsInHeaders()) if (m_CurrentRequest->IsInHeaders())
{ {
// The request headers are not yet complete // The request headers are not yet complete
return false; return;
} }
// The request has finished parsing its headers successfully, notify of it: // The request has finished parsing its headers successfully, notify of it:
@ -186,11 +196,13 @@ bool cHTTPConnection::DataReceived(const char * a_Data, size_t a_Size)
// Process the rest of the incoming data into the request body: // Process the rest of the incoming data into the request body:
if (a_Size > BytesConsumed) if (a_Size > BytesConsumed)
{ {
return cHTTPConnection::DataReceived(a_Data + BytesConsumed, a_Size - BytesConsumed); cHTTPConnection::OnReceivedData(a_Data + BytesConsumed, a_Size - BytesConsumed);
return;
} }
else else
{ {
return cHTTPConnection::DataReceived("", 0); // If the request has zero body length, let it be processed right-away cHTTPConnection::OnReceivedData("", 0); // If the request has zero body length, let it be processed right-away
return;
} }
} }
@ -210,8 +222,9 @@ bool cHTTPConnection::DataReceived(const char * a_Data, size_t a_Size)
if (!m_CurrentRequest->DoesAllowKeepAlive()) if (!m_CurrentRequest->DoesAllowKeepAlive())
{ {
m_State = wcsInvalid; m_State = wcsInvalid;
m_HTTPServer.CloseConnection(*this); m_Link->Close();
return true; m_Link.reset();
return;
} }
delete m_CurrentRequest; delete m_CurrentRequest;
m_CurrentRequest = nullptr; m_CurrentRequest = nullptr;
@ -225,32 +238,39 @@ bool cHTTPConnection::DataReceived(const char * a_Data, size_t a_Size)
break; break;
} }
} }
return false;
} }
void cHTTPConnection::GetOutgoingData(AString & a_Data) void cHTTPConnection::OnRemoteClosed(void)
{
std::swap(a_Data, m_OutgoingData);
}
void cHTTPConnection::SocketClosed(void)
{ {
if (m_CurrentRequest != nullptr) if (m_CurrentRequest != nullptr)
{ {
m_HTTPServer.RequestFinished(*this, *m_CurrentRequest); m_HTTPServer.RequestFinished(*this, *m_CurrentRequest);
} }
m_HTTPServer.CloseConnection(*this); m_Link.reset();
} }
void cHTTPConnection::OnError(int a_ErrorCode, const AString & a_ErrorMsg)
{
OnRemoteClosed();
}
void cHTTPConnection::SendData(const void * a_Data, size_t a_Size)
{
m_Link->Send(a_Data, a_Size);
}

View File

@ -9,7 +9,7 @@
#pragma once #pragma once
#include "../OSSupport/SocketThreads.h" #include "../OSSupport/Network.h"
@ -25,7 +25,7 @@ class cHTTPRequest;
class cHTTPConnection : class cHTTPConnection :
public cSocketThreads::cCallback public cTCPLink::cCallbacks
{ {
public: public:
@ -78,9 +78,6 @@ protected:
/** Status in which the request currently is */ /** Status in which the request currently is */
eState m_State; eState m_State;
/** Data that is queued for sending, once the socket becomes writable */
AString m_OutgoingData;
/** The request being currently received /** The request being currently received
Valid only between having parsed the headers and finishing receiving the body. */ Valid only between having parsed the headers and finishing receiving the body. */
cHTTPRequest * m_CurrentRequest; cHTTPRequest * m_CurrentRequest;
@ -88,18 +85,34 @@ protected:
/** Number of bytes that remain to read for the complete body of the message to be received. /** Number of bytes that remain to read for the complete body of the message to be received.
Valid only in wcsRecvBody */ Valid only in wcsRecvBody */
size_t m_CurrentRequestBodyRemaining; size_t m_CurrentRequestBodyRemaining;
/** The network link attached to this connection. */
cTCPLinkPtr m_Link;
// cSocketThreads::cCallback overrides: // cTCPLink::cCallbacks overrides:
/** Data is received from the client. /** The link instance has been created, remember it. */
Returns true if the connection has been closed as the result of parsing the data. */ virtual void OnLinkCreated(cTCPLinkPtr a_Link) override;
virtual bool DataReceived(const char * a_Data, size_t a_Size) override;
/** Data is received from the client. */
virtual void OnReceivedData(const char * a_Data, size_t a_Size) override;
/** Data can be sent to client */ /** The socket has been closed for any reason. */
virtual void GetOutgoingData(AString & a_Data) override; virtual void OnRemoteClosed(void) override;
/** The socket has been closed for any reason */ /** An error has occurred on the socket. */
virtual void SocketClosed(void) override; virtual void OnError(int a_ErrorCode, const AString & a_ErrorMsg) override;
// Overridable:
/** Called to send raw data over the link. Descendants may provide data transformations (SSL etc.) */
virtual void SendData(const void * a_Data, size_t a_Size);
/** Sends the raw data over the link.
Descendants may provide data transformations (SSL etc.) via the overridable SendData() function. */
void SendData(const AString & a_Data)
{
SendData(a_Data.data(), a_Data.size());
}
} ; } ;
typedef std::vector<cHTTPConnection *> cHTTPConnections; typedef std::vector<cHTTPConnection *> cHTTPConnections;

View File

@ -118,12 +118,46 @@ class cDebugCallbacks :
////////////////////////////////////////////////////////////////////////////////
// cHTTPServerListenCallbacks:
class cHTTPServerListenCallbacks:
public cNetwork::cListenCallbacks
{
public:
cHTTPServerListenCallbacks(cHTTPServer & a_HTTPServer, UInt16 a_Port):
m_HTTPServer(a_HTTPServer),
m_Port(a_Port)
{
}
protected:
/** The HTTP server instance that we're attached to. */
cHTTPServer & m_HTTPServer;
/** The port for which this instance is responsible. */
UInt16 m_Port;
// cNetwork::cListenCallbacks overrides:
virtual cTCPLink::cCallbacksPtr OnIncomingConnection(const AString & a_RemoteIPAddress, UInt16 a_RemotePort) override
{
return m_HTTPServer.OnIncomingConnection(a_RemoteIPAddress, a_RemotePort);
}
virtual void OnAccepted(cTCPLink & a_Link) override {}
virtual void OnError(int a_ErrorCode, const AString & a_ErrorMsg) override
{
LOGWARNING("HTTP server error on port %d: %d (%s)", m_Port, a_ErrorCode, a_ErrorMsg.c_str());
}
};
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
// cHTTPServer: // cHTTPServer:
cHTTPServer::cHTTPServer(void) : cHTTPServer::cHTTPServer(void) :
m_ListenThreadIPv4(*this, cSocket::IPv4, "WebServer"),
m_ListenThreadIPv6(*this, cSocket::IPv6, "WebServer"),
m_Callbacks(nullptr) m_Callbacks(nullptr)
{ {
} }
@ -141,7 +175,7 @@ cHTTPServer::~cHTTPServer()
bool cHTTPServer::Initialize(const AString & a_PortsIPv4, const AString & a_PortsIPv6) bool cHTTPServer::Initialize(void)
{ {
// Read the HTTPS cert + key: // Read the HTTPS cert + key:
AString CertFile = cFile::ReadWholeFile("webadmin/httpscert.crt"); AString CertFile = cFile::ReadWholeFile("webadmin/httpscert.crt");
@ -177,18 +211,6 @@ bool cHTTPServer::Initialize(const AString & a_PortsIPv4, const AString & a_Port
{ {
LOGINFO("WebServer: The server is running in secure HTTPS mode."); LOGINFO("WebServer: The server is running in secure HTTPS mode.");
} }
// Open up requested ports:
bool HasAnyPort;
m_ListenThreadIPv4.SetReuseAddr(true);
m_ListenThreadIPv6.SetReuseAddr(true);
HasAnyPort = m_ListenThreadIPv4.Initialize(a_PortsIPv4);
HasAnyPort = m_ListenThreadIPv6.Initialize(a_PortsIPv6) || HasAnyPort;
if (!HasAnyPort)
{
return false;
}
return true; return true;
} }
@ -196,19 +218,28 @@ bool cHTTPServer::Initialize(const AString & a_PortsIPv4, const AString & a_Port
bool cHTTPServer::Start(cCallbacks & a_Callbacks) bool cHTTPServer::Start(cCallbacks & a_Callbacks, const AStringVector & a_Ports)
{ {
m_Callbacks = &a_Callbacks; m_Callbacks = &a_Callbacks;
if (!m_ListenThreadIPv4.Start())
// Open up requested ports:
for (auto port : a_Ports)
{ {
return false; UInt16 PortNum = static_cast<UInt16>(atoi(port.c_str()));
} if (PortNum == 0)
if (!m_ListenThreadIPv6.Start()) {
{ LOGWARNING("WebServer: Invalid port value: \"%s\". Ignoring.", port.c_str());
m_ListenThreadIPv4.Stop(); continue;
return false; }
} auto Handle = cNetwork::Listen(PortNum, std::make_shared<cHTTPServerListenCallbacks>(*this, PortNum));
return true; if (Handle->IsListening())
{
m_ServerHandles.push_back(Handle);
}
} // for port - a_Ports[]
// Report success if at least one port opened successfully:
return !m_ServerHandles.empty();
} }
@ -217,63 +248,30 @@ bool cHTTPServer::Start(cCallbacks & a_Callbacks)
void cHTTPServer::Stop(void) void cHTTPServer::Stop(void)
{ {
m_ListenThreadIPv4.Stop(); for (auto handle : m_ServerHandles)
m_ListenThreadIPv6.Stop();
// Drop all current connections:
cCSLock Lock(m_CSConnections);
while (!m_Connections.empty())
{ {
m_Connections.front()->Terminate(); handle->Close();
} // for itr - m_Connections[] }
m_ServerHandles.clear();
} }
void cHTTPServer::OnConnectionAccepted(cSocket & a_Socket) cTCPLink::cCallbacksPtr cHTTPServer::OnIncomingConnection(const AString & a_RemoteIPAddress, UInt16 a_RemotePort)
{ {
cHTTPConnection * Connection; UNUSED(a_RemoteIPAddress);
UNUSED(a_RemotePort);
if (m_Cert.get() != nullptr) if (m_Cert.get() != nullptr)
{ {
Connection = new cSslHTTPConnection(*this, m_Cert, m_CertPrivKey); return std::make_shared<cSslHTTPConnection>(*this, m_Cert, m_CertPrivKey);
} }
else else
{ {
Connection = new cHTTPConnection(*this); return std::make_shared<cHTTPConnection>(*this);
} }
m_SocketThreads.AddClient(a_Socket, Connection);
cCSLock Lock(m_CSConnections);
m_Connections.push_back(Connection);
}
void cHTTPServer::CloseConnection(cHTTPConnection & a_Connection)
{
m_SocketThreads.RemoveClient(&a_Connection);
cCSLock Lock(m_CSConnections);
for (cHTTPConnections::iterator itr = m_Connections.begin(), end = m_Connections.end(); itr != end; ++itr)
{
if (*itr == &a_Connection)
{
m_Connections.erase(itr);
break;
}
}
delete &a_Connection;
}
void cHTTPServer::NotifyConnectionWrite(cHTTPConnection & a_Connection)
{
m_SocketThreads.NotifyWrite(&a_Connection);
} }

View File

@ -9,8 +9,7 @@
#pragma once #pragma once
#include "../OSSupport/ListenThread.h" #include "../OSSupport/Network.h"
#include "../OSSupport/SocketThreads.h"
#include "../IniFile.h" #include "../IniFile.h"
#include "PolarSSL++/RsaPrivateKey.h" #include "PolarSSL++/RsaPrivateKey.h"
#include "PolarSSL++/CryptoKey.h" #include "PolarSSL++/CryptoKey.h"
@ -33,8 +32,7 @@ typedef std::vector<cHTTPConnection *> cHTTPConnections;
class cHTTPServer : class cHTTPServer
public cListenThread::cCallback
{ {
public: public:
class cCallbacks class cCallbacks
@ -42,44 +40,39 @@ public:
public: public:
virtual ~cCallbacks() {} virtual ~cCallbacks() {}
/** Called when a new request arrives over a connection and its headers have been parsed. /** Called when a new request arrives over a connection and all its headers have been parsed.
The request body needn't have arrived yet. The request body needn't have arrived yet. */
*/
virtual void OnRequestBegun(cHTTPConnection & a_Connection, cHTTPRequest & a_Request) = 0; virtual void OnRequestBegun(cHTTPConnection & a_Connection, cHTTPRequest & a_Request) = 0;
/** Called when another part of request body has arrived. /** Called when another part of request body has arrived.
May be called multiple times for a single request. */ May be called multiple times for a single request. */
virtual void OnRequestBody(cHTTPConnection & a_Connection, cHTTPRequest & a_Request, const char * a_Data, size_t a_Size) = 0; virtual void OnRequestBody(cHTTPConnection & a_Connection, cHTTPRequest & a_Request, const char * a_Data, size_t a_Size) = 0;
/// Called when the request body has been fully received in previous calls to OnRequestBody() /** Called when the request body has been fully received in previous calls to OnRequestBody() */
virtual void OnRequestFinished(cHTTPConnection & a_Connection, cHTTPRequest & a_Request) = 0; virtual void OnRequestFinished(cHTTPConnection & a_Connection, cHTTPRequest & a_Request) = 0;
} ; } ;
cHTTPServer(void); cHTTPServer(void);
virtual ~cHTTPServer(); virtual ~cHTTPServer();
/// Initializes the server on the specified ports /** Initializes the server - reads the cert files etc. */
bool Initialize(const AString & a_PortsIPv4, const AString & a_PortsIPv6); bool Initialize(void);
/// Starts the server and assigns the callbacks to use for incoming requests /** Starts the server and assigns the callbacks to use for incoming requests */
bool Start(cCallbacks & a_Callbacks); bool Start(cCallbacks & a_Callbacks, const AStringVector & a_Ports);
/// Stops the server, drops all current connections /** Stops the server, drops all current connections */
void Stop(void); void Stop(void);
protected: protected:
friend class cHTTPConnection; friend class cHTTPConnection;
friend class cSslHTTPConnection; friend class cSslHTTPConnection;
friend class cHTTPServerListenCallbacks;
cListenThread m_ListenThreadIPv4; /** The cNetwork API handle for the listening socket. */
cListenThread m_ListenThreadIPv6; cServerHandlePtrs m_ServerHandles;
cSocketThreads m_SocketThreads; /** The callbacks to call for various events */
cCriticalSection m_CSConnections;
cHTTPConnections m_Connections; ///< All the connections that are currently being serviced
/// The callbacks to call for various events
cCallbacks * m_Callbacks; cCallbacks * m_Callbacks;
/** The server certificate to use for the SSL connections */ /** The server certificate to use for the SSL connections */
@ -89,23 +82,18 @@ protected:
cCryptoKeyPtr m_CertPrivKey; cCryptoKeyPtr m_CertPrivKey;
// cListenThread::cCallback overrides: /** Called by cHTTPServerListenCallbacks when there's a new incoming connection.
virtual void OnConnectionAccepted(cSocket & a_Socket) override; Returns the connection instance to be used as the cTCPLink callbacks. */
cTCPLink::cCallbacksPtr OnIncomingConnection(const AString & a_RemoteIPAddress, UInt16 a_RemotePort);
/// Called by cHTTPConnection to close the connection (presumably due to an error)
void CloseConnection(cHTTPConnection & a_Connection); /** Called by cHTTPConnection when it finishes parsing the request header */
/// Called by cHTTPConnection to notify SocketThreads that there's data to be sent for the connection
void NotifyConnectionWrite(cHTTPConnection & a_Connection);
/// Called by cHTTPConnection when it finishes parsing the request header
void NewRequest(cHTTPConnection & a_Connection, cHTTPRequest & a_Request); void NewRequest(cHTTPConnection & a_Connection, cHTTPRequest & a_Request);
/** Called by cHTTPConenction when it receives more data for the request body. /** Called by cHTTPConenction when it receives more data for the request body.
May be called multiple times for a single request. */ May be called multiple times for a single request. */
void RequestBody(cHTTPConnection & a_Connection, cHTTPRequest & a_Request, const char * a_Data, size_t a_Size); void RequestBody(cHTTPConnection & a_Connection, cHTTPRequest & a_Request, const char * a_Data, size_t a_Size);
/// Called by cHTTPConnection when it detects that the request has finished (all of its body has been received) /** Called by cHTTPConnection when it detects that the request has finished (all of its body has been received) */
void RequestFinished(cHTTPConnection & a_Connection, cHTTPRequest & a_Request); void RequestFinished(cHTTPConnection & a_Connection, cHTTPRequest & a_Request);
} ; } ;

View File

@ -25,14 +25,8 @@ cSslHTTPConnection::cSslHTTPConnection(cHTTPServer & a_HTTPServer, const cX509Ce
bool cSslHTTPConnection::DataReceived(const char * a_Data, size_t a_Size) void cSslHTTPConnection::OnReceivedData(const char * a_Data, size_t a_Size)
{ {
// If there is outgoing data in the queue, notify the server that it should write it out:
if (!m_OutgoingData.empty())
{
m_HTTPServer.NotifyConnectionWrite(*this);
}
// Process the received data: // Process the received data:
const char * Data = a_Data; const char * Data = a_Data;
size_t Size = a_Size; size_t Size = a_Size;
@ -52,17 +46,18 @@ bool cSslHTTPConnection::DataReceived(const char * a_Data, size_t a_Size)
int NumRead = m_Ssl.ReadPlain(Buffer, sizeof(Buffer)); int NumRead = m_Ssl.ReadPlain(Buffer, sizeof(Buffer));
if (NumRead > 0) if (NumRead > 0)
{ {
if (super::DataReceived(Buffer, (size_t)NumRead)) super::OnReceivedData(Buffer, (size_t)NumRead);
{ }
// The socket has been closed, and the object is already deleted. Bail out. else if (NumRead == POLARSSL_ERR_NET_WANT_READ)
return true; {
} // SSL requires us to send data to peer first, do so by "sending" empty data:
SendData(nullptr, 0);
} }
// If both failed, bail out: // If both failed, bail out:
if ((BytesWritten == 0) && (NumRead <= 0)) if ((BytesWritten == 0) && (NumRead <= 0))
{ {
return false; return;
} }
} }
} }
@ -71,18 +66,20 @@ bool cSslHTTPConnection::DataReceived(const char * a_Data, size_t a_Size)
void cSslHTTPConnection::GetOutgoingData(AString & a_Data) void cSslHTTPConnection::SendData(const void * a_Data, size_t a_Size)
{ {
const char * OutgoingData = reinterpret_cast<const char *>(a_Data);
size_t pos = 0;
for (;;) for (;;)
{ {
// Write as many bytes from our buffer to SSL's encryption as possible: // Write as many bytes from our buffer to SSL's encryption as possible:
int NumWritten = 0; int NumWritten = 0;
if (!m_OutgoingData.empty()) if (pos < a_Size)
{ {
NumWritten = m_Ssl.WritePlain(m_OutgoingData.data(), m_OutgoingData.size()); NumWritten = m_Ssl.WritePlain(OutgoingData + pos, a_Size - pos);
if (NumWritten > 0) if (NumWritten > 0)
{ {
m_OutgoingData.erase(0, (size_t)NumWritten); pos += static_cast<size_t>(NumWritten);
} }
} }
@ -91,7 +88,7 @@ void cSslHTTPConnection::GetOutgoingData(AString & a_Data)
size_t NumBytes = m_Ssl.ReadOutgoing(Buffer, sizeof(Buffer)); size_t NumBytes = m_Ssl.ReadOutgoing(Buffer, sizeof(Buffer));
if (NumBytes > 0) if (NumBytes > 0)
{ {
a_Data.append(Buffer, NumBytes); m_Link->Send(Buffer, NumBytes);
} }
// If both failed, bail out: // If both failed, bail out:

View File

@ -36,8 +36,8 @@ protected:
cCryptoKeyPtr m_PrivateKey; cCryptoKeyPtr m_PrivateKey;
// cHTTPConnection overrides: // cHTTPConnection overrides:
virtual bool DataReceived (const char * a_Data, size_t a_Size) override; // Data is received from the client virtual void OnReceivedData(const char * a_Data, size_t a_Size) override; // Data is received from the client
virtual void GetOutgoingData(AString & a_Data) override; // Data can be sent to client virtual void SendData(const void * a_Data, size_t a_Size) override; // Data is to be sent to client
} ; } ;

View File

@ -19,7 +19,16 @@
/// Helper class - appends all player names together in a HTML list static const char DEFAULT_WEBADMIN_PORTS[] = "8080";
////////////////////////////////////////////////////////////////////////////////
// cPlayerAccum:
/** Helper class - appends all player names together in an HTML list */
class cPlayerAccum : class cPlayerAccum :
public cPlayerListCallback public cPlayerListCallback
{ {
@ -40,11 +49,12 @@ public:
////////////////////////////////////////////////////////////////////////////////
// cWebAdmin:
cWebAdmin::cWebAdmin(void) : cWebAdmin::cWebAdmin(void) :
m_IsInitialized(false), m_IsInitialized(false),
m_IsRunning(false), m_IsRunning(false),
m_PortsIPv4("8080"),
m_PortsIPv6(""),
m_TemplateScript("<webadmin_template>") m_TemplateScript("<webadmin_template>")
{ {
} }
@ -91,8 +101,7 @@ bool cWebAdmin::Init(void)
m_IniFile.AddHeaderComment(" Password format: Password=*password*; for example:"); m_IniFile.AddHeaderComment(" Password format: Password=*password*; for example:");
m_IniFile.AddHeaderComment(" [User:admin]"); m_IniFile.AddHeaderComment(" [User:admin]");
m_IniFile.AddHeaderComment(" Password=admin"); m_IniFile.AddHeaderComment(" Password=admin");
m_IniFile.SetValue("WebAdmin", "Port", m_PortsIPv4); m_IniFile.SetValue("WebAdmin", "Ports", DEFAULT_WEBADMIN_PORTS);
m_IniFile.SetValue("WebAdmin", "PortsIPv6", m_PortsIPv6);
m_IniFile.WriteFile("webadmin.ini"); m_IniFile.WriteFile("webadmin.ini");
} }
@ -104,10 +113,37 @@ bool cWebAdmin::Init(void)
LOGD("Initialising WebAdmin..."); LOGD("Initialising WebAdmin...");
m_PortsIPv4 = m_IniFile.GetValueSet("WebAdmin", "Port", m_PortsIPv4); // Initialize the WebAdmin template script and load the file
m_PortsIPv6 = m_IniFile.GetValueSet("WebAdmin", "PortsIPv6", m_PortsIPv6); m_TemplateScript.Create();
m_TemplateScript.RegisterAPILibs();
if (!m_TemplateScript.LoadFile(FILE_IO_PREFIX "webadmin/template.lua"))
{
LOGWARN("Could not load WebAdmin template \"%s\". WebAdmin disabled!", FILE_IO_PREFIX "webadmin/template.lua");
m_TemplateScript.Close();
m_HTTPServer.Stop();
return false;
}
if (!m_HTTPServer.Initialize(m_PortsIPv4, m_PortsIPv6)) // Load the login template, provide a fallback default if not found:
if (!LoadLoginTemplate())
{
LOGWARN("Could not load WebAdmin login template \"%s\", using fallback template.", FILE_IO_PREFIX "webadmin/login_template.html");
// Sets the fallback template:
m_LoginTemplate = \
"<h1>MCServer WebAdmin</h1>" \
"<center>" \
"<form method='get' action='webadmin/'>" \
"<input type='submit' value='Log in'>" \
"</form>" \
"</center>";
}
// Read the ports to be used:
// Note that historically the ports were stored in the "Port" and "PortsIPv6" values
m_Ports = ReadUpgradeIniPorts(m_IniFile, "WebAdmin", "Ports", "Port", "PortsIPv6", DEFAULT_WEBADMIN_PORTS);
if (!m_HTTPServer.Initialize())
{ {
return false; return false;
} }
@ -130,32 +166,7 @@ bool cWebAdmin::Start(void)
LOGD("Starting WebAdmin..."); LOGD("Starting WebAdmin...");
// Initialize the WebAdmin template script and load the file m_IsRunning = m_HTTPServer.Start(*this, m_Ports);
m_TemplateScript.Create();
m_TemplateScript.RegisterAPILibs();
if (!m_TemplateScript.LoadFile(FILE_IO_PREFIX "webadmin/template.lua"))
{
LOGWARN("Could not load WebAdmin template \"%s\". WebAdmin disabled!", FILE_IO_PREFIX "webadmin/template.lua");
m_TemplateScript.Close();
m_HTTPServer.Stop();
return false;
}
if (!LoadLoginTemplate())
{
LOGWARN("Could not load WebAdmin login template \"%s\", using fallback template.", FILE_IO_PREFIX "webadmin/login_template.html");
// Sets the fallback template:
m_LoginTemplate = \
"<h1>MCServer WebAdmin</h1>" \
"<center>" \
"<form method='get' action='webadmin/'>" \
"<input type='submit' value='Log in'>" \
"</form>" \
"</center>";
}
m_IsRunning = m_HTTPServer.Start(*this);
return m_IsRunning; return m_IsRunning;
} }

View File

@ -5,7 +5,6 @@
#pragma once #pragma once
#include "OSSupport/Socket.h"
#include "Bindings/LuaState.h" #include "Bindings/LuaState.h"
#include "IniFile.h" #include "IniFile.h"
#include "HTTPServer/HTTPServer.h" #include "HTTPServer/HTTPServer.h"
@ -135,8 +134,16 @@ public:
/** Returns the prefix needed for making a link point to the webadmin root from the given URL ("../../../webadmin"-style) */ /** Returns the prefix needed for making a link point to the webadmin root from the given URL ("../../../webadmin"-style) */
AString GetBaseURL(const AString & a_URL); AString GetBaseURL(const AString & a_URL);
AString GetIPv4Ports(void) const { return m_PortsIPv4; } /** Returns the list of ports used for the webadmin. */
AString GetIPv6Ports(void) const { return m_PortsIPv6; } AString GetPorts(void) const { return StringsConcat(m_Ports, ','); }
/** OBSOLETE: Returns the list of IPv4 ports used for the webadmin.
Currently there is no distinction between IPv4 and IPv6; use GetPorts() instead. */
AString GetIPv4Ports(void) const { return GetPorts(); }
/** OBSOLETE: Returns the list of IPv6 ports used for the webadmin.
Currently there is no distinction between IPv4 and IPv6; use GetPorts() instead. */
AString GetIPv6Ports(void) const { return GetPorts(); }
// tolua_end // tolua_end
@ -205,8 +212,8 @@ protected:
PluginList m_Plugins; PluginList m_Plugins;
AString m_PortsIPv4; /** The ports on which the webadmin is running. */
AString m_PortsIPv6; AStringVector m_Ports;
/** The Lua template script to provide templates: */ /** The Lua template script to provide templates: */
cLuaState m_TemplateScript; cLuaState m_TemplateScript;