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