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 javax.servlet.*;
28 import javax.servlet.http.*;
30 import java.util.regex.*;
32 import java.nio.file.*;
34 import org.apache.log4j.Logger;
35 import org.onap.dmaap.datarouter.node.eelf.EelfMsgs;
37 import com.att.eelf.configuration.EELFLogger;
38 import com.att.eelf.configuration.EELFManager;
43 * Servlet for handling all http and https requests to the data router node
45 * Handled requests are:
47 * GET http://<i>node</i>/internal/fetchProv - fetch the provisioning data
49 * PUT/DELETE https://<i>node</i>/internal/publish/<i>fileid</i> - n2n transfer
51 * PUT/DELETE https://<i>node</i>/publish/<i>feedid</i>/<i>fileid</i> - publsh request
53 public class NodeServlet extends HttpServlet {
54 private static Logger logger = Logger.getLogger("org.onap.dmaap.datarouter.node.NodeServlet");
55 private static NodeConfigManager config;
56 private static Pattern MetaDataPattern;
57 private static SubnetMatcher internalsubnet = new SubnetMatcher("135.207.136.128/25");
58 //Adding EELF Logger Rally:US664892
59 private static EELFLogger eelflogger = EELFManager.getInstance().getLogger("org.onap.dmaap.datarouter.node.NodeServlet");
64 // assume that \\ and \" have been replaced by X
65 String string = "\"[^\"]*\"";
66 //String string = "\"(?:[^\"\\\\]|\\\\.)*\"";
67 String number = "[+-]?(?:\\.\\d+|(?:0|[1-9]\\d*)(?:\\.\\d*)?)(?:[eE][+-]?\\d+)?";
68 String value = "(?:" + string + "|" + number + "|null|true|false)";
69 String item = string + ws + ":" + ws + value + ws;
70 String object = ws + "\\{" + ws + "(?:" + item + "(?:" + "," + ws + item + ")*)?\\}" + ws;
71 MetaDataPattern = Pattern.compile(object, Pattern.DOTALL);
72 } catch (Exception e) {
77 * Get the NodeConfigurationManager
80 config = NodeConfigManager.getInstance();
81 logger.info("NODE0101 Node Servlet Configured");
84 private boolean down(HttpServletResponse resp) throws IOException {
85 if (config.isShutdown() || !config.isConfigured()) {
86 resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
87 logger.info("NODE0102 Rejecting request: Service is being quiesced");
94 * Handle a GET for /internal/fetchProv
96 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
97 NodeUtils.setIpAndFqdnForEelf("doGet");
98 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-ATT-DR-ON-BEHALF-OF"), getIdFromPath(req) + "");
102 String path = req.getPathInfo();
103 String qs = req.getQueryString();
104 String ip = req.getRemoteAddr();
106 path = path + "?" + qs;
108 if ("/internal/fetchProv".equals(path)) {
110 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
112 } else if (path.startsWith("/internal/resetSubscription/")) {
113 String subid = path.substring(28);
114 if (subid.length() != 0 && subid.indexOf('/') == -1) {
115 NodeMain.resetQueue(subid, ip);
116 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
120 if (internalsubnet.matches(NodeUtils.getInetAddress(ip))) {
121 if (path.startsWith("/internal/logs/")) {
122 String f = path.substring(15);
123 File fn = new File(config.getLogDir() + "/" + f);
124 if (f.indexOf('/') != -1 || !fn.isFile()) {
125 logger.info("NODE0103 Rejecting invalid GET of " + path + " from " + ip);
126 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
129 byte[] buf = new byte[65536];
130 resp.setContentType("text/plain");
131 resp.setContentLength((int) fn.length());
133 InputStream is = new FileInputStream(fn);
134 OutputStream os = resp.getOutputStream();
136 while ((i = is.read(buf)) > 0) {
142 if (path.startsWith("/internal/rtt/")) {
143 String xip = path.substring(14);
144 long st = System.currentTimeMillis();
145 String status = " unknown";
147 Socket s = new Socket(xip, 443);
149 status = " connected";
150 } catch (Exception e) {
151 status = " error " + e.toString();
153 long dur = System.currentTimeMillis() - st;
154 resp.setContentType("text/plain");
156 byte[] buf = (dur + status + "\n").getBytes();
157 resp.setContentLength(buf.length);
158 resp.getOutputStream().write(buf);
162 logger.info("NODE0103 Rejecting invalid GET of " + path + " from " + ip);
163 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
168 * Handle all PUT requests
170 protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
171 NodeUtils.setIpAndFqdnForEelf("doPut");
172 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-ATT-DR-ON-BEHALF-OF"), getIdFromPath(req) + "");
173 common(req, resp, true);
177 * Handle all DELETE requests
179 protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
180 NodeUtils.setIpAndFqdnForEelf("doDelete");
181 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-ATT-DR-ON-BEHALF-OF"), getIdFromPath(req) + "");
182 common(req, resp, false);
185 private void common(HttpServletRequest req, HttpServletResponse resp, boolean isput) throws ServletException, IOException {
189 if (!req.isSecure()) {
190 logger.info("NODE0104 Rejecting insecure PUT or DELETE of " + req.getPathInfo() + " from " + req.getRemoteAddr());
191 resp.sendError(HttpServletResponse.SC_FORBIDDEN, "https required on publish requests");
194 String fileid = req.getPathInfo();
195 if (fileid == null) {
196 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req.getRemoteAddr());
197 resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid request URI. Expecting <feed-publishing-url>/<fileid>.");
200 String feedid = null;
202 String credentials = req.getHeader("Authorization");
203 if (credentials == null) {
204 logger.info("NODE0106 Rejecting unauthenticated PUT or DELETE of " + req.getPathInfo() + " from " + req.getRemoteAddr());
205 resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Authorization header required");
208 String ip = req.getRemoteAddr();
209 String lip = req.getLocalAddr();
211 String xpubid = null;
212 String rcvd = NodeUtils.logts(System.currentTimeMillis()) + ";from=" + ip + ";by=" + lip;
213 Target[] targets = null;
214 if (fileid.startsWith("/publish/")) {
215 fileid = fileid.substring(9);
216 int i = fileid.indexOf('/');
217 if (i == -1 || i == fileid.length() - 1) {
218 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req.getRemoteAddr());
219 resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid request URI. Expecting <feed-publishing-url>/<fileid>. Possible missing fileid.");
222 feedid = fileid.substring(0, i);
223 fileid = fileid.substring(i + 1);
224 pubid = config.getPublishId();
225 xpubid = req.getHeader("X-ATT-DR-PUBLISH-ID");
226 targets = config.getTargets(feedid);
227 } else if (fileid.startsWith("/internal/publish/")) {
228 if (!config.isAnotherNode(credentials, ip)) {
229 logger.info("NODE0107 Rejecting unauthorized node-to-node transfer attempt from " + ip);
230 resp.sendError(HttpServletResponse.SC_FORBIDDEN);
233 fileid = fileid.substring(18);
234 pubid = req.getHeader("X-ATT-DR-PUBLISH-ID");
235 targets = config.parseRouting(req.getHeader("X-ATT-DR-ROUTING"));
237 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req.getRemoteAddr());
238 resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid request URI. Expecting <feed-publishing-url>/<fileid>.");
241 if (fileid.indexOf('/') != -1) {
242 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req.getRemoteAddr());
243 resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid request URI. Expecting <feed-publishing-url>/<fileid>.");
246 String qs = req.getQueryString();
248 fileid = fileid + "?" + qs;
250 String hp = config.getMyName();
251 int xp = config.getExtHttpsPort();
255 String logurl = "https://" + hp + "/internal/publish/" + fileid;
256 if (feedid != null) {
257 logurl = "https://" + hp + "/publish/" + feedid + "/" + fileid;
258 String reason = config.isPublishPermitted(feedid, credentials, ip);
259 if (reason != null) {
260 logger.info("NODE0111 Rejecting unauthorized publish attempt to feed " + feedid + " fileid " + fileid + " from " + ip + " reason " + reason);
261 resp.sendError(HttpServletResponse.SC_FORBIDDEN, reason);
264 user = config.getAuthUser(feedid, credentials);
265 String newnode = config.getIngressNode(feedid, user, ip);
266 if (newnode != null) {
268 int iport = config.getExtHttpsPort();
272 String redirto = "https://" + newnode + port + "/publish/" + feedid + "/" + fileid;
273 logger.info("NODE0108 Redirecting publish attempt for feed " + feedid + " user " + user + " ip " + ip + " to " + redirto);
274 resp.sendRedirect(redirto);
277 resp.setHeader("X-ATT-DR-PUBLISH-ID", pubid);
279 String fbase = config.getSpoolDir() + "/" + pubid;
280 File data = new File(fbase);
281 File meta = new File(fbase + ".M");
282 OutputStream dos = null;
284 InputStream is = null;
286 StringBuffer mx = new StringBuffer();
287 mx.append(req.getMethod()).append('\t').append(fileid).append('\n');
288 Enumeration hnames = req.getHeaderNames();
290 while (hnames.hasMoreElements()) {
291 String hn = (String) hnames.nextElement();
292 String hnlc = hn.toLowerCase();
293 if ((isput && ("content-type".equals(hnlc) ||
294 "content-language".equals(hnlc) ||
295 "content-md5".equals(hnlc) ||
296 "content-range".equals(hnlc))) ||
297 "x-att-dr-meta".equals(hnlc) ||
298 (feedid == null && "x-att-dr-received".equals(hnlc)) ||
299 (hnlc.startsWith("x-") && !hnlc.startsWith("x-att-dr-"))) {
300 Enumeration hvals = req.getHeaders(hn);
301 while (hvals.hasMoreElements()) {
302 String hv = (String) hvals.nextElement();
303 if ("content-type".equals(hnlc)) {
306 if ("x-att-dr-meta".equals(hnlc)) {
307 if (hv.length() > 4096) {
308 logger.info("NODE0109 Rejecting publish attempt with metadata too long for feed " + feedid + " user " + user + " ip " + ip);
309 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Metadata too long");
312 if (!MetaDataPattern.matcher(hv.replaceAll("\\\\.", "X")).matches()) {
313 logger.info("NODE0109 Rejecting publish attempt with malformed metadata for feed " + feedid + " user " + user + " ip " + ip);
314 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Malformed metadata");
318 mx.append(hn).append('\t').append(hv).append('\n');
322 mx.append("X-ATT-DR-RECEIVED\t").append(rcvd).append('\n');
323 String metadata = mx.toString();
324 byte[] buf = new byte[1024 * 1024];
327 is = req.getInputStream();
328 dos = new FileOutputStream(data);
329 while ((i = is.read(buf)) > 0) {
330 dos.write(buf, 0, i);
336 } catch (IOException ioe) {
339 exlen = Long.parseLong(req.getHeader("Content-Length"));
340 } catch (Exception e) {
342 StatusLog.logPubFail(pubid, feedid, logurl, req.getMethod(), ctype, exlen, data.length(), ip, user, ioe.getMessage());
345 Path dpath = Paths.get(fbase);
346 for (Target t : targets) {
347 DestInfo di = t.getDestInfo();
349 // TODO: unknown destination
352 String dbase = di.getSpool() + "/" + pubid;
353 Files.createLink(Paths.get(dbase), dpath);
354 mw = new FileWriter(meta);
356 if (di.getSubId() == null) {
357 mw.write("X-ATT-DR-ROUTING\t" + t.getRouting() + "\n");
360 meta.renameTo(new File(dbase + ".M"));
362 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
363 resp.getOutputStream().close();
364 StatusLog.logPub(pubid, feedid, logurl, req.getMethod(), ctype, data.length(), ip, user, HttpServletResponse.SC_NO_CONTENT);
365 } catch (IOException ioe) {
366 logger.info("NODE0110 IO Exception receiving publish attempt for feed " + feedid + " user " + user + " ip " + ip + " " + ioe.toString(), ioe);
372 } catch (Exception e) {
378 } catch (Exception e) {
384 } catch (Exception e) {
389 } catch (Exception e) {
393 } catch (Exception e) {
398 private int getIdFromPath(HttpServletRequest req) {
399 String path = req.getPathInfo();
400 if (path == null || path.length() < 2)
403 return Integer.parseInt(path.substring(1));
404 } catch (NumberFormatException e) {