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 com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import org.apache.log4j.Logger;
30 import org.jetbrains.annotations.Nullable;
31 import org.onap.dmaap.datarouter.node.eelf.EelfMsgs;
34 import javax.servlet.http.HttpServlet;
35 import javax.servlet.http.HttpServletRequest;
36 import javax.servlet.http.HttpServletResponse;
38 import java.io.FileOutputStream;
39 import java.io.FileWriter;
40 import java.io.IOException;
41 import java.io.InputStream;
42 import java.io.OutputStream;
43 import java.io.Writer;
44 import java.nio.file.Files;
45 import java.nio.file.Path;
46 import java.nio.file.Paths;
47 import java.util.Enumeration;
48 import java.util.regex.Pattern;
50 import static org.onap.dmaap.datarouter.node.NodeUtils.sendResponseError;
53 * Servlet for handling all http and https requests to the data router node
55 * Handled requests are:
57 * GET http://<i>node</i>/internal/fetchProv - fetch the provisioning data
59 * PUT/DELETE https://<i>node</i>/internal/publish/<i>fileid</i> - n2n transfer
61 * PUT/DELETE https://<i>node</i>/publish/<i>feedid</i>/<i>fileid</i> - publsh request
63 public class NodeServlet extends HttpServlet {
65 private static Logger logger = Logger.getLogger("org.onap.dmaap.datarouter.node.NodeServlet");
66 private static NodeConfigManager config;
67 private static Pattern MetaDataPattern;
68 private static EELFLogger eelflogger = EELFManager.getInstance().getLogger(NodeServlet.class);
69 private static boolean isAAFFeed = false;
70 private final Delivery delivery;
73 final String ws = "\\s*";
74 // assume that \\ and \" have been replaced by X
75 final String string = "\"[^\"]*\"";
76 //String string = "\"(?:[^\"\\\\]|\\\\.)*\"";
77 final String number = "[+-]?(?:\\.\\d+|(?:0|[1-9]\\d*)(?:\\.\\d*)?)(?:[eE][+-]?\\d+)?";
78 final String value = "(?:" + string + "|" + number + "|null|true|false)";
79 final String item = string + ws + ":" + ws + value + ws;
80 final String object = ws + "\\{" + ws + "(?:" + item + "(?:" + "," + ws + item + ")*)?\\}" + ws;
81 MetaDataPattern = Pattern.compile(object, Pattern.DOTALL);
84 NodeServlet(Delivery delivery) {
85 this.delivery = delivery;
89 * Get the NodeConfigurationManager
93 config = NodeConfigManager.getInstance();
94 logger.info("NODE0101 Node Servlet Configured");
97 private boolean down(HttpServletResponse resp) throws IOException {
98 if (config.isShutdown() || !config.isConfigured()) {
99 sendResponseError(resp, HttpServletResponse.SC_SERVICE_UNAVAILABLE, logger);
100 logger.info("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.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-DMAAP-DR-ON-BEHALF-OF"),
116 getIdFromPath(req) + "");
122 } catch (IOException ioe) {
123 logger.error("IOException" + ioe.getMessage());
125 String path = req.getPathInfo();
126 String qs = req.getQueryString();
127 String ip = req.getRemoteAddr();
129 path = path + "?" + qs;
131 if ("/internal/fetchProv".equals(path)) {
133 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
135 } else if (path.startsWith("/internal/resetSubscription/")) {
136 String subid = path.substring(28);
137 if (subid.length() != 0 && subid.indexOf('/') == -1) {
138 NodeMain.resetQueue(subid, ip);
139 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
144 logger.info("NODE0103 Rejecting invalid GET of " + path + " from " + ip);
145 sendResponseError(resp, HttpServletResponse.SC_NOT_FOUND, logger);
147 eelflogger.info(EelfMsgs.EXIT);
152 * Handle all PUT requests
155 protected void doPut(HttpServletRequest req, HttpServletResponse resp) {
156 NodeUtils.setIpAndFqdnForEelf("doPut");
157 NodeUtils.setRequestIdAndInvocationId(req);
158 eelflogger.info(EelfMsgs.ENTRY);
159 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-DMAAP-DR-ON-BEHALF-OF"),
160 getIdFromPath(req) + "");
162 common(req, resp, true);
163 } catch (IOException ioe) {
164 logger.error("IOException" + ioe.getMessage());
165 eelflogger.info(EelfMsgs.EXIT);
170 * Handle all DELETE requests
173 protected void doDelete(HttpServletRequest req, HttpServletResponse resp) {
174 NodeUtils.setIpAndFqdnForEelf("doDelete");
175 NodeUtils.setRequestIdAndInvocationId(req);
176 eelflogger.info(EelfMsgs.ENTRY);
177 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-DMAAP-DR-ON-BEHALF-OF"),
178 getIdFromPath(req) + "");
180 common(req, resp, false);
181 } catch (IOException ioe) {
182 logger.error("IOException " + ioe.getMessage());
183 eelflogger.info(EelfMsgs.EXIT);
187 private void common(HttpServletRequest req, HttpServletResponse resp, boolean isput) throws IOException {
188 String fileid = getFileId(req, resp);
189 if (fileid == null) return;
190 String feedid = null;
192 String ip = req.getRemoteAddr();
193 String lip = req.getLocalAddr();
195 String xpubid = null;
196 String rcvd = NodeUtils.logts(System.currentTimeMillis()) + ";from=" + ip + ";by=" + lip;
197 Target[] targets = null;
198 if (fileid.startsWith("/delete/")) {
199 deleteFile(req, resp, fileid, pubid);
202 String credentials = req.getHeader("Authorization");
203 if (credentials == null) {
204 logger.info("NODE0106 Rejecting unauthenticated PUT or DELETE of " + req.getPathInfo() + " from " + req
206 resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Authorization header required");
207 eelflogger.info(EelfMsgs.EXIT);
210 if (fileid.startsWith("/publish/")) {
211 fileid = fileid.substring(9);
212 int i = fileid.indexOf('/');
213 if (i == -1 || i == fileid.length() - 1) {
214 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
216 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
217 "Invalid request URI. Expecting <feed-publishing-url>/<fileid>. Possible missing fileid.");
218 eelflogger.info(EelfMsgs.EXIT);
221 feedid = fileid.substring(0, i);
223 if (config.getCadiEnabeld()) {
224 String path = req.getPathInfo();
225 if (!path.startsWith("/internal") && feedid != null) {
226 String aafInstance = config.getAafInstance(feedid);
227 if (!(aafInstance.equalsIgnoreCase("legacy"))) {
229 String permission = config.getPermission(aafInstance);
230 logger.info("NodeServlet.common() permission string - " + permission);
231 //Check in CADI Framework API if user has AAF permission or not
232 if (!req.isUserInRole(permission)) {
233 String message = "AAF disallows access to permission string - " + permission;
234 logger.info("NODE0106 Rejecting unauthenticated PUT or DELETE of " + req.getPathInfo() + " from " + req.getRemoteAddr());
235 resp.sendError(HttpServletResponse.SC_FORBIDDEN, message);
236 eelflogger.info(EelfMsgs.EXIT);
243 fileid = fileid.substring(i + 1);
244 pubid = config.getPublishId();
245 xpubid = req.getHeader("X-DMAAP-DR-PUBLISH-ID");
246 targets = config.getTargets(feedid);
247 } else if (fileid.startsWith("/internal/publish/")) {
248 if (!config.isAnotherNode(credentials, ip)) {
249 logger.info("NODE0107 Rejecting unauthorized node-to-node transfer attempt from " + ip);
250 resp.sendError(HttpServletResponse.SC_FORBIDDEN);
251 eelflogger.info(EelfMsgs.EXIT);
254 fileid = fileid.substring(18);
255 pubid = req.getHeader("X-DMAAP-DR-PUBLISH-ID");
256 user = "datartr"; // SP6 : Added usr as datartr to avoid null entries for internal routing
257 targets = config.parseRouting(req.getHeader("X-DMAAP-DR-ROUTING"));
259 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
261 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
262 "Invalid request URI. Expecting <feed-publishing-url>/<fileid>.");
263 eelflogger.info(EelfMsgs.EXIT);
266 if (fileid.indexOf('/') != -1) {
267 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
269 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
270 "Invalid request URI. Expecting <feed-publishing-url>/<fileid>.");
271 eelflogger.info(EelfMsgs.EXIT);
274 String qs = req.getQueryString();
276 fileid = fileid + "?" + qs;
278 String hp = config.getMyName();
279 int xp = config.getExtHttpsPort();
283 String logurl = "https://" + hp + "/internal/publish/" + fileid;
284 if (feedid != null) {
285 logurl = "https://" + hp + "/publish/" + feedid + "/" + fileid;
288 String reason = config.isPublishPermitted(feedid, credentials, ip);
289 if (reason != null) {
290 logger.info("NODE0111 Rejecting unauthorized publish attempt to feed " + PathUtil.cleanString(feedid) + " fileid " + PathUtil.cleanString(fileid) + " from " + PathUtil.cleanString(ip) + " reason " + PathUtil.cleanString(reason));
291 resp.sendError(HttpServletResponse.SC_FORBIDDEN, reason);
292 eelflogger.info(EelfMsgs.EXIT);
295 user = config.getAuthUser(feedid, credentials);
297 String reason = config.isPublishPermitted(feedid, ip);
298 if (reason != null) {
299 logger.info("NODE0111 Rejecting unauthorized publish attempt to feed " + PathUtil.cleanString(feedid) + " fileid " + PathUtil.cleanString(fileid) + " from " + PathUtil.cleanString(ip) + " reason Invalid AAF user- " + PathUtil.cleanString(reason));
300 String message = "Invalid AAF user- " + PathUtil.cleanString(reason);
301 logger.info("NODE0106 Rejecting unauthenticated PUT or DELETE of " + PathUtil.cleanString(req.getPathInfo()) + " from " + PathUtil.cleanString(req.getRemoteAddr()));
302 resp.sendError(HttpServletResponse.SC_FORBIDDEN, message);
305 if ((req.getUserPrincipal() != null) && (req.getUserPrincipal().getName() != null)) {
306 String userName = req.getUserPrincipal().getName();
307 String[] attid = userName.split("@");
314 String newnode = config.getIngressNode(feedid, user, ip);
315 if (newnode != null) {
317 int iport = config.getExtHttpsPort();
321 String redirto = "https://" + newnode + port + "/publish/" + feedid + "/" + fileid;
322 logger.info("NODE0108 Redirecting publish attempt for feed " + PathUtil.cleanString(feedid) + " user " + PathUtil.cleanString(user) + " ip " + PathUtil.cleanString(ip) + " to " + PathUtil.cleanString(redirto)); //Fortify scan fixes - log forging
323 resp.sendRedirect(PathUtil.cleanString(redirto)); //Fortify scan fixes-open redirect - 2 issues
324 eelflogger.info(EelfMsgs.EXIT);
327 resp.setHeader("X-DMAAP-DR-PUBLISH-ID", pubid);
329 if (req.getPathInfo().startsWith("/internal/publish/")) {
330 feedid = req.getHeader("X-DMAAP-DR-FEED-ID");
332 String fbase = PathUtil.cleanString(config.getSpoolDir() + "/" + pubid); //Fortify scan fixes-Path manipulation
333 File data = new File(fbase);
334 File meta = new File(fbase + ".M");
335 OutputStream dos = null;
337 InputStream is = null;
339 StringBuffer mx = new StringBuffer();
340 mx.append(req.getMethod()).append('\t').append(fileid).append('\n');
341 Enumeration hnames = req.getHeaderNames();
343 boolean hasRequestIdHeader = false;
344 boolean hasInvocationIdHeader = false;
345 while (hnames.hasMoreElements()) {
346 String hn = (String) hnames.nextElement();
347 String hnlc = hn.toLowerCase();
348 if ((isput && ("content-type".equals(hnlc) ||
349 "content-language".equals(hnlc) ||
350 "content-md5".equals(hnlc) ||
351 "content-range".equals(hnlc))) ||
352 "x-dmaap-dr-meta".equals(hnlc) ||
353 (feedid == null && "x-dmaap-dr-received".equals(hnlc)) ||
354 (hnlc.startsWith("x-") && !hnlc.startsWith("x-dmaap-dr-"))) {
355 Enumeration hvals = req.getHeaders(hn);
356 while (hvals.hasMoreElements()) {
357 String hv = (String) hvals.nextElement();
358 if ("content-type".equals(hnlc)) {
361 if ("x-onap-requestid".equals(hnlc)) {
362 hasRequestIdHeader = true;
364 if ("x-invocationid".equals(hnlc)) {
365 hasInvocationIdHeader = true;
367 if ("x-dmaap-dr-meta".equals(hnlc)) {
368 if (hv.length() > 4096) {
369 logger.info("NODE0109 Rejecting publish attempt with metadata too long for feed " + PathUtil.cleanString(feedid) + " user " + PathUtil.cleanString(user) + " ip " + PathUtil.cleanString(ip)); //Fortify scan fixes - log forging
370 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Metadata too long");
371 eelflogger.info(EelfMsgs.EXIT);
374 if (!MetaDataPattern.matcher(hv.replaceAll("\\\\.", "X")).matches()) {
375 logger.info("NODE0109 Rejecting publish attempt with malformed metadata for feed " + PathUtil.cleanString(feedid) + " user " + PathUtil.cleanString(user) + " ip " + PathUtil.cleanString(ip)); //Fortify scan fixes - log forging
376 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Malformed metadata");
377 eelflogger.info(EelfMsgs.EXIT);
381 mx.append(hn).append('\t').append(hv).append('\n');
385 if (!hasRequestIdHeader) {
386 mx.append("X-ONAP-RequestID\t").append(MDC.get("RequestId")).append('\n');
388 if (!hasInvocationIdHeader) {
389 mx.append("X-InvocationID\t").append(MDC.get("InvocationId")).append('\n');
391 mx.append("X-DMAAP-DR-RECEIVED\t").append(rcvd).append('\n');
392 String metadata = mx.toString();
393 byte[] buf = new byte[1024 * 1024];
396 is = req.getInputStream();
397 dos = new FileOutputStream(data);
398 while ((i = is.read(buf)) > 0) {
399 dos.write(buf, 0, i);
405 } catch (IOException ioe) {
408 exlen = Long.parseLong(req.getHeader("Content-Length"));
409 } catch (Exception e) {
410 logger.error("NODE0529 Exception common: " + e);
412 StatusLog.logPubFail(pubid, feedid, logurl, req.getMethod(), ctype, exlen, data.length(), ip, user, ioe.getMessage());
413 eelflogger.info(EelfMsgs.EXIT);
416 Path dpath = Paths.get(fbase);
417 for (Target t : targets) {
418 DestInfo di = t.getDestInfo();
420 // TODO: unknown destination
423 String dbase = PathUtil.cleanString(di.getSpool() + "/" + pubid); //Fortify scan fixes-Path Manipulation
424 Files.createLink(Paths.get(dbase), dpath);
425 mw = new FileWriter(meta);
427 if (di.getSubId() == null) {
428 mw.write("X-DMAAP-DR-ROUTING\t" + t.getRouting() + "\n");
431 meta.renameTo(new File(dbase + ".M"));
434 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
436 resp.getOutputStream().close();
437 } catch (IOException ioe) {
440 exlen = Long.parseLong(req.getHeader("Content-Length"));
441 } catch (Exception e) {
442 logger.debug("NODE00000 Exception common: " + e);
444 StatusLog.logPubFail(pubid, feedid, logurl, req.getMethod(), ctype, exlen, data.length(), ip, user, ioe.getMessage());
445 //Fortify scan fixes - log forging
446 logger.info("NODE0110 IO Exception while closing IO stream " + PathUtil.cleanString(feedid) + " user " + PathUtil.cleanString(user) + " ip " + PathUtil.cleanString(ip) + " " + ioe.toString(), ioe);
451 StatusLog.logPub(pubid, feedid, logurl, req.getMethod(), ctype, data.length(), ip, user, HttpServletResponse.SC_NO_CONTENT);
452 } catch (IOException ioe) {
453 logger.info("NODE0110 IO Exception receiving publish attempt for feed " + feedid + " user " + user + " ip " + ip + " " + ioe.toString(), ioe);
454 eelflogger.info(EelfMsgs.EXIT);
460 } catch (Exception e) {
461 logger.error("NODE0530 Exception common: " + e);
467 } catch (Exception e) {
468 logger.error("NODE0531 Exception common: " + e);
474 } catch (Exception e) {
475 logger.error("NODE0532 Exception common: " + e);
480 } catch (Exception e) {
481 logger.error("NODE0533 Exception common: " + e);
485 } catch (Exception e) {
486 logger.error("NODE0534 Exception common: " + e);
491 private void deleteFile(HttpServletRequest req, HttpServletResponse resp, String fileid, String pubid) {
493 fileid = fileid.substring(8);
494 int i = fileid.indexOf('/');
495 if (i == -1 || i == fileid.length() - 1) {
496 logger.info("NODE0112 Rejecting bad URI for DELETE of " + req.getPathInfo() + " from " + req
498 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
499 "Invalid request URI. Expecting <subId>/<pubId>.");
500 eelflogger.info(EelfMsgs.EXIT);
503 String subscriptionId = fileid.substring(0, i);
504 int subId = Integer.parseInt(subscriptionId);
505 pubid = fileid.substring(i + 1);
506 String errorMessage = "Unable to delete files (" + pubid + ", " + pubid + ".M) from DR Node: "
507 + config.getMyName() + ".";
508 int subIdDir = subId - (subId % 100);
509 if (!isAuthorizedToDelete(resp, subscriptionId, errorMessage)) {
512 boolean result = delivery.markTaskSuccess(config.getSpoolBase() + "/s/" + subIdDir + "/" + subId, pubid);
514 logger.info("NODE0115 Successfully deleted files (" + pubid + ", " + pubid + ".M) from DR Node: "
515 + config.getMyName());
516 resp.setStatus(HttpServletResponse.SC_OK);
517 eelflogger.info(EelfMsgs.EXIT);
519 logger.error("NODE0116 " + errorMessage);
520 resp.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found on server.");
521 eelflogger.info(EelfMsgs.EXIT);
523 } catch (IOException ioe) {
524 logger.error("NODE0117 Unable to delete files (" + pubid + ", " + pubid + ".M) from DR Node: "
525 + config.getMyName() + ". Error: " + ioe.getMessage());
526 eelflogger.info(EelfMsgs.EXIT);
531 private String getFileId(HttpServletRequest req, HttpServletResponse resp) throws IOException {
533 eelflogger.info(EelfMsgs.EXIT);
536 if (!req.isSecure()) {
538 "NODE0104 Rejecting insecure PUT or DELETE of " + req.getPathInfo() + " from " + req
540 resp.sendError(HttpServletResponse.SC_FORBIDDEN, "https required on publish requests");
541 eelflogger.info(EelfMsgs.EXIT);
544 String fileid = req.getPathInfo();
545 if (fileid == null) {
546 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
548 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
549 "Invalid request URI. Expecting <feed-publishing-url>/<fileid>.");
550 eelflogger.info(EelfMsgs.EXIT);
556 private boolean isAuthorizedToDelete(HttpServletResponse resp, String subscriptionId, String errorMessage) throws IOException {
558 boolean deletePermitted = config.isDeletePermitted(subscriptionId);
559 if (!deletePermitted) {
560 logger.error("NODE0113 " + errorMessage + " Error: Subscription "
561 + subscriptionId + " is not a privileged subscription");
562 resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
563 eelflogger.info(EelfMsgs.EXIT);
566 } catch (NullPointerException npe) {
567 logger.error("NODE0114 " + errorMessage + " Error: Subscription " + subscriptionId + " does not exist");
568 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
569 eelflogger.info(EelfMsgs.EXIT);
575 private int getIdFromPath(HttpServletRequest req) {
576 String path = req.getPathInfo();
577 if (path == null || path.length() < 2) {
581 return Integer.parseInt(path.substring(1));
582 } catch (NumberFormatException e) {