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.NodeUtils.sendResponseError;
29 import com.att.eelf.configuration.EELFLogger;
30 import com.att.eelf.configuration.EELFManager;
32 import java.io.FileOutputStream;
33 import java.io.FileWriter;
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.io.OutputStream;
37 import java.io.Writer;
38 import java.nio.file.Files;
39 import java.nio.file.Path;
40 import java.nio.file.Paths;
41 import java.util.Enumeration;
42 import java.util.regex.Pattern;
43 import javax.servlet.http.HttpServlet;
44 import javax.servlet.http.HttpServletRequest;
45 import javax.servlet.http.HttpServletResponse;
46 import org.jetbrains.annotations.Nullable;
47 import org.onap.dmaap.datarouter.node.eelf.EelfMsgs;
51 * Servlet for handling all http and https requests to the data router node.
53 * <p>Handled requests are:
55 * GET http://<i>node</i>/internal/fetchProv - fetch the provisioning data
57 * PUT/DELETE https://<i>node</i>/internal/publish/<i>fileid</i> - n2n transfer
59 * PUT/DELETE https://<i>node</i>/publish/<i>feedid</i>/<i>fileid</i> - publsh request
61 public class NodeServlet extends HttpServlet {
63 private static final String FROM = " from ";
64 private static final String INVALID_REQUEST_URI = "Invalid request URI. Expecting <feed-publishing-url>/<fileid>.";
65 private static final String IO_EXCEPTION = "IOException";
66 private static final String ON_BEHALF_OF = "X-DMAAP-DR-ON-BEHALF-OF";
67 private static NodeConfigManager config;
68 private static Pattern metaDataPattern;
69 private static EELFLogger eelfLogger = EELFManager.getInstance().getLogger(NodeServlet.class);
72 final String ws = "\\s*";
73 // assume that \\ and \" have been replaced by X
74 final String string = "\"[^\"]*\"";
75 final String number = "[+-]?(?:\\.\\d+|(?:0|[1-9]\\d*)(?:\\.\\d*)?)(?:[eE][+-]?\\d+)?";
76 final String value = "(?:" + string + "|" + number + "|null|true|false)";
77 final String item = string + ws + ":" + ws + value + ws;
78 final String object = ws + "\\{" + ws + "(?:" + item + "(?:" + "," + ws + item + ")*)?\\}" + ws;
79 metaDataPattern = Pattern.compile(object, Pattern.DOTALL);
82 private final Delivery delivery;
84 NodeServlet(Delivery delivery) {
85 this.delivery = delivery;
89 * Get the NodeConfigurationManager.
93 config = NodeConfigManager.getInstance();
94 eelfLogger.debug("NODE0101 Node Servlet Configured");
97 private boolean down(HttpServletResponse resp) {
98 if (config.isShutdown() || !config.isConfigured()) {
99 sendResponseError(resp, HttpServletResponse.SC_SERVICE_UNAVAILABLE, eelfLogger);
100 eelfLogger.error("NODE0102 Rejecting request: Service is being quiesced");
107 * Handle a GET for /internal/fetchProv.
110 protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
111 NodeUtils.setIpAndFqdnForEelf("doGet");
112 NodeUtils.setRequestIdAndInvocationId(req);
113 eelfLogger.info(EelfMsgs.ENTRY);
115 eelfLogger.debug(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(ON_BEHALF_OF),
116 getIdFromPath(req) + "");
120 String path = req.getPathInfo();
121 String qs = req.getQueryString();
122 String ip = req.getRemoteAddr();
124 path = path + "?" + qs;
126 if ("/internal/fetchProv".equals(path)) {
128 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
130 } else if (path.startsWith("/internal/resetSubscription/")) {
131 String subid = path.substring(28);
132 if (subid.length() != 0 && subid.indexOf('/') == -1) {
133 NodeServer.resetQueue(subid, ip);
134 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
139 eelfLogger.debug("NODE0103 Rejecting invalid GET of " + path + FROM + ip);
140 sendResponseError(resp, HttpServletResponse.SC_NOT_FOUND, eelfLogger);
142 eelfLogger.info(EelfMsgs.EXIT);
147 * Handle all PUT requests.
150 protected void doPut(HttpServletRequest req, HttpServletResponse resp) {
151 NodeUtils.setIpAndFqdnForEelf("doPut");
152 NodeUtils.setRequestIdAndInvocationId(req);
153 eelfLogger.info(EelfMsgs.ENTRY);
154 eelfLogger.debug(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(ON_BEHALF_OF),
155 getIdFromPath(req) + "");
157 common(req, resp, true);
158 } catch (IOException ioe) {
159 eelfLogger.error(IO_EXCEPTION, ioe);
160 eelfLogger.info(EelfMsgs.EXIT);
165 * Handle all DELETE requests.
168 protected void doDelete(HttpServletRequest req, HttpServletResponse resp) {
169 NodeUtils.setIpAndFqdnForEelf("doDelete");
170 NodeUtils.setRequestIdAndInvocationId(req);
171 eelfLogger.info(EelfMsgs.ENTRY);
172 eelfLogger.debug(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(ON_BEHALF_OF),
173 getIdFromPath(req) + "");
175 common(req, resp, false);
176 } catch (IOException ioe) {
177 eelfLogger.error(IO_EXCEPTION, ioe);
178 eelfLogger.info(EelfMsgs.EXIT);
182 private void common(HttpServletRequest req, HttpServletResponse resp, boolean isput) throws IOException {
183 final String PUBLISH = "/publish/";
184 final String INTERNAL_PUBLISH = "/internal/publish/";
185 final String HTTPS = "https://";
186 final String USER = " user ";
187 String fileid = getFileId(req, resp);
188 if (fileid == null) {
191 String feedid = null;
193 String ip = req.getRemoteAddr();
194 String lip = req.getLocalAddr();
196 String rcvd = NodeUtils.logts(System.currentTimeMillis()) + ";from=" + ip + ";by=" + lip;
197 Target[] targets = null;
198 boolean isAAFFeed = false;
199 if (fileid.startsWith("/delete/")) {
200 deleteFile(req, resp, fileid, pubid);
203 String credentials = req.getHeader("Authorization");
204 if (credentials == null) {
205 eelfLogger.error("NODE0306 Rejecting unauthenticated PUT or DELETE of " + req.getPathInfo() + FROM + req
207 resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Authorization header required");
208 eelfLogger.info(EelfMsgs.EXIT);
211 if (fileid.startsWith(PUBLISH)) {
212 fileid = fileid.substring(9);
213 int index = fileid.indexOf('/');
214 if (index == -1 || index == fileid.length() - 1) {
215 eelfLogger.error("NODE0205 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + FROM + req
217 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
218 "Invalid request URI. Expecting <feed-publishing-url>/<fileid>. Possible missing fileid.");
219 eelfLogger.info(EelfMsgs.EXIT);
222 feedid = fileid.substring(0, index);
224 if (config.getCadiEnabled()) {
225 String path = req.getPathInfo();
226 if (!path.startsWith("/internal") && feedid != null) {
227 String aafInstance = config.getAafInstance(feedid);
228 if (!("legacy".equalsIgnoreCase(aafInstance))) {
230 String permission = config.getPermission(aafInstance);
231 eelfLogger.debug("NodeServlet.common() permission string - " + permission);
232 //Check in CADI Framework API if user has AAF permission or not
233 if (!req.isUserInRole(permission)) {
234 String message = "AAF disallows access to permission string - " + permission;
235 eelfLogger.error("NODE0307 Rejecting unauthenticated PUT or DELETE of " + req.getPathInfo()
236 + FROM + req.getRemoteAddr());
237 resp.sendError(HttpServletResponse.SC_FORBIDDEN, message);
238 eelfLogger.info(EelfMsgs.EXIT);
245 fileid = fileid.substring(index + 1);
246 pubid = config.getPublishId();
247 targets = config.getTargets(feedid);
248 } else if (fileid.startsWith(INTERNAL_PUBLISH)) {
249 if (!config.isAnotherNode(credentials, ip)) {
250 eelfLogger.error("NODE0107 Rejecting unauthorized node-to-node transfer attempt from " + ip);
251 resp.sendError(HttpServletResponse.SC_FORBIDDEN);
252 eelfLogger.info(EelfMsgs.EXIT);
255 fileid = fileid.substring(18);
256 pubid = generateAndValidatePublishId(req);
258 user = "datartr"; // SP6 : Added usr as datartr to avoid null entries for internal routing
259 targets = config.parseRouting(req.getHeader("X-DMAAP-DR-ROUTING"));
261 eelfLogger.error("NODE0204 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + FROM + req
263 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
264 INVALID_REQUEST_URI);
265 eelfLogger.info(EelfMsgs.EXIT);
268 if (fileid.indexOf('/') != -1) {
269 eelfLogger.error("NODE0202 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + FROM + req
271 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
272 INVALID_REQUEST_URI);
273 eelfLogger.info(EelfMsgs.EXIT);
276 String qs = req.getQueryString();
278 fileid = fileid + "?" + qs;
280 String hp = config.getMyName();
281 int xp = config.getExtHttpsPort();
285 String logurl = HTTPS + hp + INTERNAL_PUBLISH + fileid;
286 if (feedid != null) {
287 logurl = HTTPS + hp + PUBLISH + feedid + "/" + fileid;
290 String reason = config.isPublishPermitted(feedid, credentials, ip);
291 if (reason != null) {
292 eelfLogger.error("NODE0111 Rejecting unauthorized publish attempt to feed " + PathUtil
293 .cleanString(feedid) + " fileid " + PathUtil.cleanString(fileid) + FROM + PathUtil
294 .cleanString(ip) + " reason " + PathUtil.cleanString(reason));
295 resp.sendError(HttpServletResponse.SC_FORBIDDEN, reason);
296 eelfLogger.info(EelfMsgs.EXIT);
299 user = config.getAuthUser(feedid, credentials);
301 String reason = config.isPublishPermitted(feedid, ip);
302 if (reason != null) {
303 eelfLogger.error("NODE0111 Rejecting unauthorized publish attempt to feed " + PathUtil
304 .cleanString(feedid) + " fileid " + PathUtil.cleanString(fileid) + FROM + PathUtil
305 .cleanString(ip) + " reason Invalid AAF user- " + PathUtil.cleanString(reason));
306 String message = "Invalid AAF user- " + PathUtil.cleanString(reason);
307 eelfLogger.debug("NODE0308 Rejecting unauthenticated PUT or DELETE of " + PathUtil
308 .cleanString(req.getPathInfo()) + FROM + PathUtil.cleanString(req.getRemoteAddr()));
309 resp.sendError(HttpServletResponse.SC_FORBIDDEN, message);
312 if ((req.getUserPrincipal() != null) && (req.getUserPrincipal().getName() != null)) {
313 String userName = req.getUserPrincipal().getName();
314 String[] attid = userName.split("@");
321 String newnode = config.getIngressNode(feedid, user, ip);
322 if (newnode != null) {
324 int iport = config.getExtHttpsPort();
328 String redirto = HTTPS + newnode + port + PUBLISH + feedid + "/" + fileid;
330 .debug("NODE0108 Redirecting publish attempt for feed " + PathUtil.cleanString(feedid) + USER
331 + PathUtil.cleanString(user) + " ip " + PathUtil.cleanString(ip) + " to " + PathUtil
332 .cleanString(redirto)); //Fortify scan fixes - log forging
333 resp.sendRedirect(PathUtil.cleanString(redirto)); //Fortify scan fixes-open redirect - 2 issues
334 eelfLogger.info(EelfMsgs.EXIT);
337 resp.setHeader("X-DMAAP-DR-PUBLISH-ID", pubid);
339 if (req.getPathInfo().startsWith(INTERNAL_PUBLISH)) {
340 feedid = req.getHeader("X-DMAAP-DR-FEED-ID");
342 String fbase = PathUtil.cleanString(config.getSpoolDir() + "/" + pubid); //Fortify scan fixes-Path manipulation
343 File data = new File(fbase);
344 File meta = new File(fbase + ".M");
347 StringBuilder mx = new StringBuilder();
348 mx.append(req.getMethod()).append('\t').append(fileid).append('\n');
349 Enumeration hnames = req.getHeaderNames();
351 boolean hasRequestIdHeader = false;
352 boolean hasInvocationIdHeader = false;
353 while (hnames.hasMoreElements()) {
354 String hn = (String) hnames.nextElement();
355 String hnlc = hn.toLowerCase();
356 if ((isput && ("content-type".equals(hnlc)
357 || "content-language".equals(hnlc)
358 || "content-md5".equals(hnlc)
359 || "content-range".equals(hnlc)))
360 || "x-dmaap-dr-meta".equals(hnlc)
361 || (feedid == null && "x-dmaap-dr-received".equals(hnlc))
362 || (hnlc.startsWith("x-") && !hnlc.startsWith("x-dmaap-dr-"))) {
363 Enumeration hvals = req.getHeaders(hn);
364 while (hvals.hasMoreElements()) {
365 String hv = (String) hvals.nextElement();
366 if ("content-type".equals(hnlc)) {
369 if ("x-onap-requestid".equals(hnlc)) {
370 hasRequestIdHeader = true;
372 if ("x-invocationid".equals(hnlc)) {
373 hasInvocationIdHeader = true;
375 if ("x-dmaap-dr-meta".equals(hnlc)) {
376 if (hv.length() > 4096) {
377 eelfLogger.error("NODE0109 Rejecting publish attempt with metadata too long for feed "
378 + PathUtil.cleanString(feedid) + USER + PathUtil.cleanString(user) + " ip "
379 + PathUtil.cleanString(ip)); //Fortify scan fixes - log forging
380 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Metadata too long");
381 eelfLogger.info(EelfMsgs.EXIT);
384 if (!metaDataPattern.matcher(hv.replaceAll("\\\\.", "X")).matches()) {
385 eelfLogger.error("NODE0109 Rejecting publish attempt with malformed metadata for feed "
386 + PathUtil.cleanString(feedid) + USER + PathUtil.cleanString(user) + " ip "
387 + PathUtil.cleanString(ip)); //Fortify scan fixes - log forging
388 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Malformed metadata");
389 eelfLogger.info(EelfMsgs.EXIT);
393 mx.append(hn).append('\t').append(hv).append('\n');
397 if (!hasRequestIdHeader) {
398 mx.append("X-ONAP-RequestID\t").append(MDC.get("RequestId")).append('\n');
400 if (!hasInvocationIdHeader) {
401 mx.append("X-InvocationID\t").append(MDC.get("InvocationId")).append('\n');
403 mx.append("X-DMAAP-DR-RECEIVED\t").append(rcvd).append('\n');
404 String metadata = mx.toString();
405 long exlen = getExlen(req);
406 String message = writeInputStreamToFile(req, data);
407 if (message != null) {
408 StatusLog.logPubFail(pubid, feedid, logurl, req.getMethod(), ctype, exlen, data.length(), ip, user,
410 throw new IOException(message);
412 Path dpath = Paths.get(fbase);
413 for (Target t : targets) {
414 DestInfo di = t.getDestInfo();
416 //Handle this? : unknown destination
419 String dbase = PathUtil
420 .cleanString(di.getSpool() + "/" + pubid); //Fortify scan fixes-Path Manipulation
421 Files.createLink(Paths.get(dbase), dpath);
422 mw = new FileWriter(meta);
424 if (di.getSubId() == null) {
425 mw.write("X-DMAAP-DR-ROUTING\t" + t.getRouting() + "\n");
428 if (!meta.renameTo(new File(dbase + ".M"))) {
429 eelfLogger.error("Rename of file " + dbase + " failed.");
432 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
434 resp.getOutputStream().close();
435 } catch (IOException ioe) {
436 StatusLog.logPubFail(pubid, feedid, logurl, req.getMethod(), ctype, exlen, data.length(), ip, user,
438 //Fortify scan fixes - log forging
439 eelfLogger.error("NODE0110 IO Exception while closing IO stream " + PathUtil.cleanString(feedid)
440 + USER + PathUtil.cleanString(user) + " ip " + PathUtil.cleanString(ip) + " " + ioe
445 StatusLog.logPub(pubid, feedid, logurl, req.getMethod(), ctype, data.length(), ip, user,
446 HttpServletResponse.SC_NO_CONTENT);
447 } catch (IOException ioe) {
448 eelfLogger.error("NODE0110 IO Exception receiving publish attempt for feed " + feedid + USER + user
449 + " ip " + ip + " " + ioe.toString(), ioe);
450 eelfLogger.info(EelfMsgs.EXIT);
456 } catch (Exception e) {
457 eelfLogger.error("NODE0532 Exception common: " + e);
461 Files.delete(data.toPath());
462 Files.delete(meta.toPath());
463 } catch (Exception e) {
464 eelfLogger.error("NODE0533 Exception common: " + e);
469 private String generateAndValidatePublishId(HttpServletRequest req) throws IOException {
470 String newPubId = req.getHeader("X-DMAAP-DR-PUBLISH-ID");
474 if(newPubId.matches(regex)){
477 throw new IOException("Invalid Header X-DMAAP-DR-PUBLISH-ID");
480 private String writeInputStreamToFile(HttpServletRequest req, File data) {
481 byte[] buf = new byte[1024 * 1024];
483 try (OutputStream dos = new FileOutputStream(data);
484 InputStream is = req.getInputStream()) {
485 while ((bytesRead = is.read(buf)) > 0) {
486 dos.write(buf, 0, bytesRead);
488 } catch (IOException ioe) {
489 eelfLogger.error("NODE0530 Exception common: " + ioe, ioe);
490 eelfLogger.info(EelfMsgs.EXIT);
491 return ioe.getMessage();
496 private long getExlen(HttpServletRequest req) {
499 exlen = Long.parseLong(req.getHeader("Content-Length"));
500 } catch (Exception e) {
501 eelfLogger.error("NODE0529 Exception common: " + e);
506 private void deleteFile(HttpServletRequest req, HttpServletResponse resp, String fileid, String pubid) {
507 final String FROM_DR_MESSAGE = ".M) from DR Node: ";
509 fileid = fileid.substring(8);
510 int index = fileid.indexOf('/');
511 if (index == -1 || index == fileid.length() - 1) {
512 eelfLogger.error("NODE0112 Rejecting bad URI for DELETE of " + req.getPathInfo() + FROM + req
514 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
515 "Invalid request URI. Expecting <subId>/<pubId>.");
516 eelfLogger.info(EelfMsgs.EXIT);
519 String subscriptionId = fileid.substring(0, index);
520 int subId = Integer.parseInt(subscriptionId);
521 pubid = fileid.substring(index + 1);
522 String errorMessage = "Unable to delete files (" + pubid + ", " + pubid + FROM_DR_MESSAGE
523 + config.getMyName() + ".";
524 int subIdDir = subId - (subId % 100);
525 if (!isAuthorizedToDelete(resp, subscriptionId, errorMessage)) {
528 boolean result = delivery.markTaskSuccess(config.getSpoolBase() + "/s/" + subIdDir + "/" + subId, pubid);
530 eelfLogger.debug("NODE0115 Successfully deleted files (" + pubid + ", " + pubid + FROM_DR_MESSAGE
531 + config.getMyName());
532 resp.setStatus(HttpServletResponse.SC_OK);
533 eelfLogger.info(EelfMsgs.EXIT);
535 eelfLogger.error("NODE0116 " + errorMessage);
536 resp.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found on server.");
537 eelfLogger.info(EelfMsgs.EXIT);
539 } catch (IOException ioe) {
540 eelfLogger.error("NODE0117 Unable to delete files (" + pubid + ", " + pubid + FROM_DR_MESSAGE
541 + config.getMyName(), ioe);
542 eelfLogger.info(EelfMsgs.EXIT);
547 private String getFileId(HttpServletRequest req, HttpServletResponse resp) throws IOException {
549 eelfLogger.info(EelfMsgs.EXIT);
552 if (!req.isSecure() && config.isTlsEnabled()) {
554 "NODE0104 Rejecting insecure PUT or DELETE of " + req.getPathInfo() + FROM + req
556 resp.sendError(HttpServletResponse.SC_FORBIDDEN, "https required on publish requests");
557 eelfLogger.info(EelfMsgs.EXIT);
560 String fileid = req.getPathInfo();
561 if (fileid == null) {
562 eelfLogger.error("NODE0201 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + FROM + req
564 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
565 INVALID_REQUEST_URI);
566 eelfLogger.info(EelfMsgs.EXIT);
572 private boolean isAuthorizedToDelete(HttpServletResponse resp, String subscriptionId, String errorMessage)
575 boolean deletePermitted = config.isDeletePermitted(subscriptionId);
576 if (!deletePermitted) {
577 eelfLogger.error("NODE0113 " + errorMessage + " Error: Subscription "
578 + subscriptionId + " is not a privileged subscription");
579 resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
580 eelfLogger.info(EelfMsgs.EXIT);
583 } catch (NullPointerException npe) {
584 eelfLogger.error("NODE0114 " + errorMessage + " Error: Subscription " + subscriptionId
585 + " does not exist", npe);
586 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
587 eelfLogger.info(EelfMsgs.EXIT);
593 private int getIdFromPath(HttpServletRequest req) {
594 String path = req.getPathInfo();
595 if (path == null || path.length() < 2) {
599 return Integer.parseInt(path.substring(1));
600 } catch (NumberFormatException e) {