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 javax.servlet.ServletConfig;
40 import javax.servlet.ServletException;
41 import javax.servlet.http.HttpServletRequest;
42 import javax.servlet.http.HttpServletResponse;
43 import org.apache.commons.io.IOUtils;
44 import org.apache.http.Header;
45 import org.apache.http.HttpEntity;
46 import org.apache.http.HttpResponse;
47 import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
48 import org.apache.http.client.methods.HttpGet;
49 import org.apache.http.client.methods.HttpRequestBase;
50 import org.apache.http.conn.scheme.Scheme;
51 import org.apache.http.conn.ssl.SSLSocketFactory;
52 import org.apache.http.entity.BasicHttpEntity;
53 import org.apache.http.impl.client.AbstractHttpClient;
54 import org.apache.http.impl.client.DefaultHttpClient;
55 import org.onap.dmaap.datarouter.provisioning.utils.AafPropsUtils;
56 import org.onap.dmaap.datarouter.provisioning.utils.SynchronizerTask;
57 import org.onap.dmaap.datarouter.provisioning.utils.URLUtilities;
60 * This class is the base class for those servlets that need to proxy their requests from the standby to active server.
61 * Its methods perform the proxy function to the active server. If the active server is not reachable, a 503
62 * (SC_SERVICE_UNAVAILABLE) is returned. Only DELETE/GET/PUT/POST are supported.
65 * @version $Id: ProxyServlet.java,v 1.3 2014/03/24 18:47:10 eby Exp $
67 @SuppressWarnings("serial")
69 public class ProxyServlet extends BaseServlet {
71 private boolean inited = false;
75 * Initialize this servlet, by setting up SSL.
77 @SuppressWarnings("deprecation")
79 public void init(ServletConfig config) throws ServletException {
83 String type = AafPropsUtils.KEYSTORE_TYPE_PROPERTY;
84 String store = ProvRunner.getAafPropsUtils().getKeystorePathProperty();
85 String pass = ProvRunner.getAafPropsUtils().getKeystorePassProperty();
86 KeyStore keyStore = readStore(store, pass, type);
88 store = ProvRunner.getAafPropsUtils().getTruststorePathProperty();
89 pass = ProvRunner.getAafPropsUtils().getTruststorePassProperty();
90 KeyStore trustStore = readStore(store, pass, AafPropsUtils.TRUESTSTORE_TYPE_PROPERTY);
92 // We are connecting with the node name, but the certificate will have the CNAME
93 // So we need to accept a non-matching certificate name
94 SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore,
95 ProvRunner.getAafPropsUtils().getKeystorePassProperty(), trustStore);
96 socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
97 sch = new Scheme("https", 443, socketFactory);
99 } catch (Exception e) {
100 intlogger.error("ProxyServlet.init: " + e.getMessage(), e);
102 intlogger.info("ProxyServlet: inited = " + inited);
105 private KeyStore readStore(String store, String pass, String type) throws KeyStoreException {
106 KeyStore ks = KeyStore.getInstance(type);
107 try (FileInputStream instream = new FileInputStream(new File(store))) {
108 ks.load(instream, pass.toCharArray());
109 } catch (FileNotFoundException fileNotFoundException) {
110 intlogger.error("ProxyServlet.readStore: " + fileNotFoundException.getMessage(), fileNotFoundException);
111 } catch (Exception x) {
112 intlogger.error("READING TRUSTSTORE: " + x);
118 * Return <i>true</i> if the requester has NOT set the <i>noproxy</i> CGI variable. If they have, this indicates
119 * they want to forcibly turn the proxy off.
121 * @param req the HTTP request
122 * @return true or false
124 boolean isProxyOK(final HttpServletRequest req) {
125 String str = req.getQueryString();
127 str = str.replaceAll("&", "&");
128 for (String s : str.split("&")) {
129 if ("noproxy".equals(s) || s.startsWith("noproxy=")) {
138 * Is this the standby server? If it is, the proxy functions can be used. If not, the proxy functions should not be
139 * called, and will send a response of 500 (Internal Server Error).
141 * @return true if this server is the standby (and hence a proxy server).
143 boolean isProxyServer() {
144 SynchronizerTask st = SynchronizerTask.getSynchronizer();
145 return st.getPodState() == SynchronizerTask.STANDBY_POD;
149 * Issue a proxy DELETE to the active provisioning server.
152 public void doDelete(HttpServletRequest req, HttpServletResponse resp) {
153 doProxy(req, resp, "DELETE");
157 * Issue a proxy GET to the active provisioning server.
160 public void doGet(HttpServletRequest req, HttpServletResponse resp) {
161 doProxy(req, resp, "GET");
165 * Issue a proxy PUT to the active provisioning server.
168 public void doPut(HttpServletRequest req, HttpServletResponse resp) {
169 doProxy(req, resp, "PUT");
173 * Issue a proxy POST to the active provisioning server.
176 public void doPost(HttpServletRequest req, HttpServletResponse resp) {
177 doProxy(req, resp, "POST");
181 * Issue a proxy GET to the active provisioning server. Unlike doGet() above, this method will allow the caller to
182 * fall back to other code if the remote server is unreachable.
184 * @return true if the proxy succeeded
186 boolean doGetWithFallback(HttpServletRequest req, HttpServletResponse resp) {
189 String url = buildUrl(req);
190 intlogger.info("ProxyServlet: proxying with fallback GET " + url);
191 try (AbstractHttpClient httpclient = new DefaultHttpClient()) {
192 HttpRequestBase proxy = new HttpGet(url);
194 httpclient.getConnectionManager().getSchemeRegistry().register(sch);
196 // Copy request headers and request body
197 copyRequestHeaders(req, proxy);
199 // Execute the request
200 HttpResponse pxyResponse = httpclient.execute(proxy);
202 // Get response headers and body
203 int code = pxyResponse.getStatusLine().getStatusCode();
204 resp.setStatus(code);
205 copyResponseHeaders(pxyResponse, resp);
206 copyEntityContent(pxyResponse, resp);
209 } catch (IOException e) {
210 intlogger.error("ProxyServlet.doGetWithFallback: " + e.getMessage(), e);
212 proxy.releaseConnection();
213 httpclient.getConnectionManager().shutdown();
217 intlogger.warn("ProxyServlet: proxy disabled");
222 private void doProxy(HttpServletRequest req, HttpServletResponse resp, final String method) {
223 if (inited && isProxyServer()) {
224 String url = buildUrl(req);
225 intlogger.info("ProxyServlet: proxying " + method + " " + url);
226 try (AbstractHttpClient httpclient = new DefaultHttpClient()) {
227 ProxyHttpRequest proxy = new ProxyHttpRequest(method, url);
229 httpclient.getConnectionManager().getSchemeRegistry().register(sch);
231 // Copy request headers and request body
232 copyRequestHeaders(req, proxy);
234 handlePutOrPost(req, method, proxy);
236 // Execute the request
237 HttpResponse pxyResponse = httpclient.execute(proxy);
239 // Get response headers and body
240 int code = pxyResponse.getStatusLine().getStatusCode();
241 resp.setStatus(code);
242 copyResponseHeaders(pxyResponse, resp);
243 copyEntityContent(pxyResponse, resp);
244 } catch (IOException e) {
245 intlogger.warn("ProxyServlet.doProxy: " + e.getMessage(), e);
246 sendResponseError(resp, HttpServletResponse.SC_SERVICE_UNAVAILABLE, "", intlogger);
248 proxy.releaseConnection();
249 httpclient.getConnectionManager().shutdown();
253 intlogger.warn("ProxyServlet: proxy disabled");
254 sendResponseError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, DB_PROBLEM_MSG, intlogger);
258 private void handlePutOrPost(HttpServletRequest req, String method, ProxyHttpRequest proxy) throws IOException {
259 if ("POST".equals(method) || "PUT".equals(method)) {
260 BasicHttpEntity body = new BasicHttpEntity();
261 body.setContent(req.getInputStream());
262 body.setContentLength(-1); // -1 = unknown
263 proxy.setEntity(body);
267 private String buildUrl(HttpServletRequest req) {
268 StringBuilder sb = new StringBuilder("https://");
269 sb.append(URLUtilities.getPeerPodName());
270 sb.append(req.getRequestURI());
271 String query = req.getQueryString();
273 sb.append("?").append(query);
275 return sb.toString();
278 private void copyRequestHeaders(HttpServletRequest from, HttpRequestBase to) {
279 List<String> list = Collections.list(from.getHeaderNames());
280 for (String name : list) {
281 // Proxy code will add this one
282 if (!"Content-Length".equalsIgnoreCase(name)) {
283 to.addHeader(name, from.getHeader(name));
288 void copyResponseHeaders(HttpResponse from, HttpServletResponse to) {
289 for (Header hdr : from.getAllHeaders()) {
290 // Don't copy Date: our Jetty will add another Date header
291 if (!"Date".equals(hdr.getName())) {
292 to.addHeader(hdr.getName(), hdr.getValue());
297 void copyEntityContent(HttpResponse pxyResponse, HttpServletResponse resp) {
298 HttpEntity entity = pxyResponse.getEntity();
299 if (entity != null) {
300 try (InputStream in = entity.getContent()) {
301 IOUtils.copy(in, resp.getOutputStream());
302 } catch (Exception e) {
303 intlogger.error("ProxyServlet.copyEntityContent: " + e.getMessage(), e);
308 public static class ProxyHttpRequest extends HttpEntityEnclosingRequestBase {
310 private final String method;
312 ProxyHttpRequest(final String method, final String uri) {
314 this.method = method;
315 setURI(URI.create(uri));
319 public String getMethod() {