Merge "Add Unit Tests for NodeUtils and StatusLog"
[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         try {
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) {
83         }
84     }
85
86     /**
87      * Get the NodeConfigurationManager
88      */
89     public void init() {
90         config = NodeConfigManager.getInstance();
91         logger.info("NODE0101 Node Servlet Configured");
92     }
93
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");
98             return (true);
99         }
100         return (false);
101     }
102
103     /**
104      * Handle a GET for /internal/fetchProv
105      */
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) + "");
110         if (down(resp)) {
111             return;
112         }
113         String path = req.getPathInfo();
114         String qs = req.getQueryString();
115         String ip = req.getRemoteAddr();
116         if (qs != null) {
117             path = path + "?" + qs;
118         }
119         if ("/internal/fetchProv".equals(path)) {
120             config.gofetch(ip);
121             resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
122             return;
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);
128                 return;
129             }
130         }
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);
138                     return;
139                 }
140                 byte[] buf = new byte[65536];
141                 resp.setContentType("text/plain");
142                 resp.setContentLength((int) fn.length());
143                 resp.setStatus(200);
144                 try (InputStream is = new FileInputStream(fn)) {
145                     OutputStream os = resp.getOutputStream();
146                     int i;
147                     while ((i = is.read(buf)) > 0) {
148                         os.write(buf, 0, i);
149                     }
150                 }
151                 return;
152             }
153             if (path.startsWith("/internal/rtt/")) {
154                 String xip = path.substring(14);
155                 long st = System.currentTimeMillis();
156                 String status = " unknown";
157                 try {
158                     Socket s = new Socket(xip, 443);
159                     s.close();
160                     status = " connected";
161                 } catch (Exception e) {
162                     status = " error " + e.toString();
163                 }
164                 long dur = System.currentTimeMillis() - st;
165                 resp.setContentType("text/plain");
166                 resp.setStatus(200);
167                 byte[] buf = (dur + status + "\n").getBytes();
168                 resp.setContentLength(buf.length);
169                 resp.getOutputStream().write(buf);
170                 return;
171             }
172         }
173         logger.info("NODE0103 Rejecting invalid GET of " + path + " from " + ip);
174         resp.sendError(HttpServletResponse.SC_NOT_FOUND);
175     }
176
177     /**
178      * Handle all PUT requests
179      */
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);
185     }
186
187     /**
188      * Handle all DELETE requests
189      */
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);
195     }
196
197     private void common(HttpServletRequest req, HttpServletResponse resp, boolean isput)
198         throws ServletException, IOException {
199         if (down(resp)) {
200             return;
201         }
202         if (!req.isSecure()) {
203             logger.info(
204                 "NODE0104 Rejecting insecure PUT or DELETE of " + req.getPathInfo() + " from " + req.getRemoteAddr());
205             resp.sendError(HttpServletResponse.SC_FORBIDDEN, "https required on publish requests");
206             return;
207         }
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
211                 .getRemoteAddr());
212             resp.sendError(HttpServletResponse.SC_NOT_FOUND,
213                 "Invalid request URI.  Expecting <feed-publishing-url>/<fileid>.");
214             return;
215         }
216         String feedid = null;
217         String user = 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
221                 .getRemoteAddr());
222             resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Authorization header required");
223             return;
224         }
225         String ip = req.getRemoteAddr();
226         String lip = req.getLocalAddr();
227         String pubid = null;
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
236                     .getRemoteAddr());
237                 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
238                     "Invalid request URI.  Expecting <feed-publishing-url>/<fileid>.  Possible missing fileid.");
239                 return;
240             }
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);
250                 return;
251             }
252             fileid = fileid.substring(18);
253             pubid = req.getHeader("X-ATT-DR-PUBLISH-ID");
254             targets = config.parseRouting(req.getHeader("X-ATT-DR-ROUTING"));
255         } else {
256             logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
257                 .getRemoteAddr());
258             resp.sendError(HttpServletResponse.SC_NOT_FOUND,
259                 "Invalid request URI.  Expecting <feed-publishing-url>/<fileid>.");
260             return;
261         }
262         if (fileid.indexOf('/') != -1) {
263             logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
264                 .getRemoteAddr());
265             resp.sendError(HttpServletResponse.SC_NOT_FOUND,
266                 "Invalid request URI.  Expecting <feed-publishing-url>/<fileid>.");
267             return;
268         }
269         String qs = req.getQueryString();
270         if (qs != null) {
271             fileid = fileid + "?" + qs;
272         }
273         String hp = config.getMyName();
274         int xp = config.getExtHttpsPort();
275         if (xp != 443) {
276             hp = hp + ":" + xp;
277         }
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) {
283                 logger.info(
284                     "NODE0111 Rejecting unauthorized publish attempt to feed " + feedid + " fileid " + fileid + " from "
285                         + ip + " reason " + reason);
286                 resp.sendError(HttpServletResponse.SC_FORBIDDEN, reason);
287                 return;
288             }
289             user = config.getAuthUser(feedid, credentials);
290             String newnode = config.getIngressNode(feedid, user, ip);
291             if (newnode != null) {
292                 String port = "";
293                 int iport = config.getExtHttpsPort();
294                 if (iport != 443) {
295                     port = ":" + iport;
296                 }
297                 String redirto = "https://" + newnode + port + "/publish/" + feedid + "/" + fileid;
298                 logger.info(
299                     "NODE0108 Redirecting publish attempt for feed " + feedid + " user " + user + " ip " + ip + " to "
300                         + redirto);
301                 resp.sendRedirect(redirto);
302                 return;
303             }
304             resp.setHeader("X-ATT-DR-PUBLISH-ID", pubid);
305         }
306         String fbase = config.getSpoolDir() + "/" + pubid;
307         File data = new File(fbase);
308         File meta = new File(fbase + ".M");
309         OutputStream dos = null;
310         Writer mw = null;
311         InputStream is = null;
312         try {
313             StringBuffer mx = new StringBuffer();
314             mx.append(req.getMethod()).append('\t').append(fileid).append('\n');
315             Enumeration hnames = req.getHeaderNames();
316             String ctype = null;
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)) {
331                             ctype = hv;
332                         }
333                         if ("x-att-dr-meta".equals(hnlc)) {
334                             if (hv.length() > 4096) {
335                                 logger.info(
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");
339                                 return;
340                             }
341                             if (!MetaDataPattern.matcher(hv.replaceAll("\\\\.", "X")).matches()) {
342                                 logger.info(
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");
346                                 return;
347                             }
348                         }
349                         mx.append(hn).append('\t').append(hv).append('\n');
350                     }
351                 }
352             }
353             mx.append("X-ATT-DR-RECEIVED\t").append(rcvd).append('\n');
354             String metadata = mx.toString();
355             byte[] buf = new byte[1024 * 1024];
356             int i;
357             try {
358                 is = req.getInputStream();
359                 dos = new FileOutputStream(data);
360                 while ((i = is.read(buf)) > 0) {
361                     dos.write(buf, 0, i);
362                 }
363                 is.close();
364                 is = null;
365                 dos.close();
366                 dos = null;
367             } catch (IOException ioe) {
368                 long exlen = -1;
369                 try {
370                     exlen = Long.parseLong(req.getHeader("Content-Length"));
371                 } catch (Exception e) {
372                 }
373                 StatusLog.logPubFail(pubid, feedid, logurl, req.getMethod(), ctype, exlen, data.length(), ip, user,
374                     ioe.getMessage());
375                 throw ioe;
376             }
377             Path dpath = Paths.get(fbase);
378             for (Target t : targets) {
379                 DestInfo di = t.getDestInfo();
380                 if (di == null) {
381                     // TODO: unknown destination
382                     continue;
383                 }
384                 String dbase = di.getSpool() + "/" + pubid;
385                 Files.createLink(Paths.get(dbase), dpath);
386                 mw = new FileWriter(meta);
387                 mw.write(metadata);
388                 if (di.getSubId() == null) {
389                     mw.write("X-ATT-DR-ROUTING\t" + t.getRouting() + "\n");
390                 }
391                 mw.close();
392                 meta.renameTo(new File(dbase + ".M"));
393             }
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) {
399             logger.info(
400                 "NODE0110 IO Exception receiving publish attempt for feed " + feedid + " user " + user + " ip " + ip
401                     + " " + ioe.toString(), ioe);
402             throw ioe;
403         } finally {
404             if (is != null) {
405                 try {
406                     is.close();
407                 } catch (Exception e) {
408                 }
409             }
410             if (dos != null) {
411                 try {
412                     dos.close();
413                 } catch (Exception e) {
414                 }
415             }
416             if (mw != null) {
417                 try {
418                     mw.close();
419                 } catch (Exception e) {
420                 }
421             }
422             try {
423                 data.delete();
424             } catch (Exception e) {
425             }
426             try {
427                 meta.delete();
428             } catch (Exception e) {
429             }
430         }
431     }
432
433     private int getIdFromPath(HttpServletRequest req) {
434         String path = req.getPathInfo();
435         if (path == null || path.length() < 2) {
436             return -1;
437         }
438         try {
439             return Integer.parseInt(path.substring(1));
440         } catch (NumberFormatException e) {
441             return -1;
442         }
443     }
444 }