Replace ATT headers
[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 import org.slf4j.MDC;
50
51 /**
52  * Servlet for handling all http and https requests to the data router node
53  * <p>
54  * Handled requests are:
55  * <br>
56  * GET http://<i>node</i>/internal/fetchProv - fetch the provisioning data
57  * <br>
58  * PUT/DELETE https://<i>node</i>/internal/publish/<i>fileid</i> - n2n transfer
59  * <br>
60  * PUT/DELETE https://<i>node</i>/publish/<i>feedid</i>/<i>fileid</i> - publsh request
61  */
62 public class NodeServlet extends HttpServlet {
63
64     private static Logger logger = Logger.getLogger("org.onap.dmaap.datarouter.node.NodeServlet");
65     private static NodeConfigManager config;
66     private static Pattern MetaDataPattern;
67     //Adding EELF Logger Rally:US664892
68     private static EELFLogger eelflogger = EELFManager.getInstance()
69             .getLogger(NodeServlet.class);
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             sendResponseError(resp, HttpServletResponse.SC_SERVICE_UNAVAILABLE, logger);
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) {
104         NodeUtils.setIpAndFqdnForEelf("doGet");
105         NodeUtils.setRequestIdAndInvocationId(req);
106         eelflogger.info(EelfMsgs.ENTRY);
107         try {
108             eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-DMAAP-DR-ON-BEHALF-OF"),
109                     getIdFromPath(req) + "");
110             try {
111                 if (down(resp)) {
112                     return;
113                 }
114
115             } catch (IOException ioe) {
116                 logger.error("IOException" + ioe.getMessage());
117             }
118             String path = req.getPathInfo();
119             String qs = req.getQueryString();
120             String ip = req.getRemoteAddr();
121             if (qs != null) {
122                 path = path + "?" + qs;
123             }
124             if ("/internal/fetchProv".equals(path)) {
125                 config.gofetch(ip);
126                 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
127                 return;
128             } else if (path.startsWith("/internal/resetSubscription/")) {
129                 String subid = path.substring(28);
130                 if (subid.length() != 0 && subid.indexOf('/') == -1) {
131                     NodeMain.resetQueue(subid, ip);
132                     resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
133                     return;
134                 }
135             }
136
137             logger.info("NODE0103 Rejecting invalid GET of " + path + " from " + ip);
138             sendResponseError(resp, HttpServletResponse.SC_NOT_FOUND, logger);
139         } finally {
140             eelflogger.info(EelfMsgs.EXIT);
141         }
142     }
143
144     /**
145      * Handle all PUT requests
146      */
147     protected void doPut(HttpServletRequest req, HttpServletResponse resp) {
148         NodeUtils.setIpAndFqdnForEelf("doPut");
149         NodeUtils.setRequestIdAndInvocationId(req);
150         eelflogger.info(EelfMsgs.ENTRY);
151         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-DMAAP-DR-ON-BEHALF-OF"),
152                     getIdFromPath(req) + "");
153         try {
154             common(req, resp, true);
155         } catch (IOException ioe) {
156             logger.error("IOException" + ioe.getMessage());
157             eelflogger.info(EelfMsgs.EXIT);
158         } catch (ServletException se) {
159             logger.error("ServletException" + se.getMessage());
160             eelflogger.info(EelfMsgs.EXIT);
161         }
162     }
163
164     /**
165      * Handle all DELETE requests
166      */
167     protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
168         NodeUtils.setIpAndFqdnForEelf("doDelete");
169         NodeUtils.setRequestIdAndInvocationId(req);
170         eelflogger.info(EelfMsgs.ENTRY);
171         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-DMAAP-DR-ON-BEHALF-OF"),
172                 getIdFromPath(req) + "");
173         try {
174             common(req, resp, false);
175         } catch (IOException ioe) {
176             logger.error("IOException" + ioe.getMessage());
177             eelflogger.info(EelfMsgs.EXIT);
178         } catch (ServletException se) {
179             logger.error("ServletException" + se.getMessage());
180             eelflogger.info(EelfMsgs.EXIT);
181         }
182
183     }
184
185     private void common(HttpServletRequest req, HttpServletResponse resp, boolean isput)
186             throws ServletException, IOException {
187         if (down(resp)) {
188             eelflogger.info(EelfMsgs.EXIT);
189             return;
190         }
191         if (!req.isSecure()) {
192             logger.info(
193                     "NODE0104 Rejecting insecure PUT or DELETE of " + req.getPathInfo() + " from " + req
194                             .getRemoteAddr());
195             resp.sendError(HttpServletResponse.SC_FORBIDDEN, "https required on publish requests");
196             eelflogger.info(EelfMsgs.EXIT);
197             return;
198         }
199         String fileid = req.getPathInfo();
200         if (fileid == null) {
201             logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
202                     .getRemoteAddr());
203             resp.sendError(HttpServletResponse.SC_NOT_FOUND,
204                     "Invalid request URI.  Expecting <feed-publishing-url>/<fileid>.");
205             eelflogger.info(EelfMsgs.EXIT);
206             return;
207         }
208         String feedid = null;
209         String user = null;
210         String credentials = req.getHeader("Authorization");
211         if (credentials == null) {
212             logger.info("NODE0106 Rejecting unauthenticated PUT or DELETE of " + req.getPathInfo() + " from " + req
213                     .getRemoteAddr());
214             resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Authorization header required");
215             eelflogger.info(EelfMsgs.EXIT);
216             return;
217         }
218         String ip = req.getRemoteAddr();
219         String lip = req.getLocalAddr();
220         String pubid = null;
221         String xpubid = null;
222         String rcvd = NodeUtils.logts(System.currentTimeMillis()) + ";from=" + ip + ";by=" + lip;
223         Target[] targets = null;
224         if (fileid.startsWith("/publish/")) {
225             fileid = fileid.substring(9);
226             int i = fileid.indexOf('/');
227             if (i == -1 || i == fileid.length() - 1) {
228                 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
229                         .getRemoteAddr());
230                 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
231                         "Invalid request URI.  Expecting <feed-publishing-url>/<fileid>.  Possible missing fileid.");
232                 eelflogger.info(EelfMsgs.EXIT);
233                 return;
234             }
235             feedid = fileid.substring(0, i);
236             fileid = fileid.substring(i + 1);
237             pubid = config.getPublishId();
238             xpubid = req.getHeader("X-DMAAP-DR-PUBLISH-ID");
239             targets = config.getTargets(feedid);
240         } else if (fileid.startsWith("/internal/publish/")) {
241             if (!config.isAnotherNode(credentials, ip)) {
242                 logger.info("NODE0107 Rejecting unauthorized node-to-node transfer attempt from " + ip);
243                 resp.sendError(HttpServletResponse.SC_FORBIDDEN);
244                 eelflogger.info(EelfMsgs.EXIT);
245                 return;
246             }
247             fileid = fileid.substring(18);
248             pubid = req.getHeader("X-DMAAP-DR-PUBLISH-ID");
249             targets = config.parseRouting(req.getHeader("X-DMAAP-DR-ROUTING"));
250         } else {
251             logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
252                     .getRemoteAddr());
253             resp.sendError(HttpServletResponse.SC_NOT_FOUND,
254                     "Invalid request URI.  Expecting <feed-publishing-url>/<fileid>.");
255             eelflogger.info(EelfMsgs.EXIT);
256             return;
257         }
258         if (fileid.indexOf('/') != -1) {
259             logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
260                     .getRemoteAddr());
261             resp.sendError(HttpServletResponse.SC_NOT_FOUND,
262                     "Invalid request URI.  Expecting <feed-publishing-url>/<fileid>.");
263             eelflogger.info(EelfMsgs.EXIT);
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
282                                 + " from "
283                                 + ip + " reason " + reason);
284                 resp.sendError(HttpServletResponse.SC_FORBIDDEN, reason);
285                 eelflogger.info(EelfMsgs.EXIT);
286                 return;
287             }
288             user = config.getAuthUser(feedid, credentials);
289             String newnode = config.getIngressNode(feedid, user, ip);
290             if (newnode != null) {
291                 String port = "";
292                 int iport = config.getExtHttpsPort();
293                 if (iport != 443) {
294                     port = ":" + iport;
295                 }
296                 String redirto = "https://" + newnode + port + "/publish/" + feedid + "/" + fileid;
297                 logger.info(
298                         "NODE0108 Redirecting publish attempt for feed " + feedid + " user " + user + " ip " + ip
299                                 + " to "
300                                 + redirto);
301                 resp.sendRedirect(redirto);
302                 eelflogger.info(EelfMsgs.EXIT);
303                 return;
304             }
305             resp.setHeader("X-DMAAP-DR-PUBLISH-ID", pubid);
306         }
307         String fbase = config.getSpoolDir() + "/" + pubid;
308         File data = new File(fbase);
309         File meta = new File(fbase + ".M");
310         OutputStream dos = null;
311         Writer mw = null;
312         InputStream is = null;
313         try {
314             StringBuffer mx = new StringBuffer();
315             mx.append(req.getMethod()).append('\t').append(fileid).append('\n');
316             Enumeration hnames = req.getHeaderNames();
317             String ctype = null;
318             Boolean hasRequestIdHeader = false;
319             Boolean hasInvocationIdHeader = false;
320             while (hnames.hasMoreElements()) {
321                 String hn = (String) hnames.nextElement();
322                 String hnlc = hn.toLowerCase();
323                 if ((isput && ("content-type".equals(hnlc) ||
324                         "content-language".equals(hnlc) ||
325                         "content-md5".equals(hnlc) ||
326                         "content-range".equals(hnlc))) ||
327                         "x-dmaap-dr-meta".equals(hnlc) ||
328                         (feedid == null && "x-dmaap-dr-received".equals(hnlc)) ||
329                         (hnlc.startsWith("x-") && !hnlc.startsWith("x-dmaap-dr-"))) {
330                     Enumeration hvals = req.getHeaders(hn);
331                     while (hvals.hasMoreElements()) {
332                         String hv = (String) hvals.nextElement();
333                         if ("content-type".equals(hnlc)) {
334                             ctype = hv;
335                         }
336                         if ("x-onap-requestid".equals(hnlc)) {
337                             hasRequestIdHeader = true;
338                         }
339                         if ("x-invocationid".equals(hnlc)) {
340                             hasInvocationIdHeader = true;
341                         }
342                         if ("x-dmaap-dr-meta".equals(hnlc)) {
343                             if (hv.length() > 4096) {
344                                 logger.info(
345                                         "NODE0109 Rejecting publish attempt with metadata too long for feed " + feedid
346                                                 + " user " + user + " ip " + ip);
347                                 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Metadata too long");
348                                 eelflogger.info(EelfMsgs.EXIT);
349                                 return;
350                             }
351                             if (!MetaDataPattern.matcher(hv.replaceAll("\\\\.", "X")).matches()) {
352                                 logger.info(
353                                         "NODE0109 Rejecting publish attempt with malformed metadata for feed " + feedid
354                                                 + " user " + user + " ip " + ip);
355                                 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Malformed metadata");
356                                 eelflogger.info(EelfMsgs.EXIT);
357                                 return;
358                             }
359                         }
360                         mx.append(hn).append('\t').append(hv).append('\n');
361                     }
362                 }
363             }
364             if(!hasRequestIdHeader){
365                 mx.append("X-ONAP-RequestID\t").append(MDC.get("RequestId")).append('\n');
366             }
367             if(!hasInvocationIdHeader){
368                 mx.append("X-InvocationID\t").append(MDC.get("InvocationId")).append('\n');
369             }
370             mx.append("X-DMAAP-DR-RECEIVED\t").append(rcvd).append('\n');
371             String metadata = mx.toString();
372             byte[] buf = new byte[1024 * 1024];
373             int i;
374             try {
375                 is = req.getInputStream();
376                 dos = new FileOutputStream(data);
377                 while ((i = is.read(buf)) > 0) {
378                     dos.write(buf, 0, i);
379                 }
380                 is.close();
381                 is = null;
382                 dos.close();
383                 dos = null;
384             } catch (IOException ioe) {
385                 long exlen = -1;
386                 try {
387                     exlen = Long.parseLong(req.getHeader("Content-Length"));
388                 } catch (Exception e) {
389                 }
390                 StatusLog.logPubFail(pubid, feedid, logurl, req.getMethod(), ctype, exlen, data.length(), ip, user,
391                         ioe.getMessage());
392                 eelflogger.info(EelfMsgs.EXIT);
393                 throw ioe;
394             }
395             Path dpath = Paths.get(fbase);
396             for (Target t : targets) {
397                 DestInfo di = t.getDestInfo();
398                 if (di == null) {
399                     // TODO: unknown destination
400                     continue;
401                 }
402                 String dbase = di.getSpool() + "/" + pubid;
403                 Files.createLink(Paths.get(dbase), dpath);
404                 mw = new FileWriter(meta);
405                 mw.write(metadata);
406                 if (di.getSubId() == null) {
407                     mw.write("X-DMAAP-DR-ROUTING\t" + t.getRouting() + "\n");
408                 }
409                 mw.close();
410                 meta.renameTo(new File(dbase + ".M"));
411             }
412             resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
413             resp.getOutputStream().close();
414             StatusLog.logPub(pubid, feedid, logurl, req.getMethod(), ctype, data.length(), ip, user,
415                     HttpServletResponse.SC_NO_CONTENT);
416         } catch (IOException ioe) {
417             logger.info(
418                     "NODE0110 IO Exception receiving publish attempt for feed " + feedid + " user " + user + " ip " + ip
419                             + " " + ioe.toString(), ioe);
420             eelflogger.info(EelfMsgs.EXIT);
421             throw ioe;
422         } finally {
423             if (is != null) {
424                 try {
425                     is.close();
426                 } catch (Exception e) {
427                 }
428             }
429             if (dos != null) {
430                 try {
431                     dos.close();
432                 } catch (Exception e) {
433                 }
434             }
435             if (mw != null) {
436                 try {
437                     mw.close();
438                 } catch (Exception e) {
439                 }
440             }
441             try {
442                 data.delete();
443             } catch (Exception e) {
444             }
445             try {
446                 meta.delete();
447             } catch (Exception e) {
448             }
449         }
450     }
451
452     private int getIdFromPath(HttpServletRequest req) {
453         String path = req.getPathInfo();
454         if (path == null || path.length() < 2) {
455             return -1;
456         }
457         try {
458             return Integer.parseInt(path.substring(1));
459         } catch (NumberFormatException e) {
460             return -1;
461         }
462     }
463 }