TFTP.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.net.tftp;

  18. import java.io.IOException;
  19. import java.io.InterruptedIOException;
  20. import java.net.DatagramPacket;
  21. import java.net.SocketException;
  22. import java.time.Duration;

  23. import org.apache.commons.net.DatagramSocketClient;

  24. /**
  25.  * The TFTP class exposes a set of methods to allow you to deal with the TFTP protocol directly, in case you want to write your own TFTP client or server.
  26.  * However, almost every user should only be concerend with the {@link org.apache.commons.net.DatagramSocketClient#open open() }, and
  27.  * {@link org.apache.commons.net.DatagramSocketClient#close close() }, methods. Additionally,the a
  28.  * {@link org.apache.commons.net.DatagramSocketClient#setDefaultTimeout setDefaultTimeout() } method may be of importance for performance tuning.
  29.  * <p>
  30.  * Details regarding the TFTP protocol and the format of TFTP packets can be found in RFC 783. But the point of these classes is to keep you from having to
  31.  * worry about the internals.
  32.  *
  33.  *
  34.  * @see org.apache.commons.net.DatagramSocketClient
  35.  * @see TFTPPacket
  36.  * @see TFTPPacketException
  37.  * @see TFTPClient
  38.  */

  39. public class TFTP extends DatagramSocketClient {

  40.     /**
  41.      * The ASCII transfer mode. Its value is 0 and equivalent to NETASCII_MODE
  42.      */
  43.     public static final int ASCII_MODE = 0;

  44.     /**
  45.      * The netascii transfer mode. Its value is 0.
  46.      */
  47.     public static final int NETASCII_MODE = 0;

  48.     /**
  49.      * The binary transfer mode. Its value is 1 and equivalent to OCTET_MODE.
  50.      */
  51.     public static final int BINARY_MODE = 1;

  52.     /**
  53.      * The image transfer mode. Its value is 1 and equivalent to OCTET_MODE.
  54.      */
  55.     public static final int IMAGE_MODE = 1;

  56.     /**
  57.      * The octet transfer mode. Its value is 1.
  58.      */
  59.     public static final int OCTET_MODE = 1;

  60.     /**
  61.      * The default number of milliseconds to wait to receive a datagram before timing out. The default is 5,000 milliseconds (5 seconds).
  62.      *
  63.      * @deprecated Use {@link #DEFAULT_TIMEOUT_DURATION}.
  64.      */
  65.     @Deprecated
  66.     public static final int DEFAULT_TIMEOUT = 5000;

  67.     /**
  68.      * The default duration to wait to receive a datagram before timing out. The default is 5 seconds.
  69.      *
  70.      * @since 3.10.0
  71.      */
  72.     public static final Duration DEFAULT_TIMEOUT_DURATION = Duration.ofSeconds(5);

  73.     /**
  74.      * The default TFTP port according to RFC 783 is 69.
  75.      */
  76.     public static final int DEFAULT_PORT = 69;

  77.     /**
  78.      * The size to use for TFTP packet buffers. Its 4 plus the TFTPPacket.SEGMENT_SIZE, i.e. 516.
  79.      */
  80.     static final int PACKET_SIZE = TFTPPacket.SEGMENT_SIZE + 4;

  81.     /**
  82.      * Returns the TFTP string representation of a TFTP transfer mode. Will throw an ArrayIndexOutOfBoundsException if an invalid transfer mode is specified.
  83.      *
  84.      * @param mode The TFTP transfer mode. One of the MODE constants.
  85.      * @return The TFTP string representation of the TFTP transfer mode.
  86.      */
  87.     public static final String getModeName(final int mode) {
  88.         return TFTPRequestPacket.modeStrings[mode];
  89.     }

  90.     /** A buffer used to accelerate receives in bufferedReceive() */
  91.     private byte[] receiveBuffer;

  92.     /** A datagram used to minimize memory allocation in bufferedReceive() */
  93.     private DatagramPacket receiveDatagram;

  94.     /** A datagram used to minimize memory allocation in bufferedSend() */
  95.     private DatagramPacket sendDatagram;

  96.     /**
  97.      * A buffer used to accelerate sends in bufferedSend(). It is left package visible so that TFTPClient may be slightly more efficient during file sends. It
  98.      * saves the creation of an additional buffer and prevents a buffer copy in _newDataPcket().
  99.      */
  100.     byte[] sendBuffer;

  101.     /**
  102.      * Creates a TFTP instance with a default timeout of {@link #DEFAULT_TIMEOUT_DURATION}, a null socket, and buffered operations disabled.
  103.      */
  104.     public TFTP() {
  105.         setDefaultTimeout(DEFAULT_TIMEOUT_DURATION);
  106.         receiveBuffer = null;
  107.         receiveDatagram = null;
  108.     }

  109.     /**
  110.      * Initializes the internal buffers. Buffers are used by {@link #bufferedSend bufferedSend() } and {@link #bufferedReceive bufferedReceive() }. This method
  111.      * must be called before calling either one of those two methods. When you finish using buffered operations, you must call {@link #endBufferedOps
  112.      * endBufferedOps() }.
  113.      */
  114.     public final void beginBufferedOps() {
  115.         receiveBuffer = new byte[PACKET_SIZE];
  116.         receiveDatagram = new DatagramPacket(receiveBuffer, receiveBuffer.length);
  117.         sendBuffer = new byte[PACKET_SIZE];
  118.         sendDatagram = new DatagramPacket(sendBuffer, sendBuffer.length);
  119.     }

  120.     /**
  121.      * This is a special method to perform a more efficient packet receive. It should only be used after calling {@link #beginBufferedOps beginBufferedOps() }.
  122.      * beginBufferedOps() initializes a set of buffers used internally that prevent the new allocation of a DatagramPacket and byte array for each send and
  123.      * receive. To use these buffers you must call the bufferedReceive() and bufferedSend() methods instead of send() and receive(). You must also be certain
  124.      * that you don't manipulate the resulting packet in such a way that it interferes with future buffered operations. For example, a TFTPDataPacket received
  125.      * with bufferedReceive() will have a reference to the internal byte buffer. You must finish using this data before calling bufferedReceive() again, or else
  126.      * the data will be overwritten by the call.
  127.      *
  128.      * @return The TFTPPacket received.
  129.      * @throws InterruptedIOException If a socket timeout occurs. The Java documentation claims an InterruptedIOException is thrown on a DatagramSocket timeout,
  130.      *                                but in practice we find a SocketException is thrown. You should catch both to be safe.
  131.      * @throws SocketException        If a socket timeout occurs. The Java documentation claims an InterruptedIOException is thrown on a DatagramSocket timeout,
  132.      *                                but in practice we find a SocketException is thrown. You should catch both to be safe.
  133.      * @throws IOException            If some other I/O error occurs.
  134.      * @throws TFTPPacketException    If an invalid TFTP packet is received.
  135.      */
  136.     public final TFTPPacket bufferedReceive() throws IOException, InterruptedIOException, SocketException, TFTPPacketException {
  137.         receiveDatagram.setData(receiveBuffer);
  138.         receiveDatagram.setLength(receiveBuffer.length);
  139.         checkOpen().receive(receiveDatagram);

  140.         final TFTPPacket newTFTPPacket = TFTPPacket.newTFTPPacket(receiveDatagram);
  141.         trace("<", newTFTPPacket);
  142.         return newTFTPPacket;
  143.     }

  144.     /**
  145.      * This is a special method to perform a more efficient packet send. It should only be used after calling {@link #beginBufferedOps beginBufferedOps() }.
  146.      * beginBufferedOps() initializes a set of buffers used internally that prevent the new allocation of a DatagramPacket and byte array for each send and
  147.      * receive. To use these buffers you must call the bufferedReceive() and bufferedSend() methods instead of send() and receive(). You must also be certain
  148.      * that you don't manipulate the resulting packet in such a way that it interferes with future buffered operations. For example, a TFTPDataPacket received
  149.      * with bufferedReceive() will have a reference to the internal byte buffer. You must finish using this data before calling bufferedReceive() again, or else
  150.      * the data will be overwritten by the call.
  151.      *
  152.      * @param packet The TFTP packet to send.
  153.      * @throws IOException If some I/O error occurs.
  154.      */
  155.     public final void bufferedSend(final TFTPPacket packet) throws IOException {
  156.         trace(">", packet);
  157.         checkOpen().send(packet.newDatagram(sendDatagram, sendBuffer));
  158.     }

  159.     /**
  160.      * This method synchronizes a connection by discarding all packets that may be in the local socket buffer. This method need only be called when you
  161.      * implement your own TFTP client or server.
  162.      *
  163.      * @throws IOException if an I/O error occurs.
  164.      */
  165.     public final void discardPackets() throws IOException {
  166.         final DatagramPacket datagram = new DatagramPacket(new byte[PACKET_SIZE], PACKET_SIZE);
  167.         final Duration to = getSoTimeoutDuration();
  168.         setSoTimeout(Duration.ofMillis(1));
  169.         try {
  170.             while (true) {
  171.                 checkOpen().receive(datagram);
  172.             }
  173.         } catch (final SocketException | InterruptedIOException e) {
  174.             // Do nothing. We timed out, so we hope we're caught up.
  175.         }
  176.         setSoTimeout(to);
  177.     }

  178.     /**
  179.      * Releases the resources used to perform buffered sends and receives.
  180.      */
  181.     public final void endBufferedOps() {
  182.         receiveBuffer = null;
  183.         receiveDatagram = null;
  184.         sendBuffer = null;
  185.         sendDatagram = null;
  186.     }

  187.     /**
  188.      * Receives a TFTPPacket.
  189.      *
  190.      * @return The TFTPPacket received.
  191.      * @throws InterruptedIOException If a socket timeout occurs. The Java documentation claims an InterruptedIOException is thrown on a DatagramSocket timeout,
  192.      *                                but in practice we find a SocketException is thrown. You should catch both to be safe.
  193.      * @throws SocketException        If a socket timeout occurs. The Java documentation claims an InterruptedIOException is thrown on a DatagramSocket timeout,
  194.      *                                but in practice we find a SocketException is thrown. You should catch both to be safe.
  195.      * @throws IOException            If some other I/O error occurs.
  196.      * @throws TFTPPacketException    If an invalid TFTP packet is received.
  197.      */
  198.     public final TFTPPacket receive() throws IOException, InterruptedIOException, SocketException, TFTPPacketException {
  199.         final DatagramPacket packet;

  200.         packet = new DatagramPacket(new byte[PACKET_SIZE], PACKET_SIZE);

  201.         checkOpen().receive(packet);

  202.         final TFTPPacket newTFTPPacket = TFTPPacket.newTFTPPacket(packet);
  203.         trace("<", newTFTPPacket);
  204.         return newTFTPPacket;
  205.     }

  206.     /**
  207.      * Sends a TFTP packet to its destination.
  208.      *
  209.      * @param packet The TFTP packet to send.
  210.      * @throws IOException If some I/O error occurs.
  211.      */
  212.     public final void send(final TFTPPacket packet) throws IOException {
  213.         trace(">", packet);
  214.         checkOpen().send(packet.newDatagram());
  215.     }

  216.     /**
  217.      * Trace facility; this implementation does nothing.
  218.      * <p>
  219.      * Override it to trace the data, for example:<br>
  220.      * {@code System.out.println(direction + " " + packet.toString());}
  221.      *
  222.      * @param direction {@code >} or {@code <}
  223.      * @param packet    the packet to be sent or that has been received respectively
  224.      * @since 3.6
  225.      */
  226.     protected void trace(final String direction, final TFTPPacket packet) {
  227.     }

  228. }