blob: cf34a40b62d62c9eebc976f941b1fa5bd8313631 [file] [log] [blame]
Hesam Rahimi4a409b42016-08-12 18:37:33 -04001/*
2 * Copyright 2016-present Open Networking Laboratory
3 *
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
Matteo Gerola7e180c22017-03-30 11:57:58 +020019import java.io.ByteArrayInputStream;
20import java.io.IOException;
21import java.io.InputStream;
22import java.nio.charset.StandardCharsets;
23import java.security.KeyManagementException;
24import java.security.KeyStoreException;
25import java.security.NoSuchAlgorithmException;
26import java.security.cert.CertificateException;
27import java.security.cert.X509Certificate;
28import java.util.Base64;
29import java.util.Map;
30import java.util.concurrent.ConcurrentHashMap;
31
32import javax.net.ssl.SSLContext;
33import javax.net.ssl.TrustManager;
34import javax.net.ssl.X509TrustManager;
35import javax.ws.rs.client.Client;
36import javax.ws.rs.client.ClientBuilder;
37import javax.ws.rs.client.Entity;
38import javax.ws.rs.client.WebTarget;
39import javax.ws.rs.core.MediaType;
40import javax.ws.rs.core.Response;
41import javax.ws.rs.core.Response.Status;
42
Hesam Rahimi4a409b42016-08-12 18:37:33 -040043import org.apache.commons.io.IOUtils;
44import org.apache.http.client.methods.HttpPatch;
45import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
46import org.apache.http.entity.StringEntity;
47import org.apache.http.impl.client.CloseableHttpClient;
48import org.apache.http.impl.client.HttpClients;
49import org.apache.http.ssl.SSLContextBuilder;
50import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
51import org.onlab.packet.IpAddress;
52import org.onosproject.net.DeviceId;
53import org.onosproject.protocol.http.HttpSBController;
54import org.onosproject.protocol.rest.RestSBDevice;
55import org.slf4j.Logger;
56import org.slf4j.LoggerFactory;
57
Matteo Gerola7e180c22017-03-30 11:57:58 +020058import com.google.common.collect.ImmutableMap;
Hesam Rahimi4a409b42016-08-12 18:37:33 -040059
60/**
61 * The implementation of HttpSBController.
62 */
63public class HttpSBControllerImpl implements HttpSBController {
64
Matteo Gerola7e180c22017-03-30 11:57:58 +020065 private static final Logger log = LoggerFactory.getLogger(HttpSBControllerImpl.class);
Hesam Rahimi4a409b42016-08-12 18:37:33 -040066 private static final String XML = "xml";
67 private static final String JSON = "json";
Michele Santuaric372c222017-01-12 09:41:25 +010068 protected static final String DOUBLESLASH = "//";
69 protected static final String COLON = ":";
Hesam Rahimi4a409b42016-08-12 18:37:33 -040070 private static final int STATUS_OK = Response.Status.OK.getStatusCode();
71 private static final int STATUS_CREATED = Response.Status.CREATED.getStatusCode();
72 private static final int STATUS_ACCEPTED = Response.Status.ACCEPTED.getStatusCode();
73 private static final String HTTPS = "https";
74 private static final String AUTHORIZATION_PROPERTY = "authorization";
75 private static final String BASIC_AUTH_PREFIX = "Basic ";
76
77 private final Map<DeviceId, RestSBDevice> deviceMap = new ConcurrentHashMap<>();
78 private final Map<DeviceId, Client> clientMap = new ConcurrentHashMap<>();
79
80 public Map<DeviceId, RestSBDevice> getDeviceMap() {
81 return deviceMap;
82 }
83
84 public Map<DeviceId, Client> getClientMap() {
85 return clientMap;
86 }
87
88 @Override
89 public Map<DeviceId, RestSBDevice> getDevices() {
90 return ImmutableMap.copyOf(deviceMap);
91 }
92
93 @Override
94 public RestSBDevice getDevice(DeviceId deviceInfo) {
95 return deviceMap.get(deviceInfo);
96 }
97
98 @Override
99 public RestSBDevice getDevice(IpAddress ip, int port) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200100 return deviceMap.values().stream().filter(v -> v.ip().equals(ip) && v.port() == port).findFirst().get();
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400101 }
102
103 @Override
104 public void addDevice(RestSBDevice device) {
105 if (!deviceMap.containsKey(device.deviceId())) {
106 Client client = ignoreSslClient();
107 if (device.username() != null) {
108 String username = device.username();
109 String password = device.password() == null ? "" : device.password();
110 authenticate(client, username, password);
111 }
112 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
127 public boolean post(DeviceId device, String request, InputStream payload, String mediaType) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200128 return checkStatusCode(post(device, request, payload, typeOfMediaType(mediaType)));
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400129 }
130
131 @Override
Matteo Gerola7e180c22017-03-30 11:57:58 +0200132 public int post(DeviceId device, String request, InputStream payload, MediaType mediaType) {
133 Response response = getResponse(device, request, payload, mediaType);
134 if (response == null) {
135 return Status.NO_CONTENT.getStatusCode();
136 }
137 return response.getStatus();
138 }
139
140 @Override
141 public <T> T post(DeviceId device, String request, InputStream payload, String mediaType, Class<T> responseClass) {
142 return post(device, request, payload, typeOfMediaType(mediaType), responseClass);
143 }
144
145 @Override
146 public <T> T post(DeviceId device, String request, InputStream payload, MediaType mediaType,
147 Class<T> responseClass) {
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400148 Response response = getResponse(device, request, payload, mediaType);
149 if (response.hasEntity()) {
150 return response.readEntity(responseClass);
151 }
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 {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200163 response = wt.request(mediaType.getType())
164 .post(Entity.entity(IOUtils.toString(payload, StandardCharsets.UTF_8), mediaType.getType()));
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 {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200169 response = wt.request(mediaType.getType()).post(Entity.entity(null, mediaType.getType()));
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 {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200187 response = wt.request(mediaType.getType()).put(Entity.entity(IOUtils.
188 toString(payload, StandardCharsets.UTF_8), mediaType.getType()));
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 {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200193 response = wt.request(mediaType.getType()).put(Entity.entity(null, mediaType.getType()));
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
Matteo Gerola7e180c22017-03-30 11:57:58 +0200211 Response s = wt.request(mediaType.getType()).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));
Matteo Gerola7e180c22017-03-30 11:57:58 +0200238 input.setContentType(mediaType.getType());
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?
Matteo Gerola7e180c22017-03-30 11:57:58 +0200267 Response response = wt.request(mediaType.getType()).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;
278 default:
279 throw new IllegalArgumentException("Unsupported media type " + type);
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400280
281 }
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400282 }
283
284 private void authenticate(Client client, String username, String password) {
285 client.register(HttpAuthenticationFeature.basic(username, password));
286 }
287
288 protected WebTarget getWebTarget(DeviceId device, String request) {
289 log.debug("Sending request to URL {} ", getUrlString(device, request));
290 return clientMap.get(device).target(getUrlString(device, request));
291 }
292
293 //FIXME security issue: this trusts every SSL certificate, even if is self-signed. Also deprecated methods.
294 private CloseableHttpClient getApacheSslBypassClient() throws NoSuchAlgorithmException,
295 KeyManagementException, KeyStoreException {
296 return HttpClients.custom().
297 setHostnameVerifier(new AllowAllHostnameVerifier()).
298 setSslcontext(new SSLContextBuilder()
299 .loadTrustMaterial(null, (arg0, arg1) -> true)
300 .build()).build();
301 }
302
Michele Santuaric372c222017-01-12 09:41:25 +0100303 protected String getUrlString(DeviceId device, String request) {
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400304 if (deviceMap.get(device).url() != null) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200305 return deviceMap.get(device).protocol() + COLON + DOUBLESLASH + deviceMap.get(device).url() + request;
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400306 } else {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200307 return deviceMap.get(device).protocol() + COLON + DOUBLESLASH + deviceMap.get(device).ip().toString()
308 + COLON + deviceMap.get(device).port() + request;
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400309 }
310 }
311
312 private boolean checkReply(Response response) {
313 if (response != null) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200314 boolean statusCode = checkStatusCode(response.getStatus());
315 if (!statusCode && response.hasEntity()) {
316 log.error("Failed request, HTTP error msg : " + response.readEntity(String.class));
317 }
318 return statusCode;
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400319 }
320 log.error("Null reply from device");
321 return false;
322 }
323
324 private boolean checkStatusCode(int statusCode) {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200325 if (statusCode == STATUS_OK || statusCode == STATUS_CREATED || statusCode == STATUS_ACCEPTED) {
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400326 return true;
327 } else {
Matteo Gerola7e180c22017-03-30 11:57:58 +0200328 log.error("Failed request, HTTP error code : " + statusCode);
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400329 return false;
330 }
331 }
332
333 private Client ignoreSslClient() {
334 SSLContext sslcontext = null;
335
336 try {
337 sslcontext = SSLContext.getInstance("TLS");
338 sslcontext.init(null, new TrustManager[]{new X509TrustManager() {
339 public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
340 }
341
342 public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
343 }
344
345 public X509Certificate[] getAcceptedIssuers() {
346 return new X509Certificate[0];
347 }
348 } }, new java.security.SecureRandom());
349 } catch (NoSuchAlgorithmException | KeyManagementException e) {
350 e.printStackTrace();
351 }
352
353 return ClientBuilder.newBuilder().sslContext(sslcontext).hostnameVerifier((s1, s2) -> true).build();
354 }
Matteo Gerola7e180c22017-03-30 11:57:58 +0200355
Hesam Rahimi4a409b42016-08-12 18:37:33 -0400356}