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.net.DatagramPacket;
021import java.net.InetAddress;
022import java.nio.charset.Charset;
023
024/**
025 * An abstract class derived from TFTPPacket definiing a TFTP Request packet type. It is subclassed by the
026 * {@link org.apache.commons.net.tftp.TFTPReadRequestPacket} and {@link org.apache.commons.net.tftp.TFTPWriteRequestPacket} classes.
027 * <p>
028 * 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
029 * 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
030 * should only be concerned with the {@link org.apache.commons.net.tftp.TFTPClient} class {@link org.apache.commons.net.tftp.TFTPClient#receiveFile
031 * receiveFile()} and {@link org.apache.commons.net.tftp.TFTPClient#sendFile sendFile()} methods.
032 *
033 *
034 * @see TFTPPacket
035 * @see TFTPReadRequestPacket
036 * @see TFTPWriteRequestPacket
037 * @see TFTPPacketException
038 * @see TFTP
039 */
040
041public abstract class TFTPRequestPacket extends TFTPPacket {
042    /**
043     * An array containing the string names of the transfer modes and indexed by the transfer mode constants.
044     */
045    static final String[] modeStrings = { "netascii", "octet" };
046
047    /**
048     * A null terminated byte array representation of the ASCII names of the transfer mode constants. This is convenient for creating the TFTP request packets.
049     */
050    private static final byte[] modeBytes[] = { { (byte) 'n', (byte) 'e', (byte) 't', (byte) 'a', (byte) 's', (byte) 'c', (byte) 'i', (byte) 'i', 0 },
051            { (byte) 'o', (byte) 'c', (byte) 't', (byte) 'e', (byte) 't', 0 } };
052
053    /** The transfer mode of the request. */
054    private final int mode;
055
056    /** The file name of the request. */
057    private final String fileName;
058
059    /**
060     * 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.
061     *
062     * @param destination The host to which the packet is going to be sent.
063     * @param port        The port to which the packet is going to be sent.
064     * @param type        The type of the request (either TFTPPacket.READ_REQUEST or TFTPPacket.WRITE_REQUEST).
065     * @param fileName    The requested file name.
066     * @param mode        The requested transfer mode. This should be on of the TFTP class MODE constants (e.g., TFTP.NETASCII_MODE).
067     */
068    TFTPRequestPacket(final InetAddress destination, final int port, final int type, final String fileName, final int mode) {
069        super(type, destination, port);
070
071        this.fileName = fileName;
072        this.mode = mode;
073    }
074
075    /**
076     * Creates a request packet of a given type based on a received datagram. Assumes the datagram is at least length 4, else an ArrayIndexOutOfBoundsException
077     * may be thrown.
078     *
079     * @param type     The type of the request (either TFTPPacket.READ_REQUEST or TFTPPacket.WRITE_REQUEST).
080     * @param datagram The datagram containing the received request.
081     * @throws TFTPPacketException If the datagram isn't a valid TFTP request packet of the appropriate type.
082     */
083    TFTPRequestPacket(final int type, final DatagramPacket datagram) throws TFTPPacketException {
084        super(type, datagram.getAddress(), datagram.getPort());
085
086        final byte[] data = datagram.getData();
087
088        if (getType() != data[1]) {
089            throw new TFTPPacketException("TFTP operator code does not match type.");
090        }
091
092        final StringBuilder buffer = new StringBuilder();
093
094        int index = 2;
095        int length = datagram.getLength();
096
097        while (index < length && data[index] != 0) {
098            buffer.append((char) data[index]);
099            ++index;
100        }
101
102        this.fileName = buffer.toString();
103
104        if (index >= length) {
105            throw new TFTPPacketException("Bad file name and mode format.");
106        }
107
108        buffer.setLength(0);
109        ++index; // need to advance beyond the end of string marker
110        while (index < length && data[index] != 0) {
111            buffer.append((char) data[index]);
112            ++index;
113        }
114
115        final String modeString = buffer.toString().toLowerCase(java.util.Locale.ENGLISH);
116        length = modeStrings.length;
117
118        int mode = 0;
119        for (index = 0; index < length; index++) {
120            if (modeString.equals(modeStrings[index])) {
121                mode = index;
122                break;
123            }
124        }
125
126        this.mode = mode;
127
128        if (index >= length) {
129            throw new TFTPPacketException("Unrecognized TFTP transfer mode: " + modeString);
130            // May just want to default to binary mode instead of throwing
131            // exception.
132            // _mode = TFTP.OCTET_MODE;
133        }
134    }
135
136    /**
137     * Returns the requested file name.
138     *
139     * @return The requested file name.
140     */
141    public final String getFilename() {
142        return fileName;
143    }
144
145    /**
146     * Returns the transfer mode of the request.
147     *
148     * @return The transfer mode of the request.
149     */
150    public final int getMode() {
151        return mode;
152    }
153
154    /**
155     * 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
156     * implement his own TFTP client instead of using the {@link org.apache.commons.net.tftp.TFTPClient} class. Under normal circumstances, you should not have
157     * a need to call this method.
158     *
159     * @return A UDP datagram containing the TFTP request packet.
160     */
161    @Override
162    public final DatagramPacket newDatagram() {
163        final int fileLength;
164        final int modeLength;
165        final byte[] data;
166
167        fileLength = fileName.length();
168        modeLength = modeBytes[mode].length;
169
170        data = new byte[fileLength + modeLength + 4];
171        data[0] = 0;
172        data[1] = (byte) type;
173        System.arraycopy(fileName.getBytes(Charset.defaultCharset()), 0, data, 2, fileLength);
174        data[fileLength + 2] = 0;
175        System.arraycopy(modeBytes[mode], 0, data, fileLength + 3, modeLength);
176
177        return new DatagramPacket(data, data.length, address, port);
178    }
179
180    /**
181     * This is a method only available within the package for implementing efficient datagram transport by elminating buffering. It takes a datagram as an
182     * 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.
183     *
184     * @param datagram The datagram to create.
185     * @param data     The buffer to store the packet and to use in the datagram.
186     * @return The datagram argument.
187     */
188    @Override
189    final DatagramPacket newDatagram(final DatagramPacket datagram, final byte[] data) {
190        final int fileLength;
191        final int modeLength;
192
193        fileLength = fileName.length();
194        modeLength = modeBytes[mode].length;
195
196        data[0] = 0;
197        data[1] = (byte) type;
198        System.arraycopy(fileName.getBytes(Charset.defaultCharset()), 0, data, 2, fileLength);
199        data[fileLength + 2] = 0;
200        System.arraycopy(modeBytes[mode], 0, data, fileLength + 3, modeLength);
201
202        datagram.setAddress(address);
203        datagram.setPort(port);
204        datagram.setData(data);
205        datagram.setLength(fileLength + modeLength + 3);
206
207        return datagram;
208    }
209}