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");
72 final String ws = "\\s*";
73 // assume that \\ and \" have been replaced by X
74 final String string = "\"[^\"]*\"";
75 //String string = "\"(?:[^\"\\\\]|\\\\.)*\"";
76 final String number = "[+-]?(?:\\.\\d+|(?:0|[1-9]\\d*)(?:\\.\\d*)?)(?:[eE][+-]?\\d+)?";
77 final String value = "(?:" + string + "|" + number + "|null|true|false)";
78 final String item = string + ws + ":" + ws + value + ws;
79 final String object = ws + "\\{" + ws + "(?:" + item + "(?:" + "," + ws + item + ")*)?\\}" + ws;
80 MetaDataPattern = Pattern.compile(object, Pattern.DOTALL);
84 * Get the NodeConfigurationManager
87 config = NodeConfigManager.getInstance();
88 logger.info("NODE0101 Node Servlet Configured");
91 private boolean down(HttpServletResponse resp) throws IOException {
92 if (config.isShutdown() || !config.isConfigured()) {
93 resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
94 logger.info("NODE0102 Rejecting request: Service is being quiesced");
101 * Handle a GET for /internal/fetchProv
103 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
104 NodeUtils.setIpAndFqdnForEelf("doGet");
105 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-ATT-DR-ON-BEHALF-OF"),
106 getIdFromPath(req) + "");
110 String path = req.getPathInfo();
111 String qs = req.getQueryString();
112 String ip = req.getRemoteAddr();
114 path = path + "?" + qs;
116 if ("/internal/fetchProv".equals(path)) {
118 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
120 } else if (path.startsWith("/internal/resetSubscription/")) {
121 String subid = path.substring(28);
122 if (subid.length() != 0 && subid.indexOf('/') == -1) {
123 NodeMain.resetQueue(subid, ip);
124 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
128 if (internalsubnet.matches(NodeUtils.getInetAddress(ip))) {
129 if (path.startsWith("/internal/logs/")) {
130 String f = path.substring(15);
131 File fn = new File(config.getLogDir() + "/" + f);
132 if (f.indexOf('/') != -1 || !fn.isFile()) {
133 logger.info("NODE0103 Rejecting invalid GET of " + path + " from " + ip);
134 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
137 byte[] buf = new byte[65536];
138 resp.setContentType("text/plain");
139 resp.setContentLength((int) fn.length());
141 try (InputStream is = new FileInputStream(fn)) {
142 OutputStream os = resp.getOutputStream();
144 while ((i = is.read(buf)) > 0) {
150 if (path.startsWith("/internal/rtt/")) {
151 String xip = path.substring(14);
152 long st = System.currentTimeMillis();
153 String status = " unknown";
155 Socket s = new Socket(xip, 443);
157 status = " connected";
158 } catch (Exception e) {
159 status = " error " + e.toString();
161 long dur = System.currentTimeMillis() - st;
162 resp.setContentType("text/plain");
164 byte[] buf = (dur + status + "\n").getBytes();
165 resp.setContentLength(buf.length);
166 resp.getOutputStream().write(buf);
170 logger.info("NODE0103 Rejecting invalid GET of " + path + " from " + ip);
171 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
175 * Handle all PUT requests
177 protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
178 NodeUtils.setIpAndFqdnForEelf("doPut");
179 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-ATT-DR-ON-BEHALF-OF"),
180 getIdFromPath(req) + "");
181 common(req, resp, true);
185 * Handle all DELETE requests
187 protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
188 NodeUtils.setIpAndFqdnForEelf("doDelete");
189 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-ATT-DR-ON-BEHALF-OF"),
190 getIdFromPath(req) + "");
191 common(req, resp, false);
194 private void common(HttpServletRequest req, HttpServletResponse resp, boolean isput)
195 throws ServletException, IOException {
199 if (!req.isSecure()) {
201 "NODE0104 Rejecting insecure PUT or DELETE of " + req.getPathInfo() + " from " + req.getRemoteAddr());
202 resp.sendError(HttpServletResponse.SC_FORBIDDEN, "https required on publish requests");
205 String fileid = req.getPathInfo();
206 if (fileid == null) {
207 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
209 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
210 "Invalid request URI. Expecting <feed-publishing-url>/<fileid>.");
213 String feedid = null;
215 String credentials = req.getHeader("Authorization");
216 if (credentials == null) {
217 logger.info("NODE0106 Rejecting unauthenticated PUT or DELETE of " + req.getPathInfo() + " from " + req
219 resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Authorization header required");
222 String ip = req.getRemoteAddr();
223 String lip = req.getLocalAddr();
225 String xpubid = null;
226 String rcvd = NodeUtils.logts(System.currentTimeMillis()) + ";from=" + ip + ";by=" + lip;
227 Target[] targets = null;
228 if (fileid.startsWith("/publish/")) {
229 fileid = fileid.substring(9);
230 int i = fileid.indexOf('/');
231 if (i == -1 || i == fileid.length() - 1) {
232 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
234 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
235 "Invalid request URI. Expecting <feed-publishing-url>/<fileid>. Possible missing fileid.");
238 feedid = fileid.substring(0, i);
239 fileid = fileid.substring(i + 1);
240 pubid = config.getPublishId();
241 xpubid = req.getHeader("X-ATT-DR-PUBLISH-ID");
242 targets = config.getTargets(feedid);
243 } else if (fileid.startsWith("/internal/publish/")) {
244 if (!config.isAnotherNode(credentials, ip)) {
245 logger.info("NODE0107 Rejecting unauthorized node-to-node transfer attempt from " + ip);
246 resp.sendError(HttpServletResponse.SC_FORBIDDEN);
249 fileid = fileid.substring(18);
250 pubid = req.getHeader("X-ATT-DR-PUBLISH-ID");
251 targets = config.parseRouting(req.getHeader("X-ATT-DR-ROUTING"));
253 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
255 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
256 "Invalid request URI. Expecting <feed-publishing-url>/<fileid>.");
259 if (fileid.indexOf('/') != -1) {
260 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
262 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
263 "Invalid request URI. Expecting <feed-publishing-url>/<fileid>.");
266 String qs = req.getQueryString();
268 fileid = fileid + "?" + qs;
270 String hp = config.getMyName();
271 int xp = config.getExtHttpsPort();
275 String logurl = "https://" + hp + "/internal/publish/" + fileid;
276 if (feedid != null) {
277 logurl = "https://" + hp + "/publish/" + feedid + "/" + fileid;
278 String reason = config.isPublishPermitted(feedid, credentials, ip);
279 if (reason != null) {
281 "NODE0111 Rejecting unauthorized publish attempt to feed " + feedid + " fileid " + fileid + " from "
282 + ip + " reason " + reason);
283 resp.sendError(HttpServletResponse.SC_FORBIDDEN, reason);
286 user = config.getAuthUser(feedid, credentials);
287 String newnode = config.getIngressNode(feedid, user, ip);
288 if (newnode != null) {
290 int iport = config.getExtHttpsPort();
294 String redirto = "https://" + newnode + port + "/publish/" + feedid + "/" + fileid;
296 "NODE0108 Redirecting publish attempt for feed " + feedid + " user " + user + " ip " + ip + " to "
298 resp.sendRedirect(redirto);
301 resp.setHeader("X-ATT-DR-PUBLISH-ID", pubid);
303 String fbase = config.getSpoolDir() + "/" + pubid;
304 File data = new File(fbase);
305 File meta = new File(fbase + ".M");
306 OutputStream dos = null;
308 InputStream is = null;
310 StringBuffer mx = new StringBuffer();
311 mx.append(req.getMethod()).append('\t').append(fileid).append('\n');
312 Enumeration hnames = req.getHeaderNames();
314 while (hnames.hasMoreElements()) {
315 String hn = (String) hnames.nextElement();
316 String hnlc = hn.toLowerCase();
317 if ((isput && ("content-type".equals(hnlc) ||
318 "content-language".equals(hnlc) ||
319 "content-md5".equals(hnlc) ||
320 "content-range".equals(hnlc))) ||
321 "x-att-dr-meta".equals(hnlc) ||
322 (feedid == null && "x-att-dr-received".equals(hnlc)) ||
323 (hnlc.startsWith("x-") && !hnlc.startsWith("x-att-dr-"))) {
324 Enumeration hvals = req.getHeaders(hn);
325 while (hvals.hasMoreElements()) {
326 String hv = (String) hvals.nextElement();
327 if ("content-type".equals(hnlc)) {
330 if ("x-att-dr-meta".equals(hnlc)) {
331 if (hv.length() > 4096) {
333 "NODE0109 Rejecting publish attempt with metadata too long for feed " + feedid
334 + " user " + user + " ip " + ip);
335 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Metadata too long");
338 if (!MetaDataPattern.matcher(hv.replaceAll("\\\\.", "X")).matches()) {
340 "NODE0109 Rejecting publish attempt with malformed metadata for feed " + feedid
341 + " user " + user + " ip " + ip);
342 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Malformed metadata");
346 mx.append(hn).append('\t').append(hv).append('\n');
350 mx.append("X-ATT-DR-RECEIVED\t").append(rcvd).append('\n');
351 String metadata = mx.toString();
352 byte[] buf = new byte[1024 * 1024];
355 is = req.getInputStream();
356 dos = new FileOutputStream(data);
357 while ((i = is.read(buf)) > 0) {
358 dos.write(buf, 0, i);
364 } catch (IOException ioe) {
367 exlen = Long.parseLong(req.getHeader("Content-Length"));
368 } catch (Exception e) {
370 StatusLog.logPubFail(pubid, feedid, logurl, req.getMethod(), ctype, exlen, data.length(), ip, user,
374 Path dpath = Paths.get(fbase);
375 for (Target t : targets) {
376 DestInfo di = t.getDestInfo();
378 // TODO: unknown destination
381 String dbase = di.getSpool() + "/" + pubid;
382 Files.createLink(Paths.get(dbase), dpath);
383 mw = new FileWriter(meta);
385 if (di.getSubId() == null) {
386 mw.write("X-ATT-DR-ROUTING\t" + t.getRouting() + "\n");
389 meta.renameTo(new File(dbase + ".M"));
391 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
392 resp.getOutputStream().close();
393 StatusLog.logPub(pubid, feedid, logurl, req.getMethod(), ctype, data.length(), ip, user,
394 HttpServletResponse.SC_NO_CONTENT);
395 } catch (IOException ioe) {
397 "NODE0110 IO Exception receiving publish attempt for feed " + feedid + " user " + user + " ip " + ip
398 + " " + ioe.toString(), ioe);
404 } catch (Exception e) {
410 } catch (Exception e) {
416 } catch (Exception e) {
421 } catch (Exception e) {
425 } catch (Exception e) {
430 private int getIdFromPath(HttpServletRequest req) {
431 String path = req.getPathInfo();
432 if (path == null || path.length() < 2) {
436 return Integer.parseInt(path.substring(1));
437 } catch (NumberFormatException e) {