blob: 602d989da1ad0a96391b545d1c36dd401d2d301a [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;
40import javax.ws.rs.client.Client;
41import javax.ws.rs.client.ClientBuilder;
42import javax.ws.rs.client.Entity;
43import javax.ws.rs.client.WebTarget;
44import javax.ws.rs.core.MediaType;
45import javax.ws.rs.core.Response;
46import javax.ws.rs.core.Response.Status;
47import java.io.ByteArrayInputStream;
48import java.io.IOException;
49import java.io.InputStream;
50import java.nio.charset.StandardCharsets;
51import java.security.KeyManagementException;
52import java.security.KeyStoreException;
53import java.security.NoSuchAlgorithmException;
54import java.security.cert.CertificateException;
55import java.security.cert.X509Certificate;
56import java.util.Base64;
57import java.util.Map;
58import java.util.concurrent.ConcurrentHashMap;
Hesam Rahimi4a409b42016-08-12 18:37:33 -040059
fahadnaeemkhan02ffa712017-12-01 19:49:45 -080060import static com.google.common.base.Preconditions.checkNotNull;
61
Hesam Rahimi4a409b42016-08-12 18:37:33 -040062/**
63 * The implementation of HttpSBController.
64 */
65public class HttpSBControllerImpl implements HttpSBController {
66
Matteo Gerola7e180c22017-03-30 11:57:58 +020067 private static final Logger log = LoggerFactory.getLogger(HttpSBControllerImpl.class);
Hesam Rahimi4a409b42016-08-12 18:37:33 -040068 private static final String XML = "xml";
69 private static final String JSON = "json";
Michele Santuaric372c222017-01-12 09:41:25 +010070 protected static final String DOUBLESLASH = "//";
71 protected static final String COLON = ":";
Hesam Rahimi4a409b42016-08-12 18:37:33 -040072 private static final int STATUS_OK = Response.Status.OK.getStatusCode();
73 private static final int STATUS_CREATED = Response.Status.CREATED.getStatusCode();
74 private static final int STATUS_ACCEPTED = Response.Status.ACCEPTED.getStatusCode();
75 private static final String HTTPS = "https";
76 private static final String AUTHORIZATION_PROPERTY = "authorization";
77 private static final String BASIC_AUTH_PREFIX = "Basic ";
78
79 private final Map<DeviceId, RestSBDevice> deviceMap = new ConcurrentHashMap<>();
80 private final Map<DeviceId, Client> clientMap = new ConcurrentHashMap<>();
81
82 public Map<DeviceId, RestSBDevice> getDeviceMap() {
83 return deviceMap;
84 }
85
86 public Map<DeviceId, Client> getClientMap() {
87 return clientMap;
88 }
89
90 @Override
91 public Map<DeviceId, RestSBDevice> getDevices() {
92 return ImmutableMap.copyOf(deviceMap);
93 }
94
95 @Override
96 public RestSBDevice getDevice(DeviceId deviceInfo) {
97 return deviceMap.get(deviceInfo);
98 }
99
100 @Override
101 public RestSBDevice getDevice(IpAddress ip, int port) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200102 return deviceMap.values().stream().filter(v -> v.ip().equals(ip) && v.port() == port).findFirst().get();
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400103 }
104
105 @Override
106 public void addDevice(RestSBDevice device) {
107 if (!deviceMap.containsKey(device.deviceId())) {
108 Client client = ignoreSslClient();
fahadnaeemkhan02ffa712017-12-01 19:49:45 -0800109 authenticate(client, device);
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400110 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
fahadnaeemkhan02ffa712017-12-01 19:49:45 -0800286 private void authenticate(Client client, RestSBDevice device) {
287 AuthenticationScheme authScheme = device.authentication();
288 if (authScheme == AuthenticationScheme.NO_AUTHENTICATION) {
289 log.debug("{} scheme is specified, ignoring authentication", authScheme);
290 return;
291 } else if (authScheme == AuthenticationScheme.OAUTH2) {
292 String token = checkNotNull(device.token());
293 client.register(OAuth2ClientSupport.feature(token));
294 } else if (authScheme == AuthenticationScheme.BASIC) {
295 String username = device.username();
296 String password = device.password() == null ? "" : device.password();
297 client.register(HttpAuthenticationFeature.basic(username, password));
298 } else {
299 // TODO: Add support for other authentication schemes here.
300 throw new IllegalArgumentException(String.format("Unsupported authentication scheme: %s",
301 authScheme.name()));
302 }
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400303 }
304
305 protected WebTarget getWebTarget(DeviceId device, String request) {
306 log.debug("Sending request to URL {} ", getUrlString(device, request));
307 return clientMap.get(device).target(getUrlString(device, request));
308 }
309
310 //FIXME security issue: this trusts every SSL certificate, even if is self-signed. Also deprecated methods.
311 private CloseableHttpClient getApacheSslBypassClient() throws NoSuchAlgorithmException,
312 KeyManagementException, KeyStoreException {
313 return HttpClients.custom().
314 setHostnameVerifier(new AllowAllHostnameVerifier()).
315 setSslcontext(new SSLContextBuilder()
316 .loadTrustMaterial(null, (arg0, arg1) -> true)
317 .build()).build();
318 }
319
Michal Machbcd58c72017-06-19 17:12:34 +0200320 protected String getUrlString(DeviceId deviceId, String request) {
321 RestSBDevice restSBDevice = deviceMap.get(deviceId);
322 if (restSBDevice == null) {
323 log.warn("restSbDevice cannot be NULL!");
324 return "";
325 }
326 if (restSBDevice.url() != null) {
327 return restSBDevice.protocol() + COLON + DOUBLESLASH + restSBDevice.url() + request;
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400328 } else {
Michal Machbcd58c72017-06-19 17:12:34 +0200329 return restSBDevice.protocol() + COLON + DOUBLESLASH + restSBDevice.ip().toString()
330 + COLON + restSBDevice.port() + request;
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400331 }
332 }
333
334 private boolean checkReply(Response response) {
335 if (response != null) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200336 boolean statusCode = checkStatusCode(response.getStatus());
337 if (!statusCode && response.hasEntity()) {
338 log.error("Failed request, HTTP error msg : " + response.readEntity(String.class));
339 }
340 return statusCode;
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400341 }
342 log.error("Null reply from device");
343 return false;
344 }
345
346 private boolean checkStatusCode(int statusCode) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200347 if (statusCode == STATUS_OK || statusCode == STATUS_CREATED || statusCode == STATUS_ACCEPTED) {
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400348 return true;
349 } else {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200350 log.error("Failed request, HTTP error code : " + statusCode);
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400351 return false;
352 }
353 }
354
355 private Client ignoreSslClient() {
356 SSLContext sslcontext = null;
357
358 try {
359 sslcontext = SSLContext.getInstance("TLS");
360 sslcontext.init(null, new TrustManager[]{new X509TrustManager() {
fahadnaeemkhan02ffa712017-12-01 19:49:45 -0800361 @Override
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400362 public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
363 }
364
fahadnaeemkhan02ffa712017-12-01 19:49:45 -0800365 @Override
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400366 public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
367 }
368
fahadnaeemkhan02ffa712017-12-01 19:49:45 -0800369 @Override
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400370 public X509Certificate[] getAcceptedIssuers() {
371 return new X509Certificate[0];
372 }
373 } }, new java.security.SecureRandom());
374 } catch (NoSuchAlgorithmException | KeyManagementException e) {
375 e.printStackTrace();
376 }
377
378 return ClientBuilder.newBuilder().sslContext(sslcontext).hostnameVerifier((s1, s2) -> true).build();
379 }
Matteo Gerola7e180c22017-03-30 11:57:58 +0200380
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400381}