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