Welcome to mirror list, hosted at ThFree Co, Russian Federation.

LwipSocket.cpp « LwipEthernet « Networking « src - github.com/Duet3D/RepRapFirmware.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 30fb787c6636c9360d473161c5999953664d4e58 (plain)
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
/*
 * LwipSocket.cpp
 *
 *  Created on: 20 Nov 2017
 *      Author: Christian
 */

// Define this to keep the ASF status codes from being included. Without it ERR_TIMEOUT is defined twice
#define NO_STATUS_CODES

#include "LwipSocket.h"

#if HAS_LWIP_NETWORKING

#include <Networking/NetworkBuffer.h>
#include <Platform/RepRap.h>

extern Mutex lwipMutex;

// ERR_IS_FATAL was defined like this in lwip 2.0.3 file err.h but isn't in 2.1.2
#define ERR_IS_FATAL(e) ((e) <= ERR_ABRT)

#ifndef UNUSED
# define UNUSED(v)		(void)(v)
#endif

//***************************************************************************************************

extern "C" {
#include "lwip/pbuf.h"
#include "lwip/tcp.h"

static void conn_err(void *arg, err_t err)
{
	LwipSocket *socket = (LwipSocket *)arg;
	if (socket != nullptr)
	{
		socket->ConnectionError(err);
	}
}

static err_t conn_recv(void *arg, tcp_pcb *pcb, pbuf *p, err_t err)
{
	UNUSED(err);

	LwipSocket *socket = (LwipSocket *)arg;
	if (socket != nullptr)
	{
		if (p != nullptr)
		{
			socket->DataReceived(p);
		}
		else
		{
			socket->ConnectionClosedGracefully();
		}
		return ERR_OK;
	}

	tcp_abort(pcb);
	return ERR_ABRT;
}

static err_t conn_sent(void *arg, tcp_pcb *pcb, u16_t len)
{
	UNUSED(pcb);

	LwipSocket *socket = (LwipSocket *)arg;
	if (socket != nullptr)
	{
		socket->DataSent(len);
	}

	return ERR_OK;
}

}	// end extern "C"

//***************************************************************************************************

// LwipSocket class

LwipSocket::LwipSocket(NetworkInterface *iface) noexcept : Socket(iface), connectionPcb(nullptr),
		receivedData(nullptr), state(SocketState::disabled)
{
	ReInit();
}

bool LwipSocket::AcceptConnection(tcp_pcb *pcb) noexcept
{
	if (state == SocketState::listening && pcb->local_port == localPort)
	{
		ReInit();
		state = SocketState::connected;
		whenConnected = millis();

		connectionPcb = pcb;
		remoteIPAddress.SetV4LittleEndian(pcb->remote_ip.addr);
		remotePort = pcb->remote_port;

		tcp_arg(pcb, this);
		tcp_err(pcb, conn_err);
		tcp_recv(pcb, conn_recv);
		tcp_sent(pcb, conn_sent);
		return true;
	}
	return false;
}

void LwipSocket::DataReceived(pbuf *data) noexcept
{
	if (state != SocketState::closing)
	{
		// Store it for the NetworkResponder
		pbuf *const rdata = receivedData;
		if (rdata == nullptr)
		{
			receivedData = data;
		}
		else
		{
			pbuf_cat(rdata, data);
		}
	}
	else
	{
		// Don't process any more data if the connection is going down
		pbuf_free(data);
	}
}

void LwipSocket::DataSent(size_t numBytes) noexcept
{
	if (numBytes <= unAcked)
	{
		unAcked -= numBytes;
	}
	else
	{
		// Should never happen
		unAcked = 0;
	}

	if (unAcked == 0)
	{
		// Reset the write timer when all data has been ACKed
		whenWritten = 0;
	}
}

void LwipSocket::ConnectionClosedGracefully() noexcept
{
	if (connectionPcb != nullptr)
	{
		tcp_err(connectionPcb, nullptr);
		tcp_recv(connectionPcb, nullptr);
		tcp_sent(connectionPcb, nullptr);
		tcp_close(connectionPcb);
		connectionPcb = nullptr;
	}

	if (state == SocketState::closing)
	{
		state = SocketState::listening;
	}
	else
	{
		state = SocketState::clientDisconnecting;
		whenClosed = millis();
	}
}

void LwipSocket::ConnectionError(err_t err) noexcept
{
	DiscardReceivedData();
	connectionPcb = nullptr;

	state = (localPort == 0)
				? SocketState::disabled
				: (responderFound && state != SocketState::closing)
				  	? SocketState::aborted
				  	: SocketState::listening;
}

// Initialise a TCP socket
void LwipSocket::Init(SocketNumber skt, TcpPort serverPort, NetworkProtocol p) noexcept
{
	UNUSED(skt);
	localPort = serverPort;
	protocol = p;

	state = SocketState::listening;
	ReInit();
}

void LwipSocket::TerminateAndDisable() noexcept
{
	Terminate();
	state = SocketState::disabled;
}

void LwipSocket::ReInit() noexcept
{
	DiscardReceivedData();
	whenConnected = whenWritten = whenClosed = 0;
	responderFound = false;
	readIndex = unAcked = 0;
}

// Close a connection when the last packet has been sent
void LwipSocket::Close() noexcept
{
	if (state != SocketState::disabled && state != SocketState::listening)
	{
		MutexLocker lock(lwipMutex);
		DiscardReceivedData();
		state = SocketState::closing;
		whenClosed = millis();

		if (protocol == FtpDataProtocol)
		{
			localPort = 0;					// don't re-listen automatically
		}
	}
}

// Terminate a connection immediately
void LwipSocket::Terminate() noexcept
{
	if (state != SocketState::disabled)
	{
		MutexLocker lock(lwipMutex);
		if (connectionPcb != nullptr)
		{
			tcp_err(connectionPcb, nullptr);
			tcp_recv(connectionPcb, nullptr);
			tcp_sent(connectionPcb, nullptr);
			tcp_abort(connectionPcb);
			connectionPcb = nullptr;
		}

		DiscardReceivedData();
		whenClosed = millis();
		state = (localPort == 0) ? SocketState::disabled : SocketState::listening;
	}
}

// Return true if there is or may soon be more data to read
bool LwipSocket::CanRead() const noexcept
{
	return (state == SocketState::connected)
		|| (state == SocketState::clientDisconnecting && receivedData != nullptr);
}

bool LwipSocket::CanSend() const noexcept
{
	return (state == SocketState::connected);
}

// Get the next received pbuf, skipping any empty ones (we can get empty ones from lwip)
pbuf *LwipSocket::GetNextReceivedPbuf() noexcept
{
	pbuf *rdata;
	while ((rdata = receivedData) != nullptr && rdata->len == 0)
	{
		debugPrintf("Discarding empty pbuf\n");
		MutexLocker lock(lwipMutex);
		receivedData = rdata->next;
		rdata->next = nullptr;
		pbuf_free(rdata);
		readIndex = 0;
	}
	return rdata;
}

// Read 1 character from the receive buffers, returning true if successful
bool LwipSocket::ReadChar(char& c) noexcept
{
	pbuf *const rdata = GetNextReceivedPbuf();
	if (rdata != nullptr)
	{
		const char * const data = (const char *)rdata->payload;
		c = data[readIndex++];

		const uint16_t rlen = rdata->len;
		if (readIndex >= rlen)
		{
			// Free the buffer. Grab the mutex first to prevent lwip appending more data to it.
			MutexLocker lock(lwipMutex);

			receivedData = rdata->next;
			rdata->next = nullptr;
			pbuf_free(rdata);
			readIndex = 0;

			// Tell lwip we have taken this data
			if (connectionPcb != nullptr)
			{
				tcp_recved(connectionPcb, rlen);
			}
		}

		return true;
	}

	c = 0;
	return false;
}

// Return a pointer to data in a buffer and a length available
bool LwipSocket::ReadBuffer(const uint8_t *&buffer, size_t &len) noexcept
{
	pbuf *const rdata = GetNextReceivedPbuf();
	if (rdata != nullptr)
	{
		const uint8_t * const data = (const uint8_t *)rdata->payload;
		buffer = &data[readIndex];
		len = rdata->len - readIndex;
		return true;
	}

	return false;
}

// Flag some data as taken from the receive buffers. We never take data from more than one buffer at a time.
void LwipSocket::Taken(size_t len) noexcept
{
	pbuf *const rdata = receivedData;
	if (rdata != nullptr)			// should always be true
	{
		readIndex += len;
		const uint16_t rlen = rdata->len;
		if (readIndex >= rlen)
		{
			// Free the buffer. Grab the mutex first to prevent lwip appending more data to it.
			MutexLocker lock(lwipMutex);

			// Free the first item of the pbuf chain if the number of taken bytes exceeds its size
			receivedData = rdata->next;
			rdata->next = nullptr;
			pbuf_free(rdata);
			readIndex = 0;

			// Notify LwIP
			if (connectionPcb != nullptr)
			{
				tcp_recved(connectionPcb, rlen);
			}
		}
	}
}

// Poll a socket to see if it needs to be serviced
void LwipSocket::Poll() noexcept
{
	// Deal with transfers that went so quickly that we haven't got a responder yet
	bool wasShortTransfer = !responderFound && (state == SocketState::clientDisconnecting);
	if (wasShortTransfer)
	{
		state = SocketState::connected;
	}

	switch (state)
	{
	case SocketState::listening:
		// Socket is listening but no client has connected to it yet
		break;

	case SocketState::connected:
		if (responderFound)
		{
			// Are we still waiting for data to be written?
			if (whenWritten != 0 && millis() - whenWritten >= MaxWriteTime)
			{
				Terminate();
			}
		}
		else
		{
			// Try to find a responder to deal with this connection
			if (reprap.GetNetwork().FindResponder(this, protocol))
			{
				responderFound = true;
			}
			else if (millis() - whenConnected >= FindResponderTimeout)
			{
				Terminate();
			}
		}
		break;

	case SocketState::clientDisconnecting:
	case SocketState::closing:
	{
		// The connection is being closed, but we may be waiting for sent data to be ACKed
		// or for the received data to be processed by a NetworkResponder
		bool timeoutExceeded = millis() - whenClosed > MaxAckTime;
		if (unAcked == 0 || timeoutExceeded)
		{
			if (connectionPcb != nullptr)
			{
				tcp_err(connectionPcb, nullptr);
				tcp_recv(connectionPcb, nullptr);
				tcp_sent(connectionPcb, nullptr);
				if (unAcked == 0)
				{
					tcp_close(connectionPcb);
				}
				else
				{
					tcp_abort(connectionPcb);
				}
				connectionPcb = nullptr;
			}

			if (receivedData == nullptr || timeoutExceeded)
			{
				DiscardReceivedData();
				state = (localPort == 0) ? SocketState::disabled : SocketState::listening;
			}
		}
		break;
	}

	default:
		// Nothing to do
		break;
	}

	// Restore previous disconnecting state if necessary
	if (wasShortTransfer)
	{
		state = SocketState::clientDisconnecting;
	}
}

// Discard any received data for this transaction. Acquire the lwip mutex before calling this.
void LwipSocket::DiscardReceivedData() noexcept
{
	pbuf *const rdata = receivedData;
	if (rdata != nullptr)
	{
		receivedData = nullptr;
		pbuf_free(rdata);
	}
	readIndex = 0;
}

// Send the data, returning the length buffered
size_t LwipSocket::Send(const uint8_t *data, size_t length) noexcept
{
	MutexLocker lock(lwipMutex);

	if (!CanSend())
	{
		// Don't bother if we cannot send anything at all+
		return 0;
	}

	const size_t bytesLeft = tcp_sndbuf(connectionPcb);
	if (length != 0 && bytesLeft != 0)
	{
		// See how many bytes we can send
		size_t bytesToSend = length;
		if (bytesLeft < length)
		{
			bytesToSend = bytesLeft;
		}

		// Try to send data until we succeed
		err_t err;
		do
		{
			err = tcp_write(connectionPcb, data, bytesToSend, 0);
			if (ERR_IS_FATAL(err))
			{
				Terminate();
				return 0;
			}
			else if (err == ERR_MEM)
			{
				if (bytesToSend == 1 || tcp_sndqueuelen(connectionPcb) >= TCP_SND_QUEUELEN)
				{
					// The buffers are full - try again later
					tcp_output(connectionPcb);
					return 0;
				}
				bytesToSend /= 2;
			}
		}
		while (err == ERR_MEM);

		// Try to send it now
		if (ERR_IS_FATAL(tcp_output(connectionPcb)))
		{
			Terminate();
			return 0;
		}

		// We could successfully send some data
		whenWritten = millis();
		unAcked += bytesToSend;

		return bytesToSend;
	}

	return 0;
}

#endif	// HAS_LWIP_NETWORKING

// End