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