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;
28 import java.io.FileInputStream;
29 import java.io.FileNotFoundException;
30 import java.io.IOException;
31 import java.io.InputStream;
33 import java.security.KeyStore;
34 import java.security.KeyStoreException;
35 import java.util.Collections;
36 import java.util.List;
37 import java.util.Properties;
38 import javax.servlet.ServletConfig;
39 import javax.servlet.ServletException;
40 import javax.servlet.http.HttpServletRequest;
41 import javax.servlet.http.HttpServletResponse;
42 import org.apache.commons.io.IOUtils;
43 import org.apache.http.Header;
44 import org.apache.http.HttpEntity;
45 import org.apache.http.HttpResponse;
46 import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
47 import org.apache.http.client.methods.HttpGet;
48 import org.apache.http.client.methods.HttpRequestBase;
49 import org.apache.http.conn.scheme.Scheme;
50 import org.apache.http.conn.ssl.SSLSocketFactory;
51 import org.apache.http.entity.BasicHttpEntity;
52 import org.apache.http.impl.client.AbstractHttpClient;
53 import org.apache.http.impl.client.DefaultHttpClient;
54 import org.onap.dmaap.datarouter.provisioning.utils.DB;
55 import org.onap.dmaap.datarouter.provisioning.utils.URLUtilities;
58 * This class is the base class for those servlets that need to proxy their requests from the standby to active server.
59 * Its methods perform the proxy function to the active server. If the active server is not reachable, a 503
60 * (SC_SERVICE_UNAVAILABLE) is returned. Only DELETE/GET/PUT/POST are supported.
63 * @version $Id: ProxyServlet.java,v 1.3 2014/03/24 18:47:10 eby Exp $
65 @SuppressWarnings("serial")
66 public class ProxyServlet extends BaseServlet {
68 private boolean inited = false;
72 * Initialize this servlet, by setting up SSL.
74 @SuppressWarnings("deprecation")
76 public void init(ServletConfig config) throws ServletException {
80 Properties props = (new DB()).getProperties();
81 String type = props.getProperty(Main.KEYSTORE_TYPE_PROPERTY, "jks");
82 String store = props.getProperty(Main.KEYSTORE_PATH_PROPERTY);
83 String pass = props.getProperty(Main.KEYSTORE_PASSWORD_PROPERTY);
84 KeyStore keyStore = readStore(store, pass, type);
86 store = props.getProperty(Main.TRUSTSTORE_PATH_PROPERTY);
87 pass = props.getProperty(Main.TRUSTSTORE_PASSWORD_PROPERTY);
88 if (store == null || store.length() == 0) {
89 store = Main.DEFAULT_TRUSTSTORE;
92 KeyStore trustStore = readStore(store, pass, KeyStore.getDefaultType());
94 // We are connecting with the node name, but the certificate will have the CNAME
95 // So we need to accept a non-matching certificate name
96 SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore,
97 props.getProperty(Main.KEYSTORE_PASSWORD_PROPERTY), trustStore);
98 socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
99 sch = new Scheme("https", 443, socketFactory);
101 } catch (Exception e) {
104 intlogger.info("ProxyServlet: inited = " + inited);
107 private KeyStore readStore(String store, String pass, String type) throws KeyStoreException {
108 KeyStore ks = KeyStore.getInstance(type);
109 try (FileInputStream instream = new FileInputStream(new File(store))) {
110 ks.load(instream, pass.toCharArray());
111 } catch (FileNotFoundException fileNotFoundException) {
112 intlogger.error("ProxyServlet: " + fileNotFoundException.getMessage());
113 } catch (Exception x) {
114 System.err.println("READING TRUSTSTORE: " + x);
120 * Return <i>true</i> if the requester has NOT set the <i>noproxy</i> CGI variable. If they have, this indicates
121 * they want to forcibly turn the proxy off.
123 * @param req the HTTP request
124 * @return true or false
126 protected boolean isProxyOK(final HttpServletRequest req) {
127 String t = req.getQueryString();
129 t = t.replaceAll("&", "&");
130 for (String s : t.split("&")) {
131 if (s.equals("noproxy") || s.startsWith("noproxy=")) {
140 * Is this the standby server? If it is, the proxy functions can be used. If not, the proxy functions should not be
141 * called, and will send a response of 500 (Internal Server Error).
143 * @return true if this server is the standby (and hence a proxy server).
145 public boolean isProxyServer() {
146 SynchronizerTask st = SynchronizerTask.getSynchronizer();
147 return st.getState() == SynchronizerTask.STANDBY;
151 * Issue a proxy DELETE to the active provisioning server.
154 public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
155 doProxy(req, resp, "DELETE");
159 * Issue a proxy GET to the active provisioning server.
162 public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
163 doProxy(req, resp, "GET");
167 * Issue a proxy PUT to the active provisioning server.
170 public void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
171 doProxy(req, resp, "PUT");
175 * Issue a proxy POST to the active provisioning server.
178 public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
179 doProxy(req, resp, "POST");
183 * Issue a proxy GET to the active provisioning server. Unlike doGet() above, this method will allow the caller to
184 * fall back to other code if the remote server is unreachable.
186 * @return true if the proxy succeeded
188 public boolean doGetWithFallback(HttpServletRequest req, HttpServletResponse resp) throws IOException {
191 String url = buildUrl(req);
192 intlogger.info("ProxyServlet: proxying with fallback GET " + url);
193 try (AbstractHttpClient httpclient = new DefaultHttpClient()) {
194 HttpRequestBase proxy = new HttpGet(url);
196 httpclient.getConnectionManager().getSchemeRegistry().register(sch);
198 // Copy request headers and request body
199 copyRequestHeaders(req, proxy);
201 // Execute the request
202 HttpResponse pxy_response = httpclient.execute(proxy);
204 // Get response headers and body
205 int code = pxy_response.getStatusLine().getStatusCode();
206 resp.setStatus(code);
207 copyResponseHeaders(pxy_response, resp);
209 HttpEntity entity = pxy_response.getEntity();
210 if (entity != null) {
211 InputStream in = entity.getContent();
212 IOUtils.copy(in, resp.getOutputStream());
217 } catch (IOException e) {
218 System.err.println("ProxyServlet: " + e);
221 proxy.releaseConnection();
222 httpclient.getConnectionManager().shutdown();
226 intlogger.warn("ProxyServlet: proxy disabled");
231 private void doProxy(HttpServletRequest req, HttpServletResponse resp, final String method) throws IOException {
232 if (inited && isProxyServer()) {
233 String url = buildUrl(req);
234 intlogger.info("ProxyServlet: proxying " + method + " " + url);
235 try (AbstractHttpClient httpclient = new DefaultHttpClient()) {
236 ProxyHttpRequest proxy = new ProxyHttpRequest(method, url);
238 httpclient.getConnectionManager().getSchemeRegistry().register(sch);
240 // Copy request headers and request body
241 copyRequestHeaders(req, proxy);
242 if (method.equals("POST") || method.equals("PUT")) {
243 BasicHttpEntity body = new BasicHttpEntity();
244 body.setContent(req.getInputStream());
245 body.setContentLength(-1); // -1 = unknown
246 proxy.setEntity(body);
249 // Execute the request
250 HttpResponse pxy_response = httpclient.execute(proxy);
252 // Get response headers and body
253 int code = pxy_response.getStatusLine().getStatusCode();
254 resp.setStatus(code);
255 copyResponseHeaders(pxy_response, resp);
257 HttpEntity entity = pxy_response.getEntity();
258 if (entity != null) {
259 InputStream in = entity.getContent();
260 IOUtils.copy(in, resp.getOutputStream());
263 } catch (IOException e) {
264 intlogger.warn("ProxyServlet: " + e);
265 resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
268 proxy.releaseConnection();
269 httpclient.getConnectionManager().shutdown();
273 intlogger.warn("ProxyServlet: proxy disabled");
274 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
278 private String buildUrl(HttpServletRequest req) {
279 StringBuilder sb = new StringBuilder("https://");
280 sb.append(URLUtilities.getPeerPodName());
281 sb.append(req.getRequestURI());
282 String q = req.getQueryString();
284 sb.append("?").append(q);
286 return sb.toString();
289 private void copyRequestHeaders(HttpServletRequest from, HttpRequestBase to) {
290 @SuppressWarnings("unchecked")
291 List<String> list = Collections.list(from.getHeaderNames());
292 for (String name : list) {
293 // Proxy code will add this one
294 if (!name.equalsIgnoreCase("Content-Length")) {
295 to.addHeader(name, from.getHeader(name));
300 private void copyResponseHeaders(HttpResponse from, HttpServletResponse to) {
301 for (Header hdr : from.getAllHeaders()) {
302 // Don't copy Date: our Jetty will add another Date header
303 if (!hdr.getName().equals("Date")) {
304 to.addHeader(hdr.getName(), hdr.getValue());
309 public class ProxyHttpRequest extends HttpEntityEnclosingRequestBase {
311 private final String method;
313 public ProxyHttpRequest(final String method, final String uri) {
315 this.method = method;
316 setURI(URI.create(uri));
320 public String getMethod() {