1 /*******************************************************************************
2 * ============LICENSE_START==================================================
4 * * ===========================================================================
5 * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6 * * ===========================================================================
7 * * Licensed under the Apache License, Version 2.0 (the "License");
8 * * you may not use this file except in compliance with the License.
9 * * You may obtain a copy of the License at
11 * * http://www.apache.org/licenses/LICENSE-2.0
13 * * Unless required by applicable law or agreed to in writing, software
14 * * distributed under the License is distributed on an "AS IS" BASIS,
15 * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * * See the License for the specific language governing permissions and
17 * * limitations under the License.
18 * * ============LICENSE_END====================================================
20 * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 ******************************************************************************/
25 package org.onap.dmaap.datarouter.node;
27 import static org.onap.dmaap.datarouter.node.utils.NodeUtils.sendResponseError;
29 import com.att.eelf.configuration.EELFLogger;
30 import com.att.eelf.configuration.EELFManager;
31 import jakarta.servlet.http.HttpServlet;
33 import java.io.FileOutputStream;
34 import java.io.FileWriter;
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.io.OutputStream;
38 import java.io.Writer;
39 import java.nio.file.Files;
40 import java.nio.file.Path;
41 import java.nio.file.Paths;
42 import java.util.Enumeration;
43 import java.util.regex.Pattern;
44 import jakarta.servlet.http.HttpServletRequest;
45 import jakarta.servlet.http.HttpServletResponse;
46 import org.jetbrains.annotations.Nullable;
47 import org.onap.dmaap.datarouter.node.delivery.Delivery;
48 import org.onap.dmaap.datarouter.node.eelf.EelfMsgs;
49 import org.onap.dmaap.datarouter.node.log.StatusLog;
50 import org.onap.dmaap.datarouter.node.utils.NodeUtils;
54 * Servlet for handling all http and https requests to the data router node.
56 * <p>Handled requests are:
58 * GET http://<i>node</i>/internal/fetchProv - fetch the provisioning data
60 * PUT/DELETE https://<i>node</i>/internal/publish/<i>fileid</i> - n2n transfer
62 * PUT/DELETE https://<i>node</i>/publish/<i>feedid</i>/<i>fileid</i> - publsh request
64 public class NodeServlet extends HttpServlet {
66 private static final String FROM = " from ";
67 private static final String INVALID_REQUEST_URI = "Invalid request URI. Expecting <feed-publishing-url>/<fileid>.";
68 private static final String IO_EXCEPTION = "IOException";
69 private static final String ON_BEHALF_OF = "X-DMAAP-DR-ON-BEHALF-OF";
70 private final NodeConfigManager config;
71 private static final Pattern metaDataPattern;
72 private static final EELFLogger eelfLogger = EELFManager.getInstance().getLogger(NodeServlet.class);
75 final String ws = "\\s*";
76 // assume that \\ and \" have been replaced by X
77 final String string = "\"[^\"]*\"";
78 final String number = "[+-]?(?:\\.\\d+|(?:0|[1-9]\\d*)(?:\\.\\d*)?)(?:[eE][+-]?\\d+)?";
79 final String value = "(?:" + string + "|" + number + "|null|true|false)";
80 final String item = string + ws + ":" + ws + value + ws;
81 final String object = ws + "\\{" + ws + "(?:" + item + "(?:" + "," + ws + item + ")*)?\\}" + ws;
82 metaDataPattern = Pattern.compile(object, Pattern.DOTALL);
85 private final Delivery delivery;
87 NodeServlet(Delivery delivery, NodeConfigManager nodeConfigManager) {
88 config = nodeConfigManager;
89 this.delivery = delivery;
93 * Get the NodeConfigurationManager.
97 eelfLogger.debug("NODE0101 Node Servlet Configured");
100 private boolean down(HttpServletResponse resp) {
101 if (config.isShutdown() || !config.isConfigured()) {
102 sendResponseError(resp, HttpServletResponse.SC_SERVICE_UNAVAILABLE, eelfLogger);
103 eelfLogger.error("NODE0102 Rejecting request: Service is being quiesced");
110 * Handle a GET for /internal/fetchProv.
113 protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
114 NodeUtils.setIpAndFqdnForEelf("doGet");
115 NodeUtils.setRequestIdAndInvocationId(req);
116 eelfLogger.info(EelfMsgs.ENTRY);
118 eelfLogger.debug(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(ON_BEHALF_OF),
119 getIdFromPath(req) + "");
123 String path = req.getPathInfo();
124 String qs = req.getQueryString();
125 String ip = req.getRemoteAddr();
127 path = path + "?" + qs;
129 if ("/internal/fetchProv".equals(path)) {
131 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
133 } else if (path.startsWith("/internal/resetSubscription/")) {
134 String subid = path.substring(28);
135 if (subid.length() != 0 && subid.indexOf('/') == -1) {
136 NodeServer.resetQueue(subid, ip);
137 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
142 eelfLogger.debug("NODE0103 Rejecting invalid GET of " + path + FROM + ip);
143 sendResponseError(resp, HttpServletResponse.SC_NOT_FOUND, eelfLogger);
145 eelfLogger.info(EelfMsgs.EXIT);
150 * Handle all PUT requests.
153 protected void doPut(HttpServletRequest req, HttpServletResponse resp) {
154 NodeUtils.setIpAndFqdnForEelf("doPut");
155 NodeUtils.setRequestIdAndInvocationId(req);
156 eelfLogger.info(EelfMsgs.ENTRY);
157 eelfLogger.debug(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(ON_BEHALF_OF),
158 getIdFromPath(req) + "");
160 common(req, resp, true);
161 } catch (IOException ioe) {
162 eelfLogger.error(IO_EXCEPTION, ioe);
163 eelfLogger.info(EelfMsgs.EXIT);
168 * Handle all DELETE requests.
171 protected void doDelete(HttpServletRequest req, HttpServletResponse resp) {
172 NodeUtils.setIpAndFqdnForEelf("doDelete");
173 NodeUtils.setRequestIdAndInvocationId(req);
174 eelfLogger.info(EelfMsgs.ENTRY);
175 eelfLogger.debug(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(ON_BEHALF_OF),
176 getIdFromPath(req) + "");
178 common(req, resp, false);
179 } catch (IOException ioe) {
180 eelfLogger.error(IO_EXCEPTION, ioe);
181 eelfLogger.info(EelfMsgs.EXIT);
185 private void common(HttpServletRequest req, HttpServletResponse resp, boolean isput) throws IOException {
186 final String PUBLISH = "/publish/";
187 final String INTERNAL_PUBLISH = "/internal/publish/";
188 final String HTTPS = "https://";
189 final String USER = " user ";
190 String fileid = getFileId(req, resp);
191 if (fileid == null) {
194 String feedid = null;
196 String ip = req.getRemoteAddr();
197 String lip = req.getLocalAddr();
199 String rcvd = NodeUtils.logts(System.currentTimeMillis()) + ";from=" + ip + ";by=" + lip;
201 if (fileid.startsWith("/delete/")) {
202 deleteFile(req, resp, fileid, pubid);
205 String credentials = req.getHeader("Authorization");
206 if (credentials == null) {
207 eelfLogger.error("NODE0306 Rejecting unauthenticated PUT or DELETE of " + req.getPathInfo() + FROM + req
209 resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Authorization header required");
210 eelfLogger.info(EelfMsgs.EXIT);
213 if (fileid.startsWith(PUBLISH)) {
214 fileid = fileid.substring(9);
215 int index = fileid.indexOf('/');
216 if (index == -1 || index == fileid.length() - 1) {
217 eelfLogger.error("NODE0205 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + FROM + req
219 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
220 "Invalid request URI. Expecting <feed-publishing-url>/<fileid>. Possible missing fileid.");
221 eelfLogger.info(EelfMsgs.EXIT);
224 feedid = fileid.substring(0, index);
225 fileid = fileid.substring(index + 1);
226 pubid = config.getPublishId();
227 targets = config.getTargets(feedid);
228 } else if (fileid.startsWith(INTERNAL_PUBLISH)) {
229 if (!config.isAnotherNode(credentials, ip)) {
230 eelfLogger.error("NODE0107 Rejecting unauthorized node-to-node transfer attempt from " + ip);
231 resp.sendError(HttpServletResponse.SC_FORBIDDEN);
232 eelfLogger.info(EelfMsgs.EXIT);
235 fileid = fileid.substring(18);
236 pubid = generateAndValidatePublishId(req);
237 targets = config.parseRouting(req.getHeader("X-DMAAP-DR-ROUTING"));
239 eelfLogger.error("NODE0204 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + FROM + req
241 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
242 INVALID_REQUEST_URI);
243 eelfLogger.info(EelfMsgs.EXIT);
246 if (fileid.indexOf('/') != -1) {
247 eelfLogger.error("NODE0202 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + FROM + req
249 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
250 INVALID_REQUEST_URI);
251 eelfLogger.info(EelfMsgs.EXIT);
254 String qs = req.getQueryString();
256 fileid = fileid + "?" + qs;
258 String hp = config.getMyName();
259 int xp = config.getExtHttpsPort();
263 String logurl = HTTPS + hp + INTERNAL_PUBLISH + fileid;
264 if (feedid != null) {
265 logurl = HTTPS + hp + PUBLISH + feedid + "/" + fileid;
266 String reason = config.isPublishPermitted(feedid, credentials, ip);
267 if (reason != null) {
268 eelfLogger.info("NODE0111 Rejecting unauthorized publish attempt to feed " + feedid + " fileid "
269 + fileid + " from " + ip + " reason " + reason);
270 resp.sendError(javax.servlet.http.HttpServletResponse.SC_FORBIDDEN, reason);
271 eelfLogger.info(EelfMsgs.EXIT);
274 user = config.getAuthUser(feedid, credentials);
275 String newnode = config.getIngressNode(feedid, user, ip);
276 if (newnode != null) {
278 int iport = config.getExtHttpsPort();
282 String redirto = HTTPS + newnode + port + PUBLISH + feedid + "/" + fileid;
284 .debug("NODE0108 Redirecting publish attempt for feed " + PathUtil.cleanString(feedid) + USER
285 + PathUtil.cleanString(user) + " ip " + PathUtil.cleanString(ip) + " to " + PathUtil
286 .cleanString(redirto)); //Fortify scan fixes - log forging
287 resp.sendRedirect(PathUtil.cleanString(redirto)); //Fortify scan fixes-open redirect - 2 issues
288 eelfLogger.info(EelfMsgs.EXIT);
291 resp.setHeader("X-DMAAP-DR-PUBLISH-ID", pubid);
293 if (req.getPathInfo().startsWith(INTERNAL_PUBLISH)) {
294 feedid = req.getHeader("X-DMAAP-DR-FEED-ID");
296 String fbase = PathUtil.cleanString(config.getSpoolDir() + "/" + pubid); //Fortify scan fixes-Path manipulation
297 File data = new File(fbase);
298 File meta = new File(fbase + ".M");
301 StringBuilder mx = new StringBuilder();
302 mx.append(req.getMethod()).append('\t').append(fileid).append('\n');
303 Enumeration<String> hnames = req.getHeaderNames();
305 boolean hasRequestIdHeader = false;
306 boolean hasInvocationIdHeader = false;
307 while (hnames.hasMoreElements()) {
308 String hn = hnames.nextElement();
309 String hnlc = hn.toLowerCase();
310 if ((isput && ("content-type".equals(hnlc)
311 || "content-language".equals(hnlc)
312 || "content-md5".equals(hnlc)
313 || "content-range".equals(hnlc)))
314 || "x-dmaap-dr-meta".equals(hnlc)
315 || (feedid == null && "x-dmaap-dr-received".equals(hnlc))
316 || (hnlc.startsWith("x-") && !hnlc.startsWith("x-dmaap-dr-"))) {
317 Enumeration<String> hvals = req.getHeaders(hn);
318 while (hvals.hasMoreElements()) {
319 String hv = hvals.nextElement();
320 if ("content-type".equals(hnlc)) {
323 if ("x-onap-requestid".equals(hnlc)) {
324 hasRequestIdHeader = true;
326 if ("x-invocationid".equals(hnlc)) {
327 hasInvocationIdHeader = true;
329 if ("x-dmaap-dr-meta".equals(hnlc)) {
330 if (hv.length() > 4096) {
331 eelfLogger.error("NODE0109 Rejecting publish attempt with metadata too long for feed "
332 + PathUtil.cleanString(feedid) + USER + PathUtil.cleanString(user) + " ip "
333 + PathUtil.cleanString(ip)); //Fortify scan fixes - log forging
334 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Metadata too long");
335 eelfLogger.info(EelfMsgs.EXIT);
338 if (!metaDataPattern.matcher(hv.replaceAll("\\\\.", "X")).matches()) {
339 eelfLogger.error("NODE0109 Rejecting publish attempt with malformed metadata for feed "
340 + PathUtil.cleanString(feedid) + USER + PathUtil.cleanString(user) + " ip "
341 + PathUtil.cleanString(ip)); //Fortify scan fixes - log forging
342 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Malformed metadata");
343 eelfLogger.info(EelfMsgs.EXIT);
347 mx.append(hn).append('\t').append(hv).append('\n');
351 if (!hasRequestIdHeader) {
352 mx.append("X-ONAP-RequestID\t").append(MDC.get("RequestId")).append('\n');
354 if (!hasInvocationIdHeader) {
355 mx.append("X-InvocationID\t").append(MDC.get("InvocationId")).append('\n');
357 mx.append("X-DMAAP-DR-RECEIVED\t").append(rcvd).append('\n');
358 String metadata = mx.toString();
359 long exlen = getExlen(req);
360 String message = writeInputStreamToFile(req, data);
361 if (message != null) {
362 StatusLog.logPubFail(pubid, feedid, logurl, req.getMethod(), ctype, exlen, data.length(), ip, user,
364 throw new IOException(message);
366 Path dpath = Paths.get(fbase);
367 for (Target t : targets) {
368 DestInfo di = t.getDestInfo();
370 //Handle this? : unknown destination
373 String dbase = PathUtil
374 .cleanString(di.getSpool() + "/" + pubid); //Fortify scan fixes-Path Manipulation
375 Files.createLink(Paths.get(dbase), dpath);
376 mw = new FileWriter(meta);
378 if (di.getSubId() == null) {
379 mw.write("X-DMAAP-DR-ROUTING\t" + t.getRouting() + "\n");
382 if (!meta.renameTo(new File(dbase + ".M"))) {
383 eelfLogger.error("Rename of file " + dbase + " failed.");
386 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
388 resp.getOutputStream().close();
389 } catch (IOException ioe) {
390 StatusLog.logPubFail(pubid, feedid, logurl, req.getMethod(), ctype, exlen, data.length(), ip, user,
392 //Fortify scan fixes - log forging
393 eelfLogger.error("NODE0110 IO Exception while closing IO stream " + PathUtil.cleanString(feedid)
394 + USER + PathUtil.cleanString(user) + " ip " + PathUtil.cleanString(ip) + " " + ioe
399 StatusLog.logPub(pubid, feedid, logurl, req.getMethod(), ctype, data.length(), ip, user,
400 HttpServletResponse.SC_NO_CONTENT);
401 } catch (IOException ioe) {
402 eelfLogger.error("NODE0110 IO Exception receiving publish attempt for feed " + feedid + USER + user
403 + " ip " + ip + " " + ioe.toString(), ioe);
404 eelfLogger.info(EelfMsgs.EXIT);
410 } catch (Exception e) {
411 eelfLogger.error("NODE0532 Exception common: " + e);
415 Files.delete(data.toPath());
416 Files.delete(meta.toPath());
417 } catch (Exception e) {
418 eelfLogger.error("NODE0533 Exception common: " + e);
423 private String generateAndValidatePublishId(HttpServletRequest req) throws IOException {
424 String newPubId = req.getHeader("X-DMAAP-DR-PUBLISH-ID");
428 if(newPubId.matches(regex)){
431 throw new IOException("Invalid Header X-DMAAP-DR-PUBLISH-ID");
434 private String writeInputStreamToFile(HttpServletRequest req, File data) {
435 byte[] buf = new byte[1024 * 1024];
437 try (OutputStream dos = new FileOutputStream(data);
438 InputStream is = req.getInputStream()) {
439 while ((bytesRead = is.read(buf)) > 0) {
440 dos.write(buf, 0, bytesRead);
442 } catch (IOException ioe) {
443 eelfLogger.error("NODE0530 Exception common: " + ioe, ioe);
444 eelfLogger.info(EelfMsgs.EXIT);
445 return ioe.getMessage();
450 private long getExlen(HttpServletRequest req) {
453 exlen = Long.parseLong(req.getHeader("Content-Length"));
454 } catch (Exception e) {
455 eelfLogger.error("NODE0529 Exception common: " + e);
460 private void deleteFile(HttpServletRequest req, HttpServletResponse resp, String fileid, String pubid) {
461 final String FROM_DR_MESSAGE = ".M) from DR Node: ";
463 fileid = fileid.substring(8);
464 int index = fileid.indexOf('/');
465 if (index == -1 || index == fileid.length() - 1) {
466 eelfLogger.error("NODE0112 Rejecting bad URI for DELETE of " + req.getPathInfo() + FROM + req
468 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
469 "Invalid request URI. Expecting <subId>/<pubId>.");
470 eelfLogger.info(EelfMsgs.EXIT);
473 String subscriptionId = fileid.substring(0, index);
474 int subId = Integer.parseInt(subscriptionId);
475 pubid = fileid.substring(index + 1);
476 String errorMessage = "Unable to delete files (" + pubid + ", " + pubid + FROM_DR_MESSAGE
477 + config.getMyName() + ".";
478 int subIdDir = subId - (subId % 100);
479 if (!isAuthorizedToDelete(resp, subscriptionId, errorMessage)) {
482 boolean result = delivery.markTaskSuccess(config.getSpoolBase() + "/s/" + subIdDir + "/" + subId, pubid);
484 eelfLogger.debug("NODE0115 Successfully deleted files (" + pubid + ", " + pubid + FROM_DR_MESSAGE
485 + config.getMyName());
486 resp.setStatus(HttpServletResponse.SC_OK);
487 eelfLogger.info(EelfMsgs.EXIT);
489 eelfLogger.error("NODE0116 " + errorMessage);
490 resp.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found on server.");
491 eelfLogger.info(EelfMsgs.EXIT);
493 } catch (IOException ioe) {
494 eelfLogger.error("NODE0117 Unable to delete files (" + pubid + ", " + pubid + FROM_DR_MESSAGE
495 + config.getMyName(), ioe);
496 eelfLogger.info(EelfMsgs.EXIT);
501 private String getFileId(HttpServletRequest req, HttpServletResponse resp) throws IOException {
503 eelfLogger.info(EelfMsgs.EXIT);
506 if (!req.isSecure() && config.isTlsEnabled()) {
508 "NODE0104 Rejecting insecure PUT or DELETE of " + req.getPathInfo() + FROM + req
510 resp.sendError(HttpServletResponse.SC_FORBIDDEN, "https required on publish requests");
511 eelfLogger.info(EelfMsgs.EXIT);
514 String fileid = req.getPathInfo();
515 if (fileid == null) {
516 eelfLogger.error("NODE0201 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + FROM + req
518 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
519 INVALID_REQUEST_URI);
520 eelfLogger.info(EelfMsgs.EXIT);
526 private boolean isAuthorizedToDelete(HttpServletResponse resp, String subscriptionId, String errorMessage)
529 boolean deletePermitted = config.isDeletePermitted(subscriptionId);
530 if (!deletePermitted) {
531 eelfLogger.error("NODE0113 " + errorMessage + " Error: Subscription "
532 + subscriptionId + " is not a privileged subscription");
533 resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
534 eelfLogger.info(EelfMsgs.EXIT);
537 } catch (NullPointerException npe) {
538 eelfLogger.error("NODE0114 " + errorMessage + " Error: Subscription " + subscriptionId
539 + " does not exist", npe);
540 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
541 eelfLogger.info(EelfMsgs.EXIT);
547 private int getIdFromPath(HttpServletRequest req) {
548 String path = req.getPathInfo();
549 if (path == null || path.length() < 2) {
553 return Integer.parseInt(path.substring(1));
554 } catch (NumberFormatException e) {
560 * Utility class that validates the path url formed from
561 * the string passed in the request parameters.
563 static class PathUtil {
566 throw new IllegalStateException("Utility Class");
570 * This method takes String as the parameter and return the filtered path string.
572 * @param string String to clean
573 * @return A cleaned String
575 static String cleanString(String string) {
576 if (string == null) {
579 StringBuilder cleanString = new StringBuilder();
580 for (int i = 0; i < string.length(); ++i) {
581 cleanString.append(cleanChar(string.charAt(i)));
583 return cleanString.toString();
587 * This method filters the valid special characters in path string.
589 * @param character The char to be cleaned
590 * @return The cleaned char
592 private static char cleanChar(char character) {
594 for (int i = 48; i < 58; ++i) {
595 if (character == i) {
600 for (int i = 65; i < 91; ++i) {
601 if (character == i) {
606 for (int i = 97; i < 123; ++i) {
607 if (character == i) {
611 return getValidCharacter(character);
614 private static char getValidCharacter(char character) {
615 // other valid characters