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 *      http://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 *
037 *
038 * @see org.apache.commons.net.DatagramSocketClient
039 * @see TFTPPacket
040 * @see TFTPPacketException
041 * @see TFTPClient
042 */
043
044public class TFTP extends DatagramSocketClient {
045    /**
046     * The ascii transfer mode. Its value is 0 and equivalent to NETASCII_MODE
047     */
048    public static final int ASCII_MODE = 0;
049
050    /**
051     * The netascii transfer mode. Its value is 0.
052     */
053    public static final int NETASCII_MODE = 0;
054
055    /**
056     * The binary transfer mode. Its value is 1 and equivalent to OCTET_MODE.
057     */
058    public static final int BINARY_MODE = 1;
059
060    /**
061     * The image transfer mode. Its value is 1 and equivalent to OCTET_MODE.
062     */
063    public static final int IMAGE_MODE = 1;
064
065    /**
066     * The octet transfer mode. Its value is 1.
067     */
068    public static final int OCTET_MODE = 1;
069
070    /**
071     * The default number of milliseconds to wait to receive a datagram before timing out. The default is 5,000 milliseconds (5 seconds).
072     *
073     * @deprecated Use {@link #DEFAULT_TIMEOUT_DURATION}.
074     */
075    @Deprecated
076    public static final int DEFAULT_TIMEOUT = 5000;
077
078    /**
079     * The default duration to wait to receive a datagram before timing out. The default is 5 seconds.
080     *
081     * @since 3.10.0
082     */
083    public static final Duration DEFAULT_TIMEOUT_DURATION = Duration.ofSeconds(5);
084
085    /**
086     * The default TFTP port according to RFC 783 is 69.
087     */
088    public static final int DEFAULT_PORT = 69;
089
090    /**
091     * The size to use for TFTP packet buffers. Its 4 plus the TFTPPacket.SEGMENT_SIZE, i.e. 516.
092     */
093    static final int PACKET_SIZE = TFTPPacket.SEGMENT_SIZE + 4;
094
095    /**
096     * Returns the TFTP string representation of a TFTP transfer mode. Will throw an ArrayIndexOutOfBoundsException if an invalid transfer mode is specified.
097     *
098     * @param mode The TFTP transfer mode. One of the MODE constants.
099     * @return The TFTP string representation of the TFTP transfer mode.
100     */
101    public static final String getModeName(final int mode) {
102        return TFTPRequestPacket.modeStrings[mode];
103    }
104
105    /** A buffer used to accelerate receives in bufferedReceive() */
106    private byte[] receiveBuffer;
107
108    /** A datagram used to minimize memory allocation in bufferedReceive() */
109    private DatagramPacket receiveDatagram;
110
111    /** A datagram used to minimize memory allocation in bufferedSend() */
112    private DatagramPacket sendDatagram;
113
114    /**
115     * 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
116     * saves the creation of an additional buffer and prevents a buffer copy in _newDataPcket().
117     */
118    byte[] sendBuffer;
119
120    /**
121     * Creates a TFTP instance with a default timeout of {@link #DEFAULT_TIMEOUT_DURATION}, a null socket, and buffered operations disabled.
122     */
123    public TFTP() {
124        setDefaultTimeout(DEFAULT_TIMEOUT_DURATION);
125        receiveBuffer = null;
126        receiveDatagram = null;
127    }
128
129    /**
130     * Initializes the internal buffers. Buffers are used by {@link #bufferedSend bufferedSend() } and {@link #bufferedReceive bufferedReceive() }. This method
131     * must be called before calling either one of those two methods. When you finish using buffered operations, you must call {@link #endBufferedOps
132     * endBufferedOps() }.
133     */
134    public final void beginBufferedOps() {
135        receiveBuffer = new byte[PACKET_SIZE];
136        receiveDatagram = new DatagramPacket(receiveBuffer, receiveBuffer.length);
137        sendBuffer = new byte[PACKET_SIZE];
138        sendDatagram = new DatagramPacket(sendBuffer, sendBuffer.length);
139    }
140
141    /**
142     * This is a special method to perform a more efficient packet receive. It should only be used after calling {@link #beginBufferedOps beginBufferedOps() }.
143     * beginBufferedOps() initializes a set of buffers used internally that prevent the new allocation of a DatagramPacket and byte array for each send and
144     * receive. To use these buffers you must call the bufferedReceive() and bufferedSend() methods instead of send() and receive(). You must also be certain
145     * that you don't manipulate the resulting packet in such a way that it interferes with future buffered operations. For example, a TFTPDataPacket received
146     * with bufferedReceive() will have a reference to the internal byte buffer. You must finish using this data before calling bufferedReceive() again, or else
147     * the data will be overwritten by the call.
148     *
149     * @return The TFTPPacket received.
150     * @throws InterruptedIOException If a socket timeout occurs. The Java documentation claims an InterruptedIOException is thrown on a DatagramSocket timeout,
151     *                                but in practice we find a SocketException is thrown. You should catch both to be safe.
152     * @throws SocketException        If a socket timeout occurs. The Java documentation claims an InterruptedIOException is thrown on a DatagramSocket timeout,
153     *                                but in practice we find a SocketException is thrown. You should catch both to be safe.
154     * @throws IOException            If some other I/O error occurs.
155     * @throws TFTPPacketException    If an invalid TFTP packet is received.
156     */
157    public final TFTPPacket bufferedReceive() throws IOException, InterruptedIOException, SocketException, TFTPPacketException {
158        receiveDatagram.setData(receiveBuffer);
159        receiveDatagram.setLength(receiveBuffer.length);
160        checkOpen().receive(receiveDatagram);
161
162        final TFTPPacket newTFTPPacket = TFTPPacket.newTFTPPacket(receiveDatagram);
163        trace("<", newTFTPPacket);
164        return newTFTPPacket;
165    }
166
167    /**
168     * This is a special method to perform a more efficient packet send. It should only be used after calling {@link #beginBufferedOps beginBufferedOps() }.
169     * beginBufferedOps() initializes a set of buffers used internally that prevent the new allocation of a DatagramPacket and byte array for each send and
170     * receive. To use these buffers you must call the bufferedReceive() and bufferedSend() methods instead of send() and receive(). You must also be certain
171     * that you don't manipulate the resulting packet in such a way that it interferes with future buffered operations. For example, a TFTPDataPacket received
172     * with bufferedReceive() will have a reference to the internal byte buffer. You must finish using this data before calling bufferedReceive() again, or else
173     * the data will be overwritten by the call.
174     *
175     * @param packet The TFTP packet to send.
176     * @throws IOException If some I/O error occurs.
177     */
178    public final void bufferedSend(final TFTPPacket packet) throws IOException {
179        trace(">", packet);
180        checkOpen().send(packet.newDatagram(sendDatagram, sendBuffer));
181    }
182
183    /**
184     * 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
185     * implement your own TFTP client or server.
186     *
187     * @throws IOException if an I/O error occurs.
188     */
189    public final void discardPackets() throws IOException {
190        final DatagramPacket datagram = new DatagramPacket(new byte[PACKET_SIZE], PACKET_SIZE);
191        final Duration to = getSoTimeoutDuration();
192        setSoTimeout(Duration.ofMillis(1));
193        try {
194            while (true) {
195                checkOpen().receive(datagram);
196            }
197        } catch (final SocketException | InterruptedIOException e) {
198            // Do nothing. We timed out, so we hope we're caught up.
199        }
200        setSoTimeout(to);
201    }
202
203    /**
204     * Releases the resources used to perform buffered sends and receives.
205     */
206    public final void endBufferedOps() {
207        receiveBuffer = null;
208        receiveDatagram = null;
209        sendBuffer = null;
210        sendDatagram = null;
211    }
212
213    /**
214     * Receives a TFTPPacket.
215     *
216     * @return The TFTPPacket received.
217     * @throws InterruptedIOException If a socket timeout occurs. The Java documentation claims an InterruptedIOException is thrown on a DatagramSocket timeout,
218     *                                but in practice we find a SocketException is thrown. You should catch both to be safe.
219     * @throws SocketException        If a socket timeout occurs. The Java documentation claims an InterruptedIOException is thrown on a DatagramSocket timeout,
220     *                                but in practice we find a SocketException is thrown. You should catch both to be safe.
221     * @throws IOException            If some other I/O error occurs.
222     * @throws TFTPPacketException    If an invalid TFTP packet is received.
223     */
224    public final TFTPPacket receive() throws IOException, InterruptedIOException, SocketException, TFTPPacketException {
225        final DatagramPacket packet;
226
227        packet = new DatagramPacket(new byte[PACKET_SIZE], PACKET_SIZE);
228
229        checkOpen().receive(packet);
230
231        final TFTPPacket newTFTPPacket = TFTPPacket.newTFTPPacket(packet);
232        trace("<", newTFTPPacket);
233        return newTFTPPacket;
234    }
235
236    /**
237     * Sends a TFTP packet to its destination.
238     *
239     * @param packet The TFTP packet to send.
240     * @throws IOException If some I/O error occurs.
241     */
242    public final void send(final TFTPPacket packet) throws IOException {
243        trace(">", packet);
244        checkOpen().send(packet.newDatagram());
245    }
246
247    /**
248     * Trace facility; this implementation does nothing.
249     * <p>
250     * Override it to trace the data, for example:<br>
251     * {@code System.out.println(direction + " " + packet.toString());}
252     *
253     * @param direction {@code >} or {@code <}
254     * @param packet    the packet to be sent or that has been received respectively
255     * @since 3.6
256     */
257    protected void trace(final String direction, final TFTPPacket packet) {
258    }
259
260}