tftp_server_misc.c
Go to the documentation of this file.
1 /**
2  * @file tftp_server_misc.c
3  * @brief Helper functions for TFTP server
4  *
5  * @section License
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  *
9  * Copyright (C) 2010-2026 Oryx Embedded SARL. All rights reserved.
10  *
11  * This file is part of CycloneTCP Open.
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * as published by the Free Software Foundation; either version 2
16  * of the License, or (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26  *
27  * @author Oryx Embedded SARL (www.oryx-embedded.com)
28  * @version 2.6.8
29  **/
30 
31 //Switch to the appropriate trace level
32 #define TRACE_LEVEL TFTP_TRACE_LEVEL
33 
34 //Dependencies
35 #include "core/net.h"
36 #include "tftp/tftp_server.h"
37 #include "tftp/tftp_server_misc.h"
38 #include "debug.h"
39 
40 //Check TCP/IP stack configuration
41 #if (TFTP_SERVER_SUPPORT == ENABLED)
42 
43 
44 /**
45  * @brief Handle periodic operations
46  * @param[in] context Pointer to the TFTP server context
47  **/
48 
50 {
51  uint_t i;
53  TftpClientConnection *connection;
54 
55  //Get current time
57 
58  //Handle periodic operations
59  for(i = 0; i < TFTP_SERVER_MAX_CONNECTIONS; i++)
60  {
61  //Point to the structure describing the current connection
62  connection = &context->connection[i];
63 
64  //Check current state
65  if(connection->state == TFTP_STATE_READING ||
66  connection->state == TFTP_STATE_WRITING ||
67  connection->state == TFTP_STATE_READ_COMPLETE)
68  {
69  //Check current time
70  if((time - connection->timestamp) >= TFTP_SERVER_TIMEOUT)
71  {
72  //Handle retransmissions
73  if(connection->retransmitCount < TFTP_SERVER_MAX_RETRIES)
74  {
75  //Retransmit the last packet
76  tftpServerRetransmitPacket(connection);
77 
78  //Save the time at which the packet was sent
79  connection->timestamp = osGetSystemTime();
80  //Increment retransmission counter
81  connection->retransmitCount++;
82  }
83  else
84  {
85  //Close connection
86  tftpServerCloseConnection(connection);
87  }
88  }
89  }
90  else if(connection->state == TFTP_STATE_WRITE_COMPLETE)
91  {
92  //The host sending the final ACK will wait for a while before
93  //terminating in order to retransmit the final ACK if it has been
94  //lost (refer to RFC 1350, section 6)
95  if((time - connection->timestamp) >= TFTP_SERVER_FINAL_DELAY)
96  {
97  //Close connection
98  tftpServerCloseConnection(connection);
99  }
100  }
101  }
102 }
103 
104 
105 /**
106  * @brief Find a connection that matches a given client
107  * @param[in] context Pointer to the TFTP server context
108  * @param[in] interface Network interface
109  * @param[in] clientIpAddr IP address of the client
110  * @param[in] clientPort Port number used by the client
111  * @return Pointer to the matching connection, if any
112  **/
113 
115  NetInterface *interface, const IpAddr *clientIpAddr, uint16_t clientPort)
116 {
117  uint_t i;
118  TftpClientConnection *connection;
119 
120  //Loop through the connection table
121  for(i = 0; i < TFTP_SERVER_MAX_CONNECTIONS; i++)
122  {
123  //Point to the current entry
124  connection = &context->connection[i];
125 
126  //Check the state of the current connection
127  if(connection->state != TFTP_STATE_CLOSED)
128  {
129  //Matching connection found?
130  if(connection->interface == interface &&
131  ipCompAddr(&connection->clientIpAddr, clientIpAddr) &&
132  connection->clientPort == clientPort)
133  {
134  return connection;
135  }
136  }
137  }
138 
139  //No matching connection found
140  return NULL;
141 }
142 
143 
144 /**
145  * @brief Create a new connection
146  * @param[in] context Pointer to the TFTP server context
147  * @param[in] interface Network interface to be used
148  * @param[in] clientIpAddr IP address of the client
149  * @param[in] clientPort Port number used by the client
150  * @return Pointer to the structure describing the connection
151  **/
152 
154  NetInterface *interface, const IpAddr *clientIpAddr, uint16_t clientPort)
155 {
156  error_t error;
157  uint_t i;
158  systime_t time;
159  Socket *socket;
160  TftpClientConnection *connection;
161  TftpClientConnection *oldestConnection;
162 
163  //Get current time
164  time = osGetSystemTime();
165 
166  //Keep track of the oldest connection that is waiting to retransmit
167  //the final ACK
168  oldestConnection = NULL;
169 
170  //Loop through the connection table
171  for(i = 0; i < TFTP_SERVER_MAX_CONNECTIONS; i++)
172  {
173  //Point to the current entry
174  connection = &context->connection[i];
175 
176  //Check the state of the current connection
177  if(connection->state == TFTP_STATE_CLOSED)
178  {
179  //The current entry is available
180  break;
181  }
182  else if(connection->state == TFTP_STATE_WRITE_COMPLETE)
183  {
184  //Keep track of the oldest connection that is waiting to retransmit
185  //the final ACK
186  if(oldestConnection == NULL)
187  {
188  oldestConnection = connection;
189  }
190  else if((time - connection->timestamp) > (time - oldestConnection->timestamp))
191  {
192  oldestConnection = connection;
193  }
194  }
195  }
196 
197  //The oldest connection that is waiting to retransmit the final ACK can be
198  //reused when the connection table runs out of space
200  {
201  //Close the oldest connection
202  tftpServerCloseConnection(oldestConnection);
203  //Reuse the connection
204  connection = oldestConnection;
205  }
206 
207  //Valid connection?
208  if(connection != NULL)
209  {
210  //Open a UDP socket
211  socket = socketOpenEx(context->netContext, SOCKET_TYPE_DGRAM,
213 
214  //Valid socket handle?
215  if(socket != NULL)
216  {
217  //Associate the socket with the relevant interface
218  error = socketBindToInterface(socket, interface);
219 
220  //Check status code
221  if(!error)
222  {
223  //Connect the socket to the remote TFTP client
224  error = socketConnect(socket, clientIpAddr, clientPort);
225  }
226 
227  //Check status code
228  if(!error)
229  {
230  //Clear the structure describing the connection
231  osMemset(connection, 0, sizeof(TftpClientConnection));
232 
233  //Attach TFTP server context
234  connection->context = context;
235  //Attach socket handle
236  connection->socket = socket;
237 
238  //Save client's parameters
239  connection->interface = interface;
240  connection->clientIpAddr = *clientIpAddr;
241  connection->clientPort = clientPort;
242 
243  //Update connection state
244  connection->state = TFTP_STATE_OPEN;
245  }
246  else
247  {
248  //Clean up side effects
250  }
251  }
252  else
253  {
254  //Failed to open socket
255  error = ERROR_OPEN_FAILED;
256  }
257  }
258 
259  //Pointer to the structure describing the connection
260  return (error == NO_ERROR) ? connection : NULL;
261 }
262 
263 
264 /**
265  * @brief Close connection
266  * @param[in] connection Pointer to the client connection
267  **/
268 
270 {
271  //Valid connection?
272  if(connection != NULL)
273  {
274  //Debug message
275  TRACE_INFO("TFTP Server: Closing connection...\r\n");
276 
277  //Any active connection?
278  if(connection->socket != NULL)
279  {
280  //Close UDP socket
281  socketClose(connection->socket);
282  connection->socket = NULL;
283  }
284 
285  //Check whether a read or write operation is in progress
286  if(connection->file != NULL)
287  {
288  //Properly close the file before closing the connection
289  if(connection->context->closeFileCallback != NULL)
290  {
291  //Invoke user callback function
292  connection->context->closeFileCallback(connection->file);
293  }
294 
295  //Mark the file as closed
296  connection->file = NULL;
297  }
298 
299  //Mark the connection as closed
300  connection->state = TFTP_STATE_CLOSED;
301  }
302 }
303 
304 
305 /**
306  * @brief Accept connection request
307  * @param[in] context Pointer to the TFTP server context
308  **/
309 
311 {
312  error_t error;
313  uint16_t opcode;
314  SocketMsg msg;
315 
316  //Point to the receive buffer
317  msg = SOCKET_DEFAULT_MSG;
318  msg.data = context->packet;
320 
321  //Read incoming TFTP packet
322  error = socketReceiveMsg(context->socket, &msg, 0);
323 
324  //Check status code
325  if(!error)
326  {
327  //Make sure the length of the packet is acceptable
328  if(msg.length >= sizeof(uint16_t))
329  {
330  //Debug message
331  TRACE_INFO("TFTP Server: Accepting connection from %s port %" PRIu16 "...\r\n",
332  ipAddrToString(&msg.srcIpAddr, NULL), msg.srcPort);
333 
334  //The TFTP header consists of a 2 byte opcode field which indicates
335  //the packet's type (refer to RFC 1350, section 3)
336  opcode = LOAD16BE(context->packet);
337 
338  //Check packet type
339  if(opcode == TFTP_OPCODE_RRQ)
340  {
341  //Process RRQ packet
343  msg.srcPort, (TftpRrqPacket *) context->packet, msg.length);
344  }
345  else if(opcode == TFTP_OPCODE_WRQ)
346  {
347  //Process WRQ packet
349  msg.srcPort, (TftpWrqPacket *) context->packet, msg.length);
350  }
351  else
352  {
353  //Discard incoming packet
354  }
355  }
356  }
357 }
358 
359 
360 /**
361  * @brief Process incoming packet
362  * @param[in] context Pointer to the TFTP server context
363  * @param[in] connection Pointer to the client connection
364  **/
365 
367  TftpClientConnection *connection)
368 {
369  error_t error;
370  size_t length;
371  uint16_t opcode;
372  IpAddr clientIpAddr;
373  uint16_t clientPort;
374 
375  //Read incoming TFTP packet
376  error = socketReceiveFrom(connection->socket, &clientIpAddr, &clientPort,
377  context->packet, TFTP_SERVER_MAX_PACKET_SIZE, &length, 0);
378 
379  //Check status code
380  if(!error)
381  {
382  //Make sure the length of the packet is acceptable
383  if(length >= sizeof(uint16_t))
384  {
385  //The TFTP header consists of a 2 byte opcode field which indicates
386  //the packet's type (refer to RFC 1350, section 3)
387  opcode = LOAD16BE(context->packet);
388 
389  //Check packet type
390  if(opcode == TFTP_OPCODE_DATA)
391  {
392  //Process DATA packet
393  tftpServerProcessDataPacket(connection,
394  (TftpDataPacket *) context->packet, length);
395  }
396  else if(opcode == TFTP_OPCODE_ACK)
397  {
398  //Process ACK packet
399  tftpServerProcessAckPacket(connection,
400  (TftpAckPacket *) context->packet, length);
401  }
402  else if(opcode == TFTP_OPCODE_ERROR)
403  {
404  //Process ERROR packet
405  tftpServerProcessErrorPacket(connection,
406  (TftpErrorPacket *) context->packet, length);
407  }
408  else
409  {
410  //Discard incoming packet
411  }
412  }
413  }
414 }
415 
416 
417 /**
418  * @brief Process incoming RRQ packet
419  * @param[in] context Pointer to the TFTP server context
420  * @param[in] interface Network interface on which the packet was received
421  * @param[in] clientIpAddr IP address of the client
422  * @param[in] clientPort Port number used by the client
423  * @param[in] rrqPacket Pointer to the RRQ packet
424  * @param[in] length Length of the packet, in bytes
425  **/
426 
428  NetInterface *interface, const IpAddr *clientIpAddr, uint16_t clientPort,
429  const TftpRrqPacket *rrqPacket, size_t length)
430 {
431  const char_t *mode;
432  TftpClientConnection *connection;
433 
434  //Debug message
435  TRACE_DEBUG("TFTP Server: RRQ packet received (%" PRIuSIZE " bytes)...\r\n",
436  length);
437 
438  //Make sure the length of the RRQ packet is acceptable
439  if(length <= sizeof(TftpRrqPacket))
440  {
441  return;
442  }
443 
444  //Compute the number of bytes that follows the 2-byte opcode
445  length -= sizeof(TftpRrqPacket);
446 
447  //Point to the incoming RRQ packet
448  rrqPacket = (TftpRrqPacket *) context->packet;
449 
450  //Malformed RRQ packet?
451  if(rrqPacket->filename[length - 1] != '\0')
452  {
453  return;
454  }
455 
456  //Compute the length of the mode string
457  length -= osStrlen(rrqPacket->filename) + 1;
458 
459  //Malformed RRQ packet?
460  if(length == 0)
461  {
462  return;
463  }
464 
465  //Point to the mode string
466  mode = rrqPacket->filename + osStrlen(rrqPacket->filename) + 1;
467 
468  //Debug message
469  TRACE_DEBUG(" Opcode = %u\r\n", ntohs(rrqPacket->opcode));
470  TRACE_DEBUG(" Filename = %s\r\n", rrqPacket->filename);
471  TRACE_DEBUG(" Mode = %s\r\n", mode);
472 
473  //Check whether a matching connection exists
474  connection = tftpServerFindConnection(context, interface, clientIpAddr,
475  clientPort);
476 
477  //Matching connection found?
478  if(connection != NULL)
479  {
480  //Retransmit the first DATA packet
481  tftpServerRetransmitPacket(connection);
482  }
483  else
484  {
485  //Create a new connection
486  connection = tftpServerOpenConnection(context, interface, clientIpAddr,
487  clientPort);
488 
489  //Valid connection?
490  if(connection != NULL)
491  {
492  //Open the specified file for reading
493  if(context->openFileCallback != NULL)
494  {
495  //Invoke user callback function
496  connection->file = context->openFileCallback(rrqPacket->filename,
497  mode, FALSE);
498  }
499  else
500  {
501  //No callback function defined
502  connection->file = NULL;
503  }
504 
505  //Check if the file was successfully opened
506  if(connection->file != NULL)
507  {
508  //The read operation is in progress
509  connection->state = TFTP_STATE_READING;
510  //Initialize block number
511  connection->block = 1;
512  //The first block starts at the beginning of the file
513  connection->offset = 0;
514 
515  //Send the first DATA packet
516  tftpServerSendDataPacket(connection);
517  }
518  else
519  {
520  //If the reply is an error packet, then the request has been denied
521  //refer to RFC 1350, section 4)
523  "Failed to open file");
524 
525  //Close the connection
526  tftpServerCloseConnection(connection);
527  }
528  }
529  }
530 }
531 
532 
533 /**
534  * @brief Process incoming WRQ packet
535  * @param[in] context Pointer to the TFTP server context
536  * @param[in] interface Network interface on which the packet was received
537  * @param[in] clientIpAddr IP address of the client
538  * @param[in] clientPort Port number used by the client
539  * @param[in] wrqPacket Pointer to the WRQ packet
540  * @param[in] length Length of the packet, in bytes
541  **/
542 
544  NetInterface *interface, const IpAddr *clientIpAddr, uint16_t clientPort,
545  const TftpWrqPacket *wrqPacket, size_t length)
546 {
547  const char_t *mode;
548  TftpClientConnection *connection;
549 
550  //Debug message
551  TRACE_DEBUG("TFTP Server: WRQ packet received (%" PRIuSIZE " bytes)...\r\n",
552  length);
553 
554  //Make sure the length of the WRQ packet is acceptable
555  if(length <= sizeof(TftpWrqPacket))
556  {
557  return;
558  }
559 
560  //Compute the number of bytes that follows the 2-byte opcode
561  length -= sizeof(TftpWrqPacket);
562 
563  //Point to the incoming WRQ packet
564  wrqPacket = (TftpWrqPacket *) context->packet;
565 
566  //Malformed WRQ packet?
567  if(wrqPacket->filename[length - 1] != '\0')
568  {
569  return;
570  }
571 
572  //Compute the length of the mode string
573  length -= osStrlen(wrqPacket->filename) + 1;
574 
575  //Malformed WRQ packet?
576  if(length == 0)
577  {
578  return;
579  }
580 
581  //Point to the mode string
582  mode = wrqPacket->filename + osStrlen(wrqPacket->filename) + 1;
583 
584  //Debug message
585  TRACE_DEBUG(" Opcode = %u\r\n", ntohs(wrqPacket->opcode));
586  TRACE_DEBUG(" Filename = %s\r\n", wrqPacket->filename);
587  TRACE_DEBUG(" Mode = %s\r\n", mode);
588 
589  //Check whether a matching connection exists
590  connection = tftpServerFindConnection(context, interface, clientIpAddr,
591  clientPort);
592 
593  //Matching connection found?
594  if(connection != NULL)
595  {
596  //Retransmit the ACK packet
597  tftpServerRetransmitPacket(connection);
598  }
599  else
600  {
601  //Create a new connection
602  connection = tftpServerOpenConnection(context, interface, clientIpAddr,
603  clientPort);
604 
605  //Valid connection?
606  if(connection != NULL)
607  {
608  //Open the specified file for writing
609  if(context->openFileCallback != NULL)
610  {
611  //Invoke user callback function
612  connection->file = context->openFileCallback(wrqPacket->filename,
613  mode, TRUE);
614  }
615  else
616  {
617  //No callback function defined
618  connection->file = NULL;
619  }
620 
621  //Check if the file was successfully opened
622  if(connection->file != NULL)
623  {
624  //The write operation is in progress
625  connection->state = TFTP_STATE_WRITING;
626  //Initialize block number
627  connection->block = 0;
628  //The first block starts at the beginning of the file
629  connection->offset = 0;
630 
631  //The positive response to a write request is an acknowledgment
632  //packet with block number zero
633  tftpServerSendAckPacket(connection);
634 
635  //Increment block number
636  connection->block++;
637  }
638  else
639  {
640  //If the reply is an error packet, then the request has been denied
641  //refer to RFC 1350, section 4)
643  "Failed to open file");
644 
645  //Close the connection
646  tftpServerCloseConnection(connection);
647  }
648  }
649  }
650 }
651 
652 
653 /**
654  * @brief Process incoming DATA packet
655  * @param[in] connection Pointer to the client connection
656  * @param[in] dataPacket Pointer to the DATA packet
657  * @param[in] length Length of the packet, in bytes
658  **/
659 
661  const TftpDataPacket *dataPacket, size_t length)
662 {
663  error_t error;
664 
665  //Debug message
666  TRACE_DEBUG("TFTP Server: DATA packet received (%" PRIuSIZE " bytes)...\r\n",
667  length);
668 
669  //Make sure the length of the DATA packet is acceptable
670  if(length < sizeof(TftpDataPacket))
671  {
672  return;
673  }
674 
675  //Calculate the length of the data
676  length -= sizeof(TftpDataPacket);
677 
678  //Debug message
679  TRACE_DEBUG(" Opcode = %" PRIu16 "\r\n", ntohs(dataPacket->opcode));
680  TRACE_DEBUG(" Block = %" PRIu16 "\r\n", ntohs(dataPacket->block));
681 
682  //Check current state
683  if(connection->state == TFTP_STATE_WRITING)
684  {
685  //Check block number
686  if(ntohs(dataPacket->block) == connection->block)
687  {
688  //Make sure the whole block lies within the range of representable
689  //file offsets
690  if(connection->offset <= (SIZE_MAX - TFTP_SERVER_BLOCK_SIZE))
691  {
692  //Write data to the output file
693  if(connection->context->writeFileCallback != NULL)
694  {
695  //Invoke user callback function
696  error = connection->context->writeFileCallback(connection->file,
697  connection->offset, dataPacket->data, length);
698  }
699  else
700  {
701  //No callback function defined
702  error = ERROR_WRITE_FAILED;
703  }
704  }
705  else
706  {
707  //The file is too large to be transferred
708  error = ERROR_OUT_OF_RANGE;
709  }
710 
711  //Check status code
712  if(!error)
713  {
714  //Acknowledge the DATA packet
715  tftpServerSendAckPacket(connection);
716 
717  //Increment block number
718  connection->block++;
719 
720  //A data packet of less than 512 bytes signals termination of the transfer
722  {
723  //Properly close the file
724  if(connection->context->closeFileCallback != NULL)
725  {
726  //Invoke user callback function
727  connection->context->closeFileCallback(connection->file);
728  }
729 
730  //Mark the file as closed
731  connection->file = NULL;
732 
733  //The host sending the final ACK will wait for a while before terminating
734  //in order to retransmit the final ACK if it has been lost
735  connection->state = TFTP_STATE_WRITE_COMPLETE;
736 
737  //Save current time
738  connection->timestamp = osGetSystemTime();
739  }
740  else
741  {
742  //Offset of the next block
743  connection->offset += TFTP_SERVER_BLOCK_SIZE;
744  }
745  }
746  else if(error == ERROR_OUT_OF_RANGE)
747  {
748  //The file is too large to be transferred
750  "File too large");
751 
752  //A TFTP server may terminate after sending an error message
753  tftpServerCloseConnection(connection);
754  }
755  else
756  {
757  //An error occurs during the transfer
759  "Failed to write file");
760 
761  //A TFTP server may terminate after sending an error message
762  tftpServerCloseConnection(connection);
763  }
764  }
765  else
766  {
767  //Retransmit the ACK packet
768  tftpServerRetransmitPacket(connection);
769  }
770  }
771  else if(connection->state == TFTP_STATE_WRITE_COMPLETE)
772  {
773  //The acknowledger will know that the ACK has been lost if it receives
774  //the final DATA packet again (refer to RFC 1350, section 6)
775  tftpServerRetransmitPacket(connection);
776  }
777 }
778 
779 
780 /**
781  * @brief Process incoming ACK packet
782  * @param[in] connection Pointer to the client connection
783  * @param[in] ackPacket Pointer to the ACK packet
784  * @param[in] length Length of the packet, in bytes
785  **/
786 
788  const TftpAckPacket *ackPacket, size_t length)
789 {
790  //Debug message
791  TRACE_DEBUG("TFTP Server: ACK packet received (%" PRIuSIZE " bytes)...\r\n",
792  length);
793 
794  //Make sure the length of the ACK packet is acceptable
795  if(length < sizeof(TftpAckPacket))
796  {
797  return;
798  }
799 
800  //Debug message
801  TRACE_DEBUG(" Opcode = %" PRIu16 "\r\n", ntohs(ackPacket->opcode));
802  TRACE_DEBUG(" Block = %" PRIu16 "\r\n", ntohs(ackPacket->block));
803 
804  //Check current state
805  if(connection->state == TFTP_STATE_READING)
806  {
807  //Make sure the ACK is not a duplicate
808  if(ntohs(ackPacket->block) == connection->block)
809  {
810  //The block number increases by one for each new block of data
811  connection->block++;
812  //The file offset is maintained separately
813  connection->offset += TFTP_SERVER_BLOCK_SIZE;
814 
815  //Send DATA packet
816  tftpServerSendDataPacket(connection);
817  }
818  else
819  {
820  //Implementations must never resend the current DATA packet on
821  //receipt of a duplicate ACK (refer to RFC 1123, section 4.2.3.1)
822  }
823  }
824  else if(connection->state == TFTP_STATE_READ_COMPLETE)
825  {
826  //Make sure the ACK is not a duplicate
827  if(ntohs(ackPacket->block) == connection->block)
828  {
829  //The host sending the last DATA must retransmit it until the packet
830  //is acknowledged or the sending host times out. If the response is an
831  //ACK, the transmission was completed successfully (refer to RFC 1350,
832  //section 6)
833  tftpServerCloseConnection(connection);
834  }
835  }
836 }
837 
838 
839 /**
840  * @brief Process incoming ERROR packet
841  * @param[in] connection Pointer to the client connection
842  * @param[in] errorPacket Pointer to the ERROR packet
843  * @param[in] length Length of the packet, in bytes
844  **/
845 
847  const TftpErrorPacket *errorPacket, size_t length)
848 {
849  //Debug message
850  TRACE_DEBUG("TFTP Server: ERROR packet received (%" PRIuSIZE " bytes)...\r\n",
851  length);
852 
853  //Make sure the length of the ERROR packet is acceptable
854  if(length < sizeof(TftpErrorPacket))
855  {
856  return;
857  }
858 
859  //Debug message
860  TRACE_DEBUG(" Opcode = %" PRIu16 "\r\n", ntohs(errorPacket->opcode));
861  TRACE_DEBUG(" Error Code = %" PRIu16 "\r\n", ntohs(errorPacket->errorCode));
862 
863  //Compute the length of the error message
864  length -= sizeof(TftpErrorPacket);
865 
866  //Make sure the error message is terminated with a zero byte
867  if(length > 1 && errorPacket->errorMsg[length - 1] == '\0')
868  {
869  //Debug message
870  TRACE_DEBUG(" Error Msg = %s\r\n", errorPacket->errorMsg);
871  }
872 
873  //Close connection
874  tftpServerCloseConnection(connection);
875 }
876 
877 
878 /**
879  * @brief Send DATA packet
880  * @param[in] connection Pointer to the client connection
881  * @return Error code
882  **/
883 
885 {
886  error_t error;
887  TftpDataPacket *dataPacket;
888 
889  //Point to the buffer where to format the packet
890  dataPacket = (TftpDataPacket *) connection->packet;
891 
892  //Format DATA packet
893  dataPacket->opcode = HTONS(TFTP_OPCODE_DATA);
894  dataPacket->block = htons(connection->block);
895 
896  //Make sure the whole block lies within the range of representable file
897  //offsets
898  if(connection->offset <= (SIZE_MAX - TFTP_SERVER_BLOCK_SIZE))
899  {
900  //Read more data from the input file
901  if(connection->context->readFileCallback != NULL)
902  {
903  //Invoke user callback function
904  error = connection->context->readFileCallback(connection->file,
905  connection->offset, dataPacket->data, TFTP_SERVER_BLOCK_SIZE,
906  &connection->packetLen);
907 
908  //End of file?
909  if(error == ERROR_END_OF_FILE || error == ERROR_END_OF_STREAM)
910  {
911  //Catch exception
912  error = NO_ERROR;
913  //This is the last block of data
914  connection->packetLen = 0;
915  }
916  }
917  else
918  {
919  //No callback function defined
920  error = ERROR_READ_FAILED;
921  }
922  }
923  else
924  {
925  //The file is too large to be transferred
926  error = ERROR_OUT_OF_RANGE;
927  }
928 
929  //Check status code
930  if(!error)
931  {
932  //A data packet of less than 512 bytes signals termination of the transfer
933  if(connection->packetLen < TFTP_SERVER_BLOCK_SIZE)
934  {
935  //Properly close the file
936  if(connection->context->closeFileCallback != NULL)
937  {
938  //Invoke user callback function
939  connection->context->closeFileCallback(connection->file);
940  }
941 
942  //Mark the file as closed
943  connection->file = NULL;
944 
945  //The host sending the last DATA must retransmit it until the packet
946  //is acknowledged or the sending host times out
947  connection->state = TFTP_STATE_READ_COMPLETE;
948  }
949 
950  //Length of the DATA packet
951  connection->packetLen += sizeof(TftpAckPacket);
952 
953  //Debug message
954  TRACE_DEBUG("TFTP Server: Sending DATA packet (%" PRIuSIZE " bytes)...\r\n", connection->packetLen);
955  TRACE_DEBUG(" Opcode = %" PRIu16 "\r\n", ntohs(dataPacket->opcode));
956  TRACE_DEBUG(" Block = %" PRIu16 "\r\n", ntohs(dataPacket->block));
957 
958  //Send DATA packet
959  error = socketSend(connection->socket, connection->packet,
960  connection->packetLen, NULL, 0);
961 
962  //Save the time at which the packet was sent
963  connection->timestamp = osGetSystemTime();
964  //Reset retransmission counter
965  connection->retransmitCount = 0;
966  }
967  else if(error == ERROR_OUT_OF_RANGE)
968  {
969  //The file is too large to be transferred
971  "File too large");
972 
973  //A TFTP server may terminate after sending an error message
974  tftpServerCloseConnection(connection);
975  }
976  else
977  {
978  //An error occurs during the transfer
980  "Failed to read file");
981 
982  //A TFTP server may terminate after sending an error message
983  tftpServerCloseConnection(connection);
984  }
985 
986  //Return status code
987  return error;
988 }
989 
990 
991 /**
992  * @brief Send ACK packet
993  * @param[in] connection Pointer to the client connection
994  * @return Error code
995  **/
996 
998 {
999  error_t error;
1000  TftpAckPacket *ackPacket;
1001 
1002  //Point to the buffer where to format the packet
1003  ackPacket = (TftpAckPacket *) connection->packet;
1004 
1005  //Format ACK packet
1006  ackPacket->opcode = HTONS(TFTP_OPCODE_ACK);
1007  ackPacket->block = htons(connection->block);
1008 
1009  //Length of the ACK packet
1010  connection->packetLen = sizeof(TftpAckPacket);
1011 
1012  //Debug message
1013  TRACE_DEBUG("TFTP Server: Sending ACK packet (%" PRIuSIZE " bytes)...\r\n", connection->packetLen);
1014  TRACE_DEBUG(" Opcode = %" PRIu16 "\r\n", ntohs(ackPacket->opcode));
1015  TRACE_DEBUG(" Block = %" PRIu16 "\r\n", ntohs(ackPacket->block));
1016 
1017  //Send ACK packet
1018  error = socketSend(connection->socket, connection->packet,
1019  connection->packetLen, NULL, 0);
1020 
1021  //Save the time at which the packet was sent
1022  connection->timestamp = osGetSystemTime();
1023  //Reset retransmission counter
1024  connection->retransmitCount = 0;
1025 
1026  //Return status code
1027  return error;
1028 }
1029 
1030 
1031 /**
1032  * @brief Send ERROR packet
1033  * @param[in] connection Pointer to the client connection
1034  * @param[in] errorCode Integer indicating the nature of the error
1035  * @param[in] errorMsg Error message intended for human consumption
1036  * @return Error code
1037  **/
1038 
1040  uint16_t errorCode, const char_t *errorMsg)
1041 {
1042  error_t error;
1043  TftpErrorPacket *errorPacket;
1044 
1045  //Check the length of the error message
1047  {
1048  return ERROR_INVALID_PARAMETER;
1049  }
1050 
1051  //Point to the buffer where to format the packet
1052  errorPacket = (TftpErrorPacket *) connection->packet;
1053 
1054  //Format ERROR packet
1055  errorPacket->opcode = HTONS(TFTP_OPCODE_ERROR);
1056  errorPacket->errorCode = htons(errorCode);
1057 
1058  //Copy error message
1059  osStrcpy(errorPacket->errorMsg, errorMsg);
1060 
1061  //Length of the ERROR packet
1062  connection->packetLen = sizeof(TftpErrorPacket) + osStrlen(errorMsg) + 1;
1063 
1064  //Debug message
1065  TRACE_DEBUG("TFTP Server: Sending ERROR packet (%" PRIuSIZE " bytes)...\r\n", connection->packetLen);
1066  TRACE_DEBUG(" Opcode = %" PRIu16 "\r\n", ntohs(errorPacket->opcode));
1067  TRACE_DEBUG(" Error Code = %" PRIu16 "\r\n", ntohs(errorPacket->errorCode));
1068  TRACE_DEBUG(" Error Msg = %s\r\n", errorPacket->errorMsg);
1069 
1070  //Send ERROR packet
1071  error = socketSend(connection->socket, connection->packet,
1072  connection->packetLen, NULL, 0);
1073 
1074  //Save the time at which the packet was sent
1075  connection->timestamp = osGetSystemTime();
1076  //Reset retransmission counter
1077  connection->retransmitCount = 0;
1078 
1079  //Return status code
1080  return error;
1081 }
1082 
1083 
1084 /**
1085  * @brief Retransmit the last packet
1086  * @param[in] connection Pointer to the client connection
1087  * @return Error code
1088  **/
1089 
1091 {
1092  error_t error;
1093 
1094  //Debug message
1095  TRACE_DEBUG("TFTP Server: Retransmitting packet (%" PRIuSIZE " bytes)...\r\n",
1096  connection->packetLen);
1097 
1098  //Retransmit the last packet
1099  error = socketSend(connection->socket, connection->packet,
1100  connection->packetLen, NULL, 0);
1101 
1102  //Return status code
1103  return error;
1104 }
1105 
1106 #endif
error_t socketSend(Socket *socket, const void *data, size_t length, size_t *written, uint_t flags)
Send data to a connected socket.
Definition: socket.c:1605
char_t errorMsg[]
Definition: tftp_common.h:139
#define htons(value)
Definition: cpu_endian.h:413
void tftpServerProcessWrqPacket(TftpServerContext *context, NetInterface *interface, const IpAddr *clientIpAddr, uint16_t clientPort, const TftpWrqPacket *wrqPacket, size_t length)
Process incoming WRQ packet.
@ SOCKET_IP_PROTO_UDP
Definition: socket.h:108
uint8_t opcode
Definition: dns_common.h:193
@ ERROR_OUT_OF_RANGE
Definition: error.h:138
void tftpServerProcessPacket(TftpServerContext *context, TftpClientConnection *connection)
Process incoming packet.
@ TFTP_ERROR_NOT_DEFINED
Definition: tftp_common.h:67
@ TFTP_STATE_WRITING
Definition: tftp_server.h:125
IP network address.
Definition: ip.h:97
#define TFTP_SERVER_MAX_RETRIES
Definition: tftp_server.h:73
#define TRUE
Definition: os_port.h:50
void tftpServerCloseConnection(TftpClientConnection *connection)
Close connection.
Message and ancillary data.
Definition: socket.h:241
TftpClientConnection * tftpServerOpenConnection(TftpServerContext *context, NetInterface *interface, const IpAddr *clientIpAddr, uint16_t clientPort)
Create a new connection.
void socketClose(Socket *socket)
Close an existing socket.
Definition: socket.c:2169
TftpErrorPacket
Definition: tftp_common.h:140
#define TftpServerContext
Definition: tftp_server.h:108
@ TFTP_OPCODE_ACK
Acknowledgment.
Definition: tftp_common.h:55
char_t * ipAddrToString(const IpAddr *ipAddr, char_t *str)
Convert a binary IP address to a string representation.
Definition: ip.c:811
@ SOCKET_TYPE_DGRAM
Definition: socket.h:93
void * data
Pointer to the payload.
Definition: socket.h:242
@ TFTP_OPCODE_WRQ
Write request.
Definition: tftp_common.h:53
TftpClientConnection * tftpServerFindConnection(TftpServerContext *context, NetInterface *interface, const IpAddr *clientIpAddr, uint16_t clientPort)
Find a connection that matches a given client.
error_t tftpServerRetransmitPacket(TftpClientConnection *connection)
Retransmit the last packet.
#define osStrlen(s)
Definition: os_port.h:171
uint16_t errorCode
Definition: tftp_common.h:138
void tftpServerProcessRrqPacket(TftpServerContext *context, NetInterface *interface, const IpAddr *clientIpAddr, uint16_t clientPort, const TftpRrqPacket *rrqPacket, size_t length)
Process incoming RRQ packet.
@ ERROR_END_OF_STREAM
Definition: error.h:212
TFTP server.
error_t tftpServerSendErrorPacket(TftpClientConnection *connection, uint16_t errorCode, const char_t *errorMsg)
Send ERROR packet.
@ ERROR_OPEN_FAILED
Definition: error.h:75
void tftpServerProcessErrorPacket(TftpClientConnection *connection, const TftpErrorPacket *errorPacket, size_t length)
Process incoming ERROR packet.
@ TFTP_OPCODE_ERROR
Error.
Definition: tftp_common.h:56
TftpRrqPacket
Definition: tftp_common.h:94
NetInterface * interface
Underlying network interface.
Definition: socket.h:248
#define FALSE
Definition: os_port.h:46
const SocketMsg SOCKET_DEFAULT_MSG
Definition: socket.c:49
size_t length
Actual length of the payload, in bytes.
Definition: socket.h:244
@ ERROR_INVALID_PARAMETER
Invalid parameter.
Definition: error.h:47
TftpWrqPacket
Definition: tftp_common.h:105
error_t
Error codes.
Definition: error.h:43
bool_t ipCompAddr(const IpAddr *ipAddr1, const IpAddr *ipAddr2)
Compare IP addresses.
Definition: ip.c:318
#define TFTP_SERVER_TIMEOUT
Definition: tftp_server.h:80
#define TFTP_SERVER_MAX_PACKET_SIZE
Definition: tftp_server.h:100
int_t socket(int_t family, int_t type, int_t protocol)
Create a socket that is bound to a specific transport service provider.
Definition: bsd_socket.c:65
#define TFTP_SERVER_BLOCK_SIZE
Definition: tftp_server.h:98
#define NetInterface
Definition: net.h:40
IpAddr srcIpAddr
Source IP address.
Definition: socket.h:249
@ ERROR_END_OF_FILE
Definition: error.h:160
@ TFTP_ERROR_DISK_FULL
Definition: tftp_common.h:70
error_t socketReceiveFrom(Socket *socket, IpAddr *srcIpAddr, uint16_t *srcPort, void *data, size_t size, size_t *received, uint_t flags)
Receive a datagram from a connectionless socket.
Definition: socket.c:1841
error_t socketReceiveMsg(Socket *socket, SocketMsg *message, uint_t flags)
Receive a message from a connectionless socket.
Definition: socket.c:1991
@ TFTP_OPCODE_DATA
Data.
Definition: tftp_common.h:54
error_t socketConnect(Socket *socket, const IpAddr *remoteIpAddr, uint16_t remotePort)
Establish a connection to a specified socket.
Definition: socket.c:1458
@ TFTP_STATE_OPEN
Definition: tftp_server.h:123
@ TFTP_STATE_READING
Definition: tftp_server.h:124
#define TRACE_INFO(...)
Definition: debug.h:105
uint8_t length
Definition: tcp.h:375
#define TFTP_SERVER_MAX_CONNECTIONS
Definition: tftp_server.h:59
@ TFTP_STATE_WRITE_COMPLETE
Definition: tftp_server.h:127
@ TFTP_STATE_READ_COMPLETE
Definition: tftp_server.h:126
TftpAckPacket
Definition: tftp_common.h:128
void tftpServerTick(TftpServerContext *context)
Handle periodic operations.
#define socketBindToInterface
Definition: net_legacy.h:193
uint32_t systime_t
System time.
void tftpServerProcessAckPacket(TftpClientConnection *connection, const TftpAckPacket *ackPacket, size_t length)
Process incoming ACK packet.
#define ntohs(value)
Definition: cpu_endian.h:421
@ TFTP_STATE_CLOSED
Definition: tftp_server.h:122
#define TRACE_DEBUG(...)
Definition: debug.h:119
char char_t
Definition: compiler_port.h:55
error_t tftpServerSendAckPacket(TftpClientConnection *connection)
Send ACK packet.
void tftpServerAcceptRequest(TftpServerContext *context)
Accept connection request.
uint32_t time
error_t tftpServerSendDataPacket(TftpClientConnection *connection)
Send DATA packet.
#define HTONS(value)
Definition: cpu_endian.h:410
@ ERROR_READ_FAILED
Definition: error.h:225
@ ERROR_WRITE_FAILED
Definition: error.h:224
Socket * socketOpenEx(NetContext *context, uint_t type, uint_t protocol)
Create a socket.
Definition: socket.c:143
#define Socket
Definition: socket.h:36
#define TftpClientConnection
Definition: tftp_server.h:104
Helper functions for TFTP server.
size_t size
Size of the payload, in bytes.
Definition: socket.h:243
TftpDataPacket
Definition: tftp_common.h:117
#define PRIuSIZE
unsigned int uint_t
Definition: compiler_port.h:57
void tftpServerProcessDataPacket(TftpClientConnection *connection, const TftpDataPacket *dataPacket, size_t length)
Process incoming DATA packet.
#define LOAD16BE(p)
Definition: cpu_endian.h:186
#define osMemset(p, value, length)
Definition: os_port.h:141
TCP/IP stack core.
#define osStrcpy(s1, s2)
Definition: os_port.h:213
uint16_t srcPort
Source port.
Definition: socket.h:250
#define TFTP_SERVER_FINAL_DELAY
Definition: tftp_server.h:87
@ NO_ERROR
Success.
Definition: error.h:44
Debugging facilities.
systime_t osGetSystemTime(void)
Retrieve system time.
@ TFTP_OPCODE_RRQ
Read request.
Definition: tftp_common.h:52