Merge "Unit test base"
[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 javax.servlet.*;
28 import javax.servlet.http.*;
29 import java.util.*;
30 import java.util.regex.*;
31 import java.io.*;
32 import java.nio.file.*;
33
34 import org.apache.log4j.Logger;
35 import org.onap.dmaap.datarouter.node.eelf.EelfMsgs;
36
37 import com.att.eelf.configuration.EELFLogger;
38 import com.att.eelf.configuration.EELFManager;
39
40 import java.net.*;
41
42 /**
43  * Servlet for handling all http and https requests to the data router node
44  * <p>
45  * Handled requests are:
46  * <br>
47  * GET http://<i>node</i>/internal/fetchProv - fetch the provisioning data
48  * <br>
49  * PUT/DELETE https://<i>node</i>/internal/publish/<i>fileid</i> - n2n transfer
50  * <br>
51  * PUT/DELETE https://<i>node</i>/publish/<i>feedid</i>/<i>fileid</i> - publsh request
52  */
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");
60
61     static {
62         try {
63             String ws = "\\s*";
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) {
73         }
74     }
75
76     /**
77      * Get the NodeConfigurationManager
78      */
79     public void init() {
80         config = NodeConfigManager.getInstance();
81         logger.info("NODE0101 Node Servlet Configured");
82     }
83
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");
88             return (true);
89         }
90         return (false);
91     }
92
93     /**
94      * Handle a GET for /internal/fetchProv
95      */
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) + "");
99         if (down(resp)) {
100             return;
101         }
102         String path = req.getPathInfo();
103         String qs = req.getQueryString();
104         String ip = req.getRemoteAddr();
105         if (qs != null) {
106             path = path + "?" + qs;
107         }
108         if ("/internal/fetchProv".equals(path)) {
109             config.gofetch(ip);
110             resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
111             return;
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);
117                 return;
118             }
119         }
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);
127                     return;
128                 }
129                 byte[] buf = new byte[65536];
130                 resp.setContentType("text/plain");
131                 resp.setContentLength((int) fn.length());
132                 resp.setStatus(200);
133                 InputStream is = new FileInputStream(fn);
134                 OutputStream os = resp.getOutputStream();
135                 int i;
136                 while ((i = is.read(buf)) > 0) {
137                     os.write(buf, 0, i);
138                 }
139                 is.close();
140                 return;
141             }
142             if (path.startsWith("/internal/rtt/")) {
143                 String xip = path.substring(14);
144                 long st = System.currentTimeMillis();
145                 String status = " unknown";
146                 try {
147                     Socket s = new Socket(xip, 443);
148                     s.close();
149                     status = " connected";
150                 } catch (Exception e) {
151                     status = " error " + e.toString();
152                 }
153                 long dur = System.currentTimeMillis() - st;
154                 resp.setContentType("text/plain");
155                 resp.setStatus(200);
156                 byte[] buf = (dur + status + "\n").getBytes();
157                 resp.setContentLength(buf.length);
158                 resp.getOutputStream().write(buf);
159                 return;
160             }
161         }
162         logger.info("NODE0103 Rejecting invalid GET of " + path + " from " + ip);
163         resp.sendError(HttpServletResponse.SC_NOT_FOUND);
164         return;
165     }
166
167     /**
168      * Handle all PUT requests
169      */
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);
174     }
175
176     /**
177      * Handle all DELETE requests
178      */
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);
183     }
184
185     private void common(HttpServletRequest req, HttpServletResponse resp, boolean isput) throws ServletException, IOException {
186         if (down(resp)) {
187             return;
188         }
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");
192             return;
193         }
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>.");
198             return;
199         }
200         String feedid = null;
201         String user = 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");
206             return;
207         }
208         String ip = req.getRemoteAddr();
209         String lip = req.getLocalAddr();
210         String pubid = null;
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.");
220                 return;
221             }
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);
231                 return;
232             }
233             fileid = fileid.substring(18);
234             pubid = req.getHeader("X-ATT-DR-PUBLISH-ID");
235             targets = config.parseRouting(req.getHeader("X-ATT-DR-ROUTING"));
236         } else {
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>.");
239             return;
240         }
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>.");
244             return;
245         }
246         String qs = req.getQueryString();
247         if (qs != null) {
248             fileid = fileid + "?" + qs;
249         }
250         String hp = config.getMyName();
251         int xp = config.getExtHttpsPort();
252         if (xp != 443) {
253             hp = hp + ":" + xp;
254         }
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);
262                 return;
263             }
264             user = config.getAuthUser(feedid, credentials);
265             String newnode = config.getIngressNode(feedid, user, ip);
266             if (newnode != null) {
267                 String port = "";
268                 int iport = config.getExtHttpsPort();
269                 if (iport != 443) {
270                     port = ":" + iport;
271                 }
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);
275                 return;
276             }
277             resp.setHeader("X-ATT-DR-PUBLISH-ID", pubid);
278         }
279         String fbase = config.getSpoolDir() + "/" + pubid;
280         File data = new File(fbase);
281         File meta = new File(fbase + ".M");
282         OutputStream dos = null;
283         Writer mw = null;
284         InputStream is = null;
285         try {
286             StringBuffer mx = new StringBuffer();
287             mx.append(req.getMethod()).append('\t').append(fileid).append('\n');
288             Enumeration hnames = req.getHeaderNames();
289             String ctype = null;
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)) {
304                             ctype = hv;
305                         }
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");
310                                 return;
311                             }
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");
315                                 return;
316                             }
317                         }
318                         mx.append(hn).append('\t').append(hv).append('\n');
319                     }
320                 }
321             }
322             mx.append("X-ATT-DR-RECEIVED\t").append(rcvd).append('\n');
323             String metadata = mx.toString();
324             byte[] buf = new byte[1024 * 1024];
325             int i;
326             try {
327                 is = req.getInputStream();
328                 dos = new FileOutputStream(data);
329                 while ((i = is.read(buf)) > 0) {
330                     dos.write(buf, 0, i);
331                 }
332                 is.close();
333                 is = null;
334                 dos.close();
335                 dos = null;
336             } catch (IOException ioe) {
337                 long exlen = -1;
338                 try {
339                     exlen = Long.parseLong(req.getHeader("Content-Length"));
340                 } catch (Exception e) {
341                 }
342                 StatusLog.logPubFail(pubid, feedid, logurl, req.getMethod(), ctype, exlen, data.length(), ip, user, ioe.getMessage());
343                 throw ioe;
344             }
345             Path dpath = Paths.get(fbase);
346             for (Target t : targets) {
347                 DestInfo di = t.getDestInfo();
348                 if (di == null) {
349                     // TODO: unknown destination
350                     continue;
351                 }
352                 String dbase = di.getSpool() + "/" + pubid;
353                 Files.createLink(Paths.get(dbase), dpath);
354                 mw = new FileWriter(meta);
355                 mw.write(metadata);
356                 if (di.getSubId() == null) {
357                     mw.write("X-ATT-DR-ROUTING\t" + t.getRouting() + "\n");
358                 }
359                 mw.close();
360                 meta.renameTo(new File(dbase + ".M"));
361             }
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);
367             throw ioe;
368         } finally {
369             if (is != null) {
370                 try {
371                     is.close();
372                 } catch (Exception e) {
373                 }
374             }
375             if (dos != null) {
376                 try {
377                     dos.close();
378                 } catch (Exception e) {
379                 }
380             }
381             if (mw != null) {
382                 try {
383                     mw.close();
384                 } catch (Exception e) {
385                 }
386             }
387             try {
388                 data.delete();
389             } catch (Exception e) {
390             }
391             try {
392                 meta.delete();
393             } catch (Exception e) {
394             }
395         }
396     }
397
398     private int getIdFromPath(HttpServletRequest req) {
399         String path = req.getPathInfo();
400         if (path == null || path.length() < 2)
401             return -1;
402         try {
403             return Integer.parseInt(path.substring(1));
404         } catch (NumberFormatException e) {
405             return -1;
406         }
407     }
408 }