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