File: TunnelGateway.cpp

package info (click to toggle)
i2pd 2.58.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,612 kB
  • sloc: cpp: 59,663; makefile: 224; sh: 138
file content (243 lines) | stat: -rw-r--r-- 7,997 bytes parent folder | download | duplicates (2)
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
/*
* Copyright (c) 2013-2024, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/

#include <string.h>
#include "Crypto.h"
#include "I2PEndian.h"
#include "Log.h"
#include "RouterContext.h"
#include "Transports.h"
#include "TunnelGateway.h"

namespace i2p
{
namespace tunnel
{
	TunnelGatewayBuffer::TunnelGatewayBuffer ():
		m_CurrentTunnelDataMsg (nullptr), m_RemainingSize (0), m_NonZeroRandomBuffer (nullptr)
	{
	}

	TunnelGatewayBuffer::~TunnelGatewayBuffer ()
	{
		ClearTunnelDataMsgs ();
		if (m_NonZeroRandomBuffer) delete[] m_NonZeroRandomBuffer;
	}

	void TunnelGatewayBuffer::PutI2NPMsg (const TunnelMessageBlock& block)
	{
		bool messageCreated = false;
		if (!m_CurrentTunnelDataMsg)
		{
			CreateCurrentTunnelDataMessage ();
			if (block.data && block.data->onDrop)
			{	
				// onDrop is called for the first fragment in tunnel message
				// that's usually true for short TBMs or lookups 
				m_CurrentTunnelDataMsg->onDrop = block.data->onDrop;
				block.data->onDrop = nullptr;
			}	
			messageCreated = true;
		}

		// create delivery instructions
		uint8_t di[43]; // max delivery instruction length is 43 for tunnel
		size_t diLen = 1;// flag
		if (block.deliveryType != eDeliveryTypeLocal) // tunnel or router
		{
			if (block.deliveryType == eDeliveryTypeTunnel)
			{
				htobe32buf (di + diLen, block.tunnelID);
				diLen += 4; // tunnelID
			}

			memcpy (di + diLen, block.hash, 32);
			diLen += 32; //len
		}
		di[0] = block.deliveryType << 5; // set delivery type

		// create fragments
		const std::shared_ptr<I2NPMessage> & msg = block.data;
		size_t fullMsgLen = diLen + msg->GetLength () + 2; // delivery instructions + payload + 2 bytes length

		if (!messageCreated && fullMsgLen > m_RemainingSize) // check if we should complete previous message
		{
			size_t numFollowOnFragments = fullMsgLen / TUNNEL_DATA_MAX_PAYLOAD_SIZE;
			// length of bytes doesn't fit full tunnel message
			// every follow-on fragment adds 7 bytes
			size_t nonFit = (fullMsgLen + numFollowOnFragments*7) % TUNNEL_DATA_MAX_PAYLOAD_SIZE;
			if (!nonFit || nonFit > m_RemainingSize || m_RemainingSize < fullMsgLen/5)
			{
				CompleteCurrentTunnelDataMessage ();
				CreateCurrentTunnelDataMessage ();
			}
		}
		if (fullMsgLen <= m_RemainingSize)
		{
			// message fits. First and last fragment
			htobe16buf (di + diLen, msg->GetLength ());
			diLen += 2; // size
			memcpy (m_CurrentTunnelDataMsg->buf + m_CurrentTunnelDataMsg->len, di, diLen);
			memcpy (m_CurrentTunnelDataMsg->buf + m_CurrentTunnelDataMsg->len + diLen, msg->GetBuffer (), msg->GetLength ());
			m_CurrentTunnelDataMsg->len += diLen + msg->GetLength ();
			m_RemainingSize -= diLen + msg->GetLength ();
			if (!m_RemainingSize)
				CompleteCurrentTunnelDataMessage ();
		}
		else
		{
			if (diLen + 6 <= m_RemainingSize)
			{
				// delivery instructions fit
				uint32_t msgID;
				memcpy (&msgID, msg->GetHeader () + I2NP_HEADER_MSGID_OFFSET, 4); // in network bytes order
				size_t size = m_RemainingSize - diLen - 6; // 6 = 4 (msgID) + 2 (size)

				// first fragment
				di[0] |= 0x08; // fragmented
				htobuf32 (di + diLen, msgID);
				diLen += 4; // Message ID
				htobe16buf (di + diLen, size);
				diLen += 2; // size
				memcpy (m_CurrentTunnelDataMsg->buf + m_CurrentTunnelDataMsg->len, di, diLen);
				memcpy (m_CurrentTunnelDataMsg->buf + m_CurrentTunnelDataMsg->len + diLen, msg->GetBuffer (), size);
				m_CurrentTunnelDataMsg->len += diLen + size;
				CompleteCurrentTunnelDataMessage ();
				// follow on fragments
				int fragmentNumber = 1;
				while (size < msg->GetLength ())
				{
					CreateCurrentTunnelDataMessage ();
					uint8_t * buf = m_CurrentTunnelDataMsg->GetBuffer ();
					buf[0] = 0x80 | (fragmentNumber << 1); // frag
					bool isLastFragment = false;
					size_t s = msg->GetLength () - size;
					if (s > TUNNEL_DATA_MAX_PAYLOAD_SIZE - 7) // 7 follow on instructions
						s = TUNNEL_DATA_MAX_PAYLOAD_SIZE - 7;
					else // last fragment
					{
						buf[0] |= 0x01;
						isLastFragment = true;
					}
					htobuf32 (buf + 1, msgID); //Message ID
					htobe16buf (buf + 5, s); // size
					memcpy (buf + 7, msg->GetBuffer () + size, s);
					m_CurrentTunnelDataMsg->len += s+7;
					if (isLastFragment)
					{
						if(m_RemainingSize < (s+7)) {
							LogPrint (eLogError, "TunnelGateway: remaining size overflow: ", m_RemainingSize, " < ", s+7);
						} else {
							m_RemainingSize -= s+7;
							if (m_RemainingSize == 0)
								CompleteCurrentTunnelDataMessage ();
						}
					}
					else
						CompleteCurrentTunnelDataMessage ();
					size += s;
					fragmentNumber++;
				}
			}
			else
			{
				// delivery instructions don't fit. Create new message
				CompleteCurrentTunnelDataMessage ();
				PutI2NPMsg (block);
				// don't delete msg because it's taken care inside
			}
		}
	}

	void TunnelGatewayBuffer::ClearTunnelDataMsgs ()
	{
		m_TunnelDataMsgs.clear ();
		m_CurrentTunnelDataMsg = nullptr;
	}

	void TunnelGatewayBuffer::CreateCurrentTunnelDataMessage ()
	{
		m_CurrentTunnelDataMsg = NewI2NPTunnelMessage (true); // tunnel endpoint is at least of two tunnel messages size
		// we reserve space for padding
		m_CurrentTunnelDataMsg->offset += TUNNEL_DATA_MSG_SIZE + I2NP_HEADER_SIZE;
		m_CurrentTunnelDataMsg->len = m_CurrentTunnelDataMsg->offset;
		m_RemainingSize = TUNNEL_DATA_MAX_PAYLOAD_SIZE;
	}

	void TunnelGatewayBuffer::CompleteCurrentTunnelDataMessage ()
	{
		if (!m_CurrentTunnelDataMsg) return;
		uint8_t * payload = m_CurrentTunnelDataMsg->GetBuffer ();
		size_t size = m_CurrentTunnelDataMsg->len - m_CurrentTunnelDataMsg->offset;

		m_CurrentTunnelDataMsg->offset = m_CurrentTunnelDataMsg->len - TUNNEL_DATA_MSG_SIZE - I2NP_HEADER_SIZE;
		uint8_t * buf = m_CurrentTunnelDataMsg->GetPayload ();
		RAND_bytes (buf + 4, 16); // original IV
		memcpy (payload + size, buf + 4, 16); // copy IV for checksum
		uint8_t hash[32];
		SHA256(payload, size+16, hash);
		memcpy (buf+20, hash, 4); // checksum
		payload[-1] = 0; // zero
		ptrdiff_t paddingSize = payload - buf - 25; // 25 = 24 + 1
		if (paddingSize > 0)
		{
			// non-zero padding
			if (!m_NonZeroRandomBuffer) // first time?
			{
				m_NonZeroRandomBuffer = new uint8_t[TUNNEL_DATA_MAX_PAYLOAD_SIZE];
				RAND_bytes (m_NonZeroRandomBuffer, TUNNEL_DATA_MAX_PAYLOAD_SIZE);
				for (size_t i = 0; i < TUNNEL_DATA_MAX_PAYLOAD_SIZE; i++)
					if (!m_NonZeroRandomBuffer[i]) m_NonZeroRandomBuffer[i] = 1;
			}
			auto randomOffset = rand () % (TUNNEL_DATA_MAX_PAYLOAD_SIZE - paddingSize + 1);
			memcpy (buf + 24, m_NonZeroRandomBuffer + randomOffset, paddingSize);
		}

		// we can't fill message header yet because encryption is required
		m_TunnelDataMsgs.push_back (m_CurrentTunnelDataMsg);
		m_CurrentTunnelDataMsg = nullptr;
	}

	void TunnelGateway::SendTunnelDataMsg (const TunnelMessageBlock& block)
	{
		if (block.data)
		{
			PutTunnelDataMsg (block);
			SendBuffer ();
		}
	}

	void TunnelGateway::PutTunnelDataMsg (const TunnelMessageBlock& block)
	{
		if (block.data)
			m_Buffer.PutI2NPMsg (block);
	}

	void TunnelGateway::SendBuffer ()
	{
		// create list or tunnel messages
		m_Buffer.CompleteCurrentTunnelDataMessage ();
		std::list<std::shared_ptr<I2NPMessage> > newTunnelMsgs;
		const auto& tunnelDataMsgs = m_Buffer.GetTunnelDataMsgs ();
		for (auto& tunnelMsg : tunnelDataMsgs)
		{
			auto newMsg = CreateEmptyTunnelDataMsg (false);
			m_Tunnel.EncryptTunnelMsg (tunnelMsg, newMsg);
			htobe32buf (newMsg->GetPayload (), m_Tunnel.GetNextTunnelID ());
			newMsg->FillI2NPMessageHeader (eI2NPTunnelData);
			if (tunnelMsg->onDrop) newMsg->onDrop = tunnelMsg->onDrop;
			newTunnelMsgs.push_back (newMsg);
			m_NumSentBytes += TUNNEL_DATA_MSG_SIZE;
		}
		m_Buffer.ClearTunnelDataMsgs ();
		// send 
		if (!m_Sender) m_Sender = std::make_unique<TunnelTransportSender>();
		m_Sender->SendMessagesTo (m_Tunnel.GetNextIdentHash (), std::move (newTunnelMsgs));		
	}
}
}