001
014
015 package com.liferay.portal.util;
016
017 import com.liferay.portal.json.JSONObjectImpl;
018 import com.liferay.portal.kernel.cluster.ClusterExecutorUtil;
019 import com.liferay.portal.kernel.cluster.ClusterNode;
020 import com.liferay.portal.kernel.cluster.ClusterNodeResponse;
021 import com.liferay.portal.kernel.cluster.ClusterNodeResponses;
022 import com.liferay.portal.kernel.cluster.ClusterRequest;
023 import com.liferay.portal.kernel.cluster.FutureClusterResponses;
024 import com.liferay.portal.kernel.json.JSONObject;
025 import com.liferay.portal.kernel.license.util.LicenseManagerUtil;
026 import com.liferay.portal.kernel.log.Log;
027 import com.liferay.portal.kernel.log.LogFactoryUtil;
028 import com.liferay.portal.kernel.util.ArrayUtil;
029 import com.liferay.portal.kernel.util.Base64;
030 import com.liferay.portal.kernel.util.CharPool;
031 import com.liferay.portal.kernel.util.ClassLoaderUtil;
032 import com.liferay.portal.kernel.util.Constants;
033 import com.liferay.portal.kernel.util.ContentTypes;
034 import com.liferay.portal.kernel.util.FileUtil;
035 import com.liferay.portal.kernel.util.GetterUtil;
036 import com.liferay.portal.kernel.util.Http;
037 import com.liferay.portal.kernel.util.MethodHandler;
038 import com.liferay.portal.kernel.util.MethodKey;
039 import com.liferay.portal.kernel.util.ParamUtil;
040 import com.liferay.portal.kernel.util.PortalUtil;
041 import com.liferay.portal.kernel.util.ReleaseInfo;
042 import com.liferay.portal.kernel.util.StringPool;
043 import com.liferay.portal.kernel.util.StringUtil;
044 import com.liferay.portal.kernel.util.Validator;
045 import com.liferay.util.Encryptor;
046
047 import java.io.File;
048 import java.io.InputStream;
049
050 import java.net.Inet4Address;
051 import java.net.InetAddress;
052 import java.net.NetworkInterface;
053 import java.net.URI;
054 import java.net.URL;
055
056 import java.security.Key;
057 import java.security.KeyFactory;
058 import java.security.PublicKey;
059 import java.security.SecureRandom;
060 import java.security.spec.X509EncodedKeySpec;
061
062 import java.util.Arrays;
063 import java.util.Collections;
064 import java.util.HashMap;
065 import java.util.HashSet;
066 import java.util.Iterator;
067 import java.util.List;
068 import java.util.Map;
069 import java.util.Set;
070 import java.util.TreeMap;
071 import java.util.concurrent.TimeUnit;
072
073 import javax.crypto.KeyGenerator;
074
075 import javax.servlet.http.HttpServletRequest;
076
077 import org.apache.commons.io.IOUtils;
078 import org.apache.http.HttpEntity;
079 import org.apache.http.HttpHost;
080 import org.apache.http.HttpResponse;
081 import org.apache.http.auth.AuthScope;
082 import org.apache.http.auth.UsernamePasswordCredentials;
083 import org.apache.http.client.CredentialsProvider;
084 import org.apache.http.client.HttpClient;
085 import org.apache.http.client.methods.HttpPost;
086 import org.apache.http.conn.HttpClientConnectionManager;
087 import org.apache.http.entity.ByteArrayEntity;
088 import org.apache.http.impl.client.BasicCredentialsProvider;
089 import org.apache.http.impl.client.HttpClientBuilder;
090 import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
091
092
095 public class LicenseUtil {
096
097 public static final String LICENSE_REPOSITORY_DIR =
098 PropsValues.LIFERAY_HOME.concat("/data/license");
099
100 public static final String LICENSE_SERVER_URL = GetterUtil.get(
101 PropsUtil.get("license.server.url"), "https:
102
103 public static Map<String, String> getClusterServerInfo(String clusterNodeId)
104 throws Exception {
105
106 ClusterNode localClusterNode =
107 ClusterExecutorUtil.getLocalClusterNode();
108
109 String localClusterNodeId = localClusterNode.getClusterNodeId();
110
111 if (clusterNodeId.equals(localClusterNodeId)) {
112 return getServerInfo();
113 }
114
115 List<ClusterNode> clusterNodes = ClusterExecutorUtil.getClusterNodes();
116
117 ClusterNode clusterNode = null;
118
119 for (ClusterNode curClusterNode : clusterNodes) {
120 String curClusterNodeId = curClusterNode.getClusterNodeId();
121
122 if (curClusterNodeId.equals(clusterNodeId)) {
123 clusterNode = curClusterNode;
124
125 break;
126 }
127 }
128
129 if (clusterNode == null) {
130 return null;
131 }
132
133 try {
134 ClusterRequest clusterRequest = ClusterRequest.createUnicastRequest(
135 _getServerInfoMethodHandler, clusterNodeId);
136
137 FutureClusterResponses futureClusterResponses =
138 ClusterExecutorUtil.execute(clusterRequest);
139
140 ClusterNodeResponses clusterNodeResponses =
141 futureClusterResponses.get(20000, TimeUnit.MILLISECONDS);
142
143 ClusterNodeResponse clusterNodeResponse =
144 clusterNodeResponses.getClusterResponse(
145 clusterNode.getClusterNodeId());
146
147 return (Map<String, String>)clusterNodeResponse.getResult();
148 }
149 catch (Exception e) {
150 _log.error(e, e);
151
152 throw e;
153 }
154 }
155
156
159 @Deprecated
160 public static String getHostName() {
161 return PortalUtil.getComputerName();
162 }
163
164 public static Set<String> getIpAddresses() {
165 if (_ipAddresses != null) {
166 return new HashSet<>(_ipAddresses);
167 }
168
169 _ipAddresses = new HashSet<>();
170
171 try {
172 List<NetworkInterface> networkInterfaces = Collections.list(
173 NetworkInterface.getNetworkInterfaces());
174
175 for (NetworkInterface networkInterface : networkInterfaces) {
176 List<InetAddress> inetAddresses = Collections.list(
177 networkInterface.getInetAddresses());
178
179 for (InetAddress inetAddress : inetAddresses) {
180 if (inetAddress.isLinkLocalAddress() ||
181 inetAddress.isLoopbackAddress() ||
182 !(inetAddress instanceof Inet4Address)) {
183
184 continue;
185 }
186
187 _ipAddresses.add(inetAddress.getHostAddress());
188 }
189 }
190 }
191 catch (Exception e) {
192 _log.error("Unable to read local server's IP addresses");
193
194 _log.error(e, e);
195 }
196
197 return new HashSet<>(_ipAddresses);
198 }
199
200 public static Set<String> getMacAddresses() {
201 if (_macAddresses != null) {
202 return new HashSet<>(_macAddresses);
203 }
204
205 _macAddresses = new HashSet<>();
206
207 try {
208 List<NetworkInterface> networkInterfaces = Collections.list(
209 NetworkInterface.getNetworkInterfaces());
210
211 for (NetworkInterface networkInterface : networkInterfaces) {
212 byte[] hardwareAddress = networkInterface.getHardwareAddress();
213
214 if (ArrayUtil.isEmpty(hardwareAddress)) {
215 continue;
216 }
217
218 StringBuilder sb = new StringBuilder(
219 (hardwareAddress.length * 3) - 1);
220
221 String hexString = StringUtil.bytesToHexString(hardwareAddress);
222
223 for (int i = 0; i < hexString.length(); i += 2) {
224 if (i != 0) {
225 sb.append(CharPool.COLON);
226 }
227
228 sb.append(Character.toLowerCase(hexString.charAt(i)));
229 sb.append(Character.toLowerCase(hexString.charAt(i + 1)));
230 }
231
232 _macAddresses.add(sb.toString());
233 }
234 }
235 catch (Exception e) {
236 _log.error("Unable to read local server's MAC addresses");
237
238 _log.error(e, e);
239 }
240
241 return new HashSet<>(_macAddresses);
242 }
243
244 public static byte[] getServerIdBytes() throws Exception {
245 if (_serverIdBytes != null) {
246 return _serverIdBytes;
247 }
248
249 File serverIdFile = new File(
250 LICENSE_REPOSITORY_DIR + "/server/serverId");
251
252 if (!serverIdFile.exists()) {
253 return new byte[0];
254 }
255
256 _serverIdBytes = FileUtil.getBytes(serverIdFile);
257
258 return _serverIdBytes;
259 }
260
261 public static Map<String, String> getServerInfo() {
262 Map<String, String> serverInfo = new HashMap<>();
263
264 serverInfo.put("hostName", PortalUtil.getComputerName());
265 serverInfo.put("ipAddresses", StringUtil.merge(getIpAddresses()));
266 serverInfo.put("macAddresses", StringUtil.merge(getMacAddresses()));
267
268 return serverInfo;
269 }
270
271 public static void registerOrder(HttpServletRequest request) {
272 String orderUuid = ParamUtil.getString(request, "orderUuid");
273 String productEntryName = ParamUtil.getString(
274 request, "productEntryName");
275 int maxServers = ParamUtil.getInteger(request, "maxServers");
276
277 List<ClusterNode> clusterNodes = ClusterExecutorUtil.getClusterNodes();
278
279 if ((clusterNodes.size() <= 1) || Validator.isNull(productEntryName) ||
280 Validator.isNull(orderUuid)) {
281
282 Map<String, Object> attributes = registerOrder(
283 orderUuid, productEntryName, maxServers);
284
285 for (Map.Entry<String, Object> entry : attributes.entrySet()) {
286 request.setAttribute(entry.getKey(), entry.getValue());
287 }
288 }
289 else {
290 for (ClusterNode clusterNode : clusterNodes) {
291 boolean register = ParamUtil.getBoolean(
292 request, clusterNode.getClusterNodeId() + "_register");
293
294 if (!register) {
295 continue;
296 }
297
298 try {
299 _registerClusterOrder(
300 request, clusterNode, orderUuid, productEntryName,
301 maxServers);
302 }
303 catch (Exception e) {
304 _log.error(e, e);
305
306 InetAddress inetAddress = clusterNode.getBindInetAddress();
307
308 String message =
309 "Error contacting " + inetAddress.getHostName();
310
311 if (clusterNode.getPortalPort() != -1) {
312 message +=
313 StringPool.COLON + clusterNode.getPortalPort();
314 }
315
316 request.setAttribute(
317 clusterNode.getClusterNodeId() + "_ERROR_MESSAGE",
318 message);
319 }
320 }
321 }
322 }
323
324 public static Map<String, Object> registerOrder(
325 String orderUuid, String productEntryName, int maxServers) {
326
327 Map<String, Object> attributes = new HashMap<>();
328
329 if (Validator.isNull(orderUuid)) {
330 return attributes;
331 }
332
333 try {
334 JSONObject jsonObject = _createRequest(
335 orderUuid, productEntryName, maxServers);
336
337 String response = sendRequest(jsonObject.toString());
338
339 JSONObject responseJSONObject = new JSONObjectImpl(response);
340
341 attributes.put(
342 "ORDER_PRODUCT_ID", responseJSONObject.getString("productId"));
343 attributes.put(
344 "ORDER_PRODUCTS", _getOrderProducts(responseJSONObject));
345
346 String errorMessage = responseJSONObject.getString("errorMessage");
347
348 if (Validator.isNotNull(errorMessage)) {
349 attributes.put("ERROR_MESSAGE", errorMessage);
350
351 return attributes;
352 }
353
354 String licenseXML = responseJSONObject.getString("licenseXML");
355
356 if (Validator.isNotNull(licenseXML)) {
357 LicenseManagerUtil.registerLicense(responseJSONObject);
358
359 attributes.clear();
360 attributes.put(
361 "SUCCESS_MESSAGE",
362 "Your license has been successfully registered.");
363 }
364 }
365 catch (Exception e) {
366 _log.error(e, e);
367
368 attributes.put(
369 "ERROR_MESSAGE",
370 "There was an error contacting " + LICENSE_SERVER_URL);
371 }
372
373 return attributes;
374 }
375
376 public static String sendRequest(String request) throws Exception {
377 HttpClient httpClient = null;
378
379 HttpClientConnectionManager httpClientConnectionManager =
380 new BasicHttpClientConnectionManager();
381
382 try {
383 HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
384
385 httpClientBuilder.setConnectionManager(httpClientConnectionManager);
386
387 String serverURL = LICENSE_SERVER_URL;
388
389 if (!serverURL.endsWith(StringPool.SLASH)) {
390 serverURL += StringPool.SLASH;
391 }
392
393 serverURL += "osb-portlet/license";
394
395 URI uri = new URI(serverURL);
396
397 HttpPost httpPost = new HttpPost(uri);
398
399 CredentialsProvider credentialsProvider =
400 new BasicCredentialsProvider();
401
402 HttpHost proxyHttpHost = null;
403
404 if (Validator.isNotNull(_PROXY_URL)) {
405 if (_log.isInfoEnabled()) {
406 _log.info(
407 "Using proxy " + _PROXY_URL + StringPool.COLON +
408 _PROXY_PORT);
409 }
410
411 proxyHttpHost = new HttpHost(_PROXY_URL, _PROXY_PORT);
412
413 if (Validator.isNotNull(_PROXY_USER_NAME)) {
414 credentialsProvider.setCredentials(
415 new AuthScope(_PROXY_URL, _PROXY_PORT),
416 new UsernamePasswordCredentials(
417 _PROXY_USER_NAME, _PROXY_PASSWORD));
418 }
419 }
420
421 httpClientBuilder.setDefaultCredentialsProvider(
422 credentialsProvider);
423 httpClientBuilder.setProxy(proxyHttpHost);
424
425 httpClient = httpClientBuilder.build();
426
427 ByteArrayEntity byteArrayEntity = new ByteArrayEntity(
428 _encryptRequest(serverURL, request));
429
430 byteArrayEntity.setContentType(ContentTypes.APPLICATION_JSON);
431
432 httpPost.setEntity(byteArrayEntity);
433
434 HttpResponse httpResponse = httpClient.execute(httpPost);
435
436 HttpEntity httpEntity = httpResponse.getEntity();
437
438 String response = _decryptResponse(
439 serverURL, httpEntity.getContent());
440
441 if (_log.isDebugEnabled()) {
442 _log.debug("Server response: " + response);
443 }
444
445 if (Validator.isNull(response)) {
446 throw new Exception("Server response is null");
447 }
448
449 return response;
450 }
451 finally {
452 if (httpClient != null) {
453 httpClientConnectionManager.shutdown();
454 }
455 }
456 }
457
458 public static void writeServerProperties(byte[] serverIdBytes)
459 throws Exception {
460
461 File serverIdFile = new File(
462 LICENSE_REPOSITORY_DIR + "/server/serverId");
463
464 FileUtil.write(serverIdFile, serverIdBytes);
465 }
466
467 private static JSONObject _createRequest(
468 String orderUuid, String productEntryName, int maxServers)
469 throws Exception {
470
471 JSONObject jsonObject = new JSONObjectImpl();
472
473 jsonObject.put("version", 1);
474 jsonObject.put("orderUuid", orderUuid);
475 jsonObject.put("liferayVersion", ReleaseInfo.getBuildNumber());
476
477 if (Validator.isNull(productEntryName)) {
478 jsonObject.put(Constants.CMD, "QUERY");
479 }
480 else {
481 jsonObject.put(Constants.CMD, "REGISTER");
482
483 if (productEntryName.startsWith("basic")) {
484 jsonObject.put("productEntryName", "basic");
485
486 if (productEntryName.equals("basic-cluster")) {
487 jsonObject.put("cluster", true);
488 jsonObject.put("maxServers", maxServers);
489 }
490 else if (productEntryName.startsWith("basic-")) {
491 String[] productNameArray = StringUtil.split(
492 productEntryName, StringPool.DASH);
493
494 if (productNameArray.length >= 3) {
495 jsonObject.put("offeringEntryId", productNameArray[1]);
496 jsonObject.put("clusterId", productNameArray[2]);
497 }
498 }
499 }
500 else {
501 jsonObject.put("productEntryName", productEntryName);
502 }
503
504 jsonObject.put("hostName", PortalUtil.getComputerName());
505 jsonObject.put("ipAddresses", StringUtil.merge(getIpAddresses()));
506 jsonObject.put("macAddresses", StringUtil.merge(getMacAddresses()));
507 jsonObject.put("serverId", com.liferay.portal.license.LicenseManager.getServerId());
508 }
509
510 return jsonObject;
511 }
512
513 private static String _decryptResponse(
514 String serverURL, InputStream inputStream)
515 throws Exception {
516
517 if (serverURL.startsWith(Http.HTTPS)) {
518 return StringUtil.read(inputStream);
519 }
520
521 byte[] bytes = IOUtils.toByteArray(inputStream);
522
523 if ((bytes == null) || (bytes.length <= 0)) {
524 return null;
525 }
526
527 bytes = Encryptor.decryptUnencodedAsBytes(_symmetricKey, bytes);
528
529 return new String(bytes, StringPool.UTF8);
530 }
531
532 private static byte[] _encryptRequest(String serverURL, String request)
533 throws Exception {
534
535 byte[] bytes = request.getBytes(StringPool.UTF8);
536
537 if (serverURL.startsWith(Http.HTTPS)) {
538 return bytes;
539 }
540
541 JSONObject jsonObject = new JSONObjectImpl();
542
543 bytes = Encryptor.encryptUnencoded(_symmetricKey, bytes);
544
545 jsonObject.put("content", Base64.objectToString(bytes));
546 jsonObject.put("key", _encryptedSymmetricKey);
547
548 return jsonObject.toString().getBytes(StringPool.UTF8);
549 }
550
551 private static Map<String, String> _getOrderProducts(
552 JSONObject jsonObject) {
553
554 JSONObject productsJSONObject = jsonObject.getJSONObject(
555 "productsJSONObject");
556
557 if (productsJSONObject == null) {
558 return null;
559 }
560
561 Map<String, String> sortedMap = new TreeMap<>(
562 String.CASE_INSENSITIVE_ORDER);
563
564 Iterator<String> itr = productsJSONObject.keys();
565
566 while (itr.hasNext()) {
567 String key = itr.next();
568
569 sortedMap.put(key, productsJSONObject.getString(key));
570 }
571
572 return sortedMap;
573 }
574
575 private static void _initKeys() {
576 ClassLoader classLoader = ClassLoaderUtil.getPortalClassLoader();
577
578 if ((classLoader == null) || (_encryptedSymmetricKey != null)) {
579 return;
580 }
581
582 try {
583 URL url = classLoader.getResource(
584 "com/liferay/portal/license/public.key");
585
586 byte[] bytes = IOUtils.toByteArray(url.openStream());
587
588 X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
589 bytes);
590
591 KeyFactory keyFactory = KeyFactory.getInstance("RSA");
592
593 PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
594
595 KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
596
597 keyGenerator.init(128, new SecureRandom());
598
599 _symmetricKey = keyGenerator.generateKey();
600
601 byte[] encryptedSymmetricKey = Encryptor.encryptUnencoded(
602 publicKey, _symmetricKey.getEncoded());
603
604 _encryptedSymmetricKey = Base64.objectToString(
605 encryptedSymmetricKey);
606 }
607 catch (Exception e) {
608 _log.error(e, e);
609 }
610 }
611
612 private static void _registerClusterOrder(
613 HttpServletRequest request, ClusterNode clusterNode,
614 String orderUuid, String productEntryName, int maxServers)
615 throws Exception {
616
617 MethodHandler methodHandler = new MethodHandler(
618 _registerOrderMethodKey, orderUuid, productEntryName, maxServers);
619
620 ClusterRequest clusterRequest = ClusterRequest.createUnicastRequest(
621 methodHandler, clusterNode.getClusterNodeId());
622
623 FutureClusterResponses futureClusterResponses =
624 ClusterExecutorUtil.execute(clusterRequest);
625
626 ClusterNodeResponses clusterNodeResponses = futureClusterResponses.get(
627 20000, TimeUnit.MILLISECONDS);
628
629 ClusterNodeResponse clusterNodeResponse =
630 clusterNodeResponses.getClusterResponse(
631 clusterNode.getClusterNodeId());
632
633 Map<String, Object> attributes =
634 (Map<String, Object>)clusterNodeResponse.getResult();
635
636 for (Map.Entry<String, Object> entry : attributes.entrySet()) {
637 request.setAttribute(
638 clusterNode.getClusterNodeId() + StringPool.UNDERLINE +
639 entry.getKey(),
640 entry.getValue());
641 }
642 }
643
644 private static final String _PROXY_PASSWORD = GetterUtil.getString(
645 PropsUtil.get("license.proxy.password"));
646
647 private static final int _PROXY_PORT = GetterUtil.getInteger(
648 PropsUtil.get("license.proxy.port"), 80);
649
650 private static final String _PROXY_URL = PropsUtil.get("license.proxy.url");
651
652 private static final String _PROXY_USER_NAME = GetterUtil.getString(
653 PropsUtil.get("license.proxy.username"));
654
655 private static final Log _log = LogFactoryUtil.getLog(LicenseUtil.class);
656
657 private static String _encryptedSymmetricKey;
658 private static final MethodHandler _getServerInfoMethodHandler =
659 new MethodHandler(new MethodKey(LicenseUtil.class, "getServerInfo"));
660 private static Set<String> _ipAddresses;
661 private static Set<String> _macAddresses;
662 private static final MethodKey _registerOrderMethodKey = new MethodKey(
663 LicenseUtil.class, "registerOrder", String.class, String.class,
664 int.class);
665 private static byte[] _serverIdBytes;
666 private static Key _symmetricKey;
667
668 static {
669 _initKeys();
670 }
671
672 }