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;
30 import java.io.FileInputStream;
31 import java.io.FileOutputStream;
32 import java.io.FileWriter;
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.io.OutputStream;
36 import java.io.Writer;
37 import java.net.Socket;
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.ServletException;
44 import javax.servlet.http.HttpServlet;
45 import javax.servlet.http.HttpServletRequest;
46 import javax.servlet.http.HttpServletResponse;
47 import org.apache.log4j.Logger;
48 import org.onap.dmaap.datarouter.node.eelf.EelfMsgs;
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 SubnetMatcher internalsubnet = new SubnetMatcher("135.207.136.128/25");
67 //Adding EELF Logger Rally:US664892
68 private static EELFLogger eelflogger = EELFManager.getInstance()
69 .getLogger("org.onap.dmaap.datarouter.node.NodeServlet");
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);
82 } catch (Exception e) {
87 * Get the NodeConfigurationManager
90 config = NodeConfigManager.getInstance();
91 logger.info("NODE0101 Node Servlet Configured");
94 private boolean down(HttpServletResponse resp) throws IOException {
95 if (config.isShutdown() || !config.isConfigured()) {
96 resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
97 logger.info("NODE0102 Rejecting request: Service is being quiesced");
104 * Handle a GET for /internal/fetchProv
106 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
107 NodeUtils.setIpAndFqdnForEelf("doGet");
108 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-ATT-DR-ON-BEHALF-OF"),
109 getIdFromPath(req) + "");
113 String path = req.getPathInfo();
114 String qs = req.getQueryString();
115 String ip = req.getRemoteAddr();
117 path = path + "?" + qs;
119 if ("/internal/fetchProv".equals(path)) {
121 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
123 } else if (path.startsWith("/internal/resetSubscription/")) {
124 String subid = path.substring(28);
125 if (subid.length() != 0 && subid.indexOf('/') == -1) {
126 NodeMain.resetQueue(subid, ip);
127 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
131 if (internalsubnet.matches(NodeUtils.getInetAddress(ip))) {
132 if (path.startsWith("/internal/logs/")) {
133 String f = path.substring(15);
134 File fn = new File(config.getLogDir() + "/" + f);
135 if (f.indexOf('/') != -1 || !fn.isFile()) {
136 logger.info("NODE0103 Rejecting invalid GET of " + path + " from " + ip);
137 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
140 byte[] buf = new byte[65536];
141 resp.setContentType("text/plain");
142 resp.setContentLength((int) fn.length());
144 try (InputStream is = new FileInputStream(fn)) {
145 OutputStream os = resp.getOutputStream();
147 while ((i = is.read(buf)) > 0) {
153 if (path.startsWith("/internal/rtt/")) {
154 String xip = path.substring(14);
155 long st = System.currentTimeMillis();
156 String status = " unknown";
158 Socket s = new Socket(xip, 443);
160 status = " connected";
161 } catch (Exception e) {
162 status = " error " + e.toString();
164 long dur = System.currentTimeMillis() - st;
165 resp.setContentType("text/plain");
167 byte[] buf = (dur + status + "\n").getBytes();
168 resp.setContentLength(buf.length);
169 resp.getOutputStream().write(buf);
173 logger.info("NODE0103 Rejecting invalid GET of " + path + " from " + ip);
174 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
178 * Handle all PUT requests
180 protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
181 NodeUtils.setIpAndFqdnForEelf("doPut");
182 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-ATT-DR-ON-BEHALF-OF"),
183 getIdFromPath(req) + "");
184 common(req, resp, true);
188 * Handle all DELETE requests
190 protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
191 NodeUtils.setIpAndFqdnForEelf("doDelete");
192 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-ATT-DR-ON-BEHALF-OF"),
193 getIdFromPath(req) + "");
194 common(req, resp, false);
197 private void common(HttpServletRequest req, HttpServletResponse resp, boolean isput)
198 throws ServletException, IOException {
202 if (!req.isSecure()) {
204 "NODE0104 Rejecting insecure PUT or DELETE of " + req.getPathInfo() + " from " + req.getRemoteAddr());
205 resp.sendError(HttpServletResponse.SC_FORBIDDEN, "https required on publish requests");
208 String fileid = req.getPathInfo();
209 if (fileid == null) {
210 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
212 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
213 "Invalid request URI. Expecting <feed-publishing-url>/<fileid>.");
216 String feedid = null;
218 String credentials = req.getHeader("Authorization");
219 if (credentials == null) {
220 logger.info("NODE0106 Rejecting unauthenticated PUT or DELETE of " + req.getPathInfo() + " from " + req
222 resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Authorization header required");
225 String ip = req.getRemoteAddr();
226 String lip = req.getLocalAddr();
228 String xpubid = null;
229 String rcvd = NodeUtils.logts(System.currentTimeMillis()) + ";from=" + ip + ";by=" + lip;
230 Target[] targets = null;
231 if (fileid.startsWith("/publish/")) {
232 fileid = fileid.substring(9);
233 int i = fileid.indexOf('/');
234 if (i == -1 || i == fileid.length() - 1) {
235 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
237 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
238 "Invalid request URI. Expecting <feed-publishing-url>/<fileid>. Possible missing fileid.");
241 feedid = fileid.substring(0, i);
242 fileid = fileid.substring(i + 1);
243 pubid = config.getPublishId();
244 xpubid = req.getHeader("X-ATT-DR-PUBLISH-ID");
245 targets = config.getTargets(feedid);
246 } else if (fileid.startsWith("/internal/publish/")) {
247 if (!config.isAnotherNode(credentials, ip)) {
248 logger.info("NODE0107 Rejecting unauthorized node-to-node transfer attempt from " + ip);
249 resp.sendError(HttpServletResponse.SC_FORBIDDEN);
252 fileid = fileid.substring(18);
253 pubid = req.getHeader("X-ATT-DR-PUBLISH-ID");
254 targets = config.parseRouting(req.getHeader("X-ATT-DR-ROUTING"));
256 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
258 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
259 "Invalid request URI. Expecting <feed-publishing-url>/<fileid>.");
262 if (fileid.indexOf('/') != -1) {
263 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
265 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
266 "Invalid request URI. Expecting <feed-publishing-url>/<fileid>.");
269 String qs = req.getQueryString();
271 fileid = fileid + "?" + qs;
273 String hp = config.getMyName();
274 int xp = config.getExtHttpsPort();
278 String logurl = "https://" + hp + "/internal/publish/" + fileid;
279 if (feedid != null) {
280 logurl = "https://" + hp + "/publish/" + feedid + "/" + fileid;
281 String reason = config.isPublishPermitted(feedid, credentials, ip);
282 if (reason != null) {
284 "NODE0111 Rejecting unauthorized publish attempt to feed " + feedid + " fileid " + fileid + " from "
285 + ip + " reason " + reason);
286 resp.sendError(HttpServletResponse.SC_FORBIDDEN, reason);
289 user = config.getAuthUser(feedid, credentials);
290 String newnode = config.getIngressNode(feedid, user, ip);
291 if (newnode != null) {
293 int iport = config.getExtHttpsPort();
297 String redirto = "https://" + newnode + port + "/publish/" + feedid + "/" + fileid;
299 "NODE0108 Redirecting publish attempt for feed " + feedid + " user " + user + " ip " + ip + " to "
301 resp.sendRedirect(redirto);
304 resp.setHeader("X-ATT-DR-PUBLISH-ID", pubid);
306 String fbase = config.getSpoolDir() + "/" + pubid;
307 File data = new File(fbase);
308 File meta = new File(fbase + ".M");
309 OutputStream dos = null;
311 InputStream is = null;
313 StringBuffer mx = new StringBuffer();
314 mx.append(req.getMethod()).append('\t').append(fileid).append('\n');
315 Enumeration hnames = req.getHeaderNames();
317 while (hnames.hasMoreElements()) {
318 String hn = (String) hnames.nextElement();
319 String hnlc = hn.toLowerCase();
320 if ((isput && ("content-type".equals(hnlc) ||
321 "content-language".equals(hnlc) ||
322 "content-md5".equals(hnlc) ||
323 "content-range".equals(hnlc))) ||
324 "x-att-dr-meta".equals(hnlc) ||
325 (feedid == null && "x-att-dr-received".equals(hnlc)) ||
326 (hnlc.startsWith("x-") && !hnlc.startsWith("x-att-dr-"))) {
327 Enumeration hvals = req.getHeaders(hn);
328 while (hvals.hasMoreElements()) {
329 String hv = (String) hvals.nextElement();
330 if ("content-type".equals(hnlc)) {
333 if ("x-att-dr-meta".equals(hnlc)) {
334 if (hv.length() > 4096) {
336 "NODE0109 Rejecting publish attempt with metadata too long for feed " + feedid
337 + " user " + user + " ip " + ip);
338 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Metadata too long");
341 if (!MetaDataPattern.matcher(hv.replaceAll("\\\\.", "X")).matches()) {
343 "NODE0109 Rejecting publish attempt with malformed metadata for feed " + feedid
344 + " user " + user + " ip " + ip);
345 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Malformed metadata");
349 mx.append(hn).append('\t').append(hv).append('\n');
353 mx.append("X-ATT-DR-RECEIVED\t").append(rcvd).append('\n');
354 String metadata = mx.toString();
355 byte[] buf = new byte[1024 * 1024];
358 is = req.getInputStream();
359 dos = new FileOutputStream(data);
360 while ((i = is.read(buf)) > 0) {
361 dos.write(buf, 0, i);
367 } catch (IOException ioe) {
370 exlen = Long.parseLong(req.getHeader("Content-Length"));
371 } catch (Exception e) {
373 StatusLog.logPubFail(pubid, feedid, logurl, req.getMethod(), ctype, exlen, data.length(), ip, user,
377 Path dpath = Paths.get(fbase);
378 for (Target t : targets) {
379 DestInfo di = t.getDestInfo();
381 // TODO: unknown destination
384 String dbase = di.getSpool() + "/" + pubid;
385 Files.createLink(Paths.get(dbase), dpath);
386 mw = new FileWriter(meta);
388 if (di.getSubId() == null) {
389 mw.write("X-ATT-DR-ROUTING\t" + t.getRouting() + "\n");
392 meta.renameTo(new File(dbase + ".M"));
394 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
395 resp.getOutputStream().close();
396 StatusLog.logPub(pubid, feedid, logurl, req.getMethod(), ctype, data.length(), ip, user,
397 HttpServletResponse.SC_NO_CONTENT);
398 } catch (IOException ioe) {
400 "NODE0110 IO Exception receiving publish attempt for feed " + feedid + " user " + user + " ip " + ip
401 + " " + ioe.toString(), ioe);
407 } catch (Exception e) {
413 } catch (Exception e) {
419 } catch (Exception e) {
424 } catch (Exception e) {
428 } catch (Exception e) {
433 private int getIdFromPath(HttpServletRequest req) {
434 String path = req.getPathInfo();
435 if (path == null || path.length() < 2) {
439 return Integer.parseInt(path.substring(1));
440 } catch (NumberFormatException e) {