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