089ea7558fe084cef6ab858dad985aefeb6b4ff3
[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 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;
58
59 /**
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.
63  *
64  * @author Robert Eby
65  * @version $Id: ProxyServlet.java,v 1.3 2014/03/24 18:47:10 eby Exp $
66  */
67 @SuppressWarnings("serial")
68
69 public class ProxyServlet extends BaseServlet {
70
71     private boolean inited = false;
72     private Scheme sch;
73
74     /**
75      * Initialize this servlet, by setting up SSL.
76      */
77     @SuppressWarnings("deprecation")
78     @Override
79     public void init(ServletConfig config) throws ServletException {
80         super.init(config);
81         try {
82             // Set up keystore
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);
87             // Set up truststore
88             store = ProvRunner.getAafPropsUtils().getTruststorePathProperty();
89             pass = ProvRunner.getAafPropsUtils().getTruststorePassProperty();
90             KeyStore trustStore = readStore(store, pass, AafPropsUtils.TRUESTSTORE_TYPE_PROPERTY);
91
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);
98             inited = true;
99         } catch (Exception e) {
100             intlogger.error("ProxyServlet.init: " + e.getMessage(), e);
101         }
102         intlogger.info("ProxyServlet: inited = " + inited);
103     }
104
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);
113         }
114         return ks;
115     }
116
117     /**
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.
120      *
121      * @param req the HTTP request
122      * @return true or false
123      */
124     boolean isProxyOK(final HttpServletRequest req) {
125         String str = req.getQueryString();
126         if (str != null) {
127             str = str.replaceAll("&amp;", "&");
128             for (String s : str.split("&")) {
129                 if ("noproxy".equals(s) || s.startsWith("noproxy=")) {
130                     return false;
131                 }
132             }
133         }
134         return true;
135     }
136
137     /**
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).
140      *
141      * @return true if this server is the standby (and hence a proxy server).
142      */
143     boolean isProxyServer() {
144         SynchronizerTask st = SynchronizerTask.getSynchronizer();
145         return st.getPodState() == SynchronizerTask.STANDBY_POD;
146     }
147
148     /**
149      * Issue a proxy DELETE to the active provisioning server.
150      */
151     @Override
152     public void doDelete(HttpServletRequest req, HttpServletResponse resp) {
153         doProxy(req, resp, "DELETE");
154     }
155
156     /**
157      * Issue a proxy GET to the active provisioning server.
158      */
159     @Override
160     public void doGet(HttpServletRequest req, HttpServletResponse resp) {
161         doProxy(req, resp, "GET");
162     }
163
164     /**
165      * Issue a proxy PUT to the active provisioning server.
166      */
167     @Override
168     public void doPut(HttpServletRequest req, HttpServletResponse resp) {
169         doProxy(req, resp, "PUT");
170     }
171
172     /**
173      * Issue a proxy POST to the active provisioning server.
174      */
175     @Override
176     public void doPost(HttpServletRequest req, HttpServletResponse resp) {
177         doProxy(req, resp, "POST");
178     }
179
180     /**
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.
183      *
184      * @return true if the proxy succeeded
185      */
186     boolean doGetWithFallback(HttpServletRequest req, HttpServletResponse resp) {
187         boolean rv = false;
188         if (inited) {
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);
193                 try {
194                     httpclient.getConnectionManager().getSchemeRegistry().register(sch);
195
196                     // Copy request headers and request body
197                     copyRequestHeaders(req, proxy);
198
199                     // Execute the request
200                     HttpResponse pxyResponse = httpclient.execute(proxy);
201
202                     // Get response headers and body
203                     int code = pxyResponse.getStatusLine().getStatusCode();
204                     resp.setStatus(code);
205                     copyResponseHeaders(pxyResponse, resp);
206                     copyEntityContent(pxyResponse, resp);
207                     rv = true;
208
209                 } catch (IOException e) {
210                     intlogger.error("ProxyServlet.doGetWithFallback: " + e.getMessage(), e);
211                 } finally {
212                     proxy.releaseConnection();
213                     httpclient.getConnectionManager().shutdown();
214                 }
215             }
216         } else {
217             intlogger.warn("ProxyServlet: proxy disabled");
218         }
219         return rv;
220     }
221
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);
228                 try {
229                     httpclient.getConnectionManager().getSchemeRegistry().register(sch);
230
231                     // Copy request headers and request body
232                     copyRequestHeaders(req, proxy);
233
234                     handlePutOrPost(req, method, proxy);
235
236                     // Execute the request
237                     HttpResponse pxyResponse = httpclient.execute(proxy);
238
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);
247                 } finally {
248                     proxy.releaseConnection();
249                     httpclient.getConnectionManager().shutdown();
250                 }
251             }
252         } else {
253             intlogger.warn("ProxyServlet: proxy disabled");
254             sendResponseError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, DB_PROBLEM_MSG, intlogger);
255         }
256     }
257
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);
264         }
265     }
266
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();
272         if (query != null) {
273             sb.append("?").append(query);
274         }
275         return sb.toString();
276     }
277
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));
284             }
285         }
286     }
287
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());
293             }
294         }
295     }
296
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);
304             }
305         }
306     }
307
308     public static class ProxyHttpRequest extends HttpEntityEnclosingRequestBase {
309
310         private final String method;
311
312         ProxyHttpRequest(final String method, final String uri) {
313             super();
314             this.method = method;
315             setURI(URI.create(uri));
316         }
317
318         @Override
319         public String getMethod() {
320             return method;
321         }
322     }
323 }