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.net.DatagramPacket;
021import java.net.InetAddress;
022import java.nio.charset.Charset;
023import java.nio.charset.StandardCharsets;
024import java.util.HashMap;
025import java.util.Locale;
026import java.util.Map;
027
028/**
029 * An abstract class derived from TFTPPacket definiing a TFTP Request packet type. It is subclassed by the
030 * {@link org.apache.commons.net.tftp.TFTPReadRequestPacket} and {@link org.apache.commons.net.tftp.TFTPWriteRequestPacket} classes.
031 * <p>
032 * 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
033 * worry about the internals. Additionally, only very few people should have to care about any of the TFTPPacket classes or derived classes. Almost all users
034 * should only be concerned with the {@link org.apache.commons.net.tftp.TFTPClient} class {@link org.apache.commons.net.tftp.TFTPClient#receiveFile
035 * receiveFile()} and {@link org.apache.commons.net.tftp.TFTPClient#sendFile sendFile()} methods.
036 * </p>
037 *
038 * @see TFTPPacket
039 * @see TFTPReadRequestPacket
040 * @see TFTPWriteRequestPacket
041 * @see TFTPPacketException
042 * @see TFTP
043 */
044
045public abstract class TFTPRequestPacket extends TFTPPacket {
046    /**
047     * An array containing the string names of the transfer modes and indexed by the transfer mode constants.
048     */
049    static final String[] modeStrings = { "netascii", "octet" };
050
051    /**
052     * A null terminated byte array representation of the ASCII names of the transfer mode constants. This is convenient for creating the TFTP request packets.
053     */
054    private static final byte[] modeBytes[] = { { (byte) 'n', (byte) 'e', (byte) 't', (byte) 'a', (byte) 's', (byte) 'c', (byte) 'i', (byte) 'i', 0 },
055            { (byte) 'o', (byte) 'c', (byte) 't', (byte) 'e', (byte) 't', 0 } };
056
057    /** The transfer mode of the request. */
058    private final int mode;
059
060    /** The file name of the request. */
061    private final String fileName;
062
063    /** The option values */
064    private final Map<String, String> options = new HashMap<>();
065
066    /**
067     * Creates a request packet of a given type to be sent to a host at a given port with a file name and transfer mode request.
068     *
069     * @param destination The host to which the packet is going to be sent.
070     * @param port        The port to which the packet is going to be sent.
071     * @param type        The type of the request (either TFTPPacket.READ_REQUEST or TFTPPacket.WRITE_REQUEST).
072     * @param fileName    The requested file name.
073     * @param mode        The requested transfer mode. This should be on of the TFTP class MODE constants (e.g., TFTP.NETASCII_MODE).
074     */
075    TFTPRequestPacket(final InetAddress destination, final int port, final int type, final String fileName, final int mode) {
076        super(type, destination, port);
077
078        this.fileName = fileName;
079        this.mode = mode;
080    }
081
082    /**
083     * Creates a request packet of a given type based on a received datagram. Assumes the datagram is at least length 4, else an ArrayIndexOutOfBoundsException
084     * may be thrown.
085     *
086     * @param type     The type of the request (either TFTPPacket.READ_REQUEST or TFTPPacket.WRITE_REQUEST).
087     * @param datagram The datagram containing the received request.
088     * @throws TFTPPacketException If the datagram isn't a valid TFTP request packet of the appropriate type.
089     */
090    TFTPRequestPacket(final int type, final DatagramPacket datagram) throws TFTPPacketException {
091        super(type, datagram.getAddress(), datagram.getPort());
092
093        final byte[] data = datagram.getData();
094
095        if (getType() != data[1]) {
096            throw new TFTPPacketException("TFTP operator code does not match type.");
097        }
098
099        final StringBuilder buffer = new StringBuilder();
100
101        int index = 2;
102        final int length = datagram.getLength();
103
104        while (index < length && data[index] != 0) {
105            buffer.append((char) data[index]);
106            ++index;
107        }
108
109        this.fileName = buffer.toString();
110
111        if (index >= length) {
112            throw new TFTPPacketException("Bad file name and mode format.");
113        }
114
115        buffer.setLength(0);
116        ++index; // need to advance beyond the end of string marker
117        while (index < length && data[index] != 0) {
118            buffer.append((char) data[index]);
119            ++index;
120        }
121
122        final String modeString = buffer.toString().toLowerCase(Locale.ENGLISH);
123        final int modeStringsLength = modeStrings.length;
124
125        int mode = 0;
126        int modeIndex;
127        for (modeIndex = 0; modeIndex < modeStringsLength; modeIndex++) {
128            if (modeString.equals(modeStrings[modeIndex])) {
129                mode = modeIndex;
130                break;
131            }
132        }
133
134        this.mode = mode;
135
136        if (modeIndex >= modeStringsLength) {
137            throw new TFTPPacketException("Unrecognized TFTP transfer mode: " + modeString);
138            // May just want to default to binary mode instead of throwing
139            // exception.
140            // _mode = TFTP.OCTET_MODE;
141        }
142
143        ++index;
144        while (index < length) {
145            int start = index;
146            for (; data[index] != 0; ++index) {
147                if (index >= length) {
148                    throw new TFTPPacketException("Invalid option format");
149                }
150            }
151            final String option = new String(data, start, index - start, StandardCharsets.US_ASCII);
152            ++index;
153            start = index;
154            for (; data[index] != 0; ++index) {
155                if (index >= length) {
156                    throw new TFTPPacketException("Invalid option format");
157                }
158            }
159            final String octets = new String(data, start, index - start, StandardCharsets.US_ASCII);
160            this.options.put(option, octets);
161            ++index;
162        }
163    }
164
165    /**
166     * Gets the requested file name.
167     *
168     * @return The requested file name.
169     */
170    public final String getFilename() {
171        return fileName;
172    }
173
174    /**
175     * Gets the transfer mode of the request.
176     *
177     * @return The transfer mode of the request.
178     */
179    public final int getMode() {
180        return mode;
181    }
182
183    /**
184     * Gets the options extensions of the request as a map.
185     * The keys are the option names and the values are the option values.
186     *
187     * @return The options extensions of the request as a map.
188     * @since 3.12.0
189     */
190    public final Map<String, String> getOptions() {
191        return options;
192    }
193
194    /**
195     * Creates a UDP datagram containing all the TFTP request packet data in the proper format. This is a method exposed to the programmer in case he wants to
196     * implement his own TFTP client instead of using the {@link org.apache.commons.net.tftp.TFTPClient} class. Under normal circumstances, you should not have
197     * a need to call this method.
198     *
199     * @return A UDP datagram containing the TFTP request packet.
200     */
201    @Override
202    public final DatagramPacket newDatagram() {
203        final int fileLength;
204        final int modeLength;
205        final byte[] data;
206
207        fileLength = fileName.length();
208        modeLength = modeBytes[mode].length;
209
210        int optionsLength = 0;
211        for (final Map.Entry<String, String> entry : options.entrySet()) {
212            optionsLength += entry.getKey().length() + 1 + entry.getValue().length() + 1;
213        }
214        data = new byte[fileLength + modeLength + 3 + optionsLength];
215        data[0] = 0;
216        data[1] = (byte) type;
217        System.arraycopy(fileName.getBytes(Charset.defaultCharset()), 0, data, 2, fileLength);
218        data[fileLength + 2] = 0;
219        System.arraycopy(modeBytes[mode], 0, data, fileLength + 3, modeLength);
220
221        if (optionsLength > 0) {
222            handleOptions(data, fileLength, modeLength);
223        }
224
225        return new DatagramPacket(data, data.length, address, port);
226    }
227
228    /**
229     * This is a method only available within the package for implementing efficient datagram transport by elminating buffering. It takes a datagram as an
230     * argument, and a byte buffer in which to store the raw datagram data. Inside the method, the data is set as the datagram's data and the datagram returned.
231     *
232     * @param datagram The datagram to create.
233     * @param data     The buffer to store the packet and to use in the datagram.
234     * @return The datagram argument.
235     */
236    @Override
237    final DatagramPacket newDatagram(final DatagramPacket datagram, final byte[] data) {
238        final int fileLength;
239        final int modeLength;
240
241        fileLength = fileName.length();
242        modeLength = modeBytes[mode].length;
243
244        data[0] = 0;
245        data[1] = (byte) type;
246        System.arraycopy(fileName.getBytes(Charset.defaultCharset()), 0, data, 2, fileLength);
247        data[fileLength + 2] = 0;
248        System.arraycopy(modeBytes[mode], 0, data, fileLength + 3, modeLength);
249
250        handleOptions(data, fileLength, modeLength);
251
252        datagram.setAddress(address);
253        datagram.setPort(port);
254        datagram.setData(data);
255        datagram.setLength(fileLength + modeLength + 3);
256
257        return datagram;
258    }
259
260    private void handleOptions(final byte[] data, final int fileLength, final int modeLength) {
261        int index = fileLength + modeLength + 2;
262        for (final Map.Entry<String, String> entry : options.entrySet()) {
263            data[index] = 0;
264            final String key = entry.getKey();
265            final String value = entry.getValue();
266
267            System.arraycopy(key.getBytes(StandardCharsets.US_ASCII), 0, data, ++index, key.length());
268            index += key.length();
269            data[index++] = 0;
270
271            System.arraycopy(value.getBytes(StandardCharsets.US_ASCII), 0, data, index, value.length());
272            index += value.length();
273        }
274    }
275}