1 /*******************************************************************************
2 * ============LICENSE_START==================================================
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
11 * * http://www.apache.org/licenses/LICENSE-2.0
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====================================================
20 * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 ******************************************************************************/
24 package org.onap.dmaap.datarouter.subscriber;
26 import org.apache.commons.codec.binary.Base64;
27 import org.apache.log4j.Logger;
29 import javax.servlet.ServletConfig;
30 import javax.servlet.http.HttpServlet;
31 import javax.servlet.http.HttpServletRequest;
32 import javax.servlet.http.HttpServletResponse;
34 import java.net.URLEncoder;
35 import java.nio.file.Files;
36 import java.nio.file.Paths;
37 import java.nio.file.StandardCopyOption;
38 import java.nio.file.attribute.PosixFilePermissions;
40 import static org.onap.dmaap.datarouter.subscriber.Subscriber.props;
42 public class SubscriberServlet extends HttpServlet {
44 private static Logger logger = Logger.getLogger("org.onap.dmaap.datarouter.subscriber.SubscriberServlet");
45 private String outputDirectory;
46 private String basicAuth;
49 * Configure this subscriberservlet. Configuration parameters from config.getInitParameter() are:
51 * <li>Login - The login expected in the Authorization header (default "LOGIN").
52 * <li>Password - The password expected in the Authorization header (default "PASSWORD").
53 * <li>outputDirectory - The directory where files are placed (default "tmp").
57 public void init(ServletConfig config) {
58 String login = props.getProperty("org.onap.dmaap.datarouter.subscriber.auth.user", "LOGIN");
59 String password = props.getProperty("org.onap.dmaap.datarouter.subscriber.auth.password", "PASSWORD");
60 outputDirectory = props.getProperty("org.onap.dmaap.datarouter.subscriber.delivery.dir", "/tmp");
62 Files.createDirectory(Paths.get(outputDirectory), PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxrwxrwx")));
63 } catch (IOException e) {
64 logger.info("SubServlet: Failed to create delivery dir: " + e.getMessage());
67 basicAuth = "Basic " + Base64.encodeBase64String((login + ":" + password).getBytes());
71 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
72 File filesPath = new File(outputDirectory);
73 File[] filesArr = filesPath.listFiles();
74 assert filesArr != null;
75 for (File file: filesArr) {
76 try (BufferedReader in = new BufferedReader(new FileReader(file))) {
77 String line = in.readLine();
78 while (line != null) {
85 * Invoke common(req, resp, false).
88 protected void doPut(HttpServletRequest req, HttpServletResponse resp) {
90 common(req, resp, false);
91 } catch (IOException e) {
92 logger.info("SubServlet: Failed to doPut: " + req.getRemoteAddr() + " : " + req.getPathInfo(), e);
96 * Invoke common(req, resp, true).
99 protected void doDelete(HttpServletRequest req, HttpServletResponse resp) {
101 common(req, resp, true);
102 } catch (IOException e) {
103 logger.info("SubServlet: Failed to doDelete: " + req.getRemoteAddr() + " : " + req.getPathInfo(), e);
107 * Process a PUT or DELETE request.
109 * <li>Verify that the request contains an Authorization header
110 * or else UNAUTHORIZED.
111 * <li>Verify that the Authorization header matches the configured
112 * Login and Password or else FORBIDDEN.
113 * <li>If the request is PUT, store the message body as a file
114 * in the configured outputDirectory directory protecting against
115 * evil characters in the received FileID. The file is created
116 * initially with its name prefixed with a ".", and once it is complete, it is
117 * renamed to remove the leading "." character.
118 * <li>If the request is DELETE, instead delete the file (if it exists) from the configured outputDirectory directory.
119 * <li>Respond with NO_CONTENT.
122 private void common(HttpServletRequest req, HttpServletResponse resp, boolean isdelete) throws IOException {
123 String authHeader = req.getHeader("Authorization");
124 if (authHeader == null) {
125 logger.info("Rejecting request with no Authorization header from " + req.getRemoteAddr() + ": " + req.getPathInfo());
126 resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
129 if (!basicAuth.equals(authHeader)) {
130 logger.info("Rejecting request with incorrect Authorization header from " + req.getRemoteAddr() + ": " + req.getPathInfo());
131 resp.sendError(HttpServletResponse.SC_FORBIDDEN);
134 String fileid = req.getPathInfo();
135 fileid = fileid.substring(fileid.lastIndexOf('/') + 1);
136 String queryString = req.getQueryString();
137 if (queryString != null) {
138 fileid = fileid + "?" + queryString;
140 String publishid = req.getHeader("X-ATT-DR-PUBLISH-ID");
141 String filename = URLEncoder.encode(fileid, "UTF-8").replaceAll("^\\.", "%2E").replaceAll("\\*", "%2A");
142 String fullPath = outputDirectory + "/" + filename;
143 String tmpPath = outputDirectory + "/." + filename;
146 Files.deleteIfExists(Paths.get(fullPath));
147 logger.info("Received delete for file id " + fileid + " from " + req.getRemoteAddr() + " publish id " + publishid + " as " + fullPath);
149 new File(tmpPath).createNewFile();
150 try (InputStream is = req.getInputStream(); OutputStream os = new FileOutputStream(tmpPath)) {
151 byte[] buf = new byte[65536];
153 while ((i = is.read(buf)) > 0) {
157 Files.move(Paths.get(tmpPath), Paths.get(fullPath), StandardCopyOption.REPLACE_EXISTING);
158 logger.info("Received file id " + fileid + " from " + req.getRemoteAddr() + " publish id " + publishid + " as " + fullPath);
159 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
161 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
162 } catch (IOException ioe) {
163 Files.deleteIfExists(Paths.get(tmpPath));
164 logger.info("Failed to process file " + fullPath + " from " + req.getRemoteAddr() + ": " + req.getPathInfo());