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