blob: 4a893fcb7941752003fa7d3937856c063437e864 [file] [log] [blame]
Hesam Rahimi4a409b42016-08-12 18:37:33 -04001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2016-present Open Networking Foundation
Hesam Rahimi4a409b42016-08-12 18:37:33 -04003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.onosproject.protocol.http.ctl;
18
Michal Machbcd58c72017-06-19 17:12:34 +020019import com.google.common.collect.ImmutableMap;
Hesam Rahimi4a409b42016-08-12 18:37:33 -040020import org.apache.commons.io.IOUtils;
21import org.apache.http.client.methods.HttpPatch;
22import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
23import org.apache.http.entity.StringEntity;
24import org.apache.http.impl.client.CloseableHttpClient;
25import org.apache.http.impl.client.HttpClients;
26import org.apache.http.ssl.SSLContextBuilder;
27import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
28import org.onlab.packet.IpAddress;
29import org.onosproject.net.DeviceId;
30import org.onosproject.protocol.http.HttpSBController;
31import org.onosproject.protocol.rest.RestSBDevice;
32import org.slf4j.Logger;
33import org.slf4j.LoggerFactory;
34
Michal Machbcd58c72017-06-19 17:12:34 +020035import javax.net.ssl.SSLContext;
36import javax.net.ssl.TrustManager;
37import javax.net.ssl.X509TrustManager;
38import javax.ws.rs.client.Client;
39import javax.ws.rs.client.ClientBuilder;
40import javax.ws.rs.client.Entity;
41import javax.ws.rs.client.WebTarget;
42import javax.ws.rs.core.MediaType;
43import javax.ws.rs.core.Response;
44import javax.ws.rs.core.Response.Status;
45import java.io.ByteArrayInputStream;
46import java.io.IOException;
47import java.io.InputStream;
48import java.nio.charset.StandardCharsets;
49import java.security.KeyManagementException;
50import java.security.KeyStoreException;
51import java.security.NoSuchAlgorithmException;
52import java.security.cert.CertificateException;
53import java.security.cert.X509Certificate;
54import java.util.Base64;
55import java.util.Map;
56import java.util.concurrent.ConcurrentHashMap;
Hesam Rahimi4a409b42016-08-12 18:37:33 -040057
58/**
59 * The implementation of HttpSBController.
60 */
61public class HttpSBControllerImpl implements HttpSBController {
62
Matteo Gerola7e180c22017-03-30 11:57:58 +020063 private static final Logger log = LoggerFactory.getLogger(HttpSBControllerImpl.class);
Hesam Rahimi4a409b42016-08-12 18:37:33 -040064 private static final String XML = "xml";
65 private static final String JSON = "json";
Michele Santuaric372c222017-01-12 09:41:25 +010066 protected static final String DOUBLESLASH = "//";
67 protected static final String COLON = ":";
Hesam Rahimi4a409b42016-08-12 18:37:33 -040068 private static final int STATUS_OK = Response.Status.OK.getStatusCode();
69 private static final int STATUS_CREATED = Response.Status.CREATED.getStatusCode();
70 private static final int STATUS_ACCEPTED = Response.Status.ACCEPTED.getStatusCode();
71 private static final String HTTPS = "https";
72 private static final String AUTHORIZATION_PROPERTY = "authorization";
73 private static final String BASIC_AUTH_PREFIX = "Basic ";
74
75 private final Map<DeviceId, RestSBDevice> deviceMap = new ConcurrentHashMap<>();
76 private final Map<DeviceId, Client> clientMap = new ConcurrentHashMap<>();
77
78 public Map<DeviceId, RestSBDevice> getDeviceMap() {
79 return deviceMap;
80 }
81
82 public Map<DeviceId, Client> getClientMap() {
83 return clientMap;
84 }
85
86 @Override
87 public Map<DeviceId, RestSBDevice> getDevices() {
88 return ImmutableMap.copyOf(deviceMap);
89 }
90
91 @Override
92 public RestSBDevice getDevice(DeviceId deviceInfo) {
93 return deviceMap.get(deviceInfo);
94 }
95
96 @Override
97 public RestSBDevice getDevice(IpAddress ip, int port) {
Matteo Gerola7e180c22017-03-30 11:57:58 +020098 return deviceMap.values().stream().filter(v -> v.ip().equals(ip) && v.port() == port).findFirst().get();
Hesam Rahimi4a409b42016-08-12 18:37:33 -040099 }
100
101 @Override
102 public void addDevice(RestSBDevice device) {
103 if (!deviceMap.containsKey(device.deviceId())) {
104 Client client = ignoreSslClient();
105 if (device.username() != null) {
106 String username = device.username();
107 String password = device.password() == null ? "" : device.password();
108 authenticate(client, username, password);
109 }
110 clientMap.put(device.deviceId(), client);
111 deviceMap.put(device.deviceId(), device);
112 } else {
113 log.warn("Trying to add a device that is already existing {}", device.deviceId());
114 }
115
116 }
117
118 @Override
119 public void removeDevice(DeviceId deviceId) {
120 clientMap.remove(deviceId);
121 deviceMap.remove(deviceId);
122 }
123
124 @Override
125 public boolean post(DeviceId device, String request, InputStream payload, String mediaType) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200126 return checkStatusCode(post(device, request, payload, typeOfMediaType(mediaType)));
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400127 }
128
129 @Override
Matteo Gerola7e180c22017-03-30 11:57:58 +0200130 public int post(DeviceId device, String request, InputStream payload, MediaType mediaType) {
131 Response response = getResponse(device, request, payload, mediaType);
132 if (response == null) {
133 return Status.NO_CONTENT.getStatusCode();
134 }
135 return response.getStatus();
136 }
137
138 @Override
139 public <T> T post(DeviceId device, String request, InputStream payload, String mediaType, Class<T> responseClass) {
140 return post(device, request, payload, typeOfMediaType(mediaType), responseClass);
141 }
142
143 @Override
144 public <T> T post(DeviceId device, String request, InputStream payload, MediaType mediaType,
145 Class<T> responseClass) {
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400146 Response response = getResponse(device, request, payload, mediaType);
Palash Kalada4798d2017-05-23 20:16:55 +0900147 if (response != null && response.hasEntity()) {
Hesam Rahimi96305542017-06-07 13:59:48 -0400148 // Do not read the entity if the responseClass is of type Response. This would allow the
149 // caller to receive the Response directly and try to read its appropriate entity locally.
150 return responseClass == Response.class ? (T) response : response.readEntity(responseClass);
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400151 }
152 log.error("Response from device {} for request {} contains no entity", device, request);
153 return null;
154 }
155
Matteo Gerola7e180c22017-03-30 11:57:58 +0200156 private Response getResponse(DeviceId device, String request, InputStream payload, MediaType mediaType) {
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400157
158 WebTarget wt = getWebTarget(device, request);
159
160 Response response = null;
161 if (payload != null) {
162 try {
Eunjin Choi51244d32017-05-15 14:09:56 +0900163 response = wt.request(mediaType)
164 .post(Entity.entity(IOUtils.toString(payload, StandardCharsets.UTF_8), mediaType));
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400165 } catch (IOException e) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200166 log.error("Cannot do POST {} request on device {} because can't read payload", request, device);
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400167 }
168 } else {
Georgios Katsikas186b9582017-05-31 17:25:54 +0200169 response = wt.request(mediaType).post(Entity.entity(null, mediaType));
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400170 }
171 return response;
172 }
173
174 @Override
175 public boolean put(DeviceId device, String request, InputStream payload, String mediaType) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200176 return checkStatusCode(put(device, request, payload, typeOfMediaType(mediaType)));
177 }
178
179 @Override
180 public int put(DeviceId device, String request, InputStream payload, MediaType mediaType) {
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400181
182 WebTarget wt = getWebTarget(device, request);
183
184 Response response = null;
185 if (payload != null) {
186 try {
Eunjin Choi51244d32017-05-15 14:09:56 +0900187 response = wt.request(mediaType).put(Entity.entity(IOUtils.
188 toString(payload, StandardCharsets.UTF_8), mediaType));
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400189 } catch (IOException e) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200190 log.error("Cannot do PUT {} request on device {} because can't read payload", request, device);
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400191 }
192 } else {
Eunjin Choi51244d32017-05-15 14:09:56 +0900193 response = wt.request(mediaType).put(Entity.entity(null, mediaType));
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400194 }
Matteo Gerola7e180c22017-03-30 11:57:58 +0200195
196 if (response == null) {
197 return Status.NO_CONTENT.getStatusCode();
198 }
199 return response.getStatus();
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400200 }
201
202 @Override
203 public InputStream get(DeviceId device, String request, String mediaType) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200204 return get(device, request, typeOfMediaType(mediaType));
205 }
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400206
Matteo Gerola7e180c22017-03-30 11:57:58 +0200207 @Override
208 public InputStream get(DeviceId device, String request, MediaType mediaType) {
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400209 WebTarget wt = getWebTarget(device, request);
210
Eunjin Choi51244d32017-05-15 14:09:56 +0900211 Response s = wt.request(mediaType).get();
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400212
213 if (checkReply(s)) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200214 return new ByteArrayInputStream(s.readEntity((String.class)).getBytes(StandardCharsets.UTF_8));
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400215 }
216 return null;
217 }
218
219 @Override
220 public boolean patch(DeviceId device, String request, InputStream payload, String mediaType) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200221 return checkStatusCode(patch(device, request, payload, typeOfMediaType(mediaType)));
222 }
223
224 @Override
225 public int patch(DeviceId device, String request, InputStream payload, MediaType mediaType) {
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400226
227 try {
228 log.debug("Url request {} ", getUrlString(device, request));
229 HttpPatch httprequest = new HttpPatch(getUrlString(device, request));
230 if (deviceMap.get(device).username() != null) {
231 String pwd = deviceMap.get(device).password() == null ? "" : COLON + deviceMap.get(device).password();
232 String userPassword = deviceMap.get(device).username() + pwd;
233 String base64string = Base64.getEncoder().encodeToString(userPassword.getBytes(StandardCharsets.UTF_8));
234 httprequest.addHeader(AUTHORIZATION_PROPERTY, BASIC_AUTH_PREFIX + base64string);
235 }
236 if (payload != null) {
237 StringEntity input = new StringEntity(IOUtils.toString(payload, StandardCharsets.UTF_8));
Eunjin Choi51244d32017-05-15 14:09:56 +0900238 input.setContentType(mediaType.toString());
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400239 httprequest.setEntity(input);
240 }
241 CloseableHttpClient httpClient;
242 if (deviceMap.containsKey(device) && deviceMap.get(device).protocol().equals(HTTPS)) {
243 httpClient = getApacheSslBypassClient();
244 } else {
245 httpClient = HttpClients.createDefault();
246 }
Matteo Gerola7e180c22017-03-30 11:57:58 +0200247 return httpClient.execute(httprequest).getStatusLine().getStatusCode();
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400248 } catch (IOException | NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200249 log.error("Cannot do PATCH {} request on device {}", request, device, e);
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400250 }
Matteo Gerola7e180c22017-03-30 11:57:58 +0200251 return Status.BAD_REQUEST.getStatusCode();
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400252 }
253
254 @Override
255 public boolean delete(DeviceId device, String request, InputStream payload, String mediaType) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200256 return checkStatusCode(delete(device, request, payload, typeOfMediaType(mediaType)));
257 }
258
259 @Override
260 public int delete(DeviceId device, String request, InputStream payload, MediaType mediaType) {
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400261
262 WebTarget wt = getWebTarget(device, request);
263
Matteo Gerola7e180c22017-03-30 11:57:58 +0200264 // FIXME: do we need to delete an entry by enclosing data in DELETE
265 // request?
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400266 // wouldn't it be nice to use PUT to implement the similar concept?
Eunjin Choi51244d32017-05-15 14:09:56 +0900267 Response response = wt.request(mediaType).delete();
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400268
Matteo Gerola7e180c22017-03-30 11:57:58 +0200269 return response.getStatus();
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400270 }
271
Matteo Gerola7e180c22017-03-30 11:57:58 +0200272 private MediaType typeOfMediaType(String type) {
273 switch (type) {
274 case XML:
275 return MediaType.APPLICATION_XML_TYPE;
276 case JSON:
277 return MediaType.APPLICATION_JSON_TYPE;
Michal Machf0ce45e2017-06-20 11:54:08 +0200278 case MediaType.WILDCARD:
279 return MediaType.WILDCARD_TYPE;
Matteo Gerola7e180c22017-03-30 11:57:58 +0200280 default:
281 throw new IllegalArgumentException("Unsupported media type " + type);
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400282
283 }
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400284 }
285
286 private void authenticate(Client client, String username, String password) {
287 client.register(HttpAuthenticationFeature.basic(username, password));
288 }
289
290 protected WebTarget getWebTarget(DeviceId device, String request) {
291 log.debug("Sending request to URL {} ", getUrlString(device, request));
292 return clientMap.get(device).target(getUrlString(device, request));
293 }
294
295 //FIXME security issue: this trusts every SSL certificate, even if is self-signed. Also deprecated methods.
296 private CloseableHttpClient getApacheSslBypassClient() throws NoSuchAlgorithmException,
297 KeyManagementException, KeyStoreException {
298 return HttpClients.custom().
299 setHostnameVerifier(new AllowAllHostnameVerifier()).
300 setSslcontext(new SSLContextBuilder()
301 .loadTrustMaterial(null, (arg0, arg1) -> true)
302 .build()).build();
303 }
304
Michal Machbcd58c72017-06-19 17:12:34 +0200305 protected String getUrlString(DeviceId deviceId, String request) {
306 RestSBDevice restSBDevice = deviceMap.get(deviceId);
307 if (restSBDevice == null) {
308 log.warn("restSbDevice cannot be NULL!");
309 return "";
310 }
311 if (restSBDevice.url() != null) {
312 return restSBDevice.protocol() + COLON + DOUBLESLASH + restSBDevice.url() + request;
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400313 } else {
Michal Machbcd58c72017-06-19 17:12:34 +0200314 return restSBDevice.protocol() + COLON + DOUBLESLASH + restSBDevice.ip().toString()
315 + COLON + restSBDevice.port() + request;
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400316 }
317 }
318
319 private boolean checkReply(Response response) {
320 if (response != null) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200321 boolean statusCode = checkStatusCode(response.getStatus());
322 if (!statusCode && response.hasEntity()) {
323 log.error("Failed request, HTTP error msg : " + response.readEntity(String.class));
324 }
325 return statusCode;
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400326 }
327 log.error("Null reply from device");
328 return false;
329 }
330
331 private boolean checkStatusCode(int statusCode) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200332 if (statusCode == STATUS_OK || statusCode == STATUS_CREATED || statusCode == STATUS_ACCEPTED) {
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400333 return true;
334 } else {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200335 log.error("Failed request, HTTP error code : " + statusCode);
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400336 return false;
337 }
338 }
339
340 private Client ignoreSslClient() {
341 SSLContext sslcontext = null;
342
343 try {
344 sslcontext = SSLContext.getInstance("TLS");
345 sslcontext.init(null, new TrustManager[]{new X509TrustManager() {
346 public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
347 }
348
349 public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
350 }
351
352 public X509Certificate[] getAcceptedIssuers() {
353 return new X509Certificate[0];
354 }
355 } }, new java.security.SecureRandom());
356 } catch (NoSuchAlgorithmException | KeyManagementException e) {
357 e.printStackTrace();
358 }
359
360 return ClientBuilder.newBuilder().sslContext(sslcontext).hostnameVerifier((s1, s2) -> true).build();
361 }
Matteo Gerola7e180c22017-03-30 11:57:58 +0200362
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400363}