View Javadoc
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  
18  package org.apache.commons.net.tftp;
19  
20  import java.net.DatagramPacket;
21  import java.net.InetAddress;
22  
23  /**
24   * An abstract class derived from TFTPPacket definiing a TFTP Request packet type. It is subclassed by the
25   * {@link org.apache.commons.net.tftp.TFTPReadRequestPacket} and {@link org.apache.commons.net.tftp.TFTPWriteRequestPacket} classes.
26   * <p>
27   * 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
28   * 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
29   * should only be concerned with the {@link org.apache.commons.net.tftp.TFTPClient} class {@link org.apache.commons.net.tftp.TFTPClient#receiveFile
30   * receiveFile()} and {@link org.apache.commons.net.tftp.TFTPClient#sendFile sendFile()} methods.
31   *
32   *
33   * @see TFTPPacket
34   * @see TFTPReadRequestPacket
35   * @see TFTPWriteRequestPacket
36   * @see TFTPPacketException
37   * @see TFTP
38   */
39  
40  public abstract class TFTPRequestPacket extends TFTPPacket {
41      /**
42       * An array containing the string names of the transfer modes and indexed by the transfer mode constants.
43       */
44      static final String[] modeStrings = { "netascii", "octet" };
45  
46      /**
47       * A null terminated byte array representation of the ascii names of the transfer mode constants. This is convenient for creating the TFTP request packets.
48       */
49      private static final byte[] modeBytes[] = { { (byte) 'n', (byte) 'e', (byte) 't', (byte) 'a', (byte) 's', (byte) 'c', (byte) 'i', (byte) 'i', 0 },
50              { (byte) 'o', (byte) 'c', (byte) 't', (byte) 'e', (byte) 't', 0 } };
51  
52      /** The transfer mode of the request. */
53      private final int mode;
54  
55      /** The file name of the request. */
56      private final String fileName;
57  
58      /**
59       * 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.
60       *
61       * @param destination The host to which the packet is going to be sent.
62       * @param port        The port to which the packet is going to be sent.
63       * @param type        The type of the request (either TFTPPacket.READ_REQUEST or TFTPPacket.WRITE_REQUEST).
64       * @param fileName    The requested file name.
65       * @param mode        The requested transfer mode. This should be on of the TFTP class MODE constants (e.g., TFTP.NETASCII_MODE).
66       */
67      TFTPRequestPacket(final InetAddress destination, final int port, final int type, final String fileName, final int mode) {
68          super(type, destination, port);
69  
70          this.fileName = fileName;
71          this.mode = mode;
72      }
73  
74      /**
75       * Creates a request packet of a given type based on a received datagram. Assumes the datagram is at least length 4, else an ArrayIndexOutOfBoundsException
76       * may be thrown.
77       *
78       * @param type     The type of the request (either TFTPPacket.READ_REQUEST or TFTPPacket.WRITE_REQUEST).
79       * @param datagram The datagram containing the received request.
80       * @throws TFTPPacketException If the datagram isn't a valid TFTP request packet of the appropriate type.
81       */
82      TFTPRequestPacket(final int type, final DatagramPacket datagram) throws TFTPPacketException {
83          super(type, datagram.getAddress(), datagram.getPort());
84  
85          final byte[] data = datagram.getData();
86  
87          if (getType() != data[1]) {
88              throw new TFTPPacketException("TFTP operator code does not match type.");
89          }
90  
91          final StringBuilder buffer = new StringBuilder();
92  
93          int index = 2;
94          int length = datagram.getLength();
95  
96          while (index < length && data[index] != 0) {
97              buffer.append((char) data[index]);
98              ++index;
99          }
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 }