TFTPRequestPacket.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.net.tftp;

  18. import java.net.DatagramPacket;
  19. import java.net.InetAddress;
  20. import java.nio.charset.Charset;

  21. /**
  22.  * An abstract class derived from TFTPPacket definiing a TFTP Request packet type. It is subclassed by the
  23.  * {@link org.apache.commons.net.tftp.TFTPReadRequestPacket} and {@link org.apache.commons.net.tftp.TFTPWriteRequestPacket} classes.
  24.  * <p>
  25.  * 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
  26.  * 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
  27.  * should only be concerned with the {@link org.apache.commons.net.tftp.TFTPClient} class {@link org.apache.commons.net.tftp.TFTPClient#receiveFile
  28.  * receiveFile()} and {@link org.apache.commons.net.tftp.TFTPClient#sendFile sendFile()} methods.
  29.  *
  30.  *
  31.  * @see TFTPPacket
  32.  * @see TFTPReadRequestPacket
  33.  * @see TFTPWriteRequestPacket
  34.  * @see TFTPPacketException
  35.  * @see TFTP
  36.  */

  37. public abstract class TFTPRequestPacket extends TFTPPacket {
  38.     /**
  39.      * An array containing the string names of the transfer modes and indexed by the transfer mode constants.
  40.      */
  41.     static final String[] modeStrings = { "netascii", "octet" };

  42.     /**
  43.      * A null terminated byte array representation of the ASCII names of the transfer mode constants. This is convenient for creating the TFTP request packets.
  44.      */
  45.     private static final byte[] modeBytes[] = { { (byte) 'n', (byte) 'e', (byte) 't', (byte) 'a', (byte) 's', (byte) 'c', (byte) 'i', (byte) 'i', 0 },
  46.             { (byte) 'o', (byte) 'c', (byte) 't', (byte) 'e', (byte) 't', 0 } };

  47.     /** The transfer mode of the request. */
  48.     private final int mode;

  49.     /** The file name of the request. */
  50.     private final String fileName;

  51.     /**
  52.      * 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.
  53.      *
  54.      * @param destination The host to which the packet is going to be sent.
  55.      * @param port        The port to which the packet is going to be sent.
  56.      * @param type        The type of the request (either TFTPPacket.READ_REQUEST or TFTPPacket.WRITE_REQUEST).
  57.      * @param fileName    The requested file name.
  58.      * @param mode        The requested transfer mode. This should be on of the TFTP class MODE constants (e.g., TFTP.NETASCII_MODE).
  59.      */
  60.     TFTPRequestPacket(final InetAddress destination, final int port, final int type, final String fileName, final int mode) {
  61.         super(type, destination, port);

  62.         this.fileName = fileName;
  63.         this.mode = mode;
  64.     }

  65.     /**
  66.      * Creates a request packet of a given type based on a received datagram. Assumes the datagram is at least length 4, else an ArrayIndexOutOfBoundsException
  67.      * may be thrown.
  68.      *
  69.      * @param type     The type of the request (either TFTPPacket.READ_REQUEST or TFTPPacket.WRITE_REQUEST).
  70.      * @param datagram The datagram containing the received request.
  71.      * @throws TFTPPacketException If the datagram isn't a valid TFTP request packet of the appropriate type.
  72.      */
  73.     TFTPRequestPacket(final int type, final DatagramPacket datagram) throws TFTPPacketException {
  74.         super(type, datagram.getAddress(), datagram.getPort());

  75.         final byte[] data = datagram.getData();

  76.         if (getType() != data[1]) {
  77.             throw new TFTPPacketException("TFTP operator code does not match type.");
  78.         }

  79.         final StringBuilder buffer = new StringBuilder();

  80.         int index = 2;
  81.         int length = datagram.getLength();

  82.         while (index < length && data[index] != 0) {
  83.             buffer.append((char) data[index]);
  84.             ++index;
  85.         }

  86.         this.fileName = buffer.toString();

  87.         if (index >= length) {
  88.             throw new TFTPPacketException("Bad file name and mode format.");
  89.         }

  90.         buffer.setLength(0);
  91.         ++index; // need to advance beyond the end of string marker
  92.         while (index < length && data[index] != 0) {
  93.             buffer.append((char) data[index]);
  94.             ++index;
  95.         }

  96.         final String modeString = buffer.toString().toLowerCase(java.util.Locale.ENGLISH);
  97.         length = modeStrings.length;

  98.         int mode = 0;
  99.         for (index = 0; index < length; index++) {
  100.             if (modeString.equals(modeStrings[index])) {
  101.                 mode = index;
  102.                 break;
  103.             }
  104.         }

  105.         this.mode = mode;

  106.         if (index >= length) {
  107.             throw new TFTPPacketException("Unrecognized TFTP transfer mode: " + modeString);
  108.             // May just want to default to binary mode instead of throwing
  109.             // exception.
  110.             // _mode = TFTP.OCTET_MODE;
  111.         }
  112.     }

  113.     /**
  114.      * Returns the requested file name.
  115.      *
  116.      * @return The requested file name.
  117.      */
  118.     public final String getFilename() {
  119.         return fileName;
  120.     }

  121.     /**
  122.      * Returns the transfer mode of the request.
  123.      *
  124.      * @return The transfer mode of the request.
  125.      */
  126.     public final int getMode() {
  127.         return mode;
  128.     }

  129.     /**
  130.      * 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
  131.      * implement his own TFTP client instead of using the {@link org.apache.commons.net.tftp.TFTPClient} class. Under normal circumstances, you should not have
  132.      * a need to call this method.
  133.      *
  134.      * @return A UDP datagram containing the TFTP request packet.
  135.      */
  136.     @Override
  137.     public final DatagramPacket newDatagram() {
  138.         final int fileLength;
  139.         final int modeLength;
  140.         final byte[] data;

  141.         fileLength = fileName.length();
  142.         modeLength = modeBytes[mode].length;

  143.         data = new byte[fileLength + modeLength + 4];
  144.         data[0] = 0;
  145.         data[1] = (byte) type;
  146.         System.arraycopy(fileName.getBytes(Charset.defaultCharset()), 0, data, 2, fileLength);
  147.         data[fileLength + 2] = 0;
  148.         System.arraycopy(modeBytes[mode], 0, data, fileLength + 3, modeLength);

  149.         return new DatagramPacket(data, data.length, address, port);
  150.     }

  151.     /**
  152.      * This is a method only available within the package for implementing efficient datagram transport by elminating buffering. It takes a datagram as an
  153.      * 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.
  154.      *
  155.      * @param datagram The datagram to create.
  156.      * @param data     The buffer to store the packet and to use in the datagram.
  157.      * @return The datagram argument.
  158.      */
  159.     @Override
  160.     final DatagramPacket newDatagram(final DatagramPacket datagram, final byte[] data) {
  161.         final int fileLength;
  162.         final int modeLength;

  163.         fileLength = fileName.length();
  164.         modeLength = modeBytes[mode].length;

  165.         data[0] = 0;
  166.         data[1] = (byte) type;
  167.         System.arraycopy(fileName.getBytes(Charset.defaultCharset()), 0, data, 2, fileLength);
  168.         data[fileLength + 2] = 0;
  169.         System.arraycopy(modeBytes[mode], 0, data, fileLength + 3, modeLength);

  170.         datagram.setAddress(address);
  171.         datagram.setPort(port);
  172.         datagram.setData(data);
  173.         datagram.setLength(fileLength + modeLength + 3);

  174.         return datagram;
  175.     }
  176. }