Merge "Fix formatting"
[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 static org.onap.dmaap.datarouter.node.NodeUtils.sendResponseError;
28
29 import com.att.eelf.configuration.EELFLogger;
30 import com.att.eelf.configuration.EELFManager;
31 import java.io.File;
32 import java.io.FileOutputStream;
33 import java.io.FileWriter;
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.io.OutputStream;
37 import java.io.Writer;
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     //Adding EELF Logger Rally:US664892
67     private static EELFLogger eelflogger = EELFManager.getInstance()
68             .getLogger("org.onap.dmaap.datarouter.node.NodeServlet");
69
70     static {
71         final String ws = "\\s*";
72         // assume that \\ and \" have been replaced by X
73         final String string = "\"[^\"]*\"";
74         //String string = "\"(?:[^\"\\\\]|\\\\.)*\"";
75         final String number = "[+-]?(?:\\.\\d+|(?:0|[1-9]\\d*)(?:\\.\\d*)?)(?:[eE][+-]?\\d+)?";
76         final String value = "(?:" + string + "|" + number + "|null|true|false)";
77         final String item = string + ws + ":" + ws + value + ws;
78         final String object = ws + "\\{" + ws + "(?:" + item + "(?:" + "," + ws + item + ")*)?\\}" + ws;
79         MetaDataPattern = Pattern.compile(object, Pattern.DOTALL);
80     }
81
82     /**
83      * Get the NodeConfigurationManager
84      */
85     public void init() {
86         config = NodeConfigManager.getInstance();
87         logger.info("NODE0101 Node Servlet Configured");
88     }
89
90     private boolean down(HttpServletResponse resp) throws IOException {
91         if (config.isShutdown() || !config.isConfigured()) {
92             sendResponseError(resp, HttpServletResponse.SC_SERVICE_UNAVAILABLE, logger);
93             logger.info("NODE0102 Rejecting request: Service is being quiesced");
94             return (true);
95         }
96         return (false);
97     }
98
99     /**
100      * Handle a GET for /internal/fetchProv
101      */
102     protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
103         NodeUtils.setIpAndFqdnForEelf("doGet");
104         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-ATT-DR-ON-BEHALF-OF"),
105                 getIdFromPath(req) + "");
106         try {
107             if (down(resp)) {
108                 return;
109             }
110
111         } catch (IOException ioe) {
112             logger.error("IOException" + ioe.getMessage());
113         }
114         String path = req.getPathInfo();
115         String qs = req.getQueryString();
116         String ip = req.getRemoteAddr();
117         if (qs != null) {
118             path = path + "?" + qs;
119         }
120         if ("/internal/fetchProv".equals(path)) {
121             config.gofetch(ip);
122             resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
123             return;
124         } else if (path.startsWith("/internal/resetSubscription/")) {
125             String subid = path.substring(28);
126             if (subid.length() != 0 && subid.indexOf('/') == -1) {
127                 NodeMain.resetQueue(subid, ip);
128                 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
129                 return;
130             }
131         }
132
133         logger.info("NODE0103 Rejecting invalid GET of " + path + " from " + ip);
134         sendResponseError(resp, HttpServletResponse.SC_NOT_FOUND, logger);
135     }
136
137     /**
138      * Handle all PUT requests
139      */
140     protected void doPut(HttpServletRequest req, HttpServletResponse resp) {
141         NodeUtils.setIpAndFqdnForEelf("doPut");
142         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-ATT-DR-ON-BEHALF-OF"),
143                 getIdFromPath(req) + "");
144         try {
145             common(req, resp, true);
146         } catch (IOException ioe) {
147             logger.error("IOException" + ioe.getMessage());
148         } catch (ServletException se) {
149             logger.error("ServletException" + se.getMessage());
150         }
151     }
152
153     /**
154      * Handle all DELETE requests
155      */
156     protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
157         NodeUtils.setIpAndFqdnForEelf("doDelete");
158         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-ATT-DR-ON-BEHALF-OF"),
159                 getIdFromPath(req) + "");
160         try {
161             common(req, resp, false);
162         } catch (IOException ioe) {
163             logger.error("IOException" + ioe.getMessage());
164         } catch (ServletException se) {
165             logger.error("ServletException" + se.getMessage());
166         }
167     }
168
169     private void common(HttpServletRequest req, HttpServletResponse resp, boolean isput)
170             throws ServletException, IOException {
171         if (down(resp)) {
172             return;
173         }
174         if (!req.isSecure()) {
175             logger.info(
176                     "NODE0104 Rejecting insecure PUT or DELETE of " + req.getPathInfo() + " from " + req
177                             .getRemoteAddr());
178             resp.sendError(HttpServletResponse.SC_FORBIDDEN, "https required on publish requests");
179             return;
180         }
181         String fileid = req.getPathInfo();
182         if (fileid == null) {
183             logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
184                     .getRemoteAddr());
185             resp.sendError(HttpServletResponse.SC_NOT_FOUND,
186                     "Invalid request URI.  Expecting <feed-publishing-url>/<fileid>.");
187             return;
188         }
189         String feedid = null;
190         String user = null;
191         String credentials = req.getHeader("Authorization");
192         if (credentials == null) {
193             logger.info("NODE0106 Rejecting unauthenticated PUT or DELETE of " + req.getPathInfo() + " from " + req
194                     .getRemoteAddr());
195             resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Authorization header required");
196             return;
197         }
198         String ip = req.getRemoteAddr();
199         String lip = req.getLocalAddr();
200         String pubid = null;
201         String xpubid = null;
202         String rcvd = NodeUtils.logts(System.currentTimeMillis()) + ";from=" + ip + ";by=" + lip;
203         Target[] targets = null;
204         if (fileid.startsWith("/publish/")) {
205             fileid = fileid.substring(9);
206             int i = fileid.indexOf('/');
207             if (i == -1 || i == fileid.length() - 1) {
208                 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
209                         .getRemoteAddr());
210                 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
211                         "Invalid request URI.  Expecting <feed-publishing-url>/<fileid>.  Possible missing fileid.");
212                 return;
213             }
214             feedid = fileid.substring(0, i);
215             fileid = fileid.substring(i + 1);
216             pubid = config.getPublishId();
217             xpubid = req.getHeader("X-ATT-DR-PUBLISH-ID");
218             targets = config.getTargets(feedid);
219         } else if (fileid.startsWith("/internal/publish/")) {
220             if (!config.isAnotherNode(credentials, ip)) {
221                 logger.info("NODE0107 Rejecting unauthorized node-to-node transfer attempt from " + ip);
222                 resp.sendError(HttpServletResponse.SC_FORBIDDEN);
223                 return;
224             }
225             fileid = fileid.substring(18);
226             pubid = req.getHeader("X-ATT-DR-PUBLISH-ID");
227             targets = config.parseRouting(req.getHeader("X-ATT-DR-ROUTING"));
228         } else {
229             logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
230                     .getRemoteAddr());
231             resp.sendError(HttpServletResponse.SC_NOT_FOUND,
232                     "Invalid request URI.  Expecting <feed-publishing-url>/<fileid>.");
233             return;
234         }
235         if (fileid.indexOf('/') != -1) {
236             logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
237                     .getRemoteAddr());
238             resp.sendError(HttpServletResponse.SC_NOT_FOUND,
239                     "Invalid request URI.  Expecting <feed-publishing-url>/<fileid>.");
240             return;
241         }
242         String qs = req.getQueryString();
243         if (qs != null) {
244             fileid = fileid + "?" + qs;
245         }
246         String hp = config.getMyName();
247         int xp = config.getExtHttpsPort();
248         if (xp != 443) {
249             hp = hp + ":" + xp;
250         }
251         String logurl = "https://" + hp + "/internal/publish/" + fileid;
252         if (feedid != null) {
253             logurl = "https://" + hp + "/publish/" + feedid + "/" + fileid;
254             String reason = config.isPublishPermitted(feedid, credentials, ip);
255             if (reason != null) {
256                 logger.info(
257                         "NODE0111 Rejecting unauthorized publish attempt to feed " + feedid + " fileid " + fileid
258                                 + " from "
259                                 + ip + " reason " + reason);
260                 resp.sendError(HttpServletResponse.SC_FORBIDDEN, reason);
261                 return;
262             }
263             user = config.getAuthUser(feedid, credentials);
264             String newnode = config.getIngressNode(feedid, user, ip);
265             if (newnode != null) {
266                 String port = "";
267                 int iport = config.getExtHttpsPort();
268                 if (iport != 443) {
269                     port = ":" + iport;
270                 }
271                 String redirto = "https://" + newnode + port + "/publish/" + feedid + "/" + fileid;
272                 logger.info(
273                         "NODE0108 Redirecting publish attempt for feed " + feedid + " user " + user + " ip " + ip
274                                 + " to "
275                                 + redirto);
276                 resp.sendRedirect(redirto);
277                 return;
278             }
279             resp.setHeader("X-ATT-DR-PUBLISH-ID", pubid);
280         }
281         String fbase = config.getSpoolDir() + "/" + pubid;
282         File data = new File(fbase);
283         File meta = new File(fbase + ".M");
284         OutputStream dos = null;
285         InputStream is = null;
286         try (Writer mw = new FileWriter(meta)) {
287             StringBuffer mx = new StringBuffer();
288             mx.append(req.getMethod()).append('\t').append(fileid).append('\n');
289             Enumeration hnames = req.getHeaderNames();
290             String ctype = null;
291             while (hnames.hasMoreElements()) {
292                 String hn = (String) hnames.nextElement();
293                 String hnlc = hn.toLowerCase();
294                 if ((isput && ("content-type".equals(hnlc) ||
295                         "content-language".equals(hnlc) ||
296                         "content-md5".equals(hnlc) ||
297                         "content-range".equals(hnlc))) ||
298                         "x-att-dr-meta".equals(hnlc) ||
299                         (feedid == null && "x-att-dr-received".equals(hnlc)) ||
300                         (hnlc.startsWith("x-") && !hnlc.startsWith("x-att-dr-"))) {
301                     Enumeration hvals = req.getHeaders(hn);
302                     while (hvals.hasMoreElements()) {
303                         String hv = (String) hvals.nextElement();
304                         if ("content-type".equals(hnlc)) {
305                             ctype = hv;
306                         }
307                         if ("x-att-dr-meta".equals(hnlc)) {
308                             if (hv.length() > 4096) {
309                                 logger.info(
310                                         "NODE0109 Rejecting publish attempt with metadata too long for feed " + feedid
311                                                 + " user " + user + " ip " + ip);
312                                 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Metadata too long");
313                                 return;
314                             }
315                             if (!MetaDataPattern.matcher(hv.replaceAll("\\\\.", "X")).matches()) {
316                                 logger.info(
317                                         "NODE0109 Rejecting publish attempt with malformed metadata for feed " + feedid
318                                                 + " user " + user + " ip " + ip);
319                                 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Malformed metadata");
320                                 return;
321                             }
322                         }
323                         mx.append(hn).append('\t').append(hv).append('\n');
324                     }
325                 }
326             }
327             mx.append("X-ATT-DR-RECEIVED\t").append(rcvd).append('\n');
328             String metadata = mx.toString();
329             byte[] buf = new byte[1024 * 1024];
330             int i;
331             try {
332                 is = req.getInputStream();
333                 dos = new FileOutputStream(data);
334                 while ((i = is.read(buf)) > 0) {
335                     dos.write(buf, 0, i);
336                 }
337                 is.close();
338                 is = null;
339                 dos.close();
340                 dos = null;
341             } catch (IOException ioe) {
342                 long exlen = -1;
343                 try {
344                     exlen = Long.parseLong(req.getHeader("Content-Length"));
345                 } catch (Exception e) {
346                 }
347                 StatusLog.logPubFail(pubid, feedid, logurl, req.getMethod(), ctype, exlen, data.length(), ip, user,
348                         ioe.getMessage());
349                 throw ioe;
350             }
351             Path dpath = Paths.get(fbase);
352             for (Target t : targets) {
353                 DestInfo di = t.getDestInfo();
354                 if (di == null) {
355                     // TODO: unknown destination
356                     continue;
357                 }
358                 String dbase = di.getSpool() + "/" + pubid;
359                 Files.createLink(Paths.get(dbase), dpath);
360                 mw.write(metadata);
361                 if (di.getSubId() == null) {
362                     mw.write("X-ATT-DR-ROUTING\t" + t.getRouting() + "\n");
363                 }
364                 meta.renameTo(new File(dbase + ".M"));
365             }
366             resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
367             resp.getOutputStream().close();
368             StatusLog.logPub(pubid, feedid, logurl, req.getMethod(), ctype, data.length(), ip, user,
369                     HttpServletResponse.SC_NO_CONTENT);
370         } catch (IOException ioe) {
371             logger.info(
372                     "NODE0110 IO Exception receiving publish attempt for feed " + feedid + " user " + user + " ip " + ip
373                             + " " + ioe.toString(), ioe);
374             throw ioe;
375         } finally {
376             if (is != null) {
377                 try {
378                     is.close();
379                 } catch (Exception e) {
380                 }
381             }
382             if (dos != null) {
383                 try {
384                     dos.close();
385                 } catch (Exception e) {
386                 }
387             }
388             try {
389                 data.delete();
390             } catch (Exception e) {
391             }
392             try {
393                 meta.delete();
394             } catch (Exception e) {
395             }
396         }
397     }
398
399     private int getIdFromPath(HttpServletRequest req) {
400         String path = req.getPathInfo();
401         if (path == null || path.length() < 2) {
402             return -1;
403         }
404         try {
405             return Integer.parseInt(path.substring(1));
406         } catch (NumberFormatException e) {
407             return -1;
408         }
409     }
410 }