72d55a4cf66c5f92bd8f9bcdb9f932871f2e692a
[dmaap/datarouter.git] / datarouter-prov / src / main / java / org / onap / dmaap / datarouter / provisioning / ProxyServlet.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
25 package org.onap.dmaap.datarouter.provisioning;
26
27 import static org.onap.dmaap.datarouter.provisioning.utils.HttpServletUtils.sendResponseError;
28
29 import java.io.File;
30 import java.io.FileInputStream;
31 import java.io.FileNotFoundException;
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.net.URI;
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;
59
60 /**
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.
64  *
65  * @author Robert Eby
66  * @version $Id: ProxyServlet.java,v 1.3 2014/03/24 18:47:10 eby Exp $
67  */
68 @SuppressWarnings("serial")
69
70 public class ProxyServlet extends BaseServlet {
71
72     private boolean inited = false;
73     private Scheme sch;
74
75     /**
76      * Initialize this servlet, by setting up SSL.
77      */
78     @SuppressWarnings("deprecation")
79     @Override
80     public void init(ServletConfig config) throws ServletException {
81         super.init(config);
82         try {
83             // Set up keystore
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);
88             // Set up truststore
89             store = Main.aafPropsUtils.getTruststorePathProperty();
90             pass = Main.aafPropsUtils.getTruststorePassProperty();
91             if (store == null || store.length() == 0) {
92                 store = AafPropsUtils.DEFAULT_TRUSTSTORE;
93                 pass = "changeit";
94             }
95             KeyStore trustStore = readStore(store, pass, AafPropsUtils.TRUESTSTORE_TYPE_PROPERTY);
96
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);
103             inited = true;
104         } catch (Exception e) {
105             intlogger.error("ProxyServlet.init: " + e.getMessage(), e);
106         }
107         intlogger.info("ProxyServlet: inited = " + inited);
108     }
109
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);
118         }
119         return ks;
120     }
121
122     /**
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.
125      *
126      * @param req the HTTP request
127      * @return true or false
128      */
129     boolean isProxyOK(final HttpServletRequest req) {
130         String str = req.getQueryString();
131         if (str != null) {
132             str = str.replaceAll("&amp;", "&");
133             for (String s : str.split("&")) {
134                 if ("noproxy".equals(s) || s.startsWith("noproxy=")) {
135                     return false;
136                 }
137             }
138         }
139         return true;
140     }
141
142     /**
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).
145      *
146      * @return true if this server is the standby (and hence a proxy server).
147      */
148     boolean isProxyServer() {
149         SynchronizerTask st = SynchronizerTask.getSynchronizer();
150         return st.getPodState() == SynchronizerTask.STANDBY_POD;
151     }
152
153     /**
154      * Issue a proxy DELETE to the active provisioning server.
155      */
156     @Override
157     public void doDelete(HttpServletRequest req, HttpServletResponse resp) {
158         doProxy(req, resp, "DELETE");
159     }
160
161     /**
162      * Issue a proxy GET to the active provisioning server.
163      */
164     @Override
165     public void doGet(HttpServletRequest req, HttpServletResponse resp) {
166         doProxy(req, resp, "GET");
167     }
168
169     /**
170      * Issue a proxy PUT to the active provisioning server.
171      */
172     @Override
173     public void doPut(HttpServletRequest req, HttpServletResponse resp) {
174         doProxy(req, resp, "PUT");
175     }
176
177     /**
178      * Issue a proxy POST to the active provisioning server.
179      */
180     @Override
181     public void doPost(HttpServletRequest req, HttpServletResponse resp) {
182         doProxy(req, resp, "POST");
183     }
184
185     /**
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.
188      *
189      * @return true if the proxy succeeded
190      */
191     boolean doGetWithFallback(HttpServletRequest req, HttpServletResponse resp) {
192         boolean rv = false;
193         if (inited) {
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);
198                 try {
199                     httpclient.getConnectionManager().getSchemeRegistry().register(sch);
200
201                     // Copy request headers and request body
202                     copyRequestHeaders(req, proxy);
203
204                     // Execute the request
205                     HttpResponse pxyResponse = httpclient.execute(proxy);
206
207                     // Get response headers and body
208                     int code = pxyResponse.getStatusLine().getStatusCode();
209                     resp.setStatus(code);
210                     copyResponseHeaders(pxyResponse, resp);
211                     copyEntityContent(pxyResponse, resp);
212                     rv = true;
213
214                 } catch (IOException e) {
215                     intlogger.error("ProxyServlet.doGetWithFallback: " + e.getMessage(), e);
216                 } finally {
217                     proxy.releaseConnection();
218                     httpclient.getConnectionManager().shutdown();
219                 }
220             }
221         } else {
222             intlogger.warn("ProxyServlet: proxy disabled");
223         }
224         return rv;
225     }
226
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);
233                 try {
234                     httpclient.getConnectionManager().getSchemeRegistry().register(sch);
235
236                     // Copy request headers and request body
237                     copyRequestHeaders(req, proxy);
238
239                     handlePutOrPost(req, method, proxy);
240
241                     // Execute the request
242                     HttpResponse pxyResponse = httpclient.execute(proxy);
243
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);
252                 } finally {
253                     proxy.releaseConnection();
254                     httpclient.getConnectionManager().shutdown();
255                 }
256             }
257         } else {
258             intlogger.warn("ProxyServlet: proxy disabled");
259             sendResponseError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, DB_PROBLEM_MSG, intlogger);
260         }
261     }
262
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);
269         }
270     }
271
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();
277         if (query != null) {
278             sb.append("?").append(query);
279         }
280         return sb.toString();
281     }
282
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));
289             }
290         }
291     }
292
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());
298             }
299         }
300     }
301
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);
309             }
310         }
311     }
312
313     public static class ProxyHttpRequest extends HttpEntityEnclosingRequestBase {
314
315         private final String method;
316
317         ProxyHttpRequest(final String method, final String uri) {
318             super();
319             this.method = method;
320             setURI(URI.create(uri));
321         }
322
323         @Override
324         public String getMethod() {
325             return method;
326         }
327     }
328 }