summaryrefslogtreecommitdiffstats
path: root/src/HTTP/SslHTTPServerConnection.cpp
blob: b32a24a885fcc6bf60dd8b86cac20985834fd820 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117

// SslHTTPConnection.cpp

// Implements the cSslHTTPServerConnection class representing a HTTP connection made over a SSL link

#include "Globals.h"
#include "SslHTTPServerConnection.h"
#include "HTTPServer.h"





cSslHTTPServerConnection::cSslHTTPServerConnection(
	cHTTPServer & a_HTTPServer,
	const std::shared_ptr<const cSslConfig> & a_Config
) :
	Super(a_HTTPServer), m_Ssl(64000)
{
	if (a_Config != nullptr)
	{
		m_Ssl.Initialize(a_Config);
	}
	else
	{
		m_Ssl.Initialize(false);
	}
}





cSslHTTPServerConnection::~cSslHTTPServerConnection()
{
	m_Ssl.NotifyClose();
}





void cSslHTTPServerConnection::OnReceivedData(const char * a_Data, size_t a_Size)
{
	// Process the received data:
	const char * Data = a_Data;
	size_t Size = a_Size;
	for (;;)
	{
		// Try to write as many bytes into Ssl's "incoming" buffer as possible:
		size_t BytesWritten = 0;
		if (Size > 0)
		{
			BytesWritten = m_Ssl.WriteIncoming(Data, Size);
			Data += BytesWritten;
			Size -= BytesWritten;
		}

		// Try to read as many bytes from SSL's decryption as possible:
		char Buffer[32000];
		int NumRead = m_Ssl.ReadPlain(Buffer, sizeof(Buffer));
		if (NumRead > 0)
		{
			Super::OnReceivedData(Buffer, static_cast<size_t>(NumRead));
			// The link may have closed while processing the data, bail out:
			return;
		}
		else if (NumRead == MBEDTLS_ERR_SSL_WANT_READ)
		{
			// SSL requires us to send data to peer first, do so by "sending" empty data:
			SendData(nullptr, 0);
		}

		// If both failed, bail out:
		if ((BytesWritten == 0) && (NumRead <= 0))
		{
			return;
		}
	}
}





void cSslHTTPServerConnection::SendData(const void * a_Data, size_t a_Size)
{
	const char * OutgoingData = static_cast<const char *>(a_Data);
	size_t pos = 0;
	for (;;)
	{
		// Write as many bytes from our buffer to SSL's encryption as possible:
		int NumWritten = 0;
		if (pos < a_Size)
		{
			NumWritten = m_Ssl.WritePlain(OutgoingData + pos, a_Size - pos);
			if (NumWritten > 0)
			{
				pos += static_cast<size_t>(NumWritten);
			}
		}

		// Read as many bytes from SSL's "outgoing" buffer as possible:
		char Buffer[32000];
		size_t NumBytes = m_Ssl.ReadOutgoing(Buffer, sizeof(Buffer));
		if (NumBytes > 0)
		{
			m_Link->Send(Buffer, NumBytes);
		}

		// If both failed, bail out:
		if ((NumWritten <= 0) && (NumBytes == 0))
		{
			return;
		}
	}
}