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 ******************************************************************************/
25 package org.onap.dmaap.datarouter.provisioning;
27 import static org.onap.dmaap.datarouter.provisioning.utils.HttpServletUtils.sendResponseError;
30 import java.io.FileInputStream;
31 import java.io.FileNotFoundException;
32 import java.io.IOException;
33 import java.io.InputStream;
35 import java.security.KeyStore;
36 import java.security.KeyStoreException;
37 import java.util.Collections;
38 import java.util.List;
39 import java.util.Properties;
40 import javax.servlet.ServletConfig;
41 import javax.servlet.ServletException;
42 import javax.servlet.http.HttpServletRequest;
43 import javax.servlet.http.HttpServletResponse;
44 import org.apache.commons.io.IOUtils;
45 import org.apache.http.Header;
46 import org.apache.http.HttpEntity;
47 import org.apache.http.HttpResponse;
48 import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
49 import org.apache.http.client.methods.HttpGet;
50 import org.apache.http.client.methods.HttpRequestBase;
51 import org.apache.http.conn.scheme.Scheme;
52 import org.apache.http.conn.ssl.SSLSocketFactory;
53 import org.apache.http.entity.BasicHttpEntity;
54 import org.apache.http.impl.client.AbstractHttpClient;
55 import org.apache.http.impl.client.DefaultHttpClient;
56 import org.onap.dmaap.datarouter.provisioning.utils.AafPropsUtils;
57 import org.onap.dmaap.datarouter.provisioning.utils.DB;
58 import org.onap.dmaap.datarouter.provisioning.utils.URLUtilities;
61 * This class is the base class for those servlets that need to proxy their requests from the standby to active server.
62 * Its methods perform the proxy function to the active server. If the active server is not reachable, a 503
63 * (SC_SERVICE_UNAVAILABLE) is returned. Only DELETE/GET/PUT/POST are supported.
66 * @version $Id: ProxyServlet.java,v 1.3 2014/03/24 18:47:10 eby Exp $
68 @SuppressWarnings("serial")
70 public class ProxyServlet extends BaseServlet {
72 private boolean inited = false;
76 * Initialize this servlet, by setting up SSL.
78 @SuppressWarnings("deprecation")
80 public void init(ServletConfig config) throws ServletException {
84 String type = AafPropsUtils.KEYSTORE_TYPE_PROPERTY;
85 String store = Main.aafPropsUtils.getKeystorePathProperty();
86 String pass = Main.aafPropsUtils.getKeystorePassProperty();
87 KeyStore keyStore = readStore(store, pass, type);
89 store = Main.aafPropsUtils.getTruststorePathProperty();
90 pass = Main.aafPropsUtils.getTruststorePassProperty();
91 if (store == null || store.length() == 0) {
92 store = AafPropsUtils.DEFAULT_TRUSTSTORE;
95 KeyStore trustStore = readStore(store, pass, AafPropsUtils.TRUESTSTORE_TYPE_PROPERTY);
97 // We are connecting with the node name, but the certificate will have the CNAME
98 // So we need to accept a non-matching certificate name
99 SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore,
100 Main.aafPropsUtils.getKeystorePassProperty(), trustStore);
101 socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
102 sch = new Scheme("https", 443, socketFactory);
104 } catch (Exception e) {
105 intlogger.error("ProxyServlet.init: " + e.getMessage(), e);
107 intlogger.info("ProxyServlet: inited = " + inited);
110 private KeyStore readStore(String store, String pass, String type) throws KeyStoreException {
111 KeyStore ks = KeyStore.getInstance(type);
112 try (FileInputStream instream = new FileInputStream(new File(store))) {
113 ks.load(instream, pass.toCharArray());
114 } catch (FileNotFoundException fileNotFoundException) {
115 intlogger.error("ProxyServlet.readStore: " + fileNotFoundException.getMessage(), fileNotFoundException);
116 } catch (Exception x) {
117 intlogger.error("READING TRUSTSTORE: " + x);
123 * Return <i>true</i> if the requester has NOT set the <i>noproxy</i> CGI variable. If they have, this indicates
124 * they want to forcibly turn the proxy off.
126 * @param req the HTTP request
127 * @return true or false
129 boolean isProxyOK(final HttpServletRequest req) {
130 String str = req.getQueryString();
132 str = str.replaceAll("&", "&");
133 for (String s : str.split("&")) {
134 if ("noproxy".equals(s) || s.startsWith("noproxy=")) {
143 * Is this the standby server? If it is, the proxy functions can be used. If not, the proxy functions should not be
144 * called, and will send a response of 500 (Internal Server Error).
146 * @return true if this server is the standby (and hence a proxy server).
148 boolean isProxyServer() {
149 SynchronizerTask st = SynchronizerTask.getSynchronizer();
150 return st.getPodState() == SynchronizerTask.STANDBY_POD;
154 * Issue a proxy DELETE to the active provisioning server.
157 public void doDelete(HttpServletRequest req, HttpServletResponse resp) {
158 doProxy(req, resp, "DELETE");
162 * Issue a proxy GET to the active provisioning server.
165 public void doGet(HttpServletRequest req, HttpServletResponse resp) {
166 doProxy(req, resp, "GET");
170 * Issue a proxy PUT to the active provisioning server.
173 public void doPut(HttpServletRequest req, HttpServletResponse resp) {
174 doProxy(req, resp, "PUT");
178 * Issue a proxy POST to the active provisioning server.
181 public void doPost(HttpServletRequest req, HttpServletResponse resp) {
182 doProxy(req, resp, "POST");
186 * Issue a proxy GET to the active provisioning server. Unlike doGet() above, this method will allow the caller to
187 * fall back to other code if the remote server is unreachable.
189 * @return true if the proxy succeeded
191 boolean doGetWithFallback(HttpServletRequest req, HttpServletResponse resp) {
194 String url = buildUrl(req);
195 intlogger.info("ProxyServlet: proxying with fallback GET " + url);
196 try (AbstractHttpClient httpclient = new DefaultHttpClient()) {
197 HttpRequestBase proxy = new HttpGet(url);
199 httpclient.getConnectionManager().getSchemeRegistry().register(sch);
201 // Copy request headers and request body
202 copyRequestHeaders(req, proxy);
204 // Execute the request
205 HttpResponse pxyResponse = httpclient.execute(proxy);
207 // Get response headers and body
208 int code = pxyResponse.getStatusLine().getStatusCode();
209 resp.setStatus(code);
210 copyResponseHeaders(pxyResponse, resp);
211 copyEntityContent(pxyResponse, resp);
214 } catch (IOException e) {
215 intlogger.error("ProxyServlet.doGetWithFallback: " + e.getMessage(), e);
217 proxy.releaseConnection();
218 httpclient.getConnectionManager().shutdown();
222 intlogger.warn("ProxyServlet: proxy disabled");
227 private void doProxy(HttpServletRequest req, HttpServletResponse resp, final String method) {
228 if (inited && isProxyServer()) {
229 String url = buildUrl(req);
230 intlogger.info("ProxyServlet: proxying " + method + " " + url);
231 try (AbstractHttpClient httpclient = new DefaultHttpClient()) {
232 ProxyHttpRequest proxy = new ProxyHttpRequest(method, url);
234 httpclient.getConnectionManager().getSchemeRegistry().register(sch);
236 // Copy request headers and request body
237 copyRequestHeaders(req, proxy);
239 handlePutOrPost(req, method, proxy);
241 // Execute the request
242 HttpResponse pxyResponse = httpclient.execute(proxy);
244 // Get response headers and body
245 int code = pxyResponse.getStatusLine().getStatusCode();
246 resp.setStatus(code);
247 copyResponseHeaders(pxyResponse, resp);
248 copyEntityContent(pxyResponse, resp);
249 } catch (IOException e) {
250 intlogger.warn("ProxyServlet.doProxy: " + e.getMessage(), e);
251 sendResponseError(resp, HttpServletResponse.SC_SERVICE_UNAVAILABLE, "", intlogger);
253 proxy.releaseConnection();
254 httpclient.getConnectionManager().shutdown();
258 intlogger.warn("ProxyServlet: proxy disabled");
259 sendResponseError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, DB_PROBLEM_MSG, intlogger);
263 private void handlePutOrPost(HttpServletRequest req, String method, ProxyHttpRequest proxy) throws IOException {
264 if ("POST".equals(method) || "PUT".equals(method)) {
265 BasicHttpEntity body = new BasicHttpEntity();
266 body.setContent(req.getInputStream());
267 body.setContentLength(-1); // -1 = unknown
268 proxy.setEntity(body);
272 private String buildUrl(HttpServletRequest req) {
273 StringBuilder sb = new StringBuilder("https://");
274 sb.append(URLUtilities.getPeerPodName());
275 sb.append(req.getRequestURI());
276 String query = req.getQueryString();
278 sb.append("?").append(query);
280 return sb.toString();
283 private void copyRequestHeaders(HttpServletRequest from, HttpRequestBase to) {
284 List<String> list = Collections.list(from.getHeaderNames());
285 for (String name : list) {
286 // Proxy code will add this one
287 if (!"Content-Length".equalsIgnoreCase(name)) {
288 to.addHeader(name, from.getHeader(name));
293 void copyResponseHeaders(HttpResponse from, HttpServletResponse to) {
294 for (Header hdr : from.getAllHeaders()) {
295 // Don't copy Date: our Jetty will add another Date header
296 if (!"Date".equals(hdr.getName())) {
297 to.addHeader(hdr.getName(), hdr.getValue());
302 void copyEntityContent(HttpResponse pxyResponse, HttpServletResponse resp) {
303 HttpEntity entity = pxyResponse.getEntity();
304 if (entity != null) {
305 try (InputStream in = entity.getContent()) {
306 IOUtils.copy(in, resp.getOutputStream());
307 } catch (Exception e) {
308 intlogger.error("ProxyServlet.copyEntityContent: " + e.getMessage(), e);
313 public static class ProxyHttpRequest extends HttpEntityEnclosingRequestBase {
315 private final String method;
317 ProxyHttpRequest(final String method, final String uri) {
319 this.method = method;
320 setURI(URI.create(uri));
324 public String getMethod() {