forked from reprappro/RepRapFirmware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Network.cpp
1508 lines (1279 loc) · 35.8 KB
/
Network.cpp
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/****************************************************************************************************
RepRapFirmware - Network: RepRapPro Ormerod with Arduino Due controller
2014-04-05 Created from portions taken out of Platform.cpp by dc42
2014-04-07 Added portions of httpd.c. These portions are subject to the following copyright notice:
* Copyright (c) 2001-2003 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <[email protected]>
*
* (end httpd.c copyright notice)
****************************************************************************************************/
#include "RepRapFirmware.h"
#ifdef LWIP_STATS
#include "lwip/src/include/lwip/stats.h"
#endif
extern "C"
{
#include "lwipopts.h"
#include "lwip/src/include/lwip/tcp.h"
#include "contrib/apps/netbios/netbios.h"
}
static tcp_pcb *http_pcb = NULL;
static tcp_pcb *ftp_main_pcb = NULL;
static tcp_pcb *ftp_pasv_pcb = NULL;
static tcp_pcb *telnet_pcb = NULL;
static bool closingDataPort = false;
static volatile bool lwipLocked = false;
static NetworkTransaction *sendingTransaction = NULL;
static char sendingWindow[TCP_WND];
static uint16_t sendingWindowSize, sentDataOutstanding;
static uint8_t sendingRetries;
static uint16_t httpPort = 80;
// Called only by LWIP to put out a message.
// May be called from C as well as C++
extern "C" void RepRapNetworkMessage(const char* s)
{
#ifdef LWIP_DEBUG
reprap.GetPlatform()->Message(DEBUG_MESSAGE, "%s", s);
#else
reprap.GetPlatform()->Message(HOST_MESSAGE, "%s", s);
#endif
}
/*-----------------------------------------------------------------------------------*/
extern "C"
{
// Lock functions for LWIP (LWIP generally isn't thread-safe)
bool LockLWIP()
{
if (lwipLocked)
return false;
lwipLocked = true;
return true;
}
void UnlockLWIP()
{
lwipLocked = false;
}
// Callback functions for the EMAC driver (called from ISR)
static void emac_read_packet(uint32_t ul_status)
{
// Because the LWIP stack can become corrupted if we work with it in parallel,
// we may have to wait for the next Spin() call to read the next packet.
if (LockLWIP())
{
do {
// read all queued packets from the RX buffer
} while (ethernet_read());
UnlockLWIP();
}
else
{
reprap.GetNetwork()->ReadPacket();
ethernet_set_rx_callback(NULL);
}
}
// Callback functions called by LWIP (may be called from ISR)
static void conn_err(void *arg, err_t err)
{
// Report the error to the monitor
reprap.GetPlatform()->Message(HOST_MESSAGE, "Network: Connection error, code %d\n", err);
ConnectionState *cs = (ConnectionState*)arg;
if (cs != NULL)
{
reprap.GetNetwork()->ConnectionClosed(cs, false); // tell the higher levels about the error
if (sendingTransaction == cs->sendingTransaction)
{
sendingTransaction = NULL;
sentDataOutstanding = 0;
}
}
}
/*-----------------------------------------------------------------------------------*/
static err_t conn_poll(void *arg, tcp_pcb *pcb)
{
ConnectionState *cs = (ConnectionState*)arg;
if (cs != NULL && sendingTransaction != NULL && cs == sendingTransaction->GetConnection())
{
// We tried to send data, but didn't receive an ACK within reasonable time.
sendingRetries++;
if (sendingRetries == 4)
{
reprap.GetPlatform()->Message(HOST_MESSAGE, "Network: Poll received error!\n");
tcp_abort(pcb);
return ERR_ABRT;
}
// Try to send the remaining data once again
err_t err = tcp_write(pcb, sendingWindow + (sendingWindowSize - sentDataOutstanding), sentDataOutstanding, 0);
if (err == ERR_OK)
{
tcp_output(pcb);
}
else
{
reprap.GetPlatform()->Message(HOST_MESSAGE, "Network: tcp_write in conn_poll failed with code %d\n", err);
tcp_abort(pcb);
return ERR_ABRT;
}
}
return ERR_OK;
}
/*-----------------------------------------------------------------------------------*/
static err_t conn_sent(void *arg, tcp_pcb *pcb, u16_t len)
{
LWIP_UNUSED_ARG(pcb);
ConnectionState *cs = (ConnectionState*)arg;
if (cs != NULL)
{
reprap.GetNetwork()->SentPacketAcknowledged(cs, len);
}
return ERR_OK;
}
/*-----------------------------------------------------------------------------------*/
static err_t conn_recv(void *arg, tcp_pcb *pcb, pbuf *p, err_t err)
{
ConnectionState *cs = (ConnectionState*)arg;
if (err == ERR_OK && cs != NULL)
{
if (cs->pcb != pcb)
{
reprap.GetPlatform()->Message(HOST_MESSAGE, "Network: Mismatched pcb!\n");
tcp_abort(pcb);
return ERR_ABRT;
}
if (p != NULL)
{
// Tell higher levels that we are receiving data
reprap.GetNetwork()->ReceiveInput(p, cs);
}
else if (cs->persistConnection)
{
// This is called when the connection has been gracefully closed, but LWIP doesn't close these
// connections automatically. That's why we must do it once all packets have been read.
reprap.GetNetwork()->ConnectionClosedGracefully(cs);
}
}
return ERR_OK;
}
/*-----------------------------------------------------------------------------------*/
static err_t conn_accept(void *arg, tcp_pcb *pcb, err_t err)
{
LWIP_UNUSED_ARG(arg);
LWIP_UNUSED_ARG(err);
tcp_setprio(pcb, TCP_PRIO_MIN);
//RepRapNetworkMessage("conn_accept\n");
/* Allocate a new ConnectionState for this connection */
ConnectionState *cs = reprap.GetNetwork()->ConnectionAccepted(pcb);
if (cs == NULL)
{
tcp_abort(pcb);
return ERR_ABRT;
}
/* Keep the listening PCBs running */
switch (pcb->local_port) // tell LWIP to accept further connections on the listening PCB
{
case ftpPort: // FTP
tcp_accepted(ftp_main_pcb);
break;
case telnetPort: // Telnet
tcp_accepted(telnet_pcb);
break;
default: // HTTP and FTP data
tcp_accepted((pcb->local_port == httpPort) ? http_pcb : ftp_pasv_pcb);
break;
}
tcp_arg(pcb, cs); // tell LWIP that this is the structure we wish to be passed for our callbacks
tcp_recv(pcb, conn_recv); // tell LWIP that we wish to be informed of incoming data by a call to the conn_recv() function
tcp_err(pcb, conn_err);
tcp_poll(pcb, conn_poll, 4);
return ERR_OK;
}
} // end extern "C"
/*-----------------------------------------------------------------------------------*/
// These functions (are) should be called only once at the start.
void httpd_init()
{
static int httpInitCount = 0;
httpInitCount++;
if (httpInitCount > 1)
{
reprap.GetPlatform()->Message(HOST_MESSAGE, "httpd_init() called more than once.\n");
}
tcp_pcb* pcb = tcp_new();
tcp_bind(pcb, IP_ADDR_ANY, httpPort);
http_pcb = tcp_listen(pcb);
tcp_accept(http_pcb, conn_accept);
}
void ftpd_init()
{
static int ftpInitCount = 0;
ftpInitCount++;
if (ftpInitCount > 1)
{
reprap.GetPlatform()->Message(HOST_MESSAGE, "ftpd_init() called more than once.\n");
}
tcp_pcb* pcb = tcp_new();
tcp_bind(pcb, IP_ADDR_ANY, ftpPort);
ftp_main_pcb = tcp_listen(pcb);
tcp_accept(ftp_main_pcb, conn_accept);
}
void telnetd_init()
{
static int telnetInitCount = 0;
telnetInitCount++;
if (telnetInitCount > 1)
{
reprap.GetPlatform()->Message(HOST_MESSAGE, "telnetd_init() called more than once.\n");
}
tcp_pcb* pcb = tcp_new();
tcp_bind(pcb, IP_ADDR_ANY, telnetPort);
telnet_pcb = tcp_listen(pcb);
tcp_accept(telnet_pcb, conn_accept);
}
//***************************************************************************************************
// Network/Ethernet class
Network::Network(Platform* p)
: platform(p), isEnabled(true), state(NetworkInactive), readingData(false),
freeTransactions(NULL), readyTransactions(NULL), writingTransactions(NULL),
dataCs(NULL), ftpCs(NULL), telnetCs(NULL), freeSendBuffers(NULL), freeConnections(NULL)
{
for (size_t i = 0; i < networkTransactionCount; i++)
{
freeTransactions = new NetworkTransaction(freeTransactions);
}
for (size_t i = 0; i < tcpOutputBufferCount; i++)
{
freeSendBuffers = new SendBuffer(freeSendBuffers);
}
for (size_t i = 0; i < numConnections; i++)
{
ConnectionState *cs = new ConnectionState;
cs->next = freeConnections;
freeConnections = cs;
}
strcpy(hostname, HOSTNAME);
}
void Network::AppendTransaction(NetworkTransaction* volatile* list, NetworkTransaction *r)
{
r->next = NULL;
while (*list != NULL)
{
list = &((*list)->next);
}
*list = r;
}
void Network::PrependTransaction(NetworkTransaction* volatile* list, NetworkTransaction *r)
{
r->next = *list;
*list = r;
}
void Network::Init()
{
if (!isEnabled)
{
platform->Message(HOST_MESSAGE, "Attempting to start the network when it is disabled.\n");
return;
}
init_ethernet(platform->MACAddress(), hostname);
longWait = platform->Time();
state = NetworkInitializing;
}
void Network::Spin()
{
// Basically we can't do anything if we can't interact with LWIP
if (!LockLWIP())
{
platform->ClassReport(longWait);
return;
}
if (state == NetworkActive)
{
// See if we can read any packets
if (readingData)
{
readingData = false;
do {
// read all queued packets from the RX buffer
} while (ethernet_read());
ethernet_set_rx_callback(&emac_read_packet);
}
// See if we can send anything
NetworkTransaction *r = writingTransactions;
if (r != NULL && r->Send())
{
// We're done, free up this transaction
ConnectionState *cs = r->cs;
NetworkTransaction *rn = r->nextWrite;
writingTransactions = r->next;
AppendTransaction(&freeTransactions, r);
// If there is more data to write on this connection, do it next time
if (cs != NULL)
{
cs->sendingTransaction = rn;
}
if (rn != NULL)
{
PrependTransaction(&writingTransactions, rn);
}
}
}
else if (state == NetworkInitializing && establish_ethernet_link())
{
start_ethernet(platform->IPAddress(), platform->NetMask(), platform->GateWay());
ethernet_set_rx_callback(&emac_read_packet);
httpd_init();
ftpd_init();
telnetd_init();
netbios_init();
state = NetworkActive;
}
UnlockLWIP();
platform->ClassReport(longWait);
}
void Network::Interrupt()
{
if (state != NetworkInactive && LockLWIP())
{
ethernet_timers_update();
UnlockLWIP();
}
}
void Network::Diagnostics()
{
platform->AppendMessage(BOTH_MESSAGE, "Network Diagnostics:\n");
uint8_t numFreeConnections = 0;
ConnectionState *freeConn = freeConnections;
while (freeConn != NULL)
{
numFreeConnections++;
freeConn = freeConn->next;
}
platform->AppendMessage(BOTH_MESSAGE, "Free connections: %d of %d\n", numFreeConnections, numConnections);
uint8_t numFreeTransactions = 0;
NetworkTransaction *freeTrans = freeTransactions;
while (freeTrans != NULL)
{
numFreeTransactions++;
freeTrans = freeTrans->next;
}
platform->AppendMessage(BOTH_MESSAGE, "Free transactions: %d of %d\n", numFreeTransactions, networkTransactionCount);
uint16_t numFreeSendBuffs = 0;
SendBuffer *freeSendBuff = freeSendBuffers;
while (freeSendBuff != NULL)
{
numFreeSendBuffs++;
freeSendBuff = freeSendBuff->next;
}
platform->AppendMessage(BOTH_MESSAGE, "Free send buffers: %d of %d\n", numFreeSendBuffs, tcpOutputBufferCount);
#if LWIP_STATS
// Normally we should NOT try to display LWIP stats here, because it uses debugPrintf(), which will hang the system is no USB cable is connected.
if (reprap.Debug(moduleNetwork))
{
stats_display();
}
#endif
}
void Network::Enable()
{
if (!isEnabled)
{
readingData = true;
// EMAC RX callback will be reset on next Spin calls
Init();
isEnabled = true;
}
}
void Network::Disable()
{
if (isEnabled)
{
readingData = false;
ethernet_set_rx_callback(NULL);
state = NetworkInactive;
isEnabled = false;
}
}
bool Network::IsEnabled() const
{
return isEnabled;
}
uint16_t Network::GetHttpPort() const
{
return httpPort;
}
void Network::SetHttpPort(uint16_t port)
{
if (state == NetworkActive && port != httpPort)
{
// Close old HTTP port
tcp_close(http_pcb);
// Create a new one for the new port
tcp_pcb* pcb = tcp_new();
tcp_bind(pcb, IP_ADDR_ANY, port);
http_pcb = tcp_listen(pcb);
tcp_accept(http_pcb, conn_accept);
}
httpPort = port;
}
bool Network::AllocateSendBuffer(SendBuffer *&buffer)
{
buffer = freeSendBuffers;
if (buffer == NULL)
{
platform->Message(HOST_MESSAGE, "Network: Could not allocate send buffer!\n");
return false;
}
freeSendBuffers = buffer->next;
buffer->bytesToWrite = 0;
buffer->next = NULL;
return true;
}
SendBuffer *Network::ReleaseSendBuffer(SendBuffer *buffer)
{
// If we used up all available send buffers, reset freeSendBuffers here
if (freeSendBuffers == NULL)
{
freeSendBuffers = buffer;
freeSendBuffers->next = NULL;
return NULL;
}
// Get the last item in the chain
SendBuffer *lastItem = freeSendBuffers;
while (lastItem->next != NULL)
{
lastItem = lastItem->next;
}
// Append the send buffer to be released
lastItem->next = buffer;
lastItem = buffer->next;
buffer->next = NULL;
// And return the next one of the send buffer being freed
return lastItem;
}
void Network::SentPacketAcknowledged(ConnectionState *cs, unsigned int len)
{
if (cs != NULL && sendingTransaction != NULL && cs == sendingTransaction->GetConnection())
{
if (sentDataOutstanding > len)
{
sentDataOutstanding -= len;
}
else
{
sendingTransaction = NULL;
sentDataOutstanding = 0;
}
}
// debugPrintf("Network SentPacketAcknowledged: invalid cs=%08x\n", (unsigned int)cs);
}
// This is called when a connection is being established and returns an initialised ConnectionState instance.
ConnectionState *Network::ConnectionAccepted(tcp_pcb *pcb)
{
ConnectionState *cs = freeConnections;
if (cs == NULL)
{
platform->Message(HOST_MESSAGE, "Network::ConnectionAccepted() - no free ConnectionStates!\n");
return NULL;
}
NetworkTransaction* r = freeTransactions;
if (r == NULL)
{
platform->Message(HOST_MESSAGE, "Network::ConnectionAccepted() - no free transactions!\n");
return NULL;
}
freeConnections = cs->next;
cs->Init(pcb);
r->Set(NULL, cs, connected);
freeTransactions = r->next;
AppendTransaction(&readyTransactions, r);
return cs;
}
// This is called when a connection is being closed or has gone down.
// It must set the state of any NetworkTransaction that refers to it to connection lost.
void Network::ConnectionClosed(ConnectionState* cs, bool closeConnection)
{
// make sure these connections are not reused
if (cs == dataCs)
{
dataCs = NULL;
}
if (cs == ftpCs)
{
ftpCs = NULL;
}
if (cs == telnetCs)
{
telnetCs = NULL;
}
// inform the Webserver that we are about to remove an existing connection
tcp_pcb *pcb = cs->pcb;
if (pcb != NULL)
{
reprap.GetWebserver()->ConnectionLost(cs);
if (closeConnection)
{
tcp_arg(pcb, NULL);
tcp_sent(pcb, NULL);
tcp_recv(pcb, NULL);
tcp_poll(pcb, NULL, 4);
tcp_close(pcb);
cs->pcb = NULL;
}
}
// cs points to a connection state block that the caller is about to release, so we need to stop referring to it.
// There may be one NetworkTransaction in the writing or closing list referring to it, and possibly more than one in the ready list.
for (NetworkTransaction* r = readyTransactions; r != NULL; r = r->next)
{
if (r->cs == cs)
{
r->SetConnectionLost();
}
}
if (cs->sendingTransaction != NULL)
{
cs->sendingTransaction->SetConnectionLost();
cs->sendingTransaction = NULL;
}
cs->next = freeConnections;
freeConnections = cs;
}
void Network::ConnectionClosedGracefully(ConnectionState *cs)
{
NetworkTransaction* r = freeTransactions;
if (r == NULL)
{
platform->Message(HOST_MESSAGE, "Network::ConnectionClosedGracefully() - no free transactions!\n");
return;
}
freeTransactions = r->next;
r->Set(NULL, cs, disconnected);
AppendTransaction(&readyTransactions, r);
}
bool Network::Lock()
{
return LockLWIP();
}
void Network::Unlock()
{
UnlockLWIP();
}
bool Network::InLwip() const
{
return lwipLocked;
}
void Network::ReadPacket()
{
readingData = true;
}
void Network::ReceiveInput(pbuf *pb, ConnectionState* cs)
{
NetworkTransaction* r = freeTransactions;
if (r == NULL)
{
platform->Message(HOST_MESSAGE, "Network::ReceiveInput() - no free transactions!\n");
return;
}
freeTransactions = r->next;
r->Set(pb, cs, dataReceiving);
AppendTransaction(&readyTransactions, r);
// debugPrintf("Network - input received\n");
}
// This is called by the web server to get a new received packet.
// If the connection parameter is NULL, we just return the request at the head of the ready list.
// Otherwise, we are only interested in packets received from the specified connection. If we find one than
// we move it to the head of the ready list, so that a subsequent call with a null connection parameter
// will return the same one.
NetworkTransaction *Network::GetTransaction(const ConnectionState *cs)
{
// See if there is any transaction at all
NetworkTransaction *rs = readyTransactions;
if (rs == NULL)
{
return NULL;
}
// If we're waiting for a new connection on a data port, see if there is a matching transaction available
if (cs == NULL && rs->waitingForDataConnection)
{
const uint16_t localPort = rs->GetLocalPort();
for (NetworkTransaction *rsNext = rs->next; rsNext != NULL; rsNext = rs->next)
{
if (rsNext->status == connected && rsNext->GetLocalPort() > 1023)
{
rs->next = rsNext->next; // remove rsNext from the list
rsNext->next = readyTransactions;
readyTransactions = rsNext;
return rsNext;
}
rs = rsNext;
}
return readyTransactions; // nothing found, process this transaction once again
}
// See if the first one is the transaction we're looking for
if (cs == NULL || rs->cs == cs)
{
return rs;
}
// There is at least one ready transaction, but it's not on the connection we are looking for
for (NetworkTransaction *rsNext = rs->next; rsNext != NULL; rsNext = rs->next)
{
if (rsNext->cs == cs)
{
rs->next = rsNext->next; // remove rsNext from the list
rsNext->next = readyTransactions;
readyTransactions = rsNext;
return rsNext;
}
rs = rsNext;
}
return NULL;
}
// Send the output data we already have, optionally with a file appended, then close the connection unless keepConnectionOpen is true.
// The file may be too large for our buffer, so we may have to send it in multiple transactions.
void Network::SendAndClose(FileStore *f, bool keepConnectionOpen)
{
NetworkTransaction *r = readyTransactions;
if (r == NULL)
{
return;
}
if (r->status == dataSending)
{
// This transaction is already in use for sending (e.g. a Telnet request),
// so all we have to do is to remove it from readyTransactions.
readyTransactions = r->next;
}
else
{
readyTransactions = r->next;
if (r->LostConnection())
{
if (f != NULL)
{
f->Close();
}
while (r->sendBuffer != NULL)
{
r->sendBuffer = ReleaseSendBuffer(r->sendBuffer);
}
AppendTransaction(&freeTransactions, r);
// debugPrintf("Conn lost before send\n");
}
else
{
r->FreePbuf();
r->cs->persistConnection = keepConnectionOpen;
r->fileBeingSent = f;
r->status = dataSending;
if (f != NULL && r->sendBuffer == NULL)
{
SendBuffer *buf;
if (AllocateSendBuffer(buf))
{
r->sendBuffer = buf;
r->fileBeingSent = f;
}
else
{
r->fileBeingSent = NULL;
// debugPrintf("Could not allocate send buffer for file transfer!\n");
}
}
NetworkTransaction *mySendingTransaction = r->cs->sendingTransaction;
if (mySendingTransaction == NULL)
{
r->cs->sendingTransaction = r;
AppendTransaction(&writingTransactions, r);
//debug
// r->outputBuffer[r->outputPointer] = 0;
// debugPrintf("Transaction queued for writing to network, file=%c, data=%s\n", (f ? 'Y' : 'N'), r->outputBuffer);
}
else
{
while (mySendingTransaction->nextWrite != NULL)
{
mySendingTransaction = mySendingTransaction->nextWrite;
}
mySendingTransaction->nextWrite = r;
// debugPrintf("Transaction appended to sending RS\n");
}
}
}
}
// We have no data to write and we want to keep the current connection alive if possible.
// That way we can speed up freeing the current NetworkTransaction.
void Network::CloseTransaction()
{
// Free the current NetworkTransaction's data (if any)
NetworkTransaction *r = readyTransactions;
if (r == NULL)
{
return;
}
r->FreePbuf();
// Terminate this connection if this NetworkTransaction indicates a graceful disconnect
TransactionStatus status = r->status;
if (!r->LostConnection() && status == disconnected)
{
// debugPrintf("Network: CloseRequest is closing connection cs=%08x\n", (unsigned int)locCs);
ConnectionClosed(r->cs, true);
}
// Remove the current item from readyTransactions
readyTransactions = r->next;
// Append it to freeTransactions again unless it's already on another list
if (status != dataSending)
{
AppendTransaction(&freeTransactions, r);
}
}
// The current NetworkTransaction must be processed again,
// e.g. because we're still waiting for another data connection.
void Network::WaitForDataConection()
{
NetworkTransaction *r = readyTransactions;
r->waitingForDataConnection = true;
r->inputPointer = 0; // behave as if this request hasn't been processed yet
}
void Network::OpenDataPort(uint16_t port)
{
closingDataPort = false;
tcp_pcb* pcb = tcp_new();
tcp_bind(pcb, IP_ADDR_ANY, port);
ftp_pasv_pcb = tcp_listen(pcb);
tcp_accept(ftp_pasv_pcb, conn_accept);
}
uint16_t Network::GetDataPort() const
{
return (closingDataPort || (ftp_pasv_pcb == NULL) ? 0 : ftp_pasv_pcb->local_port);
}
// Close FTP data port and purge associated PCB
void Network::CloseDataPort()
{
// See if it's already being closed
if (closingDataPort)
{
return;
}
closingDataPort = true;
// Close remote connection of our data port or do it as soon as the current transaction has finished
if (dataCs != NULL && dataCs->pcb != NULL)
{
NetworkTransaction *mySendingTransaction = dataCs->sendingTransaction;
if (mySendingTransaction != NULL)
{
mySendingTransaction->Close();
return;
}
}
// We can close it now, so do it here
if (ftp_pasv_pcb != NULL)
{
tcp_accept(ftp_pasv_pcb, NULL);
tcp_close(ftp_pasv_pcb);
ftp_pasv_pcb = NULL;
}
closingDataPort = false;
}
// These methods keep track of our connections in case we need to send to one of them
void Network::SaveDataConnection()
{
dataCs = readyTransactions->cs;
}
void Network::SaveFTPConnection()
{
ftpCs = readyTransactions->cs;
}
void Network::SaveTelnetConnection()
{
telnetCs = readyTransactions->cs;
}
// Check if there are enough resources left to allocate another NetworkTransaction for sending
bool Network::CanAcquireTransaction()
{
if (freeTransactions == NULL)
{
return false;
}
return (freeSendBuffers != NULL);
}
bool Network::AcquireFTPTransaction()
{
return AcquireTransaction(ftpCs);
}
bool Network::AcquireDataTransaction()
{
return AcquireTransaction(dataCs);
}
bool Network::AcquireTelnetTransaction()
{
return AcquireTransaction(telnetCs);
}
// Retrieves the NetworkTransaction of a sending connection to which data can be appended to,
// or prepares a released NetworkTransaction, which can easily be sent via SendAndClose.
bool Network::AcquireTransaction(ConnectionState *cs)
{
// Make sure we have a valid connection
if (cs == NULL)
{
return false;
}