Fix Sonar bugs
[dmaap/datarouter.git] / datarouter-node / src / main / java / org / onap / dmaap / datarouter / node / NodeServlet.java
1 /*******************************************************************************
2  * ============LICENSE_START==================================================
3  * * org.onap.dmaap
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
10  * *
11  *  *      http://www.apache.org/licenses/LICENSE-2.0
12  * *
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====================================================
19  * *
20  * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  * *
22  ******************************************************************************/
23
24
25 package org.onap.dmaap.datarouter.node;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import java.io.File;
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;
49
50 /**
51  * Servlet for handling all http and https requests to the data router node
52  * <p>
53  * Handled requests are:
54  * <br>
55  * GET http://<i>node</i>/internal/fetchProv - fetch the provisioning data
56  * <br>
57  * PUT/DELETE https://<i>node</i>/internal/publish/<i>fileid</i> - n2n transfer
58  * <br>
59  * PUT/DELETE https://<i>node</i>/publish/<i>feedid</i>/<i>fileid</i> - publsh request
60  */
61 public class NodeServlet extends HttpServlet {
62
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");
70
71     static {
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);
81     }
82
83     /**
84      * Get the NodeConfigurationManager
85      */
86     public void init() {
87         config = NodeConfigManager.getInstance();
88         logger.info("NODE0101 Node Servlet Configured");
89     }
90
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");
95             return (true);
96         }
97         return (false);
98     }
99
100     /**
101      * Handle a GET for /internal/fetchProv
102      */
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) + "");
107         if (down(resp)) {
108             return;
109         }
110         String path = req.getPathInfo();
111         String qs = req.getQueryString();
112         String ip = req.getRemoteAddr();
113         if (qs != null) {
114             path = path + "?" + qs;
115         }
116         if ("/internal/fetchProv".equals(path)) {
117             config.gofetch(ip);
118             resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
119             return;
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);
125                 return;
126             }
127         }
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);
135                     return;
136                 }
137                 byte[] buf = new byte[65536];
138                 resp.setContentType("text/plain");
139                 resp.setContentLength((int) fn.length());
140                 resp.setStatus(200);
141                 try (InputStream is = new FileInputStream(fn)) {
142                     OutputStream os = resp.getOutputStream();
143                     int i;
144                     while ((i = is.read(buf)) > 0) {
145                         os.write(buf, 0, i);
146                     }
147                 }
148                 return;
149             }
150             if (path.startsWith("/internal/rtt/")) {
151                 String xip = path.substring(14);
152                 long st = System.currentTimeMillis();
153                 String status = " unknown";
154                 try {
155                     Socket s = new Socket(xip, 443);
156                     s.close();
157                     status = " connected";
158                 } catch (Exception e) {
159                     status = " error " + e.toString();
160                 }
161                 long dur = System.currentTimeMillis() - st;
162                 resp.setContentType("text/plain");
163                 resp.setStatus(200);
164                 byte[] buf = (dur + status + "\n").getBytes();
165                 resp.setContentLength(buf.length);
166                 resp.getOutputStream().write(buf);
167                 return;
168             }
169         }
170         logger.info("NODE0103 Rejecting invalid GET of " + path + " from " + ip);
171         resp.sendError(HttpServletResponse.SC_NOT_FOUND);
172     }
173
174     /**
175      * Handle all PUT requests
176      */
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);
182     }
183
184     /**
185      * Handle all DELETE requests
186      */
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);
192     }
193
194     private void common(HttpServletRequest req, HttpServletResponse resp, boolean isput)
195         throws ServletException, IOException {
196         if (down(resp)) {
197             return;
198         }
199         if (!req.isSecure()) {
200             logger.info(
201                 "NODE0104 Rejecting insecure PUT or DELETE of " + req.getPathInfo() + " from " + req.getRemoteAddr());
202             resp.sendError(HttpServletResponse.SC_FORBIDDEN, "https required on publish requests");
203             return;
204         }
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
208                 .getRemoteAddr());
209             resp.sendError(HttpServletResponse.SC_NOT_FOUND,
210                 "Invalid request URI.  Expecting <feed-publishing-url>/<fileid>.");
211             return;
212         }
213         String feedid = null;
214         String user = 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
218                 .getRemoteAddr());
219             resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Authorization header required");
220             return;
221         }
222         String ip = req.getRemoteAddr();
223         String lip = req.getLocalAddr();
224         String pubid = null;
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
233                     .getRemoteAddr());
234                 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
235                     "Invalid request URI.  Expecting <feed-publishing-url>/<fileid>.  Possible missing fileid.");
236                 return;
237             }
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);
247                 return;
248             }
249             fileid = fileid.substring(18);
250             pubid = req.getHeader("X-ATT-DR-PUBLISH-ID");
251             targets = config.parseRouting(req.getHeader("X-ATT-DR-ROUTING"));
252         } else {
253             logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
254                 .getRemoteAddr());
255             resp.sendError(HttpServletResponse.SC_NOT_FOUND,
256                 "Invalid request URI.  Expecting <feed-publishing-url>/<fileid>.");
257             return;
258         }
259         if (fileid.indexOf('/') != -1) {
260             logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
261                 .getRemoteAddr());
262             resp.sendError(HttpServletResponse.SC_NOT_FOUND,
263                 "Invalid request URI.  Expecting <feed-publishing-url>/<fileid>.");
264             return;
265         }
266         String qs = req.getQueryString();
267         if (qs != null) {
268             fileid = fileid + "?" + qs;
269         }
270         String hp = config.getMyName();
271         int xp = config.getExtHttpsPort();
272         if (xp != 443) {
273             hp = hp + ":" + xp;
274         }
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) {
280                 logger.info(
281                     "NODE0111 Rejecting unauthorized publish attempt to feed " + feedid + " fileid " + fileid + " from "
282                         + ip + " reason " + reason);
283                 resp.sendError(HttpServletResponse.SC_FORBIDDEN, reason);
284                 return;
285             }
286             user = config.getAuthUser(feedid, credentials);
287             String newnode = config.getIngressNode(feedid, user, ip);
288             if (newnode != null) {
289                 String port = "";
290                 int iport = config.getExtHttpsPort();
291                 if (iport != 443) {
292                     port = ":" + iport;
293                 }
294                 String redirto = "https://" + newnode + port + "/publish/" + feedid + "/" + fileid;
295                 logger.info(
296                     "NODE0108 Redirecting publish attempt for feed " + feedid + " user " + user + " ip " + ip + " to "
297                         + redirto);
298                 resp.sendRedirect(redirto);
299                 return;
300             }
301             resp.setHeader("X-ATT-DR-PUBLISH-ID", pubid);
302         }
303         String fbase = config.getSpoolDir() + "/" + pubid;
304         File data = new File(fbase);
305         File meta = new File(fbase + ".M");
306         OutputStream dos = null;
307         Writer mw = null;
308         InputStream is = null;
309         try {
310             StringBuffer mx = new StringBuffer();
311             mx.append(req.getMethod()).append('\t').append(fileid).append('\n');
312             Enumeration hnames = req.getHeaderNames();
313             String ctype = null;
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)) {
328                             ctype = hv;
329                         }
330                         if ("x-att-dr-meta".equals(hnlc)) {
331                             if (hv.length() > 4096) {
332                                 logger.info(
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");
336                                 return;
337                             }
338                             if (!MetaDataPattern.matcher(hv.replaceAll("\\\\.", "X")).matches()) {
339                                 logger.info(
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");
343                                 return;
344                             }
345                         }
346                         mx.append(hn).append('\t').append(hv).append('\n');
347                     }
348                 }
349             }
350             mx.append("X-ATT-DR-RECEIVED\t").append(rcvd).append('\n');
351             String metadata = mx.toString();
352             byte[] buf = new byte[1024 * 1024];
353             int i;
354             try {
355                 is = req.getInputStream();
356                 dos = new FileOutputStream(data);
357                 while ((i = is.read(buf)) > 0) {
358                     dos.write(buf, 0, i);
359                 }
360                 is.close();
361                 is = null;
362                 dos.close();
363                 dos = null;
364             } catch (IOException ioe) {
365                 long exlen = -1;
366                 try {
367                     exlen = Long.parseLong(req.getHeader("Content-Length"));
368                 } catch (Exception e) {
369                 }
370                 StatusLog.logPubFail(pubid, feedid, logurl, req.getMethod(), ctype, exlen, data.length(), ip, user,
371                     ioe.getMessage());
372                 throw ioe;
373             }
374             Path dpath = Paths.get(fbase);
375             for (Target t : targets) {
376                 DestInfo di = t.getDestInfo();
377                 if (di == null) {
378                     // TODO: unknown destination
379                     continue;
380                 }
381                 String dbase = di.getSpool() + "/" + pubid;
382                 Files.createLink(Paths.get(dbase), dpath);
383                 mw = new FileWriter(meta);
384                 mw.write(metadata);
385                 if (di.getSubId() == null) {
386                     mw.write("X-ATT-DR-ROUTING\t" + t.getRouting() + "\n");
387                 }
388                 mw.close();
389                 meta.renameTo(new File(dbase + ".M"));
390             }
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) {
396             logger.info(
397                 "NODE0110 IO Exception receiving publish attempt for feed " + feedid + " user " + user + " ip " + ip
398                     + " " + ioe.toString(), ioe);
399             throw ioe;
400         } finally {
401             if (is != null) {
402                 try {
403                     is.close();
404                 } catch (Exception e) {
405                 }
406             }
407             if (dos != null) {
408                 try {
409                     dos.close();
410                 } catch (Exception e) {
411                 }
412             }
413             if (mw != null) {
414                 try {
415                     mw.close();
416                 } catch (Exception e) {
417                 }
418             }
419             try {
420                 data.delete();
421             } catch (Exception e) {
422             }
423             try {
424                 meta.delete();
425             } catch (Exception e) {
426             }
427         }
428     }
429
430     private int getIdFromPath(HttpServletRequest req) {
431         String path = req.getPathInfo();
432         if (path == null || path.length() < 2) {
433             return -1;
434         }
435         try {
436             return Integer.parseInt(path.substring(1));
437         } catch (NumberFormatException e) {
438             return -1;
439         }
440     }
441 }