001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      https://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.commons.net.tftp;
019
020import java.io.IOException;
021import java.io.InterruptedIOException;
022import java.net.DatagramPacket;
023import java.net.SocketException;
024import java.time.Duration;
025
026import org.apache.commons.net.DatagramSocketClient;
027
028/**
029 * 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.
030 * However, almost every user should only be concerend with the {@link org.apache.commons.net.DatagramSocketClient#open open()}, and
031 * {@link org.apache.commons.net.DatagramSocketClient#close close()}, methods. Additionally,the a
032 * {@link org.apache.commons.net.DatagramSocketClient#setDefaultTimeout setDefaultTimeout()} method may be of importance for performance tuning.
033 * <p>
034 * 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
035 * worry about the internals.
036 * </p>
037 *
038 * @see org.apache.commons.net.DatagramSocketClient
039 * @see TFTPPacket
040 * @see TFTPPacketException
041 * @see TFTPClient
042 */
043public class TFTP extends DatagramSocketClient {
044
045    /**
046     * The header size.
047     */
048    private static final int HEADER_SIZE = 4;
049
050    /**
051     * The ASCII transfer mode. Its value is 0 and equivalent to NETASCII_MODE
052     */
053    public static final int ASCII_MODE = 0;
054
055    /**
056     * The netascii transfer mode. Its value is 0.
057     */
058    public static final int NETASCII_MODE = 0;
059
060    /**
061     * The binary transfer mode. Its value is 1 and equivalent to OCTET_MODE.
062     */
063    public static final int BINARY_MODE = 1;
064
065    /**
066     * The image transfer mode. Its value is 1 and equivalent to OCTET_MODE.
067     */
068    public static final int IMAGE_MODE = 1;
069
070    /**
071     * The octet transfer mode. Its value is 1.
072     */
073    public static final int OCTET_MODE = 1;
074
075    /**
076     * The default number of milliseconds to wait to receive a datagram before timing out. The default is 5,000 milliseconds (5 seconds).
077     *
078     * @deprecated Use {@link #DEFAULT_TIMEOUT_DURATION}.
079     */
080    @Deprecated
081    public static final int DEFAULT_TIMEOUT = 5000;
082
083    /**
084     * The default duration to wait to receive a datagram before timing out. The default is 5 seconds.
085     *
086     * @since 3.10.0
087     */
088    public static final Duration DEFAULT_TIMEOUT_DURATION = Duration.ofSeconds(5);
089
090    /**
091     * The default TFTP port according to RFC 783 is 69.
092     */
093    public static final int DEFAULT_PORT = 69;
094
095    /**
096     * The size to use for TFTP packet buffers. Its 4 plus the TFTPPacket.SEGMENT_SIZE, i.e. 516.
097     */
098    static final int PACKET_SIZE = TFTPPacket.SEGMENT_SIZE + HEADER_SIZE;
099
100    /**
101     * Returns the TFTP string representation of a TFTP transfer mode. Will throw an ArrayIndexOutOfBoundsException if an invalid transfer mode is specified.
102     *
103     * @param mode The TFTP transfer mode. One of the MODE constants.
104     * @return The TFTP string representation of the TFTP transfer mode.
105     */
106    public static final String getModeName(final int mode) {
107        return TFTPRequestPacket.modeStrings[mode];
108    }
109
110    /** A buffer used to accelerate receives in bufferedReceive() */
111    private byte[] receiveBuffer;
112
113    /** A datagram used to minimize memory allocation in bufferedReceive() */
114    private DatagramPacket receiveDatagram;
115
116    /** A datagram used to minimize memory allocation in bufferedSend() */
117    private DatagramPacket sendDatagram;
118
119    /** Internal packet size, which is the data octet size plus 4 (for TFTP header octets) */
120    private int packetSize = PACKET_SIZE;
121
122    /** Internal state to track if the send/receive buffers are initialized */
123    private boolean buffersInitialized;
124
125    /**
126     * 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
127     * saves the creation of an additional buffer and prevents a buffer copy in _newDataPcket().
128     */
129    byte[] sendBuffer;
130
131    /**
132     * Creates a TFTP instance with a default timeout of {@link #DEFAULT_TIMEOUT_DURATION}, a null socket, and buffered operations disabled.
133     */
134    public TFTP() {
135        setDefaultTimeout(DEFAULT_TIMEOUT_DURATION);
136        receiveBuffer = null;
137        receiveDatagram = null;
138    }
139
140    /**
141     * Initializes the internal buffers. Buffers are used by {@link #bufferedSend bufferedSend()} and {@link #bufferedReceive bufferedReceive()}. This method
142     * must be called before calling either one of those two methods. When you finish using buffered operations, you must call {@link #endBufferedOps
143     * endBufferedOps()}.
144     */
145    public final void beginBufferedOps() {
146        receiveBuffer = new byte[packetSize];
147        receiveDatagram = new DatagramPacket(receiveBuffer, receiveBuffer.length);
148        sendBuffer = new byte[packetSize];
149        sendDatagram = new DatagramPacket(sendBuffer, sendBuffer.length);
150        buffersInitialized = true;
151    }
152
153    /**
154     * This is a special method to perform a more efficient packet receive. It should only be used after calling {@link #beginBufferedOps beginBufferedOps()}.
155     * beginBufferedOps() initializes a set of buffers used internally that prevent the new allocation of a DatagramPacket and byte array for each send and
156     * receive. To use these buffers you must call the bufferedReceive() and bufferedSend() methods instead of send() and receive(). You must also be certain
157     * that you don't manipulate the resulting packet in such a way that it interferes with future buffered operations. For example, a TFTPDataPacket received
158     * with bufferedReceive() will have a reference to the internal byte buffer. You must finish using this data before calling bufferedReceive() again, or else
159     * the data will be overwritten by the call.
160     *
161     * @return The TFTPPacket received.
162     * @throws InterruptedIOException If a socket timeout occurs. The Java documentation claims an InterruptedIOException is thrown on a DatagramSocket timeout,
163     *                                but in practice we find a SocketException is thrown. You should catch both to be safe.
164     * @throws SocketException        If a socket timeout occurs. The Java documentation claims an InterruptedIOException is thrown on a DatagramSocket timeout,
165     *                                but in practice we find a SocketException is thrown. You should catch both to be safe.
166     * @throws IOException            If some other I/O error occurs.
167     * @throws TFTPPacketException    If an invalid TFTP packet is received.
168     */
169    public final TFTPPacket bufferedReceive() throws IOException, InterruptedIOException, SocketException, TFTPPacketException {
170        receiveDatagram.setData(receiveBuffer);
171        receiveDatagram.setLength(receiveBuffer.length);
172        checkOpen().receive(receiveDatagram);
173
174        final TFTPPacket newTFTPPacket = TFTPPacket.newTFTPPacket(receiveDatagram);
175        trace("<", newTFTPPacket);
176        return newTFTPPacket;
177    }
178
179    /**
180     * This is a special method to perform a more efficient packet send. It should only be used after calling {@link #beginBufferedOps beginBufferedOps()}.
181     * beginBufferedOps() initializes a set of buffers used internally that prevent the new allocation of a DatagramPacket and byte array for each send and
182     * receive. To use these buffers you must call the bufferedReceive() and bufferedSend() methods instead of send() and receive(). You must also be certain
183     * that you don't manipulate the resulting packet in such a way that it interferes with future buffered operations. For example, a TFTPDataPacket received
184     * with bufferedReceive() will have a reference to the internal byte buffer. You must finish using this data before calling bufferedReceive() again, or else
185     * the data will be overwritten by the call.
186     *
187     * @param packet The TFTP packet to send.
188     * @throws IOException If some I/O error occurs.
189     */
190    public final void bufferedSend(final TFTPPacket packet) throws IOException {
191        trace(">", packet);
192        checkOpen().send(packet.newDatagram(sendDatagram, sendBuffer));
193    }
194
195    /**
196     * 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
197     * implement your own TFTP client or server.
198     *
199     * @throws IOException if an I/O error occurs.
200     */
201    public final void discardPackets() throws IOException {
202        final DatagramPacket datagram = new DatagramPacket(new byte[packetSize], packetSize);
203        final Duration to = getSoTimeoutDuration();
204        setSoTimeout(Duration.ofMillis(1));
205        try {
206            while (true) {
207                checkOpen().receive(datagram);
208            }
209        } catch (final SocketException | InterruptedIOException e) {
210            // Do nothing. We timed out, so we hope we're caught up.
211        }
212        setSoTimeout(to);
213    }
214
215    /**
216     * Releases the resources used to perform buffered sends and receives.
217     */
218    public final void endBufferedOps() {
219        receiveBuffer = null;
220        receiveDatagram = null;
221        sendBuffer = null;
222        sendDatagram = null;
223        buffersInitialized = false;
224    }
225
226    /**
227     * Receives a TFTPPacket.
228     *
229     * @return The TFTPPacket received.
230     * @throws InterruptedIOException If a socket timeout occurs. The Java documentation claims an InterruptedIOException is thrown on a DatagramSocket timeout,
231     *                                but in practice we find a SocketException is thrown. You should catch both to be safe.
232     * @throws SocketException        If a socket timeout occurs. The Java documentation claims an InterruptedIOException is thrown on a DatagramSocket timeout,
233     *                                but in practice we find a SocketException is thrown. You should catch both to be safe.
234     * @throws IOException            If some other I/O error occurs.
235     * @throws TFTPPacketException    If an invalid TFTP packet is received.
236     */
237    public final TFTPPacket receive() throws IOException, InterruptedIOException, SocketException, TFTPPacketException {
238        final DatagramPacket packet;
239
240        packet = new DatagramPacket(new byte[packetSize], packetSize);
241
242        checkOpen().receive(packet);
243
244        final TFTPPacket newTFTPPacket = TFTPPacket.newTFTPPacket(packet);
245        trace("<", newTFTPPacket);
246        return newTFTPPacket;
247    }
248
249    /**
250     * Sends a TFTP packet to its destination.
251     *
252     * @param packet The TFTP packet to send.
253     * @throws IOException If some I/O error occurs.
254     */
255    public final void send(final TFTPPacket packet) throws IOException {
256        trace(">", packet);
257        checkOpen().send(packet.newDatagram());
258    }
259
260    /**
261     * Trace facility; this implementation does nothing.
262     * <p>
263     * Override it to trace the data, for example:<br>
264     * {@code System.out.println(direction + " " + packet.toString());}
265     *
266     * @param direction {@code >} or {@code <}
267     * @param packet    the packet to be sent or that has been received respectively
268     * @since 3.6
269     */
270    protected void trace(final String direction, final TFTPPacket packet) {
271    }
272
273    /**
274     * Sets the size of the buffers used to receive and send packets.
275     * This method can be used to increase the size of the buffer to support `blksize`.
276     * For which valid values range between "8" and "65464" octets (RFC-2348).
277     * This only refers to the number of data octets, it does not include the four octets of TFTP header.
278     *
279     * @param packetSize The size of the data octets not including 4 octets for the header.
280     * @since 3.12.0
281     */
282    public final void resetBuffersToSize(final int packetSize) {
283        // the packet size should be between 8 - 65464 (inclusively) then we add 4 for the header
284        this.packetSize = Math.min(Math.max(packetSize, 8), 65464) + HEADER_SIZE;
285        // if the buffers are already initialized reinitialize
286        if (buffersInitialized) {
287            endBufferedOps();
288            beginBufferedOps();
289        }
290    }
291
292    /**
293     * Gets the buffer size of the buffered used by {@link #bufferedSend(TFTPPacket)} and {@link #bufferedReceive}.
294     *
295     * @return current buffer size
296     * @since 3.12.0
297     */
298    public int getPacketSize() {
299        return packetSize;
300    }
301}