[DMAAP-DR] Remove AAF/TLS phase 1
[dmaap/datarouter.git] / datarouter-subscriber / src / main / java / org / onap / dmaap / datarouter / subscriber / SampleSubscriberServlet.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 package org.onap.dmaap.datarouter.subscriber;
25
26 import jakarta.servlet.http.HttpServlet;
27 import jakarta.servlet.http.HttpServletRequest;
28 import jakarta.servlet.http.HttpServletResponse;
29 import java.io.File;
30 import java.io.FileOutputStream;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.io.OutputStream;
34 import java.io.PrintWriter;
35 import java.net.URLEncoder;
36 import java.nio.charset.StandardCharsets;
37 import java.nio.file.Files;
38 import java.nio.file.Paths;
39 import java.nio.file.StandardCopyOption;
40 import org.apache.commons.codec.binary.Base64;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 public class SampleSubscriberServlet extends HttpServlet {
45
46     private final Logger logger = LoggerFactory.getLogger(SampleSubscriberServlet.class);
47
48     private static String outputDirectory;
49     private static String basicAuth;
50
51     /**
52      * Configure the SampleSubscriberServlet.
53      *
54      * <ul>
55      * <li>Login - The login expected in the Authorization header (default "LOGIN").
56      * <li>Password - The password expected in the Authorization header (default "PASSWORD").
57      * <li>outputDirectory - The directory where files are placed (default
58      * "/opt/app/subscriber/delivery").
59      * </ul>
60      */
61     @Override
62     public void init() {
63         SubscriberProps props = SubscriberProps.getInstance();
64         String login = props.getValue("org.onap.dmaap.datarouter.subscriber.auth.user", "LOGIN");
65         String password = props.getValue("org.onap.dmaap.datarouter.subscriber.auth.password", "PASSWORD");
66         outputDirectory =
67                 props.getValue("org.onap.dmaap.datarouter.subscriber.delivery.dir", "/opt/app/subscriber/delivery");
68         try {
69             Files.createDirectory(Paths.get(outputDirectory));
70         } catch (IOException e) {
71             logger.error("SubServlet: Failed to create delivery dir: " + e.getMessage(), e);
72         }
73         basicAuth = "Basic " + Base64.encodeBase64String((login + ":" + password).getBytes());
74     }
75
76     @Override
77     protected void doPut(HttpServletRequest req, HttpServletResponse resp) {
78         try {
79             common(req, resp, false);
80         } catch (IOException e) {
81             logger.error("SampleSubServlet: Failed to doPut: " + req.getRemoteAddr() + " : " + req.getPathInfo(), e);
82         }
83     }
84
85     @Override
86     protected void doDelete(HttpServletRequest req, HttpServletResponse resp) {
87         try {
88             common(req, resp, true);
89         } catch (IOException e) {
90             logger.error("SampleSubServlet: Failed to doDelete: " + req.getRemoteAddr() + " : " + req.getPathInfo(), e);
91         }
92     }
93
94     /**
95      * Process a PUT or DELETE request.
96      *
97      * <ol>
98      * <li>Verify that the request contains an Authorization header or else UNAUTHORIZED.
99      * <li>Verify that the Authorization header matches the configured Login and Password or else
100      * FORBIDDEN.
101      * <li>If the request is PUT, store the message body as a file in the configured outputDirectory
102      * directory protecting against evil characters in the received FileID. The file is created
103      * initially with its name prefixed with a ".", and once it is complete, it is renamed to
104      * remove the leading "." character.
105      * <li>If the request is DELETE, instead delete the file (if it exists) from the configured
106      * outputDirectory directory.
107      * <li>Respond with NO_CONTENT.
108      * </ol>
109      */
110     private void common(HttpServletRequest req, HttpServletResponse resp, boolean isdelete) throws IOException {
111         String authHeader = req.getHeader("Authorization");
112         if (authHeader == null) {
113             logger.info("SampleSubServlet: Rejecting request with no Authorization header from " + req.getRemoteAddr()
114                                 + ": " + req.getPathInfo());
115             resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
116             return;
117         }
118         if (!basicAuth.equals(authHeader)) {
119             logger.error("SampleSubServlet: Rejecting request with incorrect Authorization header from "
120                                 + req.getRemoteAddr() + ": " + req.getPathInfo());
121             resp.sendError(HttpServletResponse.SC_FORBIDDEN);
122             return;
123         }
124         String fileid = req.getPathInfo();
125         fileid = fileid.substring(fileid.lastIndexOf('/') + 1);
126         String queryString = req.getQueryString();
127         if (queryString != null) {
128             fileid = fileid + "?" + queryString;
129         }
130         String publishid = req.getHeader("X-DMAAP-DR-PUBLISH-ID");
131         String filename = URLEncoder.encode(fileid, StandardCharsets.UTF_8).replaceAll("^\\.", "%2E").replaceAll("\\*", "%2A");
132         String fullPath = outputDirectory + "/" + filename;
133         String tmpPath = outputDirectory + "/." + filename;
134         String fullMetaDataPath = outputDirectory + "/" + filename + ".M";
135         String tmpMetaDataPath = outputDirectory + "/." + filename + ".M";
136         try {
137             if (isdelete) {
138                 Files.deleteIfExists(Paths.get(fullPath));
139                 Files.deleteIfExists(Paths.get(fullMetaDataPath));
140                 logger.info("SampleSubServlet: Received delete for file id " + fileid + " from " + req.getRemoteAddr()
141                                     + " publish id " + publishid + " as " + fullPath);
142             } else {
143                 new File(tmpPath).createNewFile();
144                 new File(tmpMetaDataPath).createNewFile();
145                 try (InputStream is = req.getInputStream(); OutputStream os = new FileOutputStream(tmpPath)) {
146                     byte[] buf = new byte[65536];
147                     int bufferSize;
148                     while ((bufferSize = is.read(buf)) > 0) {
149                         os.write(buf, 0, bufferSize);
150                     }
151                 }
152                 Files.move(Paths.get(tmpPath), Paths.get(fullPath), StandardCopyOption.REPLACE_EXISTING);
153                 try (PrintWriter writer = new PrintWriter(new FileOutputStream(tmpMetaDataPath))) {
154                     String metaData = req.getHeader("X-DMAAP-DR-META");
155                     writer.print(metaData);
156                 }
157                 Files.move(Paths.get(tmpMetaDataPath), Paths.get(fullMetaDataPath),
158                         StandardCopyOption.REPLACE_EXISTING);
159                 logger.info(
160                         "SampleSubServlet: Received file id " + fileid + " from " + req.getRemoteAddr() + " publish id "
161                                 + publishid + " as " + fullPath);
162                 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
163             }
164             resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
165         } catch (IOException ioe) {
166             Files.deleteIfExists(Paths.get(tmpPath));
167             Files.deleteIfExists(Paths.get(tmpMetaDataPath));
168             logger.error("SampleSubServlet: Failed to process file " + fullPath + " from " + req.getRemoteAddr() + ": "
169                                 + req.getPathInfo());
170             throw ioe;
171         }
172     }
173 }