blob: e8fcca0c49669684e680a0b8e51bb3150e02baad [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;
fahadnaeemkhan02ffa712017-12-01 19:49:45 -080028import org.glassfish.jersey.client.oauth2.OAuth2ClientSupport;
Hesam Rahimi4a409b42016-08-12 18:37:33 -040029import org.onlab.packet.IpAddress;
30import org.onosproject.net.DeviceId;
31import org.onosproject.protocol.http.HttpSBController;
32import org.onosproject.protocol.rest.RestSBDevice;
fahadnaeemkhan02ffa712017-12-01 19:49:45 -080033import org.onosproject.protocol.rest.RestSBDevice.AuthenticationScheme;
Hesam Rahimi4a409b42016-08-12 18:37:33 -040034import org.slf4j.Logger;
35import org.slf4j.LoggerFactory;
36
Michal Machbcd58c72017-06-19 17:12:34 +020037import javax.net.ssl.SSLContext;
38import javax.net.ssl.TrustManager;
39import javax.net.ssl.X509TrustManager;
Georgios Katsikas74a8a442018-06-26 09:23:58 +020040import javax.ws.rs.ProcessingException;
Michal Machbcd58c72017-06-19 17:12:34 +020041import javax.ws.rs.client.Client;
42import javax.ws.rs.client.ClientBuilder;
43import javax.ws.rs.client.Entity;
44import javax.ws.rs.client.WebTarget;
45import javax.ws.rs.core.MediaType;
46import javax.ws.rs.core.Response;
47import javax.ws.rs.core.Response.Status;
48import java.io.ByteArrayInputStream;
49import java.io.IOException;
50import java.io.InputStream;
51import java.nio.charset.StandardCharsets;
52import java.security.KeyManagementException;
53import java.security.KeyStoreException;
54import java.security.NoSuchAlgorithmException;
55import java.security.cert.CertificateException;
56import java.security.cert.X509Certificate;
57import java.util.Base64;
58import java.util.Map;
59import java.util.concurrent.ConcurrentHashMap;
Hesam Rahimi4a409b42016-08-12 18:37:33 -040060
fahadnaeemkhan02ffa712017-12-01 19:49:45 -080061import static com.google.common.base.Preconditions.checkNotNull;
62
Hesam Rahimi4a409b42016-08-12 18:37:33 -040063/**
64 * The implementation of HttpSBController.
65 */
66public class HttpSBControllerImpl implements HttpSBController {
67
Matteo Gerola7e180c22017-03-30 11:57:58 +020068 private static final Logger log = LoggerFactory.getLogger(HttpSBControllerImpl.class);
Hesam Rahimi4a409b42016-08-12 18:37:33 -040069 private static final String XML = "xml";
70 private static final String JSON = "json";
Michele Santuaric372c222017-01-12 09:41:25 +010071 protected static final String DOUBLESLASH = "//";
72 protected static final String COLON = ":";
Hesam Rahimi4a409b42016-08-12 18:37:33 -040073 private static final int STATUS_OK = Response.Status.OK.getStatusCode();
74 private static final int STATUS_CREATED = Response.Status.CREATED.getStatusCode();
75 private static final int STATUS_ACCEPTED = Response.Status.ACCEPTED.getStatusCode();
76 private static final String HTTPS = "https";
77 private static final String AUTHORIZATION_PROPERTY = "authorization";
78 private static final String BASIC_AUTH_PREFIX = "Basic ";
fahadnaeemkhan2675a272017-12-13 13:17:23 -080079 private static final String OAUTH2_BEARER_AUTH_PREFIX = "Bearer ";
Hesam Rahimi4a409b42016-08-12 18:37:33 -040080
81 private final Map<DeviceId, RestSBDevice> deviceMap = new ConcurrentHashMap<>();
82 private final Map<DeviceId, Client> clientMap = new ConcurrentHashMap<>();
83
84 public Map<DeviceId, RestSBDevice> getDeviceMap() {
85 return deviceMap;
86 }
87
88 public Map<DeviceId, Client> getClientMap() {
89 return clientMap;
90 }
91
92 @Override
93 public Map<DeviceId, RestSBDevice> getDevices() {
94 return ImmutableMap.copyOf(deviceMap);
95 }
96
97 @Override
98 public RestSBDevice getDevice(DeviceId deviceInfo) {
99 return deviceMap.get(deviceInfo);
100 }
101
102 @Override
103 public RestSBDevice getDevice(IpAddress ip, int port) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200104 return deviceMap.values().stream().filter(v -> v.ip().equals(ip) && v.port() == port).findFirst().get();
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400105 }
106
107 @Override
108 public void addDevice(RestSBDevice device) {
109 if (!deviceMap.containsKey(device.deviceId())) {
110 Client client = ignoreSslClient();
fahadnaeemkhan02ffa712017-12-01 19:49:45 -0800111 authenticate(client, device);
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400112 clientMap.put(device.deviceId(), client);
113 deviceMap.put(device.deviceId(), device);
114 } else {
115 log.warn("Trying to add a device that is already existing {}", device.deviceId());
116 }
117
118 }
119
120 @Override
121 public void removeDevice(DeviceId deviceId) {
122 clientMap.remove(deviceId);
123 deviceMap.remove(deviceId);
124 }
125
126 @Override
Matteo Gerola7e180c22017-03-30 11:57:58 +0200127 public int post(DeviceId device, String request, InputStream payload, MediaType mediaType) {
128 Response response = getResponse(device, request, payload, mediaType);
129 if (response == null) {
130 return Status.NO_CONTENT.getStatusCode();
131 }
132 return response.getStatus();
133 }
134
135 @Override
Matteo Gerola7e180c22017-03-30 11:57:58 +0200136 public <T> T post(DeviceId device, String request, InputStream payload, MediaType mediaType,
137 Class<T> responseClass) {
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400138 Response response = getResponse(device, request, payload, mediaType);
Palash Kalada4798d2017-05-23 20:16:55 +0900139 if (response != null && response.hasEntity()) {
Hesam Rahimi96305542017-06-07 13:59:48 -0400140 // Do not read the entity if the responseClass is of type Response. This would allow the
141 // caller to receive the Response directly and try to read its appropriate entity locally.
142 return responseClass == Response.class ? (T) response : response.readEntity(responseClass);
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400143 }
144 log.error("Response from device {} for request {} contains no entity", device, request);
145 return null;
146 }
147
Matteo Gerola7e180c22017-03-30 11:57:58 +0200148 private Response getResponse(DeviceId device, String request, InputStream payload, MediaType mediaType) {
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400149
150 WebTarget wt = getWebTarget(device, request);
151
152 Response response = null;
153 if (payload != null) {
154 try {
Eunjin Choi51244d32017-05-15 14:09:56 +0900155 response = wt.request(mediaType)
156 .post(Entity.entity(IOUtils.toString(payload, StandardCharsets.UTF_8), mediaType));
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400157 } catch (IOException e) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200158 log.error("Cannot do POST {} request on device {} because can't read payload", request, device);
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400159 }
160 } else {
Georgios Katsikas186b9582017-05-31 17:25:54 +0200161 response = wt.request(mediaType).post(Entity.entity(null, mediaType));
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400162 }
163 return response;
164 }
165
166 @Override
Matteo Gerola7e180c22017-03-30 11:57:58 +0200167 public int put(DeviceId device, String request, InputStream payload, MediaType mediaType) {
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400168
169 WebTarget wt = getWebTarget(device, request);
170
171 Response response = null;
172 if (payload != null) {
173 try {
Eunjin Choi51244d32017-05-15 14:09:56 +0900174 response = wt.request(mediaType).put(Entity.entity(IOUtils.
175 toString(payload, StandardCharsets.UTF_8), mediaType));
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400176 } catch (IOException e) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200177 log.error("Cannot do PUT {} request on device {} because can't read payload", request, device);
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400178 }
179 } else {
Eunjin Choi51244d32017-05-15 14:09:56 +0900180 response = wt.request(mediaType).put(Entity.entity(null, mediaType));
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400181 }
Matteo Gerola7e180c22017-03-30 11:57:58 +0200182
183 if (response == null) {
184 return Status.NO_CONTENT.getStatusCode();
185 }
186 return response.getStatus();
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400187 }
188
189 @Override
Matteo Gerola7e180c22017-03-30 11:57:58 +0200190 public InputStream get(DeviceId device, String request, MediaType mediaType) {
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400191 WebTarget wt = getWebTarget(device, request);
192
Eunjin Choi51244d32017-05-15 14:09:56 +0900193 Response s = wt.request(mediaType).get();
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400194
195 if (checkReply(s)) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200196 return new ByteArrayInputStream(s.readEntity((String.class)).getBytes(StandardCharsets.UTF_8));
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400197 }
198 return null;
199 }
200
201 @Override
Matteo Gerola7e180c22017-03-30 11:57:58 +0200202 public int patch(DeviceId device, String request, InputStream payload, MediaType mediaType) {
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400203
204 try {
205 log.debug("Url request {} ", getUrlString(device, request));
206 HttpPatch httprequest = new HttpPatch(getUrlString(device, request));
fahadnaeemkhan2675a272017-12-13 13:17:23 -0800207 if (deviceMap.get(device).authentication() == AuthenticationScheme.BASIC) {
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400208 String pwd = deviceMap.get(device).password() == null ? "" : COLON + deviceMap.get(device).password();
209 String userPassword = deviceMap.get(device).username() + pwd;
210 String base64string = Base64.getEncoder().encodeToString(userPassword.getBytes(StandardCharsets.UTF_8));
211 httprequest.addHeader(AUTHORIZATION_PROPERTY, BASIC_AUTH_PREFIX + base64string);
fahadnaeemkhan2675a272017-12-13 13:17:23 -0800212 } else if (deviceMap.get(device).authentication() == AuthenticationScheme.OAUTH2) {
213 String token = deviceMap.get(device).token();
214 // TODO: support token types other then bearer of OAuth2 authentication
215 httprequest.addHeader(AUTHORIZATION_PROPERTY, OAUTH2_BEARER_AUTH_PREFIX + token);
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400216 }
217 if (payload != null) {
218 StringEntity input = new StringEntity(IOUtils.toString(payload, StandardCharsets.UTF_8));
Eunjin Choi51244d32017-05-15 14:09:56 +0900219 input.setContentType(mediaType.toString());
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400220 httprequest.setEntity(input);
221 }
222 CloseableHttpClient httpClient;
223 if (deviceMap.containsKey(device) && deviceMap.get(device).protocol().equals(HTTPS)) {
224 httpClient = getApacheSslBypassClient();
225 } else {
226 httpClient = HttpClients.createDefault();
227 }
Matteo Gerola7e180c22017-03-30 11:57:58 +0200228 return httpClient.execute(httprequest).getStatusLine().getStatusCode();
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400229 } catch (IOException | NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200230 log.error("Cannot do PATCH {} request on device {}", request, device, e);
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400231 }
Matteo Gerola7e180c22017-03-30 11:57:58 +0200232 return Status.BAD_REQUEST.getStatusCode();
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400233 }
234
235 @Override
Matteo Gerola7e180c22017-03-30 11:57:58 +0200236 public int delete(DeviceId device, String request, InputStream payload, MediaType mediaType) {
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400237
238 WebTarget wt = getWebTarget(device, request);
239
Matteo Gerola7e180c22017-03-30 11:57:58 +0200240 // FIXME: do we need to delete an entry by enclosing data in DELETE
241 // request?
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400242 // wouldn't it be nice to use PUT to implement the similar concept?
Georgios Katsikas74a8a442018-06-26 09:23:58 +0200243 Response response = null;
244 try {
245 response = wt.request(mediaType).delete();
246 } catch (ProcessingException procEx) {
247 log.error("Cannot issue DELETE {} request on device {}", request, device);
248 return Status.SERVICE_UNAVAILABLE.getStatusCode();
249 }
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400250
Matteo Gerola7e180c22017-03-30 11:57:58 +0200251 return response.getStatus();
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400252 }
253
Matteo Gerola7e180c22017-03-30 11:57:58 +0200254 private MediaType typeOfMediaType(String type) {
255 switch (type) {
256 case XML:
257 return MediaType.APPLICATION_XML_TYPE;
258 case JSON:
259 return MediaType.APPLICATION_JSON_TYPE;
Michal Machf0ce45e2017-06-20 11:54:08 +0200260 case MediaType.WILDCARD:
261 return MediaType.WILDCARD_TYPE;
Matteo Gerola7e180c22017-03-30 11:57:58 +0200262 default:
263 throw new IllegalArgumentException("Unsupported media type " + type);
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400264
265 }
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400266 }
267
fahadnaeemkhan02ffa712017-12-01 19:49:45 -0800268 private void authenticate(Client client, RestSBDevice device) {
269 AuthenticationScheme authScheme = device.authentication();
270 if (authScheme == AuthenticationScheme.NO_AUTHENTICATION) {
271 log.debug("{} scheme is specified, ignoring authentication", authScheme);
272 return;
273 } else if (authScheme == AuthenticationScheme.OAUTH2) {
274 String token = checkNotNull(device.token());
275 client.register(OAuth2ClientSupport.feature(token));
276 } else if (authScheme == AuthenticationScheme.BASIC) {
277 String username = device.username();
278 String password = device.password() == null ? "" : device.password();
279 client.register(HttpAuthenticationFeature.basic(username, password));
280 } else {
281 // TODO: Add support for other authentication schemes here.
282 throw new IllegalArgumentException(String.format("Unsupported authentication scheme: %s",
283 authScheme.name()));
284 }
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400285 }
286
287 protected WebTarget getWebTarget(DeviceId device, String request) {
288 log.debug("Sending request to URL {} ", getUrlString(device, request));
289 return clientMap.get(device).target(getUrlString(device, request));
290 }
291
292 //FIXME security issue: this trusts every SSL certificate, even if is self-signed. Also deprecated methods.
293 private CloseableHttpClient getApacheSslBypassClient() throws NoSuchAlgorithmException,
294 KeyManagementException, KeyStoreException {
295 return HttpClients.custom().
296 setHostnameVerifier(new AllowAllHostnameVerifier()).
297 setSslcontext(new SSLContextBuilder()
298 .loadTrustMaterial(null, (arg0, arg1) -> true)
299 .build()).build();
300 }
301
Michal Machbcd58c72017-06-19 17:12:34 +0200302 protected String getUrlString(DeviceId deviceId, String request) {
303 RestSBDevice restSBDevice = deviceMap.get(deviceId);
304 if (restSBDevice == null) {
305 log.warn("restSbDevice cannot be NULL!");
306 return "";
307 }
308 if (restSBDevice.url() != null) {
309 return restSBDevice.protocol() + COLON + DOUBLESLASH + restSBDevice.url() + request;
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400310 } else {
Michal Machbcd58c72017-06-19 17:12:34 +0200311 return restSBDevice.protocol() + COLON + DOUBLESLASH + restSBDevice.ip().toString()
312 + COLON + restSBDevice.port() + request;
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400313 }
314 }
315
316 private boolean checkReply(Response response) {
317 if (response != null) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200318 boolean statusCode = checkStatusCode(response.getStatus());
319 if (!statusCode && response.hasEntity()) {
320 log.error("Failed request, HTTP error msg : " + response.readEntity(String.class));
321 }
322 return statusCode;
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400323 }
324 log.error("Null reply from device");
325 return false;
326 }
327
328 private boolean checkStatusCode(int statusCode) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200329 if (statusCode == STATUS_OK || statusCode == STATUS_CREATED || statusCode == STATUS_ACCEPTED) {
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400330 return true;
331 } else {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200332 log.error("Failed request, HTTP error code : " + statusCode);
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400333 return false;
334 }
335 }
336
337 private Client ignoreSslClient() {
338 SSLContext sslcontext = null;
339
340 try {
341 sslcontext = SSLContext.getInstance("TLS");
342 sslcontext.init(null, new TrustManager[]{new X509TrustManager() {
fahadnaeemkhan02ffa712017-12-01 19:49:45 -0800343 @Override
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400344 public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
345 }
346
fahadnaeemkhan02ffa712017-12-01 19:49:45 -0800347 @Override
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400348 public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
349 }
350
fahadnaeemkhan02ffa712017-12-01 19:49:45 -0800351 @Override
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400352 public X509Certificate[] getAcceptedIssuers() {
353 return new X509Certificate[0];
354 }
355 } }, new java.security.SecureRandom());
356 } catch (NoSuchAlgorithmException | KeyManagementException e) {
Ray Milkeyba547f92018-02-01 15:22:31 -0800357 throw new IllegalStateException(e);
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400358 }
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}