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 * https://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 import java.nio.charset.StandardCharsets;
24 import java.util.HashMap;
25 import java.util.Locale;
26 import java.util.Map;
27
28 /**
29 * An abstract class derived from TFTPPacket definiing a TFTP Request packet type. It is subclassed by the
30 * {@link org.apache.commons.net.tftp.TFTPReadRequestPacket} and {@link org.apache.commons.net.tftp.TFTPWriteRequestPacket} classes.
31 * <p>
32 * 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
33 * 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
34 * should only be concerned with the {@link org.apache.commons.net.tftp.TFTPClient} class {@link org.apache.commons.net.tftp.TFTPClient#receiveFile
35 * receiveFile()} and {@link org.apache.commons.net.tftp.TFTPClient#sendFile sendFile()} methods.
36 * </p>
37 *
38 * @see TFTPPacket
39 * @see TFTPReadRequestPacket
40 * @see TFTPWriteRequestPacket
41 * @see TFTPPacketException
42 * @see TFTP
43 */
44
45 public abstract class TFTPRequestPacket extends TFTPPacket {
46 /**
47 * An array containing the string names of the transfer modes and indexed by the transfer mode constants.
48 */
49 static final String[] modeStrings = { "netascii", "octet" };
50
51 /**
52 * A null terminated byte array representation of the ASCII names of the transfer mode constants. This is convenient for creating the TFTP request packets.
53 */
54 private static final byte[] modeBytes[] = { { (byte) 'n', (byte) 'e', (byte) 't', (byte) 'a', (byte) 's', (byte) 'c', (byte) 'i', (byte) 'i', 0 },
55 { (byte) 'o', (byte) 'c', (byte) 't', (byte) 'e', (byte) 't', 0 } };
56
57 /** The transfer mode of the request. */
58 private final int mode;
59
60 /** The file name of the request. */
61 private final String fileName;
62
63 /** The option values */
64 private final Map<String, String> options = new HashMap<>();
65
66 /**
67 * 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.
68 *
69 * @param destination The host to which the packet is going to be sent.
70 * @param port The port to which the packet is going to be sent.
71 * @param type The type of the request (either TFTPPacket.READ_REQUEST or TFTPPacket.WRITE_REQUEST).
72 * @param fileName The requested file name.
73 * @param mode The requested transfer mode. This should be on of the TFTP class MODE constants (e.g., TFTP.NETASCII_MODE).
74 */
75 TFTPRequestPacket(final InetAddress destination, final int port, final int type, final String fileName, final int mode) {
76 super(type, destination, port);
77
78 this.fileName = fileName;
79 this.mode = mode;
80 }
81
82 /**
83 * Creates a request packet of a given type based on a received datagram. Assumes the datagram is at least length 4, else an ArrayIndexOutOfBoundsException
84 * may be thrown.
85 *
86 * @param type The type of the request (either TFTPPacket.READ_REQUEST or TFTPPacket.WRITE_REQUEST).
87 * @param datagram The datagram containing the received request.
88 * @throws TFTPPacketException If the datagram isn't a valid TFTP request packet of the appropriate type.
89 */
90 TFTPRequestPacket(final int type, final DatagramPacket datagram) throws TFTPPacketException {
91 super(type, datagram.getAddress(), datagram.getPort());
92
93 final byte[] data = datagram.getData();
94
95 if (getType() != data[1]) {
96 throw new TFTPPacketException("TFTP operator code does not match type.");
97 }
98
99 final StringBuilder buffer = new StringBuilder();
100
101 int index = 2;
102 final int length = datagram.getLength();
103
104 while (index < length && data[index] != 0) {
105 buffer.append((char) data[index]);
106 ++index;
107 }
108
109 this.fileName = buffer.toString();
110
111 if (index >= length) {
112 throw new TFTPPacketException("Bad file name and mode format.");
113 }
114
115 buffer.setLength(0);
116 ++index; // need to advance beyond the end of string marker
117 while (index < length && data[index] != 0) {
118 buffer.append((char) data[index]);
119 ++index;
120 }
121
122 final String modeString = buffer.toString().toLowerCase(Locale.ENGLISH);
123 final int modeStringsLength = modeStrings.length;
124
125 int mode = 0;
126 int modeIndex;
127 for (modeIndex = 0; modeIndex < modeStringsLength; modeIndex++) {
128 if (modeString.equals(modeStrings[modeIndex])) {
129 mode = modeIndex;
130 break;
131 }
132 }
133
134 this.mode = mode;
135
136 if (modeIndex >= modeStringsLength) {
137 throw new TFTPPacketException("Unrecognized TFTP transfer mode: " + modeString);
138 // May just want to default to binary mode instead of throwing
139 // exception.
140 // _mode = TFTP.OCTET_MODE;
141 }
142
143 ++index;
144 while (index < length) {
145 int start = index;
146 for (; data[index] != 0; ++index) {
147 if (index >= length) {
148 throw new TFTPPacketException("Invalid option format");
149 }
150 }
151 final String option = new String(data, start, index - start, StandardCharsets.US_ASCII);
152 ++index;
153 start = index;
154 for (; data[index] != 0; ++index) {
155 if (index >= length) {
156 throw new TFTPPacketException("Invalid option format");
157 }
158 }
159 final String octets = new String(data, start, index - start, StandardCharsets.US_ASCII);
160 this.options.put(option, octets);
161 ++index;
162 }
163 }
164
165 /**
166 * Gets the requested file name.
167 *
168 * @return The requested file name.
169 */
170 public final String getFilename() {
171 return fileName;
172 }
173
174 /**
175 * Gets the transfer mode of the request.
176 *
177 * @return The transfer mode of the request.
178 */
179 public final int getMode() {
180 return mode;
181 }
182
183 /**
184 * Gets the options extensions of the request as a map.
185 * The keys are the option names and the values are the option values.
186 *
187 * @return The options extensions of the request as a map.
188 * @since 3.12.0
189 */
190 public final Map<String, String> getOptions() {
191 return options;
192 }
193
194 /**
195 * 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
196 * implement his own TFTP client instead of using the {@link org.apache.commons.net.tftp.TFTPClient} class. Under normal circumstances, you should not have
197 * a need to call this method.
198 *
199 * @return A UDP datagram containing the TFTP request packet.
200 */
201 @Override
202 public final DatagramPacket newDatagram() {
203 final int fileLength;
204 final int modeLength;
205 final byte[] data;
206
207 fileLength = fileName.length();
208 modeLength = modeBytes[mode].length;
209
210 int optionsLength = 0;
211 for (final Map.Entry<String, String> entry : options.entrySet()) {
212 optionsLength += entry.getKey().length() + 1 + entry.getValue().length() + 1;
213 }
214 data = new byte[fileLength + modeLength + 3 + optionsLength];
215 data[0] = 0;
216 data[1] = (byte) type;
217 System.arraycopy(fileName.getBytes(Charset.defaultCharset()), 0, data, 2, fileLength);
218 data[fileLength + 2] = 0;
219 System.arraycopy(modeBytes[mode], 0, data, fileLength + 3, modeLength);
220
221 if (optionsLength > 0) {
222 handleOptions(data, fileLength, modeLength);
223 }
224
225 return new DatagramPacket(data, data.length, address, port);
226 }
227
228 /**
229 * This is a method only available within the package for implementing efficient datagram transport by elminating buffering. It takes a datagram as an
230 * 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.
231 *
232 * @param datagram The datagram to create.
233 * @param data The buffer to store the packet and to use in the datagram.
234 * @return The datagram argument.
235 */
236 @Override
237 final DatagramPacket newDatagram(final DatagramPacket datagram, final byte[] data) {
238 final int fileLength;
239 final int modeLength;
240
241 fileLength = fileName.length();
242 modeLength = modeBytes[mode].length;
243
244 data[0] = 0;
245 data[1] = (byte) type;
246 System.arraycopy(fileName.getBytes(Charset.defaultCharset()), 0, data, 2, fileLength);
247 data[fileLength + 2] = 0;
248 System.arraycopy(modeBytes[mode], 0, data, fileLength + 3, modeLength);
249
250 handleOptions(data, fileLength, modeLength);
251
252 datagram.setAddress(address);
253 datagram.setPort(port);
254 datagram.setData(data);
255 datagram.setLength(fileLength + modeLength + 3);
256
257 return datagram;
258 }
259
260 private void handleOptions(final byte[] data, final int fileLength, final int modeLength) {
261 int index = fileLength + modeLength + 2;
262 for (final Map.Entry<String, String> entry : options.entrySet()) {
263 data[index] = 0;
264 final String key = entry.getKey();
265 final String value = entry.getValue();
266
267 System.arraycopy(key.getBytes(StandardCharsets.US_ASCII), 0, data, ++index, key.length());
268 index += key.length();
269 data[index++] = 0;
270
271 System.arraycopy(value.getBytes(StandardCharsets.US_ASCII), 0, data, index, value.length());
272 index += value.length();
273 }
274 }
275 }