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.onap.dmaap.datarouter.node.eelf.EelfMsgs;
33 import javax.servlet.ServletException;
34 import javax.servlet.http.HttpServlet;
35 import javax.servlet.http.HttpServletRequest;
36 import javax.servlet.http.HttpServletResponse;
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;
44 import static org.onap.dmaap.datarouter.node.NodeUtils.sendResponseError;
46 import org.jetbrains.annotations.Nullable;
48 import static org.onap.dmaap.datarouter.node.NodeUtils.*;
51 * Servlet for handling all http and https requests to the data router node
53 * 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 Logger logger = Logger.getLogger("org.onap.dmaap.datarouter.node.NodeServlet");
64 private static NodeConfigManager config;
65 private static Pattern MetaDataPattern;
66 private static EELFLogger eelflogger = EELFManager.getInstance().getLogger(NodeServlet.class);
67 private boolean isAAFFeed = false;
68 private final Delivery delivery;
71 final String ws = "\\s*";
72 // assume that \\ and \" have been replaced by X
73 final String string = "\"[^\"]*\"";
74 //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 NodeServlet(Delivery delivery) {
83 this.delivery = delivery;
87 * Get the NodeConfigurationManager
91 config = NodeConfigManager.getInstance();
92 logger.info("NODE0101 Node Servlet Configured");
95 private boolean down(HttpServletResponse resp) throws IOException {
96 if (config.isShutdown() || !config.isConfigured()) {
97 sendResponseError(resp, HttpServletResponse.SC_SERVICE_UNAVAILABLE, logger);
98 logger.info("NODE0102 Rejecting request: Service is being quiesced");
105 * Handle a GET for /internal/fetchProv
108 protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
109 NodeUtils.setIpAndFqdnForEelf("doGet");
110 NodeUtils.setRequestIdAndInvocationId(req);
111 eelflogger.info(EelfMsgs.ENTRY);
113 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-DMAAP-DR-ON-BEHALF-OF"),
114 getIdFromPath(req) + "");
120 } catch (IOException ioe) {
121 logger.error("IOException" + ioe.getMessage());
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 NodeMain.resetQueue(subid, ip);
137 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
142 logger.info("NODE0103 Rejecting invalid GET of " + path + " from " + ip);
143 sendResponseError(resp, HttpServletResponse.SC_NOT_FOUND, logger);
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.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-DMAAP-DR-ON-BEHALF-OF"),
158 getIdFromPath(req) + "");
160 common(req, resp, true);
161 } catch (IOException ioe) {
162 logger.error("IOException" + ioe.getMessage());
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.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-DMAAP-DR-ON-BEHALF-OF"),
176 getIdFromPath(req) + "");
178 common(req, resp, false);
179 } catch (IOException ioe) {
180 logger.error("IOException " + ioe.getMessage());
181 eelflogger.info(EelfMsgs.EXIT);
185 private void common(HttpServletRequest req, HttpServletResponse resp, boolean isput) throws IOException {
186 String fileid = getFileId(req, resp);
187 if (fileid == null) return;
188 String feedid = null;
190 String ip = req.getRemoteAddr();
191 String lip = req.getLocalAddr();
193 String xpubid = null;
194 String rcvd = NodeUtils.logts(System.currentTimeMillis()) + ";from=" + ip + ";by=" + lip;
195 Target[] targets = null;
196 if (fileid.startsWith("/delete/")) {
197 deleteFile(req, resp, fileid, pubid);
200 String credentials = req.getHeader("Authorization");
201 if (credentials == null) {
202 logger.info("NODE0106 Rejecting unauthenticated PUT or DELETE of " + req.getPathInfo() + " from " + req
204 resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Authorization header required");
205 eelflogger.info(EelfMsgs.EXIT);
208 if (fileid.startsWith("/publish/")) {
209 fileid = fileid.substring(9);
210 int i = fileid.indexOf('/');
211 if (i == -1 || i == fileid.length() - 1) {
212 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
214 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
215 "Invalid request URI. Expecting <feed-publishing-url>/<fileid>. Possible missing fileid.");
216 eelflogger.info(EelfMsgs.EXIT);
219 feedid = fileid.substring(0, i);
221 if (config.getCadiEnabeld()) {
222 String path = req.getPathInfo();
223 if (!path.startsWith("/internal") && feedid != null) {
224 String aafInstance = config.getAafInstance(feedid);
225 if (!(aafInstance.equalsIgnoreCase("legacy"))) {
227 String permission = config.getPermission(aafInstance);
228 logger.info("NodeServlet.common() permission string - " + permission);
229 //Check in CADI Framework API if user has AAF permission or not
230 if (!req.isUserInRole(permission)) {
231 String message = "AAF disallows access to permission string - " + permission;
232 logger.info("NODE0106 Rejecting unauthenticated PUT or DELETE of " + req.getPathInfo() + " from " + req.getRemoteAddr());
233 resp.sendError(HttpServletResponse.SC_FORBIDDEN, message);
234 eelflogger.info(EelfMsgs.EXIT);
241 fileid = fileid.substring(i + 1);
242 pubid = config.getPublishId();
243 xpubid = req.getHeader("X-DMAAP-DR-PUBLISH-ID");
244 targets = config.getTargets(feedid);
245 } else if (fileid.startsWith("/internal/publish/")) {
246 if (!config.isAnotherNode(credentials, ip)) {
247 logger.info("NODE0107 Rejecting unauthorized node-to-node transfer attempt from " + ip);
248 resp.sendError(HttpServletResponse.SC_FORBIDDEN);
249 eelflogger.info(EelfMsgs.EXIT);
252 fileid = fileid.substring(18);
253 pubid = req.getHeader("X-DMAAP-DR-PUBLISH-ID");
254 user = "datartr"; // SP6 : Added usr as datartr to avoid null entries for internal routing
255 targets = config.parseRouting(req.getHeader("X-DMAAP-DR-ROUTING"));
257 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
259 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
260 "Invalid request URI. Expecting <feed-publishing-url>/<fileid>.");
261 eelflogger.info(EelfMsgs.EXIT);
264 if (fileid.indexOf('/') != -1) {
265 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
267 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
268 "Invalid request URI. Expecting <feed-publishing-url>/<fileid>.");
269 eelflogger.info(EelfMsgs.EXIT);
272 String qs = req.getQueryString();
274 fileid = fileid + "?" + qs;
276 String hp = config.getMyName();
277 int xp = config.getExtHttpsPort();
281 String logurl = "https://" + hp + "/internal/publish/" + fileid;
282 if (feedid != null) {
283 logurl = "https://" + hp + "/publish/" + feedid + "/" + fileid;
286 String reason = config.isPublishPermitted(feedid, credentials, ip);
287 if (reason != null) {
288 logger.info("NODE0111 Rejecting unauthorized publish attempt to feed " + PathUtil.cleanString(feedid) + " fileid " + PathUtil.cleanString(fileid) + " from " + PathUtil.cleanString(ip) + " reason " + PathUtil.cleanString(reason));
289 resp.sendError(HttpServletResponse.SC_FORBIDDEN, reason);
290 eelflogger.info(EelfMsgs.EXIT);
293 user = config.getAuthUser(feedid, credentials);
295 String reason = config.isPublishPermitted(feedid, ip);
296 if (reason != null) {
297 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));
298 String message = "Invalid AAF user- " + PathUtil.cleanString(reason);
299 logger.info("NODE0106 Rejecting unauthenticated PUT or DELETE of " + PathUtil.cleanString(req.getPathInfo()) + " from " + PathUtil.cleanString(req.getRemoteAddr()));
300 resp.sendError(HttpServletResponse.SC_FORBIDDEN, message);
303 if ((req.getUserPrincipal() != null) && (req.getUserPrincipal().getName() != null)) {
304 String userName = req.getUserPrincipal().getName();
305 String[] attid = userName.split("@");
312 String newnode = config.getIngressNode(feedid, user, ip);
313 if (newnode != null) {
315 int iport = config.getExtHttpsPort();
319 String redirto = "https://" + newnode + port + "/publish/" + feedid + "/" + fileid;
320 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
321 resp.sendRedirect(PathUtil.cleanString(redirto)); //Fortify scan fixes-open redirect - 2 issues
322 eelflogger.info(EelfMsgs.EXIT);
325 resp.setHeader("X-DMAAP-DR-PUBLISH-ID", pubid);
327 if (req.getPathInfo().startsWith("/internal/publish/")) {
328 feedid = req.getHeader("X-DMAAP-DR-FEED-ID");
330 String fbase = PathUtil.cleanString(config.getSpoolDir() + "/" + pubid); //Fortify scan fixes-Path manipulation
331 File data = new File(fbase);
332 File meta = new File(fbase + ".M");
333 OutputStream dos = null;
335 InputStream is = null;
337 StringBuffer mx = new StringBuffer();
338 mx.append(req.getMethod()).append('\t').append(fileid).append('\n');
339 Enumeration hnames = req.getHeaderNames();
341 boolean hasRequestIdHeader = false;
342 boolean hasInvocationIdHeader = false;
343 while (hnames.hasMoreElements()) {
344 String hn = (String) hnames.nextElement();
345 String hnlc = hn.toLowerCase();
346 if ((isput && ("content-type".equals(hnlc) ||
347 "content-language".equals(hnlc) ||
348 "content-md5".equals(hnlc) ||
349 "content-range".equals(hnlc))) ||
350 "x-dmaap-dr-meta".equals(hnlc) ||
351 (feedid == null && "x-dmaap-dr-received".equals(hnlc)) ||
352 (hnlc.startsWith("x-") && !hnlc.startsWith("x-dmaap-dr-"))) {
353 Enumeration hvals = req.getHeaders(hn);
354 while (hvals.hasMoreElements()) {
355 String hv = (String) hvals.nextElement();
356 if ("content-type".equals(hnlc)) {
359 if ("x-onap-requestid".equals(hnlc)) {
360 hasRequestIdHeader = true;
362 if ("x-invocationid".equals(hnlc)) {
363 hasInvocationIdHeader = true;
365 if ("x-dmaap-dr-meta".equals(hnlc)) {
366 if (hv.length() > 4096) {
367 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
368 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Metadata too long");
369 eelflogger.info(EelfMsgs.EXIT);
372 if (!MetaDataPattern.matcher(hv.replaceAll("\\\\.", "X")).matches()) {
373 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
374 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Malformed metadata");
375 eelflogger.info(EelfMsgs.EXIT);
379 mx.append(hn).append('\t').append(hv).append('\n');
383 if (!hasRequestIdHeader) {
384 mx.append("X-ONAP-RequestID\t").append(MDC.get("RequestId")).append('\n');
386 if (!hasInvocationIdHeader) {
387 mx.append("X-InvocationID\t").append(MDC.get("InvocationId")).append('\n');
389 mx.append("X-DMAAP-DR-RECEIVED\t").append(rcvd).append('\n');
390 String metadata = mx.toString();
391 byte[] buf = new byte[1024 * 1024];
394 is = req.getInputStream();
395 dos = new FileOutputStream(data);
396 while ((i = is.read(buf)) > 0) {
397 dos.write(buf, 0, i);
403 } catch (IOException ioe) {
406 exlen = Long.parseLong(req.getHeader("Content-Length"));
407 } catch (Exception e) {
408 logger.error("NODE0529 Exception common: " + e);
410 StatusLog.logPubFail(pubid, feedid, logurl, req.getMethod(), ctype, exlen, data.length(), ip, user, ioe.getMessage());
411 eelflogger.info(EelfMsgs.EXIT);
414 Path dpath = Paths.get(fbase);
415 for (Target t : targets) {
416 DestInfo di = t.getDestInfo();
418 // TODO: unknown destination
421 String dbase = PathUtil.cleanString(di.getSpool() + "/" + pubid); //Fortify scan fixes-Path Manipulation
422 Files.createLink(Paths.get(dbase), dpath);
423 mw = new FileWriter(meta);
425 if (di.getSubId() == null) {
426 mw.write("X-DMAAP-DR-ROUTING\t" + t.getRouting() + "\n");
429 meta.renameTo(new File(dbase + ".M"));
432 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
434 resp.getOutputStream().close();
435 } catch (IOException ioe) {
438 exlen = Long.parseLong(req.getHeader("Content-Length"));
439 } catch (Exception e) {
440 logger.debug("NODE00000 Exception common: " + e);
442 StatusLog.logPubFail(pubid, feedid, logurl, req.getMethod(), ctype, exlen, data.length(), ip, user, ioe.getMessage());
443 //Fortify scan fixes - log forging
444 logger.info("NODE0110 IO Exception while closing IO stream " + PathUtil.cleanString(feedid) + " user " + PathUtil.cleanString(user) + " ip " + PathUtil.cleanString(ip) + " " + ioe.toString(), ioe);
449 StatusLog.logPub(pubid, feedid, logurl, req.getMethod(), ctype, data.length(), ip, user, HttpServletResponse.SC_NO_CONTENT);
450 } catch (IOException ioe) {
451 logger.info("NODE0110 IO Exception receiving publish attempt for feed " + feedid + " user " + user + " ip " + ip + " " + ioe.toString(), ioe);
452 eelflogger.info(EelfMsgs.EXIT);
458 } catch (Exception e) {
459 logger.error("NODE0530 Exception common: " + e);
465 } catch (Exception e) {
466 logger.error("NODE0531 Exception common: " + e);
472 } catch (Exception e) {
473 logger.error("NODE0532 Exception common: " + e);
478 } catch (Exception e) {
479 logger.error("NODE0533 Exception common: " + e);
483 } catch (Exception e) {
484 logger.error("NODE0534 Exception common: " + e);
489 private void deleteFile(HttpServletRequest req, HttpServletResponse resp, String fileid, String pubid) {
491 fileid = fileid.substring(8);
492 int i = fileid.indexOf('/');
493 if (i == -1 || i == fileid.length() - 1) {
494 logger.info("NODE0112 Rejecting bad URI for DELETE of " + req.getPathInfo() + " from " + req
496 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
497 "Invalid request URI. Expecting <subId>/<pubId>.");
498 eelflogger.info(EelfMsgs.EXIT);
501 String subscriptionId = fileid.substring(0, i);
502 int subId = Integer.parseInt(subscriptionId);
503 pubid = fileid.substring(i + 1);
504 String errorMessage = "Unable to delete files (" + pubid + ", " + pubid + ".M) from DR Node: "
505 + config.getMyName() + ".";
506 int subIdDir = subId - (subId % 100);
507 if (!isAuthorizedToDelete(resp, subscriptionId, errorMessage)) {
510 boolean result = delivery.markTaskSuccess(config.getSpoolBase() + "/s/" + subIdDir + "/" + subId, pubid);
512 logger.info("NODE0115 Successfully deleted files (" + pubid + ", " + pubid + ".M) from DR Node: "
513 + config.getMyName());
514 resp.setStatus(HttpServletResponse.SC_OK);
515 eelflogger.info(EelfMsgs.EXIT);
517 logger.error("NODE0116 " + errorMessage);
518 resp.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found on server.");
519 eelflogger.info(EelfMsgs.EXIT);
521 } catch (IOException ioe) {
522 logger.error("NODE0117 Unable to delete files (" + pubid + ", " + pubid + ".M) from DR Node: "
523 + config.getMyName() + ". Error: " + ioe.getMessage());
524 eelflogger.info(EelfMsgs.EXIT);
529 private String getFileId(HttpServletRequest req, HttpServletResponse resp) throws IOException {
531 eelflogger.info(EelfMsgs.EXIT);
534 if (!req.isSecure()) {
536 "NODE0104 Rejecting insecure PUT or DELETE of " + req.getPathInfo() + " from " + req
538 resp.sendError(HttpServletResponse.SC_FORBIDDEN, "https required on publish requests");
539 eelflogger.info(EelfMsgs.EXIT);
542 String fileid = req.getPathInfo();
543 if (fileid == null) {
544 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
546 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
547 "Invalid request URI. Expecting <feed-publishing-url>/<fileid>.");
548 eelflogger.info(EelfMsgs.EXIT);
554 private boolean isAuthorizedToDelete(HttpServletResponse resp, String subscriptionId, String errorMessage) throws IOException {
556 boolean deletePermitted = config.isDeletePermitted(subscriptionId);
557 if (!deletePermitted) {
558 logger.error("NODE0113 " + errorMessage + " Error: Subscription "
559 + subscriptionId + " is not a privileged subscription");
560 resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
561 eelflogger.info(EelfMsgs.EXIT);
564 } catch (NullPointerException npe) {
565 logger.error("NODE0114 " + errorMessage + " Error: Subscription " + subscriptionId + " does not exist");
566 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
567 eelflogger.info(EelfMsgs.EXIT);
573 private int getIdFromPath(HttpServletRequest req) {
574 String path = req.getPathInfo();
575 if (path == null || path.length() < 2) {
579 return Integer.parseInt(path.substring(1));
580 } catch (NumberFormatException e) {