diff --git a/ad-connector/src/main/java/net/jami/jams/ad/connector/ADConnector.java b/ad-connector/src/main/java/net/jami/jams/ad/connector/ADConnector.java index 7511476c4a0508149df3cc3c973ed1850bc33aab..60d69108635ab4312b26d8e2b425ef554f1f80c2 100644 --- a/ad-connector/src/main/java/net/jami/jams/ad/connector/ADConnector.java +++ b/ad-connector/src/main/java/net/jami/jams/ad/connector/ADConnector.java @@ -25,7 +25,9 @@ package net.jami.jams.ad.connector; import com.imperva.ddc.core.query.Endpoint; import com.jsoniter.JsonIterator; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.ad.connector.service.AuthenticationService; import net.jami.jams.ad.connector.service.UserProfileService; import net.jami.jams.common.authentication.AuthenticationSource; @@ -67,7 +69,12 @@ public class ADConnector implements AuthenticationSource { while (endpoint == null) { endpoint = endpoints.poll(); } - endpoint.setUserAccountName(ADConnector.settings.getRealm() + "\\" + settings.getUsername()); //* You can use the user's Distinguished Name as well + endpoint.setUserAccountName( + ADConnector.settings.getRealm() + + "\\" + + settings + .getUsername()); // * You can use the user's Distinguished Name as + // well endpoint.setPassword(settings.getPassword()); return endpoint; } @@ -77,13 +84,17 @@ public class ADConnector implements AuthenticationSource { while (endpoint == null) { endpoint = endpoints.poll(); } - endpoint.setUserAccountName(ADConnector.settings.getRealm() + "\\" + username); //* You can use the user's Distinguished Name as well + endpoint.setUserAccountName( + ADConnector.settings.getRealm() + + "\\" + + username); // * You can use the user's Distinguished Name as well endpoint.setPassword(password); return endpoint; } public static void returnConnection(Endpoint connection) { - connection.setUserAccountName(ADConnector.settings.getRealm() + "\\" + settings.getUsername()); + connection.setUserAccountName( + ADConnector.settings.getRealm() + "\\" + settings.getUsername()); connection.setPassword(settings.getPassword()); endpoints.add(connection); } @@ -94,20 +105,22 @@ public class ADConnector implements AuthenticationSource { } @Override - public List<UserProfile> searchUserProfiles(String queryString, String field, Optional<Integer> page) { + public List<UserProfile> searchUserProfiles( + String queryString, String field, Optional<Integer> page) { return userProfileService.getUserProfile(queryString, field, false, page); } @Override public UserProfile getUserProfile(String username) { - List<UserProfile> result = userProfileService.getUserProfile(username, "LOGON_NAME",true, Optional.empty()); - if(result == null || result.size() != 1) return null; + List<UserProfile> result = + userProfileService.getUserProfile(username, "LOGON_NAME", true, Optional.empty()); + if (result == null || result.size() != 1) return null; return result.get(0); } @Override public boolean setUserProfile(UserProfile userProfile) { - //does nothing as we cannot edit user profiles. + // does nothing as we cannot edit user profiles. return false; } diff --git a/ad-connector/src/main/java/net/jami/jams/ad/connector/service/AuthenticationService.java b/ad-connector/src/main/java/net/jami/jams/ad/connector/service/AuthenticationService.java index 1d7fda3e9841a521b9b629c418c365a61670e660..7d65b72d71aabfdb98f6d25a611af17e99edb338 100644 --- a/ad-connector/src/main/java/net/jami/jams/ad/connector/service/AuthenticationService.java +++ b/ad-connector/src/main/java/net/jami/jams/ad/connector/service/AuthenticationService.java @@ -1,30 +1,31 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.ad.connector.service; import com.imperva.ddc.core.query.ConnectionResponse; import com.imperva.ddc.core.query.Endpoint; import com.imperva.ddc.service.DirectoryConnectorService; + import net.jami.jams.ad.connector.ADConnector; public class AuthenticationService { @@ -34,16 +35,13 @@ public class AuthenticationService { Endpoint endpoint = ADConnector.getConnection(username, password); try { - ConnectionResponse connectionResponse = DirectoryConnectorService.authenticate(endpoint); + ConnectionResponse connectionResponse = + DirectoryConnectorService.authenticate(endpoint); return !connectionResponse.isError(); - } - catch (Exception e){ + } catch (Exception e) { return false; - } - finally { + } finally { ADConnector.returnConnection(endpoint); } } - - } diff --git a/ad-connector/src/main/java/net/jami/jams/ad/connector/service/UserProfileService.java b/ad-connector/src/main/java/net/jami/jams/ad/connector/service/UserProfileService.java index 9a99d5aa9ee2a6b595a51384ed93b97dee250df0..1e1bf0d78d5f93e75d43daddcd9c8279faca79b7 100644 --- a/ad-connector/src/main/java/net/jami/jams/ad/connector/service/UserProfileService.java +++ b/ad-connector/src/main/java/net/jami/jams/ad/connector/service/UserProfileService.java @@ -23,6 +23,8 @@ package net.jami.jams.ad.connector.service; +import static net.jami.jams.server.Server.dataStore; + import com.imperva.ddc.core.Connector; import com.imperva.ddc.core.language.PhraseOperator; import com.imperva.ddc.core.language.QueryAssembler; @@ -36,7 +38,10 @@ import com.imperva.ddc.core.query.FieldType; import com.imperva.ddc.core.query.ObjectType; import com.imperva.ddc.core.query.QueryRequest; import com.imperva.ddc.core.query.QueryResponse; + import lombok.extern.slf4j.Slf4j; + +import net.jami.datastore.main.DataStore; import net.jami.jams.ad.connector.ADConnector; import net.jami.jams.common.dao.StatementElement; import net.jami.jams.common.dao.StatementList; @@ -46,35 +51,58 @@ import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; -import static net.jami.jams.server.Server.dataStore; - @Slf4j public class UserProfileService { - private static final ConcurrentHashMap<String, String> fieldMap = ADConnector.settings.getFieldMappings(); + private static final ConcurrentHashMap<String, String> fieldMap = + ADConnector.settings.getFieldMappings(); - public List<UserProfile> getUserProfile(String queryString, String field, boolean exactMatch, Optional<Integer> page) { + public List<UserProfile> getUserProfile( + String queryString, String field, boolean exactMatch, Optional<Integer> page) { Endpoint endpoint = ADConnector.getConnection(); try { QueryRequest queryRequest = buildRequest(endpoint); Sentence sentence = null; if (queryString.equals("*")) { - sentence = new QueryAssembler().addPhrase(FieldType.OBJECT_CLASS, PhraseOperator.EQUAL, ObjectType.USER.toString()).closeSentence(); + sentence = + new QueryAssembler() + .addPhrase( + FieldType.OBJECT_CLASS, + PhraseOperator.EQUAL, + ObjectType.USER.toString()) + .closeSentence(); } else { if (field.equals("LOGON_NAME")) { - if(exactMatch){ - sentence = new QueryAssembler().addPhrase(FieldType.LOGON_NAME, PhraseOperator.EQUAL, queryString) - .closeSentence(); - } - else { - sentence = new QueryAssembler().addPhrase(FieldType.LOGON_NAME, PhraseOperator.CONTAINS, queryString) - .closeSentence(); + if (exactMatch) { + sentence = + new QueryAssembler() + .addPhrase( + FieldType.LOGON_NAME, + PhraseOperator.EQUAL, + queryString) + .closeSentence(); + } else { + sentence = + new QueryAssembler() + .addPhrase( + FieldType.LOGON_NAME, + PhraseOperator.CONTAINS, + queryString) + .closeSentence(); } } if (field.equals("FULL_TEXT_NAME")) { - sentence = new QueryAssembler().addPhrase(FieldType.FIRST_NAME, PhraseOperator.CONTAINS, queryString) - .addPhrase(FieldType.LAST_NAME, PhraseOperator.CONTAINS, queryString) - .closeSentence(SentenceOperator.OR); + sentence = + new QueryAssembler() + .addPhrase( + FieldType.FIRST_NAME, + PhraseOperator.CONTAINS, + queryString) + .addPhrase( + FieldType.LAST_NAME, + PhraseOperator.CONTAINS, + queryString) + .closeSentence(SentenceOperator.OR); } } queryRequest.addSearchSentence(sentence); @@ -82,24 +110,34 @@ public class UserProfileService { try (Connector connector = new Connector(queryRequest)) { queryResponse = connector.execute(); } - List<List<Field>> results = queryResponse.getAll().stream().map(EntityResponse::getValue).collect(Collectors.toList()); + List<List<Field>> results = + queryResponse.getAll().stream() + .map(EntityResponse::getValue) + .collect(Collectors.toList()); - dataStore.NUM_PAGES = (Integer) results.size() / dataStore.RESULTS_PER_PAGE; - if (results.size() % dataStore.RESULTS_PER_PAGE != 0) - dataStore.NUM_PAGES++; + DataStore.NUM_PAGES = (Integer) results.size() / DataStore.RESULTS_PER_PAGE; + if (results.size() % DataStore.RESULTS_PER_PAGE != 0) DataStore.NUM_PAGES++; if (page.isPresent() && !results.isEmpty()) { - if (results.size() < dataStore.RESULTS_PER_PAGE) + if (results.size() < DataStore.RESULTS_PER_PAGE) results = results.subList(0, results.size()); - else if (page.get() * dataStore.RESULTS_PER_PAGE > results.size()) - results = results.subList((page.get()-1) * dataStore.RESULTS_PER_PAGE, results.size()); + else if (page.get() * DataStore.RESULTS_PER_PAGE > results.size()) + results = + results.subList( + (page.get() - 1) * DataStore.RESULTS_PER_PAGE, results.size()); else - results = results.subList((page.get()-1) * dataStore.RESULTS_PER_PAGE, (page.get() * dataStore.RESULTS_PER_PAGE)); + results = + results.subList( + (page.get() - 1) * DataStore.RESULTS_PER_PAGE, + (page.get() * DataStore.RESULTS_PER_PAGE)); } if (results.size() == 0) return new ArrayList<>(); - List<UserProfile> profilesFromResponse = results.stream().map(UserProfileService::profileFromResponse).collect(Collectors.toList()); - for (UserProfile p: profilesFromResponse) { + List<UserProfile> profilesFromResponse = + results.stream() + .map(UserProfileService::profileFromResponse) + .collect(Collectors.toList()); + for (UserProfile p : profilesFromResponse) { StatementList statementList = new StatementList(); StatementElement st = new StatementElement("username", "=", p.getUsername(), ""); statementList.addStatement(st); @@ -120,9 +158,12 @@ public class UserProfileService { public static QueryRequest buildRequest(Endpoint endpoint) { QueryRequest queryRequest = new QueryRequest(); queryRequest.setDirectoryType(DirectoryType.MS_ACTIVE_DIRECTORY); - queryRequest.setEndpoints(new ArrayList<>() {{ - add(endpoint); - }}); + queryRequest.setEndpoints( + new ArrayList<>() { + { + add(endpoint); + } + }); queryRequest.setSizeLimit(1000); queryRequest.setTimeLimit(1000); queryRequest.setObjectType(ObjectType.USER); @@ -133,30 +174,34 @@ public class UserProfileService { } public static UserProfile profileFromResponse(List<Field> fields) { - fieldMap.forEach((k, v) -> { - String temp = v; - fieldMap.put(k.toLowerCase(), temp); - }); - fieldMap.forEach((k, v) -> { - char[] charArray = k.toCharArray(); - for(int i=0; i < charArray.length; i++) { - if(Character.isUpperCase( charArray[i] )) { - fieldMap.remove(k); - break; - } - } - }); + fieldMap.forEach( + (k, v) -> { + String temp = v; + fieldMap.put(k.toLowerCase(), temp); + }); + fieldMap.forEach( + (k, v) -> { + char[] charArray = k.toCharArray(); + for (int i = 0; i < charArray.length; i++) { + if (Character.isUpperCase(charArray[i])) { + fieldMap.remove(k); + break; + } + } + }); try { UserProfile userProfile = new UserProfile(); for (Field field : fields) { if (fieldMap.containsKey(field.getName())) { - UserProfile.exposedMethods.get("set" + fieldMap.get(field.getName())).invoke(userProfile, field.getValue()); + UserProfile.exposedMethods + .get("set" + fieldMap.get(field.getName())) + .invoke(userProfile, field.getValue()); } } return userProfile; } catch (Exception e) { - log.error("An error occured while trying to invoke methods: " + e.toString()); + log.error("An error occured while trying to invoke methods: " + e); return null; } } diff --git a/authentication-module/src/main/java/net/jami/jams/authmodule/PasswordUtil.java b/authentication-module/src/main/java/net/jami/jams/authmodule/PasswordUtil.java index 759f80d2f5773d439cc3185c494fb3fdb9af012f..5b9ccdbf34d6771a2b6fdccf94d6051a9c5249e0 100644 --- a/authentication-module/src/main/java/net/jami/jams/authmodule/PasswordUtil.java +++ b/authentication-module/src/main/java/net/jami/jams/authmodule/PasswordUtil.java @@ -1,29 +1,28 @@ package net.jami.jams.authmodule; import lombok.extern.slf4j.Slf4j; + import org.bouncycastle.util.encoders.Hex; +import java.security.SecureRandom; + import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.SecureRandom; @Slf4j public class PasswordUtil { static SecureRandom random = new SecureRandom(); - public static String hashPassword(String password, byte[] salt){ + public static String hashPassword(String password, byte[] salt) { try { - SecretKeyFactory skf = SecretKeyFactory.getInstance( "PBKDF2WithHmacSHA512" ); + SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512"); PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 2048, 512); - SecretKey key = skf.generateSecret( spec ); + SecretKey key = skf.generateSecret(spec); byte[] res = key.getEncoded(); return new String(Hex.encode(res)); - } - catch (Exception e){ + } catch (Exception e) { log.info("An error occurred while attempting to hash a user password: ", e.toString()); return null; } @@ -34,6 +33,4 @@ public class PasswordUtil { random.nextBytes(salt); return salt; } - - } diff --git a/authentication-module/src/main/java/net/jami/jams/authmodule/RegisterUserFlow.java b/authentication-module/src/main/java/net/jami/jams/authmodule/RegisterUserFlow.java index 284770f7c79f388e191d07dcdd451a551293bfb8..aa0082814024a1fbcfc0b2e55e43f41f9d50a893 100644 --- a/authentication-module/src/main/java/net/jami/jams/authmodule/RegisterUserFlow.java +++ b/authentication-module/src/main/java/net/jami/jams/authmodule/RegisterUserFlow.java @@ -1,28 +1,32 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.authmodule; +import static net.jami.jams.authmodule.UserAuthenticationModule.certificateAuthority; +import static net.jami.jams.authmodule.UserAuthenticationModule.datastore; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.jami.NameRegistrationRequest; import net.jami.jams.common.jami.NameServer; import net.jami.jams.common.objects.roots.X509Fields; @@ -30,33 +34,33 @@ import net.jami.jams.common.objects.user.User; import net.jami.jams.dht.DeviceReceiptGenerator; import net.jami.jams.dht.ETHAddressGenerator; -import static net.jami.jams.authmodule.UserAuthenticationModule.certificateAuthority; -import static net.jami.jams.authmodule.UserAuthenticationModule.datastore; - @Slf4j public class RegisterUserFlow { - //Get the CA, sign, return the Jami ID. - public static boolean createUser(User user, NameServer nameServer){ - //This generates the X509 Fields we need. + // Get the CA, sign, return the Jami ID. + public static boolean createUser(User user, NameServer nameServer) { + // This generates the X509 Fields we need. user.setX509Fields(new X509Fields()); user.getX509Fields().setCommonName(user.getUsername()); user = certificateAuthority.getSignedCertificate(user); String[] ethKeyPair = null; - while(ethKeyPair == null){ + while (ethKeyPair == null) { ethKeyPair = ETHAddressGenerator.generateAddress(); } user.setEthAddress(ethKeyPair[0]); user.setEthKey(ethKeyPair[1]); user.setJamiId(DeviceReceiptGenerator.generateJamiId(user)); - //Didn't exactly plan on this happening here, but this is the only place we actually need it. - //Given an interface of NameServer, we need to enroll the user or decline the enrollment before - //storing him + // Didn't exactly plan on this happening here, but this is the only place we actually need + // it. + // Given an interface of NameServer, we need to enroll the user or decline the enrollment + // before + // storing him NameRegistrationRequest nameRegistrationRequest = new NameRegistrationRequest(); nameRegistrationRequest.setOwner(ethKeyPair[0]); nameRegistrationRequest.setAddr(user.getJamiId()); - if(nameServer != null && nameServer.registerName(user.getUsername(), nameRegistrationRequest ) != 200){ - return false; + if (nameServer != null + && nameServer.registerName(user.getUsername(), nameRegistrationRequest) != 200) { + return false; } datastore.getUserDao().storeObject(user); log.info("Created the user " + user.getUsername() + " because he did not exist before!"); diff --git a/authentication-module/src/main/java/net/jami/jams/authmodule/TokenController.java b/authentication-module/src/main/java/net/jami/jams/authmodule/TokenController.java index baac8d49e8c84346f169f29b7de211264d031848..27ee8f4184abb190413ef883a697ce132376e27a 100644 --- a/authentication-module/src/main/java/net/jami/jams/authmodule/TokenController.java +++ b/authentication-module/src/main/java/net/jami/jams/authmodule/TokenController.java @@ -1,33 +1,36 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.authmodule; +import static net.jami.jams.common.objects.user.AccessLevel.DEVICE; + import com.nimbusds.jose.JOSEObjectType; import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.JWSHeader; import com.nimbusds.jose.crypto.RSASSASigner; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.SignedJWT; + import net.jami.jams.common.authmodule.AuthTokenResponse; import net.jami.jams.common.objects.user.User; @@ -35,9 +38,7 @@ import java.security.PrivateKey; import java.util.Date; import java.util.UUID; -import static net.jami.jams.common.objects.user.AccessLevel.DEVICE; - -public class TokenController{ +public class TokenController { private static PrivateKey signingKey; @@ -47,42 +48,37 @@ public class TokenController{ public AuthTokenResponse getToken(User user, String deviceId) { AuthTokenResponse authTokenResponse = new AuthTokenResponse(); - JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build(); - JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder() - .issuer("JAMS") - .subject(user.getUsername()) - .audience("JAMS") - .claim("oneTimePassword",user.getNeedsPasswordReset()) - .expirationTime(new Date(System.currentTimeMillis() + 30*60*1000)) - .notBeforeTime(new Date(System.currentTimeMillis())) - .issueTime(new Date(System.currentTimeMillis())) - .jwtID(UUID.randomUUID().toString()); - if(deviceId != null){ - builder.claim("scope",DEVICE); - builder.claim("deviceId",deviceId); + JWSHeader jwsHeader = + new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build(); + JWTClaimsSet.Builder builder = + new JWTClaimsSet.Builder() + .issuer("JAMS") + .subject(user.getUsername()) + .audience("JAMS") + .claim("oneTimePassword", user.getNeedsPasswordReset()) + .expirationTime(new Date(System.currentTimeMillis() + 30 * 60 * 1000)) + .notBeforeTime(new Date(System.currentTimeMillis())) + .issueTime(new Date(System.currentTimeMillis())) + .jwtID(UUID.randomUUID().toString()); + if (deviceId != null) { + builder.claim("scope", DEVICE); + builder.claim("deviceId", deviceId); authTokenResponse.setScope(DEVICE); - } - else{ - builder.claim("scope",user.getAccessLevel()); + } else { + builder.claim("scope", user.getAccessLevel()); authTokenResponse.setScope(user.getAccessLevel()); } - JWTClaimsSet jwtClaims = builder.build(); + JWTClaimsSet jwtClaims = builder.build(); SignedJWT signedJWT = new SignedJWT(jwsHeader, jwtClaims); try { signedJWT.sign(new RSASSASigner(signingKey)); UserAuthenticationModule.datastore.getJwtDao().storeObject(signedJWT); authTokenResponse.setAccess_token(signedJWT.serialize()); - authTokenResponse.setExpires_in(30*60L); + authTokenResponse.setExpires_in(30 * 60L); authTokenResponse.setToken_type("Bearer"); return authTokenResponse; - } - catch (Exception e){ + } catch (Exception e) { return null; } } - - - - - } diff --git a/authentication-module/src/main/java/net/jami/jams/authmodule/UserAuthenticationModule.java b/authentication-module/src/main/java/net/jami/jams/authmodule/UserAuthenticationModule.java index d9200353660c5b1c9d9214c2dc44276a110f3856..89a515a4b0472341a996e672f3c34526708c6603 100644 --- a/authentication-module/src/main/java/net/jami/jams/authmodule/UserAuthenticationModule.java +++ b/authentication-module/src/main/java/net/jami/jams/authmodule/UserAuthenticationModule.java @@ -1,29 +1,31 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.authmodule; import com.nimbusds.jwt.SignedJWT; + import lombok.extern.slf4j.Slf4j; + import net.jami.datastore.main.DataStore; import net.jami.jams.common.authentication.AuthenticationSource; import net.jami.jams.common.authentication.AuthenticationSourceType; @@ -38,6 +40,7 @@ import net.jami.jams.common.objects.user.AccessLevel; import net.jami.jams.common.objects.user.User; import net.jami.jams.common.utils.LibraryLoader; import net.jami.jams.common.utils.X509Utils; + import org.apache.commons.codec.binary.Base64; import org.bouncycastle.cert.X509CRLHolder; @@ -54,52 +57,58 @@ import java.security.cert.X509Certificate; import java.security.interfaces.RSAPublicKey; import java.util.concurrent.ConcurrentHashMap; - @Slf4j public class UserAuthenticationModule implements AuthenticationModule { - //This contains the DOMAIN-SOURCE. - //In general there is at most 2 here. - private final static String LDAP_CONNECTOR_CLASS = "net.jami.jams.ldap.connector.LDAPConnector"; - private final static String AD_CONNECTOR_CLASS = "net.jami.jams.ad.connector.ADConnector"; + // This contains the DOMAIN-SOURCE. + // In general there is at most 2 here. + private static final String LDAP_CONNECTOR_CLASS = "net.jami.jams.ldap.connector.LDAPConnector"; + private static final String AD_CONNECTOR_CLASS = "net.jami.jams.ad.connector.ADConnector"; public static DataStore datastore; public static CertificateAuthority certificateAuthority; private final TokenController tokenController; private PrivateKey privateKey = null; private PublicKey publicKey = null; - //The data storage layer for tokens. + // The data storage layer for tokens. - private final ConcurrentHashMap<AuthModuleKey, AuthenticationSource> authenticationSources = new ConcurrentHashMap<>(); + private final ConcurrentHashMap<AuthModuleKey, AuthenticationSource> authenticationSources = + new ConcurrentHashMap<>(); - public UserAuthenticationModule(DataStore dataStore, CertificateAuthority certificateAuthority) throws Exception{ + public UserAuthenticationModule(DataStore dataStore, CertificateAuthority certificateAuthority) + throws Exception { UserAuthenticationModule.datastore = dataStore; UserAuthenticationModule.certificateAuthority = certificateAuthority; - authenticationSources.put(new AuthModuleKey("LOCAL",AuthenticationSourceType.LOCAL),datastore); + authenticationSources.put( + new AuthModuleKey("LOCAL", AuthenticationSourceType.LOCAL), datastore); log.info("Started authentication module - default local source is already enabled!"); File pubkeyFile = new File(System.getProperty("user.dir") + File.separator + "oauth.pub"); - File privateKeyFile = new File(System.getProperty("user.dir") + File.separator + "oauth.key"); + File privateKeyFile = + new File(System.getProperty("user.dir") + File.separator + "oauth.key"); - if(!privateKeyFile.exists() || !pubkeyFile.exists()){ + if (!privateKeyFile.exists() || !pubkeyFile.exists()) { log.info("Generating first time private/public keys for OAuth!"); KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(4096); KeyPair kp = keyPairGenerator.generateKeyPair(); privateKey = kp.getPrivate(); publicKey = kp.getPublic(); - //Store these to file. + // Store these to file. OutputStream os; - os = new FileOutputStream(System.getProperty("user.dir") + File.separator + "oauth.key"); + os = + new FileOutputStream( + System.getProperty("user.dir") + File.separator + "oauth.key"); os.write(X509Utils.getPEMStringFromPrivateKey(privateKey).getBytes()); os.flush(); os.close(); log.info("Succesfully stored OAuth private key for future use..."); - os = new FileOutputStream(System.getProperty("user.dir") + File.separator + "oauth.pub"); + os = + new FileOutputStream( + System.getProperty("user.dir") + File.separator + "oauth.pub"); os.write(X509Utils.getPEMStringFromPubKey(publicKey).getBytes()); os.flush(); os.close(); log.info("Succesfully stored OAuth public key for future use..."); - } - else{ + } else { InputStream privateInput = new FileInputStream(privateKeyFile); privateKey = X509Utils.getKeyFromPEMString(new String(privateInput.readAllBytes())); privateInput.close(); @@ -110,29 +119,39 @@ public class UserAuthenticationModule implements AuthenticationModule { publicInput.close(); log.info("Succesfully loaded OAuth public key!"); } - //TODO: Read signing key, if file does not exist create it (also create the corresponding public key) + // TODO: Read signing key, if file does not exist create it (also create the corresponding + // public key) tokenController = new TokenController(privateKey); - //Also expose the public key programatically. + // Also expose the public key programatically. log.info("OAuth2 Token System instantiated succesfully!"); } @Override public void attachAuthSource(AuthenticationSourceType type, String settings) { - switch (type){ - case AD: loadAuthConnector(AD_CONNECTOR_CLASS,settings); break; - case LDAP: loadAuthConnector(LDAP_CONNECTOR_CLASS,settings); break; - default: break; + switch (type) { + case AD: + loadAuthConnector(AD_CONNECTOR_CLASS, settings); + break; + case LDAP: + loadAuthConnector(LDAP_CONNECTOR_CLASS, settings); + break; + default: + break; } } - private void loadAuthConnector(String className, String settings){ + private void loadAuthConnector(String className, String settings) { try { Class<?> cls = LibraryLoader.classLoader.loadClass(className); - AuthenticationSource source = (AuthenticationSource) cls.getConstructor(String.class).newInstance(settings); - authenticationSources.put(new AuthModuleKey(source.getInfo().getRealm(),source.getInfo().getAuthenticationSourceType()), source); - } - catch (Exception e){ - log.error("Could not load connector " + className + " with reason: " + e.toString()); + AuthenticationSource source = + (AuthenticationSource) cls.getConstructor(String.class).newInstance(settings); + authenticationSources.put( + new AuthModuleKey( + source.getInfo().getRealm(), + source.getInfo().getAuthenticationSourceType()), + source); + } catch (Exception e) { + log.error("Could not load connector " + className + " with reason: " + e); } } @@ -140,64 +159,71 @@ public class UserAuthenticationModule implements AuthenticationModule { public AuthTokenResponse authenticateUser(String username, String password) { AuthTokenResponse res = null; String hashPass = ""; - if(datastore.userExists(username)){ + if (datastore.userExists(username)) { StatementList statementList = new StatementList(); - StatementElement statementElement = new StatementElement("username","=",username,""); + StatementElement statementElement = new StatementElement("username", "=", username, ""); statementList.addStatement(statementElement); User user = datastore.getUserDao().getObjects(statementList).get(0); - if((user.getUserType() == AuthenticationSourceType.LOCAL)) hashPass = PasswordUtil.hashPassword(password, Base64.decodeBase64(user.getSalt())); + if ((user.getUserType() == AuthenticationSourceType.LOCAL)) + hashPass = PasswordUtil.hashPassword(password, Base64.decodeBase64(user.getSalt())); else hashPass = password; - if(hashPass != null && authenticationSources.get(new AuthModuleKey(user.getRealm(),user.getUserType())) - .authenticate(username,hashPass)) - return tokenController.getToken(user,null); + if (hashPass != null + && authenticationSources + .get(new AuthModuleKey(user.getRealm(), user.getUserType())) + .authenticate(username, hashPass)) + return tokenController.getToken(user, null); } - //The second case is much more violent, because we don't know in advance "where" this user comes - //from, so we have to infer (this is only really true for "users", all others are usually pre-marked) - //This is also the case when we store the user into the DAO - because he never existed before. - for(AuthModuleKey key : authenticationSources.keySet()){ - if(authenticationSources.get(key).authenticate(username,password)){ + // The second case is much more violent, because we don't know in advance "where" this user + // comes + // from, so we have to infer (this is only really true for "users", all others are usually + // pre-marked) + // This is also the case when we store the user into the DAO - because he never existed + // before. + for (AuthModuleKey key : authenticationSources.keySet()) { + if (authenticationSources.get(key).authenticate(username, password)) { User user = new User(); user.setUsername(username); user.setAccessLevel(AccessLevel.USER); user.setRealm(key.getRealm()); user.setUserType(key.getType()); - //This is legal with a null ONLY because in this case there is no relation with a external server. - RegisterUserFlow.createUser(user,null); - return tokenController.getToken(user,null); + // This is legal with a null ONLY because in this case there is no relation with a + // external server. + RegisterUserFlow.createUser(user, null); + return tokenController.getToken(user, null); } } return res; } @Override - public AuthTokenResponse authenticateUser(X509Certificate[] certificates, X509CRLHolder crl, - X509Certificate ca) { - //Extract the username for the certificate and verify that it is not revoked. + public AuthTokenResponse authenticateUser( + X509Certificate[] certificates, X509CRLHolder crl, X509Certificate ca) { + // Extract the username for the certificate and verify that it is not revoked. X509Certificate clientCert = certificates[1]; X509Certificate deviceCert = certificates[0]; try { - //Check if the certificate is even valid. + // Check if the certificate is even valid. clientCert.checkValidity(); - //Check if the certificate was provided by a valid authority. + // Check if the certificate was provided by a valid authority. clientCert.verify(ca.getPublicKey()); - //Here we need to make a request to the CRL to find out if it has been revoked. - if(crl.getRevokedCertificate(clientCert.getSerialNumber()) != null) return null; + // Here we need to make a request to the CRL to find out if it has been revoked. + if (crl.getRevokedCertificate(clientCert.getSerialNumber()) != null) return null; String username = X509Utils.extractDNFromCertificate(clientCert).get("CN"); - //We need to extract the deviceId from the certificate + // We need to extract the deviceId from the certificate StatementList statementList = new StatementList(); - StatementElement statementElement = new StatementElement("username","=",username,""); + StatementElement statementElement = new StatementElement("username", "=", username, ""); statementList.addStatement(statementElement); User user = datastore.getUserDao().getObjects(statementList).get(0); - return tokenController.getToken(user,X509Utils.extractDNFromCertificate(deviceCert).get("UID")); - } - catch (Exception e){ + return tokenController.getToken( + user, X509Utils.extractDNFromCertificate(deviceCert).get("UID")); + } catch (Exception e) { return null; } } @Override - public ConcurrentHashMap<AuthModuleKey, AuthenticationSource> getAuthSources(){ + public ConcurrentHashMap<AuthModuleKey, AuthenticationSource> getAuthSources() { return authenticationSources; } @@ -208,21 +234,24 @@ public class UserAuthenticationModule implements AuthenticationModule { if (type.equals(AuthenticationSourceType.AD)) className = AD_CONNECTOR_CLASS; if (type.equals(AuthenticationSourceType.LDAP)) className = LDAP_CONNECTOR_CLASS; Class<?> cls = LibraryLoader.classLoader.loadClass(className); - AuthenticationSource source = (AuthenticationSource) cls.getConstructor(String.class).newInstance(settings); + AuthenticationSource source = + (AuthenticationSource) cls.getConstructor(String.class).newInstance(settings); return source.test(); - } - catch (Exception e){ - log.error("The testing of the source was unsuccessful: " + e.toString()); + } catch (Exception e) { + log.error("The testing of the source was unsuccessful: " + e); return false; } } @Override - public boolean createUser(AuthenticationSourceType type, String realm, NameServer nameServer, User user) { - //This concept doesn't exist for LDAP or AD or any other hosted directory, in this case we simply run - //very theoretically, we should allow LDAP to publish to the public registry, but this is a lot - //more complex. - return RegisterUserFlow.createUser(user,nameServer); + public boolean createUser( + AuthenticationSourceType type, String realm, NameServer nameServer, User user) { + // This concept doesn't exist for LDAP or AD or any other hosted directory, in this case we + // simply run + // very theoretically, we should allow LDAP to publish to the public registry, but this is a + // lot + // more complex. + return RegisterUserFlow.createUser(user, nameServer); } @Override @@ -232,9 +261,9 @@ public class UserAuthenticationModule implements AuthenticationModule { @Override public char[] getOTP(String username) { - if(datastore.userExists(username)){ + if (datastore.userExists(username)) { StatementList statementList = new StatementList(); - StatementElement statementElement = new StatementElement("username","=",username,""); + StatementElement statementElement = new StatementElement("username", "=", username, ""); statementList.addStatement(statementElement); User user = datastore.getUserDao().getObjects(statementList).get(0); return (user.getPassword()).toCharArray(); @@ -248,7 +277,5 @@ public class UserAuthenticationModule implements AuthenticationModule { } @Override - public void deleteToken(SignedJWT token) { - - } + public void deleteToken(SignedJWT token) {} } diff --git a/datastore/src/main/java/net/jami/datastore/dao/AbstractDao.java b/datastore/src/main/java/net/jami/datastore/dao/AbstractDao.java index 9ca1769c68f5b69fee9a8d0bf43fa1d5525e966e..0e7f88265b66f1e135465cb5dad5cfe34a797e8d 100644 --- a/datastore/src/main/java/net/jami/datastore/dao/AbstractDao.java +++ b/datastore/src/main/java/net/jami/datastore/dao/AbstractDao.java @@ -1,30 +1,31 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.datastore.dao; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; + import net.jami.datastore.main.DataStore; import net.jami.jams.common.dao.DeleteStatementBuilder; import net.jami.jams.common.dao.SelectStatementBuilder; @@ -41,83 +42,77 @@ import java.util.List; @Slf4j public abstract class AbstractDao<T> { - @Getter @Setter - private String tableName; - @Getter @Setter - private Class<T> tClass; + @Getter @Setter private String tableName; + @Getter @Setter private Class<T> tClass; public abstract boolean storeObject(T object); - public List<T> getObjects(StatementList constraints){ + public List<T> getObjects(StatementList constraints) { List<T> result = new ArrayList<>(); SQLConnection connection = DataStore.connectionPool.getConnection(); - try{ - PreparedStatement ps = SelectStatementBuilder.buildStatement(tableName,constraints,null,connection); + try { + PreparedStatement ps = + SelectStatementBuilder.buildStatement(tableName, constraints, null, connection); ResultSet rs = ps.executeQuery(); - while(rs.next()){ + while (rs.next()) { result.add(tClass.getConstructor(ResultSet.class).newInstance(rs)); } return result; - } - catch (Exception e){ - log.error("An error has occurred while trying to fetch an object: " + e.toString()); + } catch (Exception e) { + log.error("An error has occurred while trying to fetch an object: " + e); return null; - } - finally { + } finally { DataStore.connectionPool.returnConnection(connection); } } - - public List<T> getObjects(StatementList constraints,StatementConstraints statementConstraints){ + public List<T> getObjects( + StatementList constraints, StatementConstraints statementConstraints) { List<T> result = new ArrayList<>(); SQLConnection connection = DataStore.connectionPool.getConnection(); - try{ - PreparedStatement ps = SelectStatementBuilder.buildStatement(tableName,constraints,statementConstraints,connection); + try { + PreparedStatement ps = + SelectStatementBuilder.buildStatement( + tableName, constraints, statementConstraints, connection); ResultSet rs = ps.executeQuery(); - while(rs.next()){ + while (rs.next()) { result.add(tClass.getConstructor(ResultSet.class).newInstance(rs)); } return result; - } - catch (Exception e){ - log.error("An error has occurred while trying to fetch a device: " + e.toString()); + } catch (Exception e) { + log.error("An error has occurred while trying to fetch a device: " + e); return null; - } - finally { + } finally { DataStore.connectionPool.returnConnection(connection); } } - - public boolean updateObject(StatementList update, StatementList constraints){ + public boolean updateObject(StatementList update, StatementList constraints) { SQLConnection connection = DataStore.connectionPool.getConnection(); - try{ - PreparedStatement ps = UpdateStatementBuilder.buildStatement(tableName,update,constraints,connection); + try { + PreparedStatement ps = + UpdateStatementBuilder.buildStatement( + tableName, update, constraints, connection); return ps.execute(); - } - catch (Exception e){ - log.error("An error has occurred while trying to fetch a device: " + e.toString()); + } catch (Exception e) { + log.error("An error has occurred while trying to fetch a device: " + e); return false; - } - finally { + } finally { DataStore.connectionPool.returnConnection(connection); } } - public boolean deleteObject(StatementList delete){ + public boolean deleteObject(StatementList delete) { SQLConnection connection = DataStore.connectionPool.getConnection(); - try{ - PreparedStatement ps = DeleteStatementBuilder.buildStatement(tableName,delete,connection); + try { + PreparedStatement ps = + DeleteStatementBuilder.buildStatement(tableName, delete, connection); return ps.executeUpdate() != 0; - } - catch (Exception e){ - log.error("An error has occurred while trying to fetch a device: " + e.toString()); + } catch (Exception e) { + log.error("An error has occurred while trying to fetch a device: " + e); return false; - } - finally { + } finally { DataStore.connectionPool.returnConnection(connection); } } - } diff --git a/datastore/src/main/java/net/jami/datastore/dao/ContactDao.java b/datastore/src/main/java/net/jami/datastore/dao/ContactDao.java index c429f5e1b81f241396a79d8c84d7b59b3b211614..63e839c46be4ea2f491283120afae9edafdf5985 100644 --- a/datastore/src/main/java/net/jami/datastore/dao/ContactDao.java +++ b/datastore/src/main/java/net/jami/datastore/dao/ContactDao.java @@ -24,6 +24,7 @@ package net.jami.datastore.dao; import lombok.extern.slf4j.Slf4j; + import net.jami.datastore.main.DataStore; import net.jami.jams.common.dao.StatementList; import net.jami.jams.common.dao.connectivity.SQLConnection; @@ -41,13 +42,14 @@ public class ContactDao extends AbstractDao<Contact> { this.setTClass(Contact.class); } - //Not used because the strategy here is different. + // Not used because the strategy here is different. @Override public boolean storeObject(Contact object) { SQLConnection connection = DataStore.connectionPool.getConnection(); try { - String insert = "INSERT INTO contacts (owner, uri, displayName, `timestamp`, status) VALUES " + - "(?, ?, ?, ?, ?)"; + String insert = + "INSERT INTO contacts (owner, uri, displayName, `timestamp`, status) VALUES " + + "(?, ?, ?, ?, ?)"; PreparedStatement ps = connection.getConnection().prepareStatement(insert); object.getInsert(ps); ps.executeQuery(); @@ -67,8 +69,9 @@ public class ContactDao extends AbstractDao<Contact> { PreparedStatement ps = connection.getConnection().prepareStatement(delete); ps.setString(1, contactList.get(0).getOwner()); ps.executeUpdate(); - String insert = "INSERT INTO contacts (owner, uri, displayName, timestamp, status, banned, confirmed, conversationId) VALUES " + - "(?, ?, ?, ?, ?, ?, ?, ?)"; + String insert = + "INSERT INTO contacts (owner, uri, displayName, timestamp, status, banned, confirmed, conversationId) VALUES " + + "(?, ?, ?, ?, ?, ?, ?, ?)"; for (Contact contact : contactList) { ps = connection.getConnection().prepareStatement(insert); contact.getInsert(ps); @@ -76,7 +79,7 @@ public class ContactDao extends AbstractDao<Contact> { } return true; } catch (Exception e) { - log.error("Could not update contacts: {}",e.getMessage()); + log.error("Could not update contacts: {}", e.getMessage()); return false; } finally { DataStore.connectionPool.returnConnection(connection); @@ -88,12 +91,15 @@ public class ContactDao extends AbstractDao<Contact> { SQLConnection connection = DataStore.connectionPool.getConnection(); try { - PreparedStatement ps = connection.getConnection().prepareStatement("DELETE FROM contacts WHERE owner = ? AND uri = ?"); + PreparedStatement ps = + connection + .getConnection() + .prepareStatement("DELETE FROM contacts WHERE owner = ? AND uri = ?"); ps.setString(1, constraints.getStatements().get(0).getValue()); ps.setString(2, constraints.getStatements().get(1).getValue()); return ps.executeUpdate() != 0; - } catch (SQLException e){ - log.error("Could not delete contact: " + e.toString()); + } catch (SQLException e) { + log.error("Could not delete contact: " + e); return false; } finally { DataStore.connectionPool.returnConnection(connection); diff --git a/datastore/src/main/java/net/jami/datastore/dao/DeviceDao.java b/datastore/src/main/java/net/jami/datastore/dao/DeviceDao.java index 8b2ff85b67578408fdf86558f9f6fb048c170c30..fb1310820a206016a9dad4087542247262f50c01 100644 --- a/datastore/src/main/java/net/jami/datastore/dao/DeviceDao.java +++ b/datastore/src/main/java/net/jami/datastore/dao/DeviceDao.java @@ -24,6 +24,7 @@ package net.jami.datastore.dao; import lombok.extern.slf4j.Slf4j; + import net.jami.datastore.main.DataStore; import net.jami.jams.common.dao.StatementList; import net.jami.jams.common.dao.connectivity.SQLConnection; @@ -43,14 +44,18 @@ public class DeviceDao extends AbstractDao<Device> { public boolean storeObject(Device object) { SQLConnection connection = DataStore.connectionPool.getConnection(); try { - PreparedStatement ps = connection.getConnection().prepareStatement("INSERT INTO devices " + - "(deviceId, owner, displayName, certificate, privatekey) " + - "VALUES " + - "(?, ?, ?, ?, ?)"); + PreparedStatement ps = + connection + .getConnection() + .prepareStatement( + "INSERT INTO devices " + + "(deviceId, owner, displayName, certificate, privatekey) " + + "VALUES " + + "(?, ?, ?, ?, ?)"); ps = object.getInsert(ps); return ps.executeUpdate() != 0; } catch (Exception e) { - log.error("An error has occurred while trying to store a user: " + e.toString()); + log.error("An error has occurred while trying to store a user: " + e); return false; } finally { DataStore.connectionPool.returnConnection(connection); @@ -66,13 +71,17 @@ public class DeviceDao extends AbstractDao<Device> { SQLConnection connection = DataStore.connectionPool.getConnection(); try { - PreparedStatement ps = connection.getConnection().prepareStatement("UPDATE devices SET displayName = ? WHERE owner = ? AND deviceId = ?"); + PreparedStatement ps = + connection + .getConnection() + .prepareStatement( + "UPDATE devices SET displayName = ? WHERE owner = ? AND deviceId = ?"); ps.setString(1, deviceName); ps.setString(2, user); ps.setString(3, deviceId); return ps.executeUpdate() != 0; } catch (Exception e) { - log.error("An error has occurred while trying to update a user: " + e.toString()); + log.error("An error has occurred while trying to update a user: " + e); return false; } finally { DataStore.connectionPool.returnConnection(connection); diff --git a/datastore/src/main/java/net/jami/datastore/dao/GroupDao.java b/datastore/src/main/java/net/jami/datastore/dao/GroupDao.java index 045136c89bac0c790a8ac83c9bf4f366cef8f8fd..301b00973ac2cb45ce0e2cee3fc8668d8d9daec6 100644 --- a/datastore/src/main/java/net/jami/datastore/dao/GroupDao.java +++ b/datastore/src/main/java/net/jami/datastore/dao/GroupDao.java @@ -1,6 +1,7 @@ package net.jami.datastore.dao; import lombok.extern.slf4j.Slf4j; + import net.jami.datastore.main.DataStore; import net.jami.jams.common.dao.StatementList; import net.jami.jams.common.dao.connectivity.SQLConnection; @@ -10,7 +11,7 @@ import java.sql.PreparedStatement; import java.sql.SQLException; @Slf4j -public class GroupDao extends AbstractDao<Group>{ +public class GroupDao extends AbstractDao<Group> { public GroupDao() { this.setTableName("groups"); @@ -20,17 +21,19 @@ public class GroupDao extends AbstractDao<Group>{ @Override public boolean storeObject(Group object) { SQLConnection connection = DataStore.connectionPool.getConnection(); - try{ - PreparedStatement ps = connection.getConnection().prepareStatement("INSERT INTO groups " + - "(id, name, blueprint) VALUES (?, ?, ?)"); + try { + PreparedStatement ps = + connection + .getConnection() + .prepareStatement( + "INSERT INTO groups " + + "(id, name, blueprint) VALUES (?, ?, ?)"); ps = object.getInsert(ps); return ps.executeUpdate() != 0; - } - catch (SQLException e){ - log.error("An error has occurred while trying to store a group: " + e.toString()); + } catch (SQLException e) { + log.error("An error has occurred while trying to store a group: " + e); return false; - } - finally { + } finally { DataStore.connectionPool.returnConnection(connection); } } @@ -44,18 +47,20 @@ public class GroupDao extends AbstractDao<Group>{ SQLConnection connection = DataStore.connectionPool.getConnection(); - try{ - PreparedStatement ps = connection.getConnection().prepareStatement("UPDATE groups SET name = ?, blueprint = ? WHERE id = ?"); + try { + PreparedStatement ps = + connection + .getConnection() + .prepareStatement( + "UPDATE groups SET name = ?, blueprint = ? WHERE id = ?"); ps.setString(1, name); ps.setString(2, blueprint); ps.setString(3, id); return ps.executeUpdate() != 0; - } - catch (SQLException e){ - log.error("An error has occurred while trying to update a group: " + e.toString()); + } catch (SQLException e) { + log.error("An error has occurred while trying to update a group: " + e); return false; - } - finally { + } finally { DataStore.connectionPool.returnConnection(connection); } } @@ -67,15 +72,15 @@ public class GroupDao extends AbstractDao<Group>{ SQLConnection connection = DataStore.connectionPool.getConnection(); try { - PreparedStatement ps = connection.getConnection().prepareStatement("DELETE FROM groups WHERE id = ?"); + PreparedStatement ps = + connection.getConnection().prepareStatement("DELETE FROM groups WHERE id = ?"); ps.setString(1, id); return ps.executeUpdate() != 0; - } catch (SQLException e){ - log.error("An error has occurred while trying to delete a group: " + e.toString()); + } catch (SQLException e) { + log.error("An error has occurred while trying to delete a group: " + e); return false; } finally { DataStore.connectionPool.returnConnection(connection); } } - } diff --git a/datastore/src/main/java/net/jami/datastore/dao/JwtDao.java b/datastore/src/main/java/net/jami/datastore/dao/JwtDao.java index 33b0b0b72802a973cbf3995fe2201a45a59995db..b22ce1d55c1e978f401bae1e28ba21a261c77d6f 100644 --- a/datastore/src/main/java/net/jami/datastore/dao/JwtDao.java +++ b/datastore/src/main/java/net/jami/datastore/dao/JwtDao.java @@ -24,7 +24,9 @@ package net.jami.datastore.dao; import com.nimbusds.jwt.SignedJWT; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.dao.StatementList; import java.util.List; @@ -32,8 +34,10 @@ import java.util.List; @Slf4j public class JwtDao extends AbstractDao<SignedJWT> { - private static final String SQL_STORE_TOKEN = "INSERT INTO tokens (userid,deviceId,token) VALUES (?,?,?)"; - private static final String SQL_DELETE_TOKEN = "DELETE FROM tokens WHERE userid = ? AND deviceId = ?"; + private static final String SQL_STORE_TOKEN = + "INSERT INTO tokens (userid,deviceId,token) VALUES (?,?,?)"; + private static final String SQL_DELETE_TOKEN = + "DELETE FROM tokens WHERE userid = ? AND deviceId = ?"; private static final String SQL_GET_TOKEN = "SELECT COUNT(token) FROM tokens WHERE token = ?"; public JwtDao() { @@ -43,23 +47,23 @@ public class JwtDao extends AbstractDao<SignedJWT> { @Override public boolean storeObject(SignedJWT object) { - //TODO: Implement this. + // TODO: Implement this. return true; } public boolean validateToken(SignedJWT signedJWT) { - //TODO: Implement this. + // TODO: Implement this. return true; } - //This method is not needed because we are only concerned with the existence of a token, - //we never actually look them up. + // This method is not needed because we are only concerned with the existence of a token, + // we never actually look them up. @Override public List<SignedJWT> getObjects(StatementList constraints) { return null; } - //TODO: Implement this method. + // TODO: Implement this method. @Override public boolean deleteObject(StatementList delete) { return false; diff --git a/datastore/src/main/java/net/jami/datastore/dao/PolicyDao.java b/datastore/src/main/java/net/jami/datastore/dao/PolicyDao.java index 247182325f5f325e59a4ae6ebfbcef71baf48e02..f26411982b8d41af47baa7a5e7c59303299774e1 100644 --- a/datastore/src/main/java/net/jami/datastore/dao/PolicyDao.java +++ b/datastore/src/main/java/net/jami/datastore/dao/PolicyDao.java @@ -1,6 +1,7 @@ package net.jami.datastore.dao; import lombok.extern.slf4j.Slf4j; + import net.jami.datastore.main.DataStore; import net.jami.jams.common.dao.StatementList; import net.jami.jams.common.dao.connectivity.SQLConnection; @@ -21,12 +22,15 @@ public class PolicyDao extends AbstractDao<Policy> { public boolean storeObject(Policy object) { SQLConnection connection = DataStore.connectionPool.getConnection(); try { - PreparedStatement ps = connection.getConnection().prepareStatement("INSERT INTO policies " + - "(name, policyData) VALUES (?, ?)"); + PreparedStatement ps = + connection + .getConnection() + .prepareStatement( + "INSERT INTO policies " + "(name, policyData) VALUES (?, ?)"); ps = object.getInsert(ps); return ps.executeUpdate() != 0; } catch (Exception e) { - log.error("An error has occurred while trying to store a blueprint: " + e.toString()); + log.error("An error has occurred while trying to store a blueprint: " + e); return false; } finally { DataStore.connectionPool.returnConnection(connection); @@ -42,13 +46,17 @@ public class PolicyDao extends AbstractDao<Policy> { SQLConnection connection = DataStore.connectionPool.getConnection(); try { - PreparedStatement ps = connection.getConnection().prepareStatement("UPDATE policies SET name = ?, policyData = ? WHERE name = ?"); + PreparedStatement ps = + connection + .getConnection() + .prepareStatement( + "UPDATE policies SET name = ?, policyData = ? WHERE name = ?"); ps.setString(1, name); ps.setString(2, policyData); ps.setString(3, oldName); return ps.executeUpdate() != 0; } catch (Exception e) { - log.error("An error has occurred while trying to update a blueprint: " + e.toString()); + log.error("An error has occurred while trying to update a blueprint: " + e); return false; } finally { DataStore.connectionPool.returnConnection(connection); @@ -62,11 +70,14 @@ public class PolicyDao extends AbstractDao<Policy> { SQLConnection connection = DataStore.connectionPool.getConnection(); try { - PreparedStatement ps = connection.getConnection().prepareStatement("DELETE FROM policies WHERE name = ?"); + PreparedStatement ps = + connection + .getConnection() + .prepareStatement("DELETE FROM policies WHERE name = ?"); ps.setString(1, name); return ps.executeUpdate() != 0; - } catch (SQLException e){ - log.error("An error has occurred while trying to delete a blueprint: " + e.toString()); + } catch (SQLException e) { + log.error("An error has occurred while trying to delete a blueprint: " + e); return false; } finally { DataStore.connectionPool.returnConnection(connection); diff --git a/datastore/src/main/java/net/jami/datastore/dao/SystemDao.java b/datastore/src/main/java/net/jami/datastore/dao/SystemDao.java index 65f7d7b88d74828bff93ce2b361625a7aa3e09ba..6babcfc935048b87a476c8fbbef57059ae8ff661 100644 --- a/datastore/src/main/java/net/jami/datastore/dao/SystemDao.java +++ b/datastore/src/main/java/net/jami/datastore/dao/SystemDao.java @@ -24,6 +24,7 @@ package net.jami.datastore.dao; import lombok.extern.slf4j.Slf4j; + import net.jami.datastore.main.DataStore; import net.jami.jams.common.dao.StatementList; import net.jami.jams.common.dao.connectivity.SQLConnection; @@ -43,14 +44,18 @@ public class SystemDao extends AbstractDao<SystemAccount> { public boolean storeObject(SystemAccount object) { SQLConnection connection = DataStore.connectionPool.getConnection(); try { - PreparedStatement ps = connection.getConnection().prepareStatement("INSERT INTO system " + - "(entity,certificate,privatekey)" + - "VALUES " + - "(?, ?, ?)"); + PreparedStatement ps = + connection + .getConnection() + .prepareStatement( + "INSERT INTO system " + + "(entity,certificate,privatekey)" + + "VALUES " + + "(?, ?, ?)"); ps = object.getInsert(ps); return ps.executeUpdate() != 0; } catch (Exception e) { - log.error("An error has occurred while trying to store a system entity: " + e.toString()); + log.error("An error has occurred while trying to store a system entity: " + e); return false; } finally { DataStore.connectionPool.returnConnection(connection); diff --git a/datastore/src/main/java/net/jami/datastore/dao/UserDao.java b/datastore/src/main/java/net/jami/datastore/dao/UserDao.java index 8b9cd045cb9053ea212e8d98ff6331b29da6388b..6be8ca590e777ec6d754b805ca4bebb14546a20d 100644 --- a/datastore/src/main/java/net/jami/datastore/dao/UserDao.java +++ b/datastore/src/main/java/net/jami/datastore/dao/UserDao.java @@ -24,14 +24,13 @@ package net.jami.datastore.dao; import lombok.extern.slf4j.Slf4j; + import net.jami.datastore.main.DataStore; import net.jami.jams.common.dao.StatementList; import net.jami.jams.common.dao.connectivity.SQLConnection; import net.jami.jams.common.objects.user.User; -import java.security.cert.Certificate; import java.sql.PreparedStatement; -import java.util.Objects; @Slf4j public class UserDao extends AbstractDao<User> { @@ -45,13 +44,18 @@ public class UserDao extends AbstractDao<User> { public boolean storeObject(User object) { SQLConnection connection = DataStore.connectionPool.getConnection(); try { - PreparedStatement ps = connection.getConnection().prepareStatement("INSERT INTO users " + - "(username, password, userType, realm, ethAddress, ethKey, jamiId,certificate, privatekey, accessLevel, needsPasswordReset, salt) " + - " VALUES " + "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); + PreparedStatement ps = + connection + .getConnection() + .prepareStatement( + "INSERT INTO users " + + "(username, password, userType, realm, ethAddress, ethKey, jamiId,certificate, privatekey, accessLevel, needsPasswordReset, salt) " + + " VALUES " + + "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); ps = object.getInsert(ps); return ps.executeUpdate() != 0; } catch (Exception e) { - log.error("An error has occurred while trying to store a user: " + e.toString()); + log.error("An error has occurred while trying to store a user: " + e); return false; } finally { DataStore.connectionPool.returnConnection(connection); @@ -59,18 +63,22 @@ public class UserDao extends AbstractDao<User> { } public boolean updateUserCertificate(String username, String certificate) { - SQLConnection connection = DataStore.connectionPool.getConnection(); - try { - PreparedStatement ps = connection.getConnection().prepareStatement("UPDATE users SET certificate = ? WHERE username = ?"); - ps.setString(1, certificate); - ps.setString(2, username); - return ps.executeUpdate() != 0; - } catch (Exception e) { - log.error("An error has occurred while trying to update a user certificate: " + e.toString()); - return false; - } finally { - DataStore.connectionPool.returnConnection(connection); - } + SQLConnection connection = DataStore.connectionPool.getConnection(); + try { + PreparedStatement ps = + connection + .getConnection() + .prepareStatement( + "UPDATE users SET certificate = ? WHERE username = ?"); + ps.setString(1, certificate); + ps.setString(2, username); + return ps.executeUpdate() != 0; + } catch (Exception e) { + log.error("An error has occurred while trying to update a user certificate: " + e); + return false; + } finally { + DataStore.connectionPool.returnConnection(connection); + } } @Override @@ -78,22 +86,25 @@ public class UserDao extends AbstractDao<User> { String pw = update.getStatements().get(0).getValue(); String salt = ""; - if (update.getStatements().size() > 1) - salt = update.getStatements().get(1).getValue(); + if (update.getStatements().size() > 1) salt = update.getStatements().get(1).getValue(); String user = constraints.getStatements().get(0).getValue(); SQLConnection connection = DataStore.connectionPool.getConnection(); try { - PreparedStatement ps = connection.getConnection().prepareStatement("UPDATE users SET password = ?, salt = ? WHERE username = ?"); + PreparedStatement ps = + connection + .getConnection() + .prepareStatement( + "UPDATE users SET password = ?, salt = ? WHERE username = ?"); ps.setString(1, pw); ps.setString(2, salt); ps.setString(3, user); return ps.executeUpdate() != 0; } catch (Exception e) { - log.error("An error has occurred while trying to update a user: " + e.toString()); + log.error("An error has occurred while trying to update a user: " + e); return false; } finally { DataStore.connectionPool.returnConnection(connection); diff --git a/datastore/src/main/java/net/jami/datastore/dao/UserGroupMappingsDao.java b/datastore/src/main/java/net/jami/datastore/dao/UserGroupMappingsDao.java index c58b31aa1cfc694e794c18195c59bdb36ebdc107..98afdfcbcb8eeeeaf3c7f0cff9f33396815013d9 100644 --- a/datastore/src/main/java/net/jami/datastore/dao/UserGroupMappingsDao.java +++ b/datastore/src/main/java/net/jami/datastore/dao/UserGroupMappingsDao.java @@ -1,6 +1,7 @@ package net.jami.datastore.dao; import lombok.extern.slf4j.Slf4j; + import net.jami.datastore.main.DataStore; import net.jami.jams.common.dao.StatementList; import net.jami.jams.common.dao.connectivity.SQLConnection; @@ -10,7 +11,7 @@ import java.sql.PreparedStatement; import java.sql.SQLException; @Slf4j -public class UserGroupMappingsDao extends AbstractDao<UserGroupMapping>{ +public class UserGroupMappingsDao extends AbstractDao<UserGroupMapping> { public UserGroupMappingsDao() { this.setTableName("usergroupmappings"); @@ -22,12 +23,18 @@ public class UserGroupMappingsDao extends AbstractDao<UserGroupMapping>{ SQLConnection connection = DataStore.connectionPool.getConnection(); try { - PreparedStatement ps = connection.getConnection().prepareStatement("INSERT INTO usergroupmappings " + - "(username, groupId)" + " VALUES " + "(?,?)"); + PreparedStatement ps = + connection + .getConnection() + .prepareStatement( + "INSERT INTO usergroupmappings " + + "(username, groupId)" + + " VALUES " + + "(?,?)"); ps = object.getInsert(ps); return ps.executeUpdate() != 0; } catch (Exception e) { - log.error("An error has occurred while trying to store a user profile: " + e.toString()); + log.error("An error has occurred while trying to store a user profile: " + e); return false; } finally { DataStore.connectionPool.returnConnection(connection); @@ -42,23 +49,29 @@ public class UserGroupMappingsDao extends AbstractDao<UserGroupMapping>{ SQLConnection connection = DataStore.connectionPool.getConnection(); try { - if(username.equals("*")){ - PreparedStatement ps = connection.getConnection().prepareStatement("DELETE FROM usergroupmappings WHERE groupId = ?"); + if (username.equals("*")) { + PreparedStatement ps = + connection + .getConnection() + .prepareStatement( + "DELETE FROM usergroupmappings WHERE groupId = ?"); ps.setString(1, groupId); return ps.executeUpdate() != 0; - } - else { - PreparedStatement ps = connection.getConnection().prepareStatement("DELETE FROM usergroupmappings WHERE username = ? AND groupId = ?"); + } else { + PreparedStatement ps = + connection + .getConnection() + .prepareStatement( + "DELETE FROM usergroupmappings WHERE username = ? AND groupId = ?"); ps.setString(1, username); ps.setString(2, groupId); return ps.executeUpdate() != 0; } - } catch (SQLException e){ - log.error("An error has occurred while trying to delete a group member: " + e.toString()); + } catch (SQLException e) { + log.error("An error has occurred while trying to delete a group member: " + e); return false; } finally { DataStore.connectionPool.returnConnection(connection); } } - } diff --git a/datastore/src/main/java/net/jami/datastore/dao/UserProfileDao.java b/datastore/src/main/java/net/jami/datastore/dao/UserProfileDao.java index 7fa7a52e4e1489f464f6a026576aba2264e7ad2c..fd025a6347bd26ec3a40a60a0b53d2a59012134b 100644 --- a/datastore/src/main/java/net/jami/datastore/dao/UserProfileDao.java +++ b/datastore/src/main/java/net/jami/datastore/dao/UserProfileDao.java @@ -24,6 +24,7 @@ package net.jami.datastore.dao; import lombok.extern.slf4j.Slf4j; + import net.jami.datastore.main.DataStore; import net.jami.jams.common.dao.StatementList; import net.jami.jams.common.dao.connectivity.SQLConnection; @@ -34,7 +35,7 @@ import java.sql.PreparedStatement; @Slf4j public class UserProfileDao extends AbstractDao<UserProfile> { - //Fis this to include the fields from AD/LDAP. + // Fis this to include the fields from AD/LDAP. public UserProfileDao() { this.setTableName("local_directory"); this.setTClass(UserProfile.class); @@ -45,13 +46,18 @@ public class UserProfileDao extends AbstractDao<UserProfile> { SQLConnection connection = DataStore.connectionPool.getConnection(); try { - PreparedStatement ps = connection.getConnection().prepareStatement("INSERT INTO local_directory " + - "(username, firstName, lastName, email, profilePicture, organization, phoneNumber, phoneNumberExtension, faxNumber, mobileNumber)" + - " VALUES " + "(?,?,?,?,?,?,?,?,?,?)"); + PreparedStatement ps = + connection + .getConnection() + .prepareStatement( + "INSERT INTO local_directory " + + "(username, firstName, lastName, email, profilePicture, organization, phoneNumber, phoneNumberExtension, faxNumber, mobileNumber)" + + " VALUES " + + "(?,?,?,?,?,?,?,?,?,?)"); ps = object.getInsert(ps); return ps.executeUpdate() != 0; } catch (Exception e) { - log.error("An error has occurred while trying to store a user profile: " + e.toString()); + log.error("An error has occurred while trying to store a user profile: " + e); return false; } finally { DataStore.connectionPool.returnConnection(connection); @@ -63,14 +69,18 @@ public class UserProfileDao extends AbstractDao<UserProfile> { SQLConnection connection = DataStore.connectionPool.getConnection(); try { - PreparedStatement ps = connection.getConnection().prepareStatement("UPDATE local_directory SET firstname = ?, lastName = ?, email = ?, profilePicture = ?, organization = ?, phoneNumber = ?, phoneNumberExtension = ?, faxNumber = ?, mobileNumber = ? WHERE username = ?"); + PreparedStatement ps = + connection + .getConnection() + .prepareStatement( + "UPDATE local_directory SET firstname = ?, lastName = ?, email = ?, profilePicture = ?, organization = ?, phoneNumber = ?, phoneNumberExtension = ?, faxNumber = ?, mobileNumber = ? WHERE username = ?"); for (int i = 1; i < update.getStatements().size(); i++) { ps.setString(i, update.getStatements().get(i).getValue()); } ps.setString(update.getStatements().size(), update.getStatements().get(0).getValue()); return ps.executeUpdate() != 0; } catch (Exception e) { - log.error("An error has occurred while trying to update a user profile: " + e.toString()); + log.error("An error has occurred while trying to update a user profile: " + e); return false; } finally { DataStore.connectionPool.returnConnection(connection); diff --git a/datastore/src/main/java/net/jami/datastore/main/DataStore.java b/datastore/src/main/java/net/jami/datastore/main/DataStore.java index 11da21a8a253660fc6d65d20ed56ad562e80c12e..507cafafd32087358ce6e020f844ba60eb7a2e52 100644 --- a/datastore/src/main/java/net/jami/datastore/main/DataStore.java +++ b/datastore/src/main/java/net/jami/datastore/main/DataStore.java @@ -1,29 +1,30 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.datastore.main; import lombok.Getter; import lombok.Setter; + import net.jami.datastore.dao.ContactDao; import net.jami.datastore.dao.DeviceDao; import net.jami.datastore.dao.GroupDao; @@ -40,7 +41,6 @@ import net.jami.jams.common.dao.StatementElement; import net.jami.jams.common.dao.StatementList; import net.jami.jams.common.dao.connectivity.ConnectionPool; import net.jami.jams.common.objects.user.User; -import net.jami.jams.common.objects.user.UserGroupMapping; import net.jami.jams.common.objects.user.UserProfile; import net.jami.jams.common.utils.X509Utils; @@ -50,8 +50,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; -import javax.swing.plaf.nimbus.State; - @Getter @Setter public class DataStore implements AuthenticationSource { @@ -69,9 +67,9 @@ public class DataStore implements AuthenticationSource { public static final Integer RESULTS_PER_PAGE = 24; public static Integer NUM_PAGES; - //Implicitly connect to derby. + // Implicitly connect to derby. public DataStore(String connectionString) { - Flyway flyway = Flyway.configure().dataSource(connectionString,"", "").load(); + Flyway flyway = Flyway.configure().dataSource(connectionString, "", "").load(); flyway.migrate(); connectionPool = new ConnectionPool(connectionString); userDao = new UserDao(); @@ -85,9 +83,9 @@ public class DataStore implements AuthenticationSource { userGroupMappingsDao = new UserGroupMappingsDao(); } - public boolean userExists(String username){ + public boolean userExists(String username) { StatementList statementList = new StatementList(); - StatementElement statementElement = new StatementElement("username","=",username,""); + StatementElement statementElement = new StatementElement("username", "=", username, ""); statementList.addStatement(statementElement); List<User> userList = userDao.getObjects(statementList); return (userList.size() == 1); @@ -97,38 +95,41 @@ public class DataStore implements AuthenticationSource { public boolean createUser(User user) { return userDao.storeObject(user); } + @Override - public List<UserProfile> searchUserProfiles(String queryString, String field, Optional<Integer> page) { + public List<UserProfile> searchUserProfiles( + String queryString, String field, Optional<Integer> page) { List<UserProfile> userList; if (!queryString.equals("*")) { StatementList statementList = new StatementList(); String startQueryString = queryString.concat("%"); - if(field.equals("LOGON_NAME")){ - statementList.addStatement(new StatementElement("username","LIKE", startQueryString,"")); - } - else if(field.equals("FULL_TEXT_NAME")){ - statementList.addStatement(new StatementElement("firstName","LIKE", startQueryString,"OR")); - statementList.addStatement(new StatementElement("lastName","LIKE", startQueryString, "")); + if (field.equals("LOGON_NAME")) { + statementList.addStatement( + new StatementElement("username", "LIKE", startQueryString, "")); + } else if (field.equals("FULL_TEXT_NAME")) { + statementList.addStatement( + new StatementElement("firstName", "LIKE", startQueryString, "OR")); + statementList.addStatement( + new StatementElement("lastName", "LIKE", startQueryString, "")); } userList = userProfileDao.getObjects(statementList); - } else - userList = userProfileDao.getObjects(null); + } else userList = userProfileDao.getObjects(null); - if (userList == null) - userList = new ArrayList<>(); + if (userList == null) userList = new ArrayList<>(); NUM_PAGES = (Integer) userList.size() / RESULTS_PER_PAGE; - if (userList.size() % RESULTS_PER_PAGE != 0) - NUM_PAGES++; + if (userList.size() % RESULTS_PER_PAGE != 0) NUM_PAGES++; if (page.isPresent() && !userList.isEmpty()) { - if (userList.size() < RESULTS_PER_PAGE) - userList = userList.subList(0, userList.size()); + if (userList.size() < RESULTS_PER_PAGE) userList = userList.subList(0, userList.size()); else if (page.get() * RESULTS_PER_PAGE > userList.size()) - userList = userList.subList((page.get()-1) * RESULTS_PER_PAGE, userList.size()); + userList = userList.subList((page.get() - 1) * RESULTS_PER_PAGE, userList.size()); else - userList = userList.subList((page.get()-1) * RESULTS_PER_PAGE, (page.get() * RESULTS_PER_PAGE)); + userList = + userList.subList( + (page.get() - 1) * RESULTS_PER_PAGE, + (page.get() * RESULTS_PER_PAGE)); } return userList; @@ -137,9 +138,9 @@ public class DataStore implements AuthenticationSource { @Override public UserProfile getUserProfile(String username) { StatementList statementList = new StatementList(); - statementList.addStatement(new StatementElement("username","=", username,"")); + statementList.addStatement(new StatementElement("username", "=", username, "")); List<UserProfile> userList = userProfileDao.getObjects(statementList); - if(userList.size() != 1) return null; + if (userList.size() != 1) return null; else return userList.get(0); } @@ -148,34 +149,41 @@ public class DataStore implements AuthenticationSource { return userProfileDao.storeObject(userProfile); } - public boolean updateUserProfile(UserProfile userProfile){ + public boolean updateUserProfile(UserProfile userProfile) { StatementList update = new StatementList(); - update.addStatement(new StatementElement("username","=",userProfile.getUsername(),"")); - update.addStatement(new StatementElement("firstName","=",userProfile.getFirstName(),"")); - update.addStatement(new StatementElement("lastName","=",userProfile.getLastName(),"")); - update.addStatement(new StatementElement("email","=",userProfile.getEmail(),"")); - update.addStatement(new StatementElement("profilePicture","=",userProfile.getProfilePicture(),"")); - update.addStatement(new StatementElement("organization","=",userProfile.getOrganization(),"")); - update.addStatement(new StatementElement("phoneNumber","=",userProfile.getPhoneNumber(),"")); - update.addStatement(new StatementElement("phoneNumberExtension","=",userProfile.getPhoneNumberExtension(),"")); - update.addStatement(new StatementElement("faxNumber","=",userProfile.getFaxNumber(),"")); - update.addStatement(new StatementElement("mobileNumber","=",userProfile.getMobileNumber(),"")); + update.addStatement(new StatementElement("username", "=", userProfile.getUsername(), "")); + update.addStatement(new StatementElement("firstName", "=", userProfile.getFirstName(), "")); + update.addStatement(new StatementElement("lastName", "=", userProfile.getLastName(), "")); + update.addStatement(new StatementElement("email", "=", userProfile.getEmail(), "")); + update.addStatement( + new StatementElement("profilePicture", "=", userProfile.getProfilePicture(), "")); + update.addStatement( + new StatementElement("organization", "=", userProfile.getOrganization(), "")); + update.addStatement( + new StatementElement("phoneNumber", "=", userProfile.getPhoneNumber(), "")); + update.addStatement( + new StatementElement( + "phoneNumberExtension", "=", userProfile.getPhoneNumberExtension(), "")); + update.addStatement(new StatementElement("faxNumber", "=", userProfile.getFaxNumber(), "")); + update.addStatement( + new StatementElement("mobileNumber", "=", userProfile.getMobileNumber(), "")); return userProfileDao.updateObject(update, null); } public boolean updateUserCertificate(User user) { - return userDao.updateUserCertificate(user.getUsername(), X509Utils.getPEMStringFromCertificate(user.getCertificate())); + return userDao.updateUserCertificate( + user.getUsername(), X509Utils.getPEMStringFromCertificate(user.getCertificate())); } @Override public boolean authenticate(String username, String password) { StatementList statementList = new StatementList(); - StatementElement statementElement = new StatementElement("username","=",username,""); + StatementElement statementElement = new StatementElement("username", "=", username, ""); statementList.addStatement(statementElement); List<User> userList = userDao.getObjects(statementList); - if(userList.size() != 1 || userList.get(0).getPassword() == null) return false; + if (userList.size() != 1 || userList.get(0).getPassword() == null) return false; return userList.get(0).getPassword().equals(password); } diff --git a/datastore/src/test/java/net/jami/datastore/dao/ContactDaoTest.java b/datastore/src/test/java/net/jami/datastore/dao/ContactDaoTest.java index 6052876ce29e575d65dcd61e9b592d43763e4512..94793473308c6a85bb22b897edfbb30dcd5acaf3 100644 --- a/datastore/src/test/java/net/jami/datastore/dao/ContactDaoTest.java +++ b/datastore/src/test/java/net/jami/datastore/dao/ContactDaoTest.java @@ -1,27 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.datastore.dao; -class ContactDaoTest { - -} \ No newline at end of file +class ContactDaoTest {} diff --git a/datastore/src/test/java/net/jami/datastore/dao/DAOTest.java b/datastore/src/test/java/net/jami/datastore/dao/DAOTest.java index 3335065bf4e6ff3008ad34fff65d0d8c76f4e100..5d465c9aa573bbd79c8c8452027dfd88926044de 100644 --- a/datastore/src/test/java/net/jami/datastore/dao/DAOTest.java +++ b/datastore/src/test/java/net/jami/datastore/dao/DAOTest.java @@ -1,28 +1,29 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.datastore.dao; import lombok.extern.slf4j.Slf4j; + import net.jami.datastore.main.DataStore; import net.jami.jams.common.authentication.AuthenticationSourceType; import net.jami.jams.common.dao.StatementElement; @@ -31,6 +32,7 @@ import net.jami.jams.common.objects.devices.Device; import net.jami.jams.common.objects.user.AccessLevel; import net.jami.jams.common.objects.user.User; import net.jami.jams.common.utils.X509Utils; + import org.apache.tomcat.util.codec.binary.Base64; import org.bouncycastle.util.encoders.Hex; import org.junit.jupiter.api.Assertions; @@ -52,7 +54,7 @@ class DAOTest { static String refreshedCertificate; @BeforeAll - static void setUp() throws Exception{ + static void setUp() throws Exception { DataStore dataStore = new DataStore("jdbc:derby:testdb;create=true"); Assertions.assertNotNull(DataStore.connectionPool.getConnection()); InputStream path; @@ -86,10 +88,10 @@ class DAOTest { userDAO.storeObject(user); StatementList statementList = new StatementList(); - statementList.addStatement(new StatementElement("username","=","fsidokhine","")); + statementList.addStatement(new StatementElement("username", "=", "fsidokhine", "")); User user1 = userDAO.getObjects(statementList).get(0); Assertions.assertNotNull(user1); - Assertions.assertEquals(user1.getAccessLevel(),AccessLevel.ADMIN); + Assertions.assertEquals(user1.getAccessLevel(), AccessLevel.ADMIN); } @Test @@ -109,19 +111,22 @@ class DAOTest { userDAO.storeObject(user); StatementList statementList = new StatementList(); - statementList.addStatement(new StatementElement("username","=","TestUser","")); + statementList.addStatement(new StatementElement("username", "=", "TestUser", "")); User user1 = userDAO.getObjects(statementList).get(0); Assertions.assertNotNull(user1); - Assertions.assertEquals(user1.getAccessLevel(),AccessLevel.USER); + Assertions.assertEquals(user1.getAccessLevel(), AccessLevel.USER); - userDAO.updateUserCertificate("TestUser", X509Utils.getPEMStringFromCertificate(X509Utils.getCertificateFromPEMString(refreshedCertificate))); + userDAO.updateUserCertificate( + "TestUser", + X509Utils.getPEMStringFromCertificate( + X509Utils.getCertificateFromPEMString(refreshedCertificate))); User user2 = userDAO.getObjects(statementList).get(0); Assertions.assertNotEquals(user1.getCertificate(), user2.getCertificate()); } @Test - void storeDevice(){ + void storeDevice() { Device device = new Device(); device.setDeviceId("01929833"); device.setOwner("fsidokhine"); @@ -131,13 +136,13 @@ class DAOTest { deviceDAO.storeObject(device); StatementList statementList = new StatementList(); - statementList.addStatement(new StatementElement("owner","=","fsidokhine","")); + statementList.addStatement(new StatementElement("owner", "=", "fsidokhine", "")); Device device1 = deviceDAO.getObjects(statementList).get(0); Assertions.assertNotNull(device1); } @Test - void storeAdminUser() throws Exception{ + void storeAdminUser() throws Exception { User user = new User(); user.setUsername("admin"); user.setUserType(AuthenticationSourceType.LOCAL); @@ -151,21 +156,20 @@ class DAOTest { userDAO.storeObject(user); StatementList statementList = new StatementList(); - statementList.addStatement(new StatementElement("username","=","admin","")); + statementList.addStatement(new StatementElement("username", "=", "admin", "")); User user1 = userDAO.getObjects(statementList).get(0); Assertions.assertNotNull(user1); - Assertions.assertEquals(user1.getAccessLevel(),AccessLevel.ADMIN); + Assertions.assertEquals(user1.getAccessLevel(), AccessLevel.ADMIN); } - public static String hashPassword(String password, byte[] salt){ + public static String hashPassword(String password, byte[] salt) { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.update(salt); byte[] hash = digest.digest(password.getBytes(StandardCharsets.UTF_8)); return new String(Hex.encode(hash)); - } - catch (Exception e){ + } catch (Exception e) { return null; } } -} \ No newline at end of file +} diff --git a/datastore/src/test/java/net/jami/datastore/dao/SystemDaoTest.java b/datastore/src/test/java/net/jami/datastore/dao/SystemDaoTest.java index 6e93a7bfba7991922ff01be3330faef756d58d77..8eb978de1063a68b06bbf8a87bdb959c44ed9b49 100644 --- a/datastore/src/test/java/net/jami/datastore/dao/SystemDaoTest.java +++ b/datastore/src/test/java/net/jami/datastore/dao/SystemDaoTest.java @@ -1,27 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.datastore.dao; -class SystemDaoTest { - -} \ No newline at end of file +class SystemDaoTest {} diff --git a/jami-dht/src/main/java/net/jami/jams/dht/DeviceReceiptGenerator.java b/jami-dht/src/main/java/net/jami/jams/dht/DeviceReceiptGenerator.java index c891c306025537884a3ada9d96b3efc4e55ee3ab..ccf2eeca5f591a80f9d3c049224341f290c5a926 100644 --- a/jami-dht/src/main/java/net/jami/jams/dht/DeviceReceiptGenerator.java +++ b/jami-dht/src/main/java/net/jami/jams/dht/DeviceReceiptGenerator.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.dht; /* @@ -42,7 +42,9 @@ package net.jami.jams.dht; */ import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.objects.user.User; + import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.digest.MessageDigestAlgorithms; @@ -61,8 +63,9 @@ import java.util.stream.Collectors; @Slf4j public class DeviceReceiptGenerator { - - private static void packToSign(MessageBufferPacker messagePack, PublicKey publicKey, byte[] deviceId) throws IOException { + private static void packToSign( + MessageBufferPacker messagePack, PublicKey publicKey, byte[] deviceId) + throws IOException { byte[] owner = publicKey.getEncoded(); messagePack.packMapHeader(4); messagePack.packString("seq"); @@ -73,18 +76,19 @@ public class DeviceReceiptGenerator { messagePack.packString("type"); messagePack.packInt(0); messagePack.packString("data"); - //Inner message building. + // Inner message building. MessageBufferPacker innerMessagePack = MessagePack.newDefaultBufferPacker(); innerMessagePack.packMapHeader(1); innerMessagePack.packString("dev"); innerMessagePack.packBinaryHeader(deviceId.length); innerMessagePack.addPayload(deviceId); - //Append the inner to the messagePack + // Append the inner to the messagePack messagePack.packBinaryHeader(innerMessagePack.toByteArray().length); messagePack.addPayload(innerMessagePack.toByteArray()); } - private static byte[] generateAnnoucement(PrivateKey privateKey, PublicKey publicKey, PublicKey devicePubKey){ + private static byte[] generateAnnoucement( + PrivateKey privateKey, PublicKey publicKey, PublicKey devicePubKey) { try { MessageBufferPacker outerMessagePack = MessagePack.newDefaultBufferPacker(); MessageBufferPacker messagePack = MessagePack.newDefaultBufferPacker(); @@ -93,13 +97,13 @@ public class DeviceReceiptGenerator { packToSign(messagePack, publicKey, deviceId); byte[] owner = publicKey.getEncoded(); - //Sign the message pack object using SHA-512 digest. + // Sign the message pack object using SHA-512 digest. Signature signer = Signature.getInstance("SHA512withRSA"); signer.initSign(privateKey); signer.update(messagePack.toByteArray()); byte[] signature = signer.sign(); - //Build the outer enveloper. + // Build the outer enveloper. outerMessagePack.packMapHeader(2); outerMessagePack.packString("id"); outerMessagePack.packInt(0); @@ -112,47 +116,61 @@ public class DeviceReceiptGenerator { outerMessagePack.addPayload(signature); return outerMessagePack.toByteArray(); - } - catch (Exception e){ + } catch (Exception e) { log.error("Could not build the device receipt!"); return null; } } - public static String[] generateReceipt(PrivateKey privateKey, PublicKey publicKey, PublicKey devicePubKey, String ethAddress){ + public static String[] generateReceipt( + PrivateKey privateKey, PublicKey publicKey, PublicKey devicePubKey, String ethAddress) { try { - HashMap<String, String> receipt = new LinkedHashMap<String, String>() { - @Override - public String toString() { - return "{" + entrySet().stream().map(x -> "\"" + x.getKey() + "\":\"" + x.getValue() + "\"").collect(Collectors.joining(",")) + "}"; - } - }; + HashMap<String, String> receipt = + new LinkedHashMap<String, String>() { + @Override + public String toString() { + return "{" + + entrySet().stream() + .map( + x -> + "\"" + + x.getKey() + + "\":\"" + + x.getValue() + + "\"") + .collect(Collectors.joining(",")) + + "}"; + } + }; MessageDigest digest = MessageDigest.getInstance(MessageDigestAlgorithms.SHA_1); - receipt.put("id",Hex.encodeHexString(digest.digest(publicKey.getEncoded()))); - receipt.put("dev",Hex.encodeHexString(digest.digest(devicePubKey.getEncoded()))); - receipt.put("eth",ethAddress); - receipt.put("announce", Base64.encodeBase64String(generateAnnoucement(privateKey,publicKey,devicePubKey))); + receipt.put("id", Hex.encodeHexString(digest.digest(publicKey.getEncoded()))); + receipt.put("dev", Hex.encodeHexString(digest.digest(devicePubKey.getEncoded()))); + receipt.put("eth", ethAddress); + receipt.put( + "announce", + Base64.encodeBase64String( + generateAnnoucement(privateKey, publicKey, devicePubKey))); Signature signer = Signature.getInstance("SHA512withRSA"); signer.initSign(privateKey); signer.update(receipt.toString().getBytes()); byte[] signature = signer.sign(); - return new String[]{receipt.toString(), java.util.Base64.getEncoder().encodeToString(signature)}; - } - catch (Exception e){ + return new String[] { + receipt.toString(), java.util.Base64.getEncoder().encodeToString(signature) + }; + } catch (Exception e) { log.error("Could not build generate device receipt!"); return null; } - } - public static String generateJamiId(User user){ + public static String generateJamiId(User user) { try { - return Hex.encodeHexString(MessageDigest.getInstance(MessageDigestAlgorithms.SHA_1).digest(user.getCertificate().getPublicKey().getEncoded())); - } - catch (Exception e){ - log.error("Could not generate JamiId with error " + e.toString()); + return Hex.encodeHexString( + MessageDigest.getInstance(MessageDigestAlgorithms.SHA_1) + .digest(user.getCertificate().getPublicKey().getEncoded())); + } catch (Exception e) { + log.error("Could not generate JamiId with error " + e); return null; } } - } diff --git a/jami-dht/src/main/java/net/jami/jams/dht/ETHAddressGenerator.java b/jami-dht/src/main/java/net/jami/jams/dht/ETHAddressGenerator.java index 40db8d4e8247dedc6451dad8632bc6128307d15a..798e48b6e898cba5bcf8112371eb76e3512fcc42 100644 --- a/jami-dht/src/main/java/net/jami/jams/dht/ETHAddressGenerator.java +++ b/jami-dht/src/main/java/net/jami/jams/dht/ETHAddressGenerator.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.dht; /* @@ -42,6 +42,7 @@ package net.jami.jams.dht; */ import net.jami.jams.dht.hashutils.HexBin; import net.jami.jams.dht.hashutils.Keccak256; + import org.apache.commons.codec.binary.Hex; import java.security.KeyPair; @@ -52,32 +53,29 @@ import java.security.spec.ECGenParameterSpec; public class ETHAddressGenerator { - - public static String[] generateAddress(){ + public static String[] generateAddress() { try { - KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC","SunEC"); + KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC", "SunEC"); keyGen.initialize(new ECGenParameterSpec("secp256k1")); - //Generate the Public and Private Keys + // Generate the Public and Private Keys KeyPair pair = keyGen.generateKeyPair(); ECPrivateKey ecpriv = (ECPrivateKey) pair.getPrivate(); - ECPublicKey ecpub = (ECPublicKey) pair.getPublic(); + ECPublicKey ecpub = (ECPublicKey) pair.getPublic(); - //Get the hex representations we need. - String hexPubKey = ecpub.getW().getAffineX().toString(16) + ecpub.getW().getAffineY().toString(16); - String hexPrvKey = ecpriv.getS().toString(16); + // Get the hex representations we need. + String hexPubKey = + ecpub.getW().getAffineX().toString(16) + ecpub.getW().getAffineY().toString(16); + String hexPrvKey = ecpriv.getS().toString(16); - //In ethereum the private key is just 0x + private key, so nothing to do here. + // In ethereum the private key is just 0x + private key, so nothing to do here. Keccak256 keccak256 = new Keccak256(); byte[] addressData = keccak256.digest(HexBin.decode(hexPubKey)); String address = Hex.encodeHexString(addressData); address = "0x" + address.substring(24); - //Return the address and the private key - we just store them for now. - return new String[]{address,hexPrvKey}; - } - catch (Exception e){ + // Return the address and the private key - we just store them for now. + return new String[] {address, hexPrvKey}; + } catch (Exception e) { return null; } } - - } diff --git a/jami-dht/src/main/java/net/jami/jams/dht/hashutils/Digest.java b/jami-dht/src/main/java/net/jami/jams/dht/hashutils/Digest.java index 4c683ee6a8681b0da778efb52aa2b8c868781bcf..f2420622529118f8fcdc58d31af8f0c480eeb260 100755 --- a/jami-dht/src/main/java/net/jami/jams/dht/hashutils/Digest.java +++ b/jami-dht/src/main/java/net/jami/jams/dht/hashutils/Digest.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ // $Id: Digest.java 232 2010-06-17 14:19:24Z tp $ package net.jami.jams.dht.hashutils; @@ -50,7 +50,7 @@ package net.jami.jams.dht.hashutils; * ==========================(LICENSE BEGIN)============================ * * Copyright (c) 2007-2010 Projet RNRT SAPHIR - * + * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including @@ -58,10 +58,10 @@ package net.jami.jams.dht.hashutils; * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. @@ -76,112 +76,111 @@ package net.jami.jams.dht.hashutils; * @version $Revision: 232 $ * @author Thomas Pornin <thomas.pornin@cryptolog.com> */ - public interface Digest { - /** - * Insert one more input data byte. - * - * @param in the input byte - */ - public void update(byte in); + /** + * Insert one more input data byte. + * + * @param in the input byte + */ + void update(byte in); - /** - * Insert some more bytes. - * - * @param inbuf the data bytes - */ - public void update(byte[] inbuf); + /** + * Insert some more bytes. + * + * @param inbuf the data bytes + */ + void update(byte[] inbuf); - /** - * Insert some more bytes. - * - * @param inbuf the data buffer - * @param off the data offset in {@code inbuf} - * @param len the data length (in bytes) - */ - public void update(byte[] inbuf, int off, int len); + /** + * Insert some more bytes. + * + * @param inbuf the data buffer + * @param off the data offset in {@code inbuf} + * @param len the data length (in bytes) + */ + void update(byte[] inbuf, int off, int len); - /** - * Finalize the current hash computation and return the hash value - * in a newly-allocated array. The object is resetted. - * - * @return the hash output - */ - public byte[] digest(); + /** + * Finalize the current hash computation and return the hash value + * in a newly-allocated array. The object is resetted. + * + * @return the hash output + */ + byte[] digest(); - /** - * Input some bytes, then finalize the current hash computation - * and return the hash value in a newly-allocated array. The object - * is resetted. - * - * @param inbuf the input data - * @return the hash output - */ - public byte[] digest(byte[] inbuf); + /** + * Input some bytes, then finalize the current hash computation + * and return the hash value in a newly-allocated array. The object + * is resetted. + * + * @param inbuf the input data + * @return the hash output + */ + byte[] digest(byte[] inbuf); - /** - * Finalize the current hash computation and store the hash value - * in the provided output buffer. The {@code len} parameter - * contains the maximum number of bytes that should be written; - * no more bytes than the natural hash function output length will - * be produced. If {@code len} is smaller than the natural - * hash output length, the hash output is truncated to its first - * {@code len} bytes. The object is resetted. - * - * @param outbuf the output buffer - * @param off the output offset within {@code outbuf} - * @param len the requested hash output length (in bytes) - * @return the number of bytes actually written in {@code outbuf} - */ - public int digest(byte[] outbuf, int off, int len); + /** + * Finalize the current hash computation and store the hash value + * in the provided output buffer. The {@code len} parameter + * contains the maximum number of bytes that should be written; + * no more bytes than the natural hash function output length will + * be produced. If {@code len} is smaller than the natural + * hash output length, the hash output is truncated to its first + * {@code len} bytes. The object is resetted. + * + * @param outbuf the output buffer + * @param off the output offset within {@code outbuf} + * @param len the requested hash output length (in bytes) + * @return the number of bytes actually written in {@code outbuf} + */ + int digest(byte[] outbuf, int off, int len); - /** - * Get the natural hash function output length (in bytes). - * - * @return the digest output length (in bytes) - */ - public int getDigestLength(); + /** + * Get the natural hash function output length (in bytes). + * + * @return the digest output length (in bytes) + */ + int getDigestLength(); - /** - * Reset the object: this makes it suitable for a new hash - * computation. The current computation, if any, is discarded. - */ - public void reset(); + /** + * Reset the object: this makes it suitable for a new hash + * computation. The current computation, if any, is discarded. + */ + void reset(); - /** - * Clone the current state. The returned object evolves independantly - * of this object. - * - * @return the clone - */ - public Digest copy(); + /** + * Clone the current state. The returned object evolves independantly + * of this object. + * + * @return the clone + */ + Digest copy(); - /** - * <p>Return the "block length" for the hash function. This - * value is naturally defined for iterated hash functions - * (Merkle-Damgard). It is used in HMAC (that's what the - * <a href="http://tools.ietf.org/html/rfc2104">HMAC specification</a> - * names the "{@code B}" parameter).</p> - * - * <p>If the function is "block-less" then this function may - * return {@code -n} where {@code n} is an integer such that the - * block length for HMAC ("{@code B}") will be inferred from the - * key length, by selecting the smallest multiple of {@code n} - * which is no smaller than the key length. For instance, for - * the Fugue-xxx hash functions, this function returns -4: the - * virtual block length B is the HMAC key length, rounded up to - * the next multiple of 4.</p> - * - * @return the internal block length (in bytes), or {@code -n} - */ - public int getBlockLength(); + /** + * <p>Return the "block length" for the hash function. This + * value is naturally defined for iterated hash functions + * (Merkle-Damgard). It is used in HMAC (that's what the + * <a href="http://tools.ietf.org/html/rfc2104">HMAC specification</a> + * names the "{@code B}" parameter).</p> + * + * <p>If the function is "block-less" then this function may + * return {@code -n} where {@code n} is an integer such that the + * block length for HMAC ("{@code B}") will be inferred from the + * key length, by selecting the smallest multiple of {@code n} + * which is no smaller than the key length. For instance, for + * the Fugue-xxx hash functions, this function returns -4: the + * virtual block length B is the HMAC key length, rounded up to + * the next multiple of 4.</p> + * + * @return the internal block length (in bytes), or {@code -n} + */ + int getBlockLength(); - /** - * <p>Get the display name for this function (e.g. {@code "SHA-1"} - * for SHA-1).</p> - * - * @see Object - */ - public String toString(); + /** + * <p>Get the display name for this function (e.g. {@code "SHA-1"} + * for SHA-1).</p> + * + * @see Object + */ + String toString(); } diff --git a/jami-dht/src/main/java/net/jami/jams/dht/hashutils/DigestEngine.java b/jami-dht/src/main/java/net/jami/jams/dht/hashutils/DigestEngine.java index 769c5614c3eca420f0a5575072451283bd33145d..9b81f1c1365e7fc55e403f2468a9e00050161266 100755 --- a/jami-dht/src/main/java/net/jami/jams/dht/hashutils/DigestEngine.java +++ b/jami-dht/src/main/java/net/jami/jams/dht/hashutils/DigestEngine.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ // $Id: DigestEngine.java 229 2010-06-16 20:22:27Z tp $ package net.jami.jams.dht.hashutils; @@ -42,7 +42,7 @@ package net.jami.jams.dht.hashutils; * ==========================(LICENSE BEGIN)============================ * * Copyright (c) 2007-2010 Projet RNRT SAPHIR - * + * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including @@ -50,10 +50,10 @@ package net.jami.jams.dht.hashutils; * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. @@ -68,221 +68,205 @@ package net.jami.jams.dht.hashutils; * @version $Revision: 229 $ * @author Thomas Pornin <thomas.pornin@cryptolog.com> */ - public abstract class DigestEngine implements Digest { - /** - * Reset the hash algorithm state. - */ - protected abstract void engineReset(); + /** + * Reset the hash algorithm state. + */ + protected abstract void engineReset(); - /** - * Process one block of data. - * - * @param data the data block - */ - protected abstract void processBlock(byte[] data); + /** + * Process one block of data. + * + * @param data the data block + */ + protected abstract void processBlock(byte[] data); - /** - * Perform the final padding and store the result in the - * provided buffer. This method shall call {@link #flush} - * and then {@link #update} with the appropriate padding - * data in order to get the full input data. - * - * @param buf the output buffer - * @param off the output offset - */ - protected abstract void doPadding(byte[] buf, int off); + /** + * Perform the final padding and store the result in the + * provided buffer. This method shall call {@link #flush} + * and then {@link #update} with the appropriate padding + * data in order to get the full input data. + * + * @param buf the output buffer + * @param off the output offset + */ + protected abstract void doPadding(byte[] buf, int off); - /** - * This function is called at object creation time; the - * implementation should use it to perform initialization tasks. - * After this method is called, the implementation should be ready - * to process data or meaningfully honour calls such as - * {@link #getDigestLength}</code>. - */ - protected abstract void doInit(); + /** + * This function is called at object creation time; the + * implementation should use it to perform initialization tasks. + * After this method is called, the implementation should be ready + * to process data or meaningfully honour calls such as + * {@link #getDigestLength}</code>. + */ + protected abstract void doInit(); - private int digestLen, blockLen, inputLen; - private byte[] inputBuf, outputBuf; - private long blockCount; + private int digestLen; + private final int blockLen; + private int inputLen; + private final byte[] inputBuf; + private byte[] outputBuf; + private long blockCount; - /** - * Instantiate the engine. - */ - public DigestEngine() - { - doInit(); - digestLen = getDigestLength(); - blockLen = getInternalBlockLength(); - inputBuf = new byte[blockLen]; - outputBuf = new byte[digestLen]; - inputLen = 0; - blockCount = 0; - } + /** + * Instantiate the engine. + */ + public DigestEngine() { + doInit(); + digestLen = getDigestLength(); + blockLen = getInternalBlockLength(); + inputBuf = new byte[blockLen]; + outputBuf = new byte[digestLen]; + inputLen = 0; + blockCount = 0; + } - private void adjustDigestLen() - { - if (digestLen == 0) { - digestLen = getDigestLength(); - outputBuf = new byte[digestLen]; - } - } + private void adjustDigestLen() { + if (digestLen == 0) { + digestLen = getDigestLength(); + outputBuf = new byte[digestLen]; + } + } - /** @see Digest */ - public byte[] digest() - { - adjustDigestLen(); - byte[] result = new byte[digestLen]; - digest(result, 0, digestLen); - return result; - } + /** @see Digest */ + public byte[] digest() { + adjustDigestLen(); + byte[] result = new byte[digestLen]; + digest(result, 0, digestLen); + return result; + } - /** @see Digest */ - public byte[] digest(byte[] input) - { - update(input, 0, input.length); - return digest(); - } + /** @see Digest */ + public byte[] digest(byte[] input) { + update(input, 0, input.length); + return digest(); + } - /** @see Digest */ - public int digest(byte[] buf, int offset, int len) - { - adjustDigestLen(); - if (len >= digestLen) { - doPadding(buf, offset); - reset(); - return digestLen; - } else { - doPadding(outputBuf, 0); - System.arraycopy(outputBuf, 0, buf, offset, len); - reset(); - return len; - } - } + /** @see Digest */ + public int digest(byte[] buf, int offset, int len) { + adjustDigestLen(); + if (len >= digestLen) { + doPadding(buf, offset); + reset(); + return digestLen; + } else { + doPadding(outputBuf, 0); + System.arraycopy(outputBuf, 0, buf, offset, len); + reset(); + return len; + } + } - /** @see Digest */ - public void reset() - { - engineReset(); - inputLen = 0; - blockCount = 0; - } + /** @see Digest */ + public void reset() { + engineReset(); + inputLen = 0; + blockCount = 0; + } - /** @see Digest */ - public void update(byte input) - { - inputBuf[inputLen ++] = (byte)input; - if (inputLen == blockLen) { - processBlock(inputBuf); - blockCount ++; - inputLen = 0; - } - } + /** @see Digest */ + public void update(byte input) { + inputBuf[inputLen++] = input; + if (inputLen == blockLen) { + processBlock(inputBuf); + blockCount++; + inputLen = 0; + } + } - /** @see Digest */ - public void update(byte[] input) - { - update(input, 0, input.length); - } + /** @see Digest */ + public void update(byte[] input) { + update(input, 0, input.length); + } - /** @see Digest */ - public void update(byte[] input, int offset, int len) - { - while (len > 0) { - int copyLen = blockLen - inputLen; - if (copyLen > len) - copyLen = len; - System.arraycopy(input, offset, inputBuf, inputLen, - copyLen); - offset += copyLen; - inputLen += copyLen; - len -= copyLen; - if (inputLen == blockLen) { - processBlock(inputBuf); - blockCount ++; - inputLen = 0; - } - } - } + /** @see Digest */ + public void update(byte[] input, int offset, int len) { + while (len > 0) { + int copyLen = blockLen - inputLen; + if (copyLen > len) copyLen = len; + System.arraycopy(input, offset, inputBuf, inputLen, copyLen); + offset += copyLen; + inputLen += copyLen; + len -= copyLen; + if (inputLen == blockLen) { + processBlock(inputBuf); + blockCount++; + inputLen = 0; + } + } + } - /** - * Get the internal block length. This is the length (in - * bytes) of the array which will be passed as parameter to - * {@link #processBlock}. The default implementation of this - * method calls {@link #getBlockLength} and returns the same - * value. Overriding this method is useful when the advertised - * block length (which is used, for instance, by HMAC) is - * suboptimal with regards to internal buffering needs. - * - * @return the internal block length (in bytes) - */ - protected int getInternalBlockLength() - { - return getBlockLength(); - } + /** + * Get the internal block length. This is the length (in + * bytes) of the array which will be passed as parameter to + * {@link #processBlock}. The default implementation of this + * method calls {@link #getBlockLength} and returns the same + * value. Overriding this method is useful when the advertised + * block length (which is used, for instance, by HMAC) is + * suboptimal with regards to internal buffering needs. + * + * @return the internal block length (in bytes) + */ + protected int getInternalBlockLength() { + return getBlockLength(); + } - /** - * Flush internal buffers, so that less than a block of data - * may at most be upheld. - * - * @return the number of bytes still unprocessed after the flush - */ - protected final int flush() - { - return inputLen; - } + /** + * Flush internal buffers, so that less than a block of data + * may at most be upheld. + * + * @return the number of bytes still unprocessed after the flush + */ + protected final int flush() { + return inputLen; + } - /** - * Get a reference to an internal buffer with the same size - * than a block. The contents of that buffer are defined only - * immediately after a call to {@link #flush()}: if - * {@link #flush()} return the value {@code n}, then the - * first {@code n} bytes of the array returned by this method - * are the {@code n} bytes of input data which are still - * unprocessed. The values of the remaining bytes are - * undefined and may be altered at will. - * - * @return a block-sized internal buffer - */ - protected final byte[] getBlockBuffer() - { - return inputBuf; - } + /** + * Get a reference to an internal buffer with the same size + * than a block. The contents of that buffer are defined only + * immediately after a call to {@link #flush()}: if + * {@link #flush()} return the value {@code n}, then the + * first {@code n} bytes of the array returned by this method + * are the {@code n} bytes of input data which are still + * unprocessed. The values of the remaining bytes are + * undefined and may be altered at will. + * + * @return a block-sized internal buffer + */ + protected final byte[] getBlockBuffer() { + return inputBuf; + } - /** - * Get the "block count": this is the number of times the - * {@link #processBlock} method has been invoked for the - * current hash operation. That counter is incremented - * <em>after</em> the call to {@link #processBlock}. - * - * @return the block count - */ - protected long getBlockCount() - { - return blockCount; - } + /** + * Get the "block count": this is the number of times the + * {@link #processBlock} method has been invoked for the + * current hash operation. That counter is incremented + * <em>after</em> the call to {@link #processBlock}. + * + * @return the block count + */ + protected long getBlockCount() { + return blockCount; + } - /** - * This function copies the internal buffering state to some - * other instance of a class extending {@code DigestEngine}. - * It returns a reference to the copy. This method is intended - * to be called by the implementation of the {@link #copy} - * method. - * - * @param dest the copy - * @return the value {@code dest} - */ - protected Digest copyState(DigestEngine dest) - { - dest.inputLen = inputLen; - dest.blockCount = blockCount; - System.arraycopy(inputBuf, 0, dest.inputBuf, 0, - inputBuf.length); - adjustDigestLen(); - dest.adjustDigestLen(); - System.arraycopy(outputBuf, 0, dest.outputBuf, 0, - outputBuf.length); - return dest; - } + /** + * This function copies the internal buffering state to some + * other instance of a class extending {@code DigestEngine}. + * It returns a reference to the copy. This method is intended + * to be called by the implementation of the {@link #copy} + * method. + * + * @param dest the copy + * @return the value {@code dest} + */ + protected Digest copyState(DigestEngine dest) { + dest.inputLen = inputLen; + dest.blockCount = blockCount; + System.arraycopy(inputBuf, 0, dest.inputBuf, 0, inputBuf.length); + adjustDigestLen(); + dest.adjustDigestLen(); + System.arraycopy(outputBuf, 0, dest.outputBuf, 0, outputBuf.length); + return dest; + } } diff --git a/jami-dht/src/main/java/net/jami/jams/dht/hashutils/HexBin.java b/jami-dht/src/main/java/net/jami/jams/dht/hashutils/HexBin.java index 56049bc7c26049c097c167cfa49e6e89954b8389..f1f6397105ae177d080ff808caf0e787b43cd96a 100755 --- a/jami-dht/src/main/java/net/jami/jams/dht/hashutils/HexBin.java +++ b/jami-dht/src/main/java/net/jami/jams/dht/hashutils/HexBin.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.dht.hashutils; /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -28,9 +28,9 @@ package net.jami.jams.dht.hashutils; * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -38,7 +38,6 @@ package net.jami.jams.dht.hashutils; * limitations under the License. */ - /** * format validation * @@ -49,32 +48,31 @@ package net.jami.jams.dht.hashutils; * @author Jeffrey Rodriguez * @version $Id: HexBin.java 446747 2006-09-15 21:46:20Z mrglavas $ */ -public final class HexBin { - static private final int BASELENGTH = 128; - static private final int LOOKUPLENGTH = 16; - static final private byte [] hexNumberTable = new byte[BASELENGTH]; - static final private char [] lookUpHexAlphabet = new char[LOOKUPLENGTH]; - +public final class HexBin { + private static final int BASELENGTH = 128; + private static final int LOOKUPLENGTH = 16; + private static final byte[] hexNumberTable = new byte[BASELENGTH]; + private static final char[] lookUpHexAlphabet = new char[LOOKUPLENGTH]; static { - for (int i = 0; i < BASELENGTH; i++ ) { + for (int i = 0; i < BASELENGTH; i++) { hexNumberTable[i] = -1; } - for ( int i = '9'; i >= '0'; i--) { - hexNumberTable[i] = (byte) (i-'0'); + for (int i = '9'; i >= '0'; i--) { + hexNumberTable[i] = (byte) (i - '0'); } - for ( int i = 'F'; i>= 'A'; i--) { - hexNumberTable[i] = (byte) ( i-'A' + 10 ); + for (int i = 'F'; i >= 'A'; i--) { + hexNumberTable[i] = (byte) (i - 'A' + 10); } - for ( int i = 'f'; i>= 'a'; i--) { - hexNumberTable[i] = (byte) ( i-'a' + 10 ); + for (int i = 'f'; i >= 'a'; i--) { + hexNumberTable[i] = (byte) (i - 'a' + 10); } - for(int i = 0; i<10; i++ ) { - lookUpHexAlphabet[i] = (char)('0'+i); + for (int i = 0; i < 10; i++) { + lookUpHexAlphabet[i] = (char) ('0' + i); } - for(int i = 10; i<=15; i++ ) { - lookUpHexAlphabet[i] = (char)('A'+i -10); + for (int i = 10; i <= 15; i++) { + lookUpHexAlphabet[i] = (char) ('A' + i - 10); } } @@ -84,29 +82,25 @@ public final class HexBin { * @param encoded encoded string * @return return array of byte to encode */ - static public byte[] decode(String encoded) { - if (encoded == null) - return null; + public static byte[] decode(String encoded) { + if (encoded == null) return null; int lengthData = encoded.length(); - if (lengthData % 2 != 0) - return null; + if (lengthData % 2 != 0) return null; char[] binaryData = encoded.toCharArray(); int lengthDecode = lengthData / 2; byte[] decodedData = new byte[lengthDecode]; byte temp1, temp2; char tempChar; - for( int i = 0; i<lengthDecode; i++ ){ - tempChar = binaryData[i*2]; + for (int i = 0; i < lengthDecode; i++) { + tempChar = binaryData[i * 2]; temp1 = (tempChar < BASELENGTH) ? hexNumberTable[tempChar] : -1; - if (temp1 == -1) - return null; - tempChar = binaryData[i*2+1]; + if (temp1 == -1) return null; + tempChar = binaryData[i * 2 + 1]; temp2 = (tempChar < BASELENGTH) ? hexNumberTable[tempChar] : -1; - if (temp2 == -1) - return null; - decodedData[i] = (byte)((temp1 << 4) | temp2); + if (temp2 == -1) return null; + decodedData[i] = (byte) ((temp1 << 4) | temp2); } return decodedData; } -} \ No newline at end of file +} diff --git a/jami-dht/src/main/java/net/jami/jams/dht/hashutils/Keccak256.java b/jami-dht/src/main/java/net/jami/jams/dht/hashutils/Keccak256.java index e7d020dafe51922d0794bc78873bc89fc0cd9a81..28bbd62cf2feb1734ec11e8ef8e143e0c58f4422 100755 --- a/jami-dht/src/main/java/net/jami/jams/dht/hashutils/Keccak256.java +++ b/jami-dht/src/main/java/net/jami/jams/dht/hashutils/Keccak256.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.dht.hashutils; // $Id: Keccak256.java 189 2010-05-14 21:21:46Z tp $ @@ -57,25 +57,20 @@ package net.jami.jams.dht.hashutils; * @version $Revision: 189 $ * @author Thomas Pornin <thomas.pornin@cryptolog.com> */ - public class Keccak256 extends KeccakCore { /** * Create the engine. */ - public Keccak256() - { - } + public Keccak256() {} /** @see Digest */ - public Digest copy() - { + public Digest copy() { return copyState(new Keccak256()); } /** @see Digest */ - public int getDigestLength() - { + public int getDigestLength() { return 32; } -} \ No newline at end of file +} diff --git a/jami-dht/src/main/java/net/jami/jams/dht/hashutils/KeccakCore.java b/jami-dht/src/main/java/net/jami/jams/dht/hashutils/KeccakCore.java index f006241a0203484f335fe0d5cd17317a9e5fa0e1..6bd7bd8cfb05c25ee7abd0137eb468d2ebfeefbb 100755 --- a/jami-dht/src/main/java/net/jami/jams/dht/hashutils/KeccakCore.java +++ b/jami-dht/src/main/java/net/jami/jams/dht/hashutils/KeccakCore.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ // $Id: KeccakCore.java 258 2011-07-15 22:16:50Z tp $ package net.jami.jams.dht.hashutils; @@ -58,29 +58,26 @@ package net.jami.jams.dht.hashutils; * @version $Revision: 258 $ * @author Thomas Pornin <thomas.pornin@cryptolog.com> */ - abstract class KeccakCore extends DigestEngine { - KeccakCore() - { - } + KeccakCore() {} private long[] A; private byte[] tmpOut; private static final long[] RC = { - 0x0000000000000001L, 0x0000000000008082L, - 0x800000000000808AL, 0x8000000080008000L, - 0x000000000000808BL, 0x0000000080000001L, - 0x8000000080008081L, 0x8000000000008009L, - 0x000000000000008AL, 0x0000000000000088L, - 0x0000000080008009L, 0x000000008000000AL, - 0x000000008000808BL, 0x800000000000008BL, - 0x8000000000008089L, 0x8000000000008003L, - 0x8000000000008002L, 0x8000000000000080L, - 0x000000000000800AL, 0x800000008000000AL, - 0x8000000080008081L, 0x8000000000008080L, - 0x0000000080000001L, 0x8000000080008008L + 0x0000000000000001L, 0x0000000000008082L, + 0x800000000000808AL, 0x8000000080008000L, + 0x000000000000808BL, 0x0000000080000001L, + 0x8000000080008081L, 0x8000000000008009L, + 0x000000000000008AL, 0x0000000000000088L, + 0x0000000080008009L, 0x000000008000000AL, + 0x000000008000808BL, 0x800000000000008BL, + 0x8000000000008089L, 0x8000000000008003L, + 0x8000000000008002L, 0x8000000000000080L, + 0x000000000000800AL, 0x800000008000000AL, + 0x8000000080008081L, 0x8000000000008080L, + 0x0000000080000001L, 0x8000000080008008L }; /** @@ -92,16 +89,15 @@ abstract class KeccakCore extends DigestEngine { * @param buf the destination buffer * @param off the destination offset */ - private static final void encodeLELong(long val, byte[] buf, int off) - { - buf[off + 0] = (byte)val; - buf[off + 1] = (byte)(val >>> 8); - buf[off + 2] = (byte)(val >>> 16); - buf[off + 3] = (byte)(val >>> 24); - buf[off + 4] = (byte)(val >>> 32); - buf[off + 5] = (byte)(val >>> 40); - buf[off + 6] = (byte)(val >>> 48); - buf[off + 7] = (byte)(val >>> 56); + private static final void encodeLELong(long val, byte[] buf, int off) { + buf[off] = (byte) val; + buf[off + 1] = (byte) (val >>> 8); + buf[off + 2] = (byte) (val >>> 16); + buf[off + 3] = (byte) (val >>> 24); + buf[off + 4] = (byte) (val >>> 32); + buf[off + 5] = (byte) (val >>> 40); + buf[off + 6] = (byte) (val >>> 48); + buf[off + 7] = (byte) (val >>> 56); } /** @@ -112,9 +108,8 @@ abstract class KeccakCore extends DigestEngine { * @param off the source offset * @return the decoded value */ - private static final long decodeLELong(byte[] buf, int off) - { - return (buf[off + 0] & 0xFFL) + private static final long decodeLELong(byte[] buf, int off) { + return (buf[off] & 0xFFL) | ((buf[off + 1] & 0xFFL) << 8) | ((buf[off + 2] & 0xFFL) << 16) | ((buf[off + 3] & 0xFFL) << 24) @@ -125,215 +120,212 @@ abstract class KeccakCore extends DigestEngine { } /** @see DigestEngine */ - protected void engineReset() - { + protected void engineReset() { doReset(); } /** @see DigestEngine */ - protected void processBlock(byte[] data) - { - /* Input block */ - for (int i = 0; i < data.length; i += 8) - A[i >>> 3] ^= decodeLELong(data, i); + protected void processBlock(byte[] data) { + /* Input block */ + for (int i = 0; i < data.length; i += 8) A[i >>> 3] ^= decodeLELong(data, i); long t0, t1, t2, t3, t4; long tt0, tt1, tt2, tt3, tt4; long t, kt; long c0, c1, c2, c3, c4, bnn; - /* - * Unrolling four rounds kills performance big time - * on Intel x86 Core2, in both 32-bit and 64-bit modes - * (less than 1 MB/s instead of 55 MB/s on x86-64). - * Unrolling two rounds appears to be fine. - */ + /* + * Unrolling four rounds kills performance big time + * on Intel x86 Core2, in both 32-bit and 64-bit modes + * (less than 1 MB/s instead of 55 MB/s on x86-64). + * Unrolling two rounds appears to be fine. + */ for (int j = 0; j < 24; j += 2) { - tt0 = A[ 1] ^ A[ 6]; + tt0 = A[1] ^ A[6]; tt1 = A[11] ^ A[16]; tt0 ^= A[21] ^ tt1; tt0 = (tt0 << 1) | (tt0 >>> 63); - tt2 = A[ 4] ^ A[ 9]; + tt2 = A[4] ^ A[9]; tt3 = A[14] ^ A[19]; tt0 ^= A[24]; tt2 ^= tt3; t0 = tt0 ^ tt2; - tt0 = A[ 2] ^ A[ 7]; + tt0 = A[2] ^ A[7]; tt1 = A[12] ^ A[17]; tt0 ^= A[22] ^ tt1; tt0 = (tt0 << 1) | (tt0 >>> 63); - tt2 = A[ 0] ^ A[ 5]; + tt2 = A[0] ^ A[5]; tt3 = A[10] ^ A[15]; tt0 ^= A[20]; tt2 ^= tt3; t1 = tt0 ^ tt2; - tt0 = A[ 3] ^ A[ 8]; + tt0 = A[3] ^ A[8]; tt1 = A[13] ^ A[18]; tt0 ^= A[23] ^ tt1; tt0 = (tt0 << 1) | (tt0 >>> 63); - tt2 = A[ 1] ^ A[ 6]; + tt2 = A[1] ^ A[6]; tt3 = A[11] ^ A[16]; tt0 ^= A[21]; tt2 ^= tt3; t2 = tt0 ^ tt2; - tt0 = A[ 4] ^ A[ 9]; + tt0 = A[4] ^ A[9]; tt1 = A[14] ^ A[19]; tt0 ^= A[24] ^ tt1; tt0 = (tt0 << 1) | (tt0 >>> 63); - tt2 = A[ 2] ^ A[ 7]; + tt2 = A[2] ^ A[7]; tt3 = A[12] ^ A[17]; tt0 ^= A[22]; tt2 ^= tt3; t3 = tt0 ^ tt2; - tt0 = A[ 0] ^ A[ 5]; + tt0 = A[0] ^ A[5]; tt1 = A[10] ^ A[15]; tt0 ^= A[20] ^ tt1; tt0 = (tt0 << 1) | (tt0 >>> 63); - tt2 = A[ 3] ^ A[ 8]; + tt2 = A[3] ^ A[8]; tt3 = A[13] ^ A[18]; tt0 ^= A[23]; tt2 ^= tt3; t4 = tt0 ^ tt2; - A[ 0] = A[ 0] ^ t0; - A[ 5] = A[ 5] ^ t0; + A[0] = A[0] ^ t0; + A[5] = A[5] ^ t0; A[10] = A[10] ^ t0; A[15] = A[15] ^ t0; A[20] = A[20] ^ t0; - A[ 1] = A[ 1] ^ t1; - A[ 6] = A[ 6] ^ t1; + A[1] = A[1] ^ t1; + A[6] = A[6] ^ t1; A[11] = A[11] ^ t1; A[16] = A[16] ^ t1; A[21] = A[21] ^ t1; - A[ 2] = A[ 2] ^ t2; - A[ 7] = A[ 7] ^ t2; + A[2] = A[2] ^ t2; + A[7] = A[7] ^ t2; A[12] = A[12] ^ t2; A[17] = A[17] ^ t2; A[22] = A[22] ^ t2; - A[ 3] = A[ 3] ^ t3; - A[ 8] = A[ 8] ^ t3; + A[3] = A[3] ^ t3; + A[8] = A[8] ^ t3; A[13] = A[13] ^ t3; A[18] = A[18] ^ t3; A[23] = A[23] ^ t3; - A[ 4] = A[ 4] ^ t4; - A[ 9] = A[ 9] ^ t4; + A[4] = A[4] ^ t4; + A[9] = A[9] ^ t4; A[14] = A[14] ^ t4; A[19] = A[19] ^ t4; A[24] = A[24] ^ t4; - A[ 5] = (A[ 5] << 36) | (A[ 5] >>> (64 - 36)); + A[5] = (A[5] << 36) | (A[5] >>> (64 - 36)); A[10] = (A[10] << 3) | (A[10] >>> (64 - 3)); A[15] = (A[15] << 41) | (A[15] >>> (64 - 41)); A[20] = (A[20] << 18) | (A[20] >>> (64 - 18)); - A[ 1] = (A[ 1] << 1) | (A[ 1] >>> (64 - 1)); - A[ 6] = (A[ 6] << 44) | (A[ 6] >>> (64 - 44)); + A[1] = (A[1] << 1) | (A[1] >>> (64 - 1)); + A[6] = (A[6] << 44) | (A[6] >>> (64 - 44)); A[11] = (A[11] << 10) | (A[11] >>> (64 - 10)); A[16] = (A[16] << 45) | (A[16] >>> (64 - 45)); A[21] = (A[21] << 2) | (A[21] >>> (64 - 2)); - A[ 2] = (A[ 2] << 62) | (A[ 2] >>> (64 - 62)); - A[ 7] = (A[ 7] << 6) | (A[ 7] >>> (64 - 6)); + A[2] = (A[2] << 62) | (A[2] >>> (64 - 62)); + A[7] = (A[7] << 6) | (A[7] >>> (64 - 6)); A[12] = (A[12] << 43) | (A[12] >>> (64 - 43)); A[17] = (A[17] << 15) | (A[17] >>> (64 - 15)); A[22] = (A[22] << 61) | (A[22] >>> (64 - 61)); - A[ 3] = (A[ 3] << 28) | (A[ 3] >>> (64 - 28)); - A[ 8] = (A[ 8] << 55) | (A[ 8] >>> (64 - 55)); + A[3] = (A[3] << 28) | (A[3] >>> (64 - 28)); + A[8] = (A[8] << 55) | (A[8] >>> (64 - 55)); A[13] = (A[13] << 25) | (A[13] >>> (64 - 25)); A[18] = (A[18] << 21) | (A[18] >>> (64 - 21)); A[23] = (A[23] << 56) | (A[23] >>> (64 - 56)); - A[ 4] = (A[ 4] << 27) | (A[ 4] >>> (64 - 27)); - A[ 9] = (A[ 9] << 20) | (A[ 9] >>> (64 - 20)); + A[4] = (A[4] << 27) | (A[4] >>> (64 - 27)); + A[9] = (A[9] << 20) | (A[9] >>> (64 - 20)); A[14] = (A[14] << 39) | (A[14] >>> (64 - 39)); A[19] = (A[19] << 8) | (A[19] >>> (64 - 8)); A[24] = (A[24] << 14) | (A[24] >>> (64 - 14)); bnn = ~A[12]; - kt = A[ 6] | A[12]; - c0 = A[ 0] ^ kt; + kt = A[6] | A[12]; + c0 = A[0] ^ kt; kt = bnn | A[18]; - c1 = A[ 6] ^ kt; + c1 = A[6] ^ kt; kt = A[18] & A[24]; c2 = A[12] ^ kt; - kt = A[24] | A[ 0]; + kt = A[24] | A[0]; c3 = A[18] ^ kt; - kt = A[ 0] & A[ 6]; + kt = A[0] & A[6]; c4 = A[24] ^ kt; - A[ 0] = c0; - A[ 6] = c1; + A[0] = c0; + A[6] = c1; A[12] = c2; A[18] = c3; A[24] = c4; bnn = ~A[22]; - kt = A[ 9] | A[10]; - c0 = A[ 3] ^ kt; + kt = A[9] | A[10]; + c0 = A[3] ^ kt; kt = A[10] & A[16]; - c1 = A[ 9] ^ kt; + c1 = A[9] ^ kt; kt = A[16] | bnn; c2 = A[10] ^ kt; - kt = A[22] | A[ 3]; + kt = A[22] | A[3]; c3 = A[16] ^ kt; - kt = A[ 3] & A[ 9]; + kt = A[3] & A[9]; c4 = A[22] ^ kt; - A[ 3] = c0; - A[ 9] = c1; + A[3] = c0; + A[9] = c1; A[10] = c2; A[16] = c3; A[22] = c4; bnn = ~A[19]; - kt = A[ 7] | A[13]; - c0 = A[ 1] ^ kt; + kt = A[7] | A[13]; + c0 = A[1] ^ kt; kt = A[13] & A[19]; - c1 = A[ 7] ^ kt; + c1 = A[7] ^ kt; kt = bnn & A[20]; c2 = A[13] ^ kt; - kt = A[20] | A[ 1]; + kt = A[20] | A[1]; c3 = bnn ^ kt; - kt = A[ 1] & A[ 7]; + kt = A[1] & A[7]; c4 = A[20] ^ kt; - A[ 1] = c0; - A[ 7] = c1; + A[1] = c0; + A[7] = c1; A[13] = c2; A[19] = c3; A[20] = c4; bnn = ~A[17]; - kt = A[ 5] & A[11]; - c0 = A[ 4] ^ kt; + kt = A[5] & A[11]; + c0 = A[4] ^ kt; kt = A[11] | A[17]; - c1 = A[ 5] ^ kt; + c1 = A[5] ^ kt; kt = bnn | A[23]; c2 = A[11] ^ kt; - kt = A[23] & A[ 4]; + kt = A[23] & A[4]; c3 = bnn ^ kt; - kt = A[ 4] | A[ 5]; + kt = A[4] | A[5]; c4 = A[23] ^ kt; - A[ 4] = c0; - A[ 5] = c1; + A[4] = c0; + A[5] = c1; A[11] = c2; A[17] = c3; A[23] = c4; - bnn = ~A[ 8]; + bnn = ~A[8]; kt = bnn & A[14]; - c0 = A[ 2] ^ kt; + c0 = A[2] ^ kt; kt = A[14] | A[15]; c1 = bnn ^ kt; kt = A[15] & A[21]; c2 = A[14] ^ kt; - kt = A[21] | A[ 2]; + kt = A[21] | A[2]; c3 = A[15] ^ kt; - kt = A[ 2] & A[ 8]; + kt = A[2] & A[8]; c4 = A[21] ^ kt; - A[ 2] = c0; - A[ 8] = c1; + A[2] = c0; + A[8] = c1; A[14] = c2; A[15] = c3; A[21] = c4; - A[ 0] = A[ 0] ^ RC[j + 0]; + A[0] = A[0] ^ RC[j]; - tt0 = A[ 6] ^ A[ 9]; - tt1 = A[ 7] ^ A[ 5]; - tt0 ^= A[ 8] ^ tt1; + tt0 = A[6] ^ A[9]; + tt1 = A[7] ^ A[5]; + tt0 ^= A[8] ^ tt1; tt0 = (tt0 << 1) | (tt0 >>> 63); tt2 = A[24] ^ A[22]; tt3 = A[20] ^ A[23]; @@ -345,9 +337,9 @@ abstract class KeccakCore extends DigestEngine { tt1 = A[13] ^ A[11]; tt0 ^= A[14] ^ tt1; tt0 = (tt0 << 1) | (tt0 >>> 63); - tt2 = A[ 0] ^ A[ 3]; - tt3 = A[ 1] ^ A[ 4]; - tt0 ^= A[ 2]; + tt2 = A[0] ^ A[3]; + tt3 = A[1] ^ A[4]; + tt0 ^= A[2]; tt2 ^= tt3; t1 = tt0 ^ tt2; @@ -355,9 +347,9 @@ abstract class KeccakCore extends DigestEngine { tt1 = A[19] ^ A[17]; tt0 ^= A[15] ^ tt1; tt0 = (tt0 << 1) | (tt0 >>> 63); - tt2 = A[ 6] ^ A[ 9]; - tt3 = A[ 7] ^ A[ 5]; - tt0 ^= A[ 8]; + tt2 = A[6] ^ A[9]; + tt3 = A[7] ^ A[5]; + tt0 ^= A[8]; tt2 ^= tt3; t2 = tt0 ^ tt2; @@ -371,9 +363,9 @@ abstract class KeccakCore extends DigestEngine { tt2 ^= tt3; t3 = tt0 ^ tt2; - tt0 = A[ 0] ^ A[ 3]; - tt1 = A[ 1] ^ A[ 4]; - tt0 ^= A[ 2] ^ tt1; + tt0 = A[0] ^ A[3]; + tt1 = A[1] ^ A[4]; + tt0 ^= A[2] ^ tt1; tt0 = (tt0 << 1) | (tt0 >>> 63); tt2 = A[18] ^ A[16]; tt3 = A[19] ^ A[17]; @@ -381,16 +373,16 @@ abstract class KeccakCore extends DigestEngine { tt2 ^= tt3; t4 = tt0 ^ tt2; - A[ 0] = A[ 0] ^ t0; - A[ 3] = A[ 3] ^ t0; - A[ 1] = A[ 1] ^ t0; - A[ 4] = A[ 4] ^ t0; - A[ 2] = A[ 2] ^ t0; - A[ 6] = A[ 6] ^ t1; - A[ 9] = A[ 9] ^ t1; - A[ 7] = A[ 7] ^ t1; - A[ 5] = A[ 5] ^ t1; - A[ 8] = A[ 8] ^ t1; + A[0] = A[0] ^ t0; + A[3] = A[3] ^ t0; + A[1] = A[1] ^ t0; + A[4] = A[4] ^ t0; + A[2] = A[2] ^ t0; + A[6] = A[6] ^ t1; + A[9] = A[9] ^ t1; + A[7] = A[7] ^ t1; + A[5] = A[5] ^ t1; + A[8] = A[8] ^ t1; A[12] = A[12] ^ t2; A[10] = A[10] ^ t2; A[13] = A[13] ^ t2; @@ -406,15 +398,15 @@ abstract class KeccakCore extends DigestEngine { A[20] = A[20] ^ t4; A[23] = A[23] ^ t4; A[21] = A[21] ^ t4; - A[ 3] = (A[ 3] << 36) | (A[ 3] >>> (64 - 36)); - A[ 1] = (A[ 1] << 3) | (A[ 1] >>> (64 - 3)); - A[ 4] = (A[ 4] << 41) | (A[ 4] >>> (64 - 41)); - A[ 2] = (A[ 2] << 18) | (A[ 2] >>> (64 - 18)); - A[ 6] = (A[ 6] << 1) | (A[ 6] >>> (64 - 1)); - A[ 9] = (A[ 9] << 44) | (A[ 9] >>> (64 - 44)); - A[ 7] = (A[ 7] << 10) | (A[ 7] >>> (64 - 10)); - A[ 5] = (A[ 5] << 45) | (A[ 5] >>> (64 - 45)); - A[ 8] = (A[ 8] << 2) | (A[ 8] >>> (64 - 2)); + A[3] = (A[3] << 36) | (A[3] >>> (64 - 36)); + A[1] = (A[1] << 3) | (A[1] >>> (64 - 3)); + A[4] = (A[4] << 41) | (A[4] >>> (64 - 41)); + A[2] = (A[2] << 18) | (A[2] >>> (64 - 18)); + A[6] = (A[6] << 1) | (A[6] >>> (64 - 1)); + A[9] = (A[9] << 44) | (A[9] >>> (64 - 44)); + A[7] = (A[7] << 10) | (A[7] >>> (64 - 10)); + A[5] = (A[5] << 45) | (A[5] >>> (64 - 45)); + A[8] = (A[8] << 2) | (A[8] >>> (64 - 2)); A[12] = (A[12] << 62) | (A[12] >>> (64 - 62)); A[10] = (A[10] << 6) | (A[10] >>> (64 - 6)); A[13] = (A[13] << 43) | (A[13] >>> (64 - 43)); @@ -431,177 +423,168 @@ abstract class KeccakCore extends DigestEngine { A[23] = (A[23] << 8) | (A[23] >>> (64 - 8)); A[21] = (A[21] << 14) | (A[21] >>> (64 - 14)); bnn = ~A[13]; - kt = A[ 9] | A[13]; - c0 = A[ 0] ^ kt; + kt = A[9] | A[13]; + c0 = A[0] ^ kt; kt = bnn | A[17]; - c1 = A[ 9] ^ kt; + c1 = A[9] ^ kt; kt = A[17] & A[21]; c2 = A[13] ^ kt; - kt = A[21] | A[ 0]; + kt = A[21] | A[0]; c3 = A[17] ^ kt; - kt = A[ 0] & A[ 9]; + kt = A[0] & A[9]; c4 = A[21] ^ kt; - A[ 0] = c0; - A[ 9] = c1; + A[0] = c0; + A[9] = c1; A[13] = c2; A[17] = c3; A[21] = c4; bnn = ~A[14]; - kt = A[22] | A[ 1]; + kt = A[22] | A[1]; c0 = A[18] ^ kt; - kt = A[ 1] & A[ 5]; + kt = A[1] & A[5]; c1 = A[22] ^ kt; - kt = A[ 5] | bnn; - c2 = A[ 1] ^ kt; + kt = A[5] | bnn; + c2 = A[1] ^ kt; kt = A[14] | A[18]; - c3 = A[ 5] ^ kt; + c3 = A[5] ^ kt; kt = A[18] & A[22]; c4 = A[14] ^ kt; A[18] = c0; A[22] = c1; - A[ 1] = c2; - A[ 5] = c3; + A[1] = c2; + A[5] = c3; A[14] = c4; bnn = ~A[23]; kt = A[10] | A[19]; - c0 = A[ 6] ^ kt; + c0 = A[6] ^ kt; kt = A[19] & A[23]; c1 = A[10] ^ kt; - kt = bnn & A[ 2]; + kt = bnn & A[2]; c2 = A[19] ^ kt; - kt = A[ 2] | A[ 6]; + kt = A[2] | A[6]; c3 = bnn ^ kt; - kt = A[ 6] & A[10]; - c4 = A[ 2] ^ kt; - A[ 6] = c0; + kt = A[6] & A[10]; + c4 = A[2] ^ kt; + A[6] = c0; A[10] = c1; A[19] = c2; A[23] = c3; - A[ 2] = c4; + A[2] = c4; bnn = ~A[11]; - kt = A[ 3] & A[ 7]; + kt = A[3] & A[7]; c0 = A[24] ^ kt; - kt = A[ 7] | A[11]; - c1 = A[ 3] ^ kt; + kt = A[7] | A[11]; + c1 = A[3] ^ kt; kt = bnn | A[15]; - c2 = A[ 7] ^ kt; + c2 = A[7] ^ kt; kt = A[15] & A[24]; c3 = bnn ^ kt; - kt = A[24] | A[ 3]; + kt = A[24] | A[3]; c4 = A[15] ^ kt; A[24] = c0; - A[ 3] = c1; - A[ 7] = c2; + A[3] = c1; + A[7] = c2; A[11] = c3; A[15] = c4; bnn = ~A[16]; kt = bnn & A[20]; c0 = A[12] ^ kt; - kt = A[20] | A[ 4]; + kt = A[20] | A[4]; c1 = bnn ^ kt; - kt = A[ 4] & A[ 8]; + kt = A[4] & A[8]; c2 = A[20] ^ kt; - kt = A[ 8] | A[12]; - c3 = A[ 4] ^ kt; + kt = A[8] | A[12]; + c3 = A[4] ^ kt; kt = A[12] & A[16]; - c4 = A[ 8] ^ kt; + c4 = A[8] ^ kt; A[12] = c0; A[16] = c1; A[20] = c2; - A[ 4] = c3; - A[ 8] = c4; - A[ 0] = A[ 0] ^ RC[j + 1]; - t = A[ 5]; - A[ 5] = A[18]; + A[4] = c3; + A[8] = c4; + A[0] = A[0] ^ RC[j + 1]; + t = A[5]; + A[5] = A[18]; A[18] = A[11]; A[11] = A[10]; - A[10] = A[ 6]; - A[ 6] = A[22]; + A[10] = A[6]; + A[6] = A[22]; A[22] = A[20]; A[20] = A[12]; A[12] = A[19]; A[19] = A[15]; A[15] = A[24]; - A[24] = A[ 8]; - A[ 8] = t; - t = A[ 1]; - A[ 1] = A[ 9]; - A[ 9] = A[14]; - A[14] = A[ 2]; - A[ 2] = A[13]; + A[24] = A[8]; + A[8] = t; + t = A[1]; + A[1] = A[9]; + A[9] = A[14]; + A[14] = A[2]; + A[2] = A[13]; A[13] = A[23]; - A[23] = A[ 4]; - A[ 4] = A[21]; + A[23] = A[4]; + A[4] = A[21]; A[21] = A[16]; - A[16] = A[ 3]; - A[ 3] = A[17]; - A[17] = A[ 7]; - A[ 7] = t; + A[16] = A[3]; + A[3] = A[17]; + A[17] = A[7]; + A[7] = t; } } /** @see DigestEngine */ - protected void doPadding(byte[] out, int off) - { + protected void doPadding(byte[] out, int off) { int ptr = flush(); byte[] buf = getBlockBuffer(); if ((ptr + 1) == buf.length) { - buf[ptr] = (byte)0x81; + buf[ptr] = (byte) 0x81; } else { - buf[ptr] = (byte)0x01; - for (int i = ptr + 1; i < (buf.length - 1); i ++) - buf[i] = 0; - buf[buf.length - 1] = (byte)0x80; + buf[ptr] = (byte) 0x01; + for (int i = ptr + 1; i < (buf.length - 1); i++) buf[i] = 0; + buf[buf.length - 1] = (byte) 0x80; } processBlock(buf); - A[ 1] = ~A[ 1]; - A[ 2] = ~A[ 2]; - A[ 8] = ~A[ 8]; + A[1] = ~A[1]; + A[2] = ~A[2]; + A[8] = ~A[8]; A[12] = ~A[12]; A[17] = ~A[17]; A[20] = ~A[20]; int dlen = getDigestLength(); - for (int i = 0; i < dlen; i += 8) - encodeLELong(A[i >>> 3], tmpOut, i); + for (int i = 0; i < dlen; i += 8) encodeLELong(A[i >>> 3], tmpOut, i); System.arraycopy(tmpOut, 0, out, off, dlen); } /** @see DigestEngine */ - protected void doInit() - { + protected void doInit() { A = new long[25]; tmpOut = new byte[(getDigestLength() + 7) & ~7]; doReset(); } /** @see Digest */ - public int getBlockLength() - { + public int getBlockLength() { return 200 - 2 * getDigestLength(); } - private final void doReset() - { - for (int i = 0; i < 25; i ++) - A[i] = 0; - A[ 1] = 0xFFFFFFFFFFFFFFFFL; - A[ 2] = 0xFFFFFFFFFFFFFFFFL; - A[ 8] = 0xFFFFFFFFFFFFFFFFL; + private final void doReset() { + for (int i = 0; i < 25; i++) A[i] = 0; + A[1] = 0xFFFFFFFFFFFFFFFFL; + A[2] = 0xFFFFFFFFFFFFFFFFL; + A[8] = 0xFFFFFFFFFFFFFFFFL; A[12] = 0xFFFFFFFFFFFFFFFFL; A[17] = 0xFFFFFFFFFFFFFFFFL; A[20] = 0xFFFFFFFFFFFFFFFFL; } /** @see DigestEngine */ - protected Digest copyState(KeccakCore dst) - { + protected Digest copyState(KeccakCore dst) { System.arraycopy(A, 0, dst.A, 0, 25); return super.copyState(dst); } /** @see Digest */ - public String toString() - { + public String toString() { return "Keccak-" + (getDigestLength() << 3); } -} \ No newline at end of file +} diff --git a/jami-dht/src/main/java/net/jami/jams/dht/hashutils/MDHelper.java b/jami-dht/src/main/java/net/jami/jams/dht/hashutils/MDHelper.java index 4ce77eb5584788f32a56b0244561b3e0f206fbf8..27ac58e2c4bd4ffc815fb7892f83d48b55858612 100755 --- a/jami-dht/src/main/java/net/jami/jams/dht/hashutils/MDHelper.java +++ b/jami-dht/src/main/java/net/jami/jams/dht/hashutils/MDHelper.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ // $Id: MDHelper.java 157 2010-04-26 19:03:44Z tp $ package net.jami.jams.dht.hashutils; @@ -33,7 +33,7 @@ package net.jami.jams.dht.hashutils; * ==========================(LICENSE BEGIN)============================ * * Copyright (c) 2007-2010 Projet RNRT SAPHIR - * + * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including @@ -41,10 +41,10 @@ package net.jami.jams.dht.hashutils; * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. @@ -59,118 +59,109 @@ package net.jami.jams.dht.hashutils; * @version $Revision: 157 $ * @author Thomas Pornin <thomas.pornin@cryptolog.com> */ - abstract class MDHelper extends DigestEngine { - /** - * Create the object. Little-endian padding is for MD4, MD5 and - * RIPEMD-160; the SHA family uses big-endian padding. The - * MD padding includes an encoding of the input message bit length, - * which is over 64 bits for some algorithms, 128-bit for others - * (namely SHA-384 and SHA-512). Note that this implementation - * handles only message lengths which fit on 64 bits. - * - * @param littleEndian {@code true} for little-endian padding - * @param lenlen the length encoding length, in bytes (must - * be at least 8) - */ - MDHelper(boolean littleEndian, int lenlen) - { - this(littleEndian, lenlen, (byte)0x80); - } + /** + * Create the object. Little-endian padding is for MD4, MD5 and + * RIPEMD-160; the SHA family uses big-endian padding. The + * MD padding includes an encoding of the input message bit length, + * which is over 64 bits for some algorithms, 128-bit for others + * (namely SHA-384 and SHA-512). Note that this implementation + * handles only message lengths which fit on 64 bits. + * + * @param littleEndian {@code true} for little-endian padding + * @param lenlen the length encoding length, in bytes (must + * be at least 8) + */ + MDHelper(boolean littleEndian, int lenlen) { + this(littleEndian, lenlen, (byte) 0x80); + } - /** - * Create the object. Little-endian padding is for MD4, MD5 and - * RIPEMD-160; the SHA family uses big-endian padding. The - * MD padding includes an encoding of the input message bit length, - * which is over 64 bits for some algorithms, 128-bit for others - * (namely SHA-384 and SHA-512). Note that this implementation - * handles only message lengths which fit on 64 bits. The first - * additional byte value is specified; this is normally 0x80, - * except for Tiger (not Tiger2) which uses 0x01. - * - * @param littleEndian {@code true} for little-endian padding - * @param lenlen the length encoding length, in bytes (must - * be at least 8) - * @param fbyte the first padding byte - */ - MDHelper(boolean littleEndian, int lenlen, byte fbyte) - { - this.littleEndian = littleEndian; - countBuf = new byte[lenlen]; - this.fbyte = fbyte; - } + /** + * Create the object. Little-endian padding is for MD4, MD5 and + * RIPEMD-160; the SHA family uses big-endian padding. The + * MD padding includes an encoding of the input message bit length, + * which is over 64 bits for some algorithms, 128-bit for others + * (namely SHA-384 and SHA-512). Note that this implementation + * handles only message lengths which fit on 64 bits. The first + * additional byte value is specified; this is normally 0x80, + * except for Tiger (not Tiger2) which uses 0x01. + * + * @param littleEndian {@code true} for little-endian padding + * @param lenlen the length encoding length, in bytes (must + * be at least 8) + * @param fbyte the first padding byte + */ + MDHelper(boolean littleEndian, int lenlen, byte fbyte) { + this.littleEndian = littleEndian; + countBuf = new byte[lenlen]; + this.fbyte = fbyte; + } - private boolean littleEndian; - private byte[] countBuf; - private byte fbyte; + private final boolean littleEndian; + private final byte[] countBuf; + private final byte fbyte; - /** - * Compute the padding. The padding data is input into the engine, - * which is flushed. - */ - protected void makeMDPadding() - { - int dataLen = flush(); - int blen = getBlockLength(); - long currentLength = getBlockCount() * (long)blen; - currentLength = (currentLength + (long)dataLen) * 8L; - int lenlen = countBuf.length; - if (littleEndian) { - encodeLEInt((int)currentLength, countBuf, 0); - encodeLEInt((int)(currentLength >>> 32), countBuf, 4); - } else { - encodeBEInt((int)(currentLength >>> 32), - countBuf, lenlen - 8); - encodeBEInt((int)currentLength, - countBuf, lenlen - 4); - } - int endLen = (dataLen + lenlen + blen) & ~(blen - 1); - update(fbyte); - for (int i = dataLen + 1; i < endLen - lenlen; i ++) - update((byte)0); - update(countBuf); + /** + * Compute the padding. The padding data is input into the engine, + * which is flushed. + */ + protected void makeMDPadding() { + int dataLen = flush(); + int blen = getBlockLength(); + long currentLength = getBlockCount() * (long) blen; + currentLength = (currentLength + (long) dataLen) * 8L; + int lenlen = countBuf.length; + if (littleEndian) { + encodeLEInt((int) currentLength, countBuf, 0); + encodeLEInt((int) (currentLength >>> 32), countBuf, 4); + } else { + encodeBEInt((int) (currentLength >>> 32), countBuf, lenlen - 8); + encodeBEInt((int) currentLength, countBuf, lenlen - 4); + } + int endLen = (dataLen + lenlen + blen) & ~(blen - 1); + update(fbyte); + for (int i = dataLen + 1; i < endLen - lenlen; i++) update((byte) 0); + update(countBuf); - /* - * This code is used only for debugging purposes. - * - if (flush() != 0) - throw new Error("panic: buffering went astray"); - * - */ - } + /* + * This code is used only for debugging purposes. + * + if (flush() != 0) + throw new Error("panic: buffering went astray"); + * + */ + } - /** - * Encode the 32-bit word {@code val} into the array - * {@code buf} at offset {@code off}, in little-endian - * convention (least significant byte first). - * - * @param val the value to encode - * @param buf the destination buffer - * @param off the destination offset - */ - private static final void encodeLEInt(int val, byte[] buf, int off) - { - buf[off + 0] = (byte)val; - buf[off + 1] = (byte)(val >>> 8); - buf[off + 2] = (byte)(val >>> 16); - buf[off + 3] = (byte)(val >>> 24); - } + /** + * Encode the 32-bit word {@code val} into the array + * {@code buf} at offset {@code off}, in little-endian + * convention (least significant byte first). + * + * @param val the value to encode + * @param buf the destination buffer + * @param off the destination offset + */ + private static final void encodeLEInt(int val, byte[] buf, int off) { + buf[off] = (byte) val; + buf[off + 1] = (byte) (val >>> 8); + buf[off + 2] = (byte) (val >>> 16); + buf[off + 3] = (byte) (val >>> 24); + } - /** - * Encode the 32-bit word {@code val} into the array - * {@code buf} at offset {@code off}, in big-endian - * convention (most significant byte first). - * - * @param val the value to encode - * @param buf the destination buffer - * @param off the destination offset - */ - private static final void encodeBEInt(int val, byte[] buf, int off) - { - buf[off + 0] = (byte)(val >>> 24); - buf[off + 1] = (byte)(val >>> 16); - buf[off + 2] = (byte)(val >>> 8); - buf[off + 3] = (byte)val; - } + /** + * Encode the 32-bit word {@code val} into the array + * {@code buf} at offset {@code off}, in big-endian + * convention (most significant byte first). + * + * @param val the value to encode + * @param buf the destination buffer + * @param off the destination offset + */ + private static final void encodeBEInt(int val, byte[] buf, int off) { + buf[off] = (byte) (val >>> 24); + buf[off + 1] = (byte) (val >>> 16); + buf[off + 2] = (byte) (val >>> 8); + buf[off + 3] = (byte) val; + } } diff --git a/jami-dht/src/main/java/net/jami/jams/dht/hashutils/SHA2Core.java b/jami-dht/src/main/java/net/jami/jams/dht/hashutils/SHA2Core.java index 8c3abc05cee00e1c1dfaf7d65cf09cb8439c8ac8..be76dae4e50c61ba9de6e4644d01023c87bba0cb 100755 --- a/jami-dht/src/main/java/net/jami/jams/dht/hashutils/SHA2Core.java +++ b/jami-dht/src/main/java/net/jami/jams/dht/hashutils/SHA2Core.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ // $Id: SHA2Core.java 214 2010-06-03 17:25:08Z tp $ package net.jami.jams.dht.hashutils; @@ -32,7 +32,7 @@ package net.jami.jams.dht.hashutils; * ==========================(LICENSE BEGIN)============================ * * Copyright (c) 2007-2010 Projet RNRT SAPHIR - * + * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including @@ -40,10 +40,10 @@ package net.jami.jams.dht.hashutils; * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: - * + * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. @@ -58,596 +58,590 @@ package net.jami.jams.dht.hashutils; * @version $Revision: 214 $ * @author Thomas Pornin <thomas.pornin@cryptolog.com> */ - abstract class SHA2Core extends MDHelper { - /** - * Create the object. - */ - SHA2Core() - { - super(false, 8); - } + /** + * Create the object. + */ + SHA2Core() { + super(false, 8); + } - /** private special values. */ - private static final int[] K = { - 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, - 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, - 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, - 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, - 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, - 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, - 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, - 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, - 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, - 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, - 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, - 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, - 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, - 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, - 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, - 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 - }; + /** private special values. */ + private static final int[] K = { + 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, + 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, + 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, + 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, + 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, + 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, + 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, + 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, + 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, + 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, + 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, + 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, + 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, + 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, + 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, + 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 + }; - private int[] currentVal, W; + private int[] currentVal, W; - /** @see DigestEngine */ - protected Digest copyState(SHA2Core dst) - { - System.arraycopy(currentVal, 0, dst.currentVal, 0, - currentVal.length); - return super.copyState(dst); - } + /** @see DigestEngine */ + protected Digest copyState(SHA2Core dst) { + System.arraycopy(currentVal, 0, dst.currentVal, 0, currentVal.length); + return super.copyState(dst); + } - /** @see Digest */ - public int getBlockLength() - { - return 64; - } + /** @see Digest */ + public int getBlockLength() { + return 64; + } - /** @see DigestEngine */ - protected void engineReset() - { - System.arraycopy(getInitVal(), 0, currentVal, 0, 8); - } + /** @see DigestEngine */ + protected void engineReset() { + System.arraycopy(getInitVal(), 0, currentVal, 0, 8); + } - /** - * Get the initial value for this algorithm. - * - * @return the initial value (eight 32-bit words) - */ - abstract int[] getInitVal(); + /** + * Get the initial value for this algorithm. + * + * @return the initial value (eight 32-bit words) + */ + abstract int[] getInitVal(); - /** @see DigestEngine */ - protected void doPadding(byte[] output, int outputOffset) - { - makeMDPadding(); - int olen = getDigestLength(); - for (int i = 0, j = 0; j < olen; i ++, j += 4) - encodeBEInt(currentVal[i], output, outputOffset + j); - } + /** @see DigestEngine */ + protected void doPadding(byte[] output, int outputOffset) { + makeMDPadding(); + int olen = getDigestLength(); + for (int i = 0, j = 0; j < olen; i++, j += 4) + encodeBEInt(currentVal[i], output, outputOffset + j); + } - /** @see DigestEngine */ - protected void doInit() - { - currentVal = new int[8]; - W = new int[64]; - engineReset(); - } + /** @see DigestEngine */ + protected void doInit() { + currentVal = new int[8]; + W = new int[64]; + engineReset(); + } - /** - * Encode the 32-bit word {@code val} into the array - * {@code buf} at offset {@code off}, in big-endian - * convention (most significant byte first). - * - * @param val the value to encode - * @param buf the destination buffer - * @param off the destination offset - */ - private static final void encodeBEInt(int val, byte[] buf, int off) - { - buf[off + 0] = (byte)(val >>> 24); - buf[off + 1] = (byte)(val >>> 16); - buf[off + 2] = (byte)(val >>> 8); - buf[off + 3] = (byte)val; - } + /** + * Encode the 32-bit word {@code val} into the array + * {@code buf} at offset {@code off}, in big-endian + * convention (most significant byte first). + * + * @param val the value to encode + * @param buf the destination buffer + * @param off the destination offset + */ + private static final void encodeBEInt(int val, byte[] buf, int off) { + buf[off] = (byte) (val >>> 24); + buf[off + 1] = (byte) (val >>> 16); + buf[off + 2] = (byte) (val >>> 8); + buf[off + 3] = (byte) val; + } - /** - * Decode a 32-bit big-endian word from the array {@code buf} - * at offset {@code off}. - * - * @param buf the source buffer - * @param off the source offset - * @return the decoded value - */ - private static final int decodeBEInt(byte[] buf, int off) - { - return ((buf[off] & 0xFF) << 24) - | ((buf[off + 1] & 0xFF) << 16) - | ((buf[off + 2] & 0xFF) << 8) - | (buf[off + 3] & 0xFF); - } + /** + * Decode a 32-bit big-endian word from the array {@code buf} + * at offset {@code off}. + * + * @param buf the source buffer + * @param off the source offset + * @return the decoded value + */ + private static final int decodeBEInt(byte[] buf, int off) { + return ((buf[off] & 0xFF) << 24) + | ((buf[off + 1] & 0xFF) << 16) + | ((buf[off + 2] & 0xFF) << 8) + | (buf[off + 3] & 0xFF); + } - /** - * Perform a circular rotation by {@code n} to the left - * of the 32-bit word {@code x}. The {@code n} parameter - * must lie between 1 and 31 (inclusive). - * - * @param x the value to rotate - * @param n the rotation count (between 1 and 31) - * @return the rotated value - */ - static private int circularLeft(int x, int n) - { - return (x << n) | (x >>> (32 - n)); - } + /** + * Perform a circular rotation by {@code n} to the left + * of the 32-bit word {@code x}. The {@code n} parameter + * must lie between 1 and 31 (inclusive). + * + * @param x the value to rotate + * @param n the rotation count (between 1 and 31) + * @return the rotated value + */ + private static int circularLeft(int x, int n) { + return (x << n) | (x >>> (32 - n)); + } - /** @see DigestEngine */ - protected void processBlock(byte[] data) - { - int A = currentVal[0]; - int B = currentVal[1]; - int C = currentVal[2]; - int D = currentVal[3]; - int E = currentVal[4]; - int F = currentVal[5]; - int G = currentVal[6]; - int H = currentVal[7]; + /** @see DigestEngine */ + protected void processBlock(byte[] data) { + int A = currentVal[0]; + int B = currentVal[1]; + int C = currentVal[2]; + int D = currentVal[3]; + int E = currentVal[4]; + int F = currentVal[5]; + int G = currentVal[6]; + int H = currentVal[7]; - for (int i = 0; i < 16; i ++) - W[i] = decodeBEInt(data, 4 * i); - for (int i = 16; i < 64; i ++) { - W[i] = (circularLeft(W[i - 2], 15) - ^ circularLeft(W[i - 2], 13) - ^ (W[i - 2] >>> 10)) - + W[i - 7] - + (circularLeft(W[i - 15], 25) - ^ circularLeft(W[i - 15], 14) - ^ (W[i - 15] >>> 3)) - + W[i - 16]; - } - for (int i = 0; i < 64; i ++) { - int T1 = H + (circularLeft(E, 26) ^ circularLeft(E, 21) - ^ circularLeft(E, 7)) + ((F & E) ^ (G & ~E)) - + K[i] + W[i]; - int T2 = (circularLeft(A, 30) ^ circularLeft(A, 19) - ^ circularLeft(A, 10)) - + ((A & B) ^ (A & C) ^ (B & C)); - H = G; G = F; F = E; E = D + T1; - D = C; C = B; B = A; A = T1 + T2; - } - currentVal[0] += A; - currentVal[1] += B; - currentVal[2] += C; - currentVal[3] += D; - currentVal[4] += E; - currentVal[5] += F; - currentVal[6] += G; - currentVal[7] += H; + for (int i = 0; i < 16; i++) W[i] = decodeBEInt(data, 4 * i); + for (int i = 16; i < 64; i++) { + W[i] = + (circularLeft(W[i - 2], 15) ^ circularLeft(W[i - 2], 13) ^ (W[i - 2] >>> 10)) + + W[i - 7] + + (circularLeft(W[i - 15], 25) + ^ circularLeft(W[i - 15], 14) + ^ (W[i - 15] >>> 3)) + + W[i - 16]; + } + for (int i = 0; i < 64; i++) { + int T1 = + H + + (circularLeft(E, 26) ^ circularLeft(E, 21) ^ circularLeft(E, 7)) + + ((F & E) ^ (G & ~E)) + + K[i] + + W[i]; + int T2 = + (circularLeft(A, 30) ^ circularLeft(A, 19) ^ circularLeft(A, 10)) + + ((A & B) ^ (A & C) ^ (B & C)); + H = G; + G = F; + F = E; + E = D + T1; + D = C; + C = B; + B = A; + A = T1 + T2; + } + currentVal[0] += A; + currentVal[1] += B; + currentVal[2] += C; + currentVal[3] += D; + currentVal[4] += E; + currentVal[5] += F; + currentVal[6] += G; + currentVal[7] += H; - /* - * The version below unrolls 16 rounds and inlines - * rotations. It should avoid many array accesses - * (W[] is transformed into 16 local variables) and - * data routing (16 is a multiple of 8, so the - * big rotation of the eight words becomes trivial). - * Strangely enough, it yields only a very small - * performance gain (less than 10% on Intel x86 with - * Sun JDK 6, both in 32-bit and 64-bit modes). Since - * it also probably consumes much more L1 cache, the - * simpler version above is preferred. - * - int A = currentVal[0]; - int B = currentVal[1]; - int C = currentVal[2]; - int D = currentVal[3]; - int E = currentVal[4]; - int F = currentVal[5]; - int G = currentVal[6]; - int H = currentVal[7]; - int t1, t2; - int pcount = 0; - int W0 = decodeBEInt(data, 4 * 0x0); - t1 = H + (((E >>> 6) | (E << (32 - 6))) ^ ((E >>> 11) - | (E << (32 - 11))) ^ ((E >>> 25) | (E << (32 - 25)))) - + (((F ^ G) & E) ^ G) + K[pcount + 0x0] + W0; - t2 = (((A >>> 2) | (A << (32 - 2))) ^ ((A >>> 13) - | (A << (32 - 13))) ^ ((A >>> 22) | (A << (32 - 22)))) - + ((B & C) | ((B | C) & A)); - D += t1; - H = t1 + t2; - int W1 = decodeBEInt(data, 4 * 0x1); - t1 = G + (((D >>> 6) | (D << (32 - 6))) ^ ((D >>> 11) - | (D << (32 - 11))) ^ ((D >>> 25) | (D << (32 - 25)))) - + (((E ^ F) & D) ^ F) + K[pcount + 0x1] + W1; - t2 = (((H >>> 2) | (H << (32 - 2))) ^ ((H >>> 13) - | (H << (32 - 13))) ^ ((H >>> 22) | (H << (32 - 22)))) - + ((A & B) | ((A | B) & H)); - C += t1; - G = t1 + t2; - int W2 = decodeBEInt(data, 4 * 0x2); - t1 = F + (((C >>> 6) | (C << (32 - 6))) ^ ((C >>> 11) - | (C << (32 - 11))) ^ ((C >>> 25) | (C << (32 - 25)))) - + (((D ^ E) & C) ^ E) + K[pcount + 0x2] + W2; - t2 = (((G >>> 2) | (G << (32 - 2))) ^ ((G >>> 13) - | (G << (32 - 13))) ^ ((G >>> 22) | (G << (32 - 22)))) - + ((H & A) | ((H | A) & G)); - B += t1; - F = t1 + t2; - int W3 = decodeBEInt(data, 4 * 0x3); - t1 = E + (((B >>> 6) | (B << (32 - 6))) ^ ((B >>> 11) - | (B << (32 - 11))) ^ ((B >>> 25) | (B << (32 - 25)))) - + (((C ^ D) & B) ^ D) + K[pcount + 0x3] + W3; - t2 = (((F >>> 2) | (F << (32 - 2))) ^ ((F >>> 13) - | (F << (32 - 13))) ^ ((F >>> 22) | (F << (32 - 22)))) - + ((G & H) | ((G | H) & F)); - A += t1; - E = t1 + t2; - int W4 = decodeBEInt(data, 4 * 0x4); - t1 = D + (((A >>> 6) | (A << (32 - 6))) ^ ((A >>> 11) - | (A << (32 - 11))) ^ ((A >>> 25) | (A << (32 - 25)))) - + (((B ^ C) & A) ^ C) + K[pcount + 0x4] + W4; - t2 = (((E >>> 2) | (E << (32 - 2))) ^ ((E >>> 13) - | (E << (32 - 13))) ^ ((E >>> 22) | (E << (32 - 22)))) - + ((F & G) | ((F | G) & E)); - H += t1; - D = t1 + t2; - int W5 = decodeBEInt(data, 4 * 0x5); - t1 = C + (((H >>> 6) | (H << (32 - 6))) ^ ((H >>> 11) - | (H << (32 - 11))) ^ ((H >>> 25) | (H << (32 - 25)))) - + (((A ^ B) & H) ^ B) + K[pcount + 0x5] + W5; - t2 = (((D >>> 2) | (D << (32 - 2))) ^ ((D >>> 13) - | (D << (32 - 13))) ^ ((D >>> 22) | (D << (32 - 22)))) - + ((E & F) | ((E | F) & D)); - G += t1; - C = t1 + t2; - int W6 = decodeBEInt(data, 4 * 0x6); - t1 = B + (((G >>> 6) | (G << (32 - 6))) ^ ((G >>> 11) - | (G << (32 - 11))) ^ ((G >>> 25) | (G << (32 - 25)))) - + (((H ^ A) & G) ^ A) + K[pcount + 0x6] + W6; - t2 = (((C >>> 2) | (C << (32 - 2))) ^ ((C >>> 13) - | (C << (32 - 13))) ^ ((C >>> 22) | (C << (32 - 22)))) - + ((D & E) | ((D | E) & C)); - F += t1; - B = t1 + t2; - int W7 = decodeBEInt(data, 4 * 0x7); - t1 = A + (((F >>> 6) | (F << (32 - 6))) ^ ((F >>> 11) - | (F << (32 - 11))) ^ ((F >>> 25) | (F << (32 - 25)))) - + (((G ^ H) & F) ^ H) + K[pcount + 0x7] + W7; - t2 = (((B >>> 2) | (B << (32 - 2))) ^ ((B >>> 13) - | (B << (32 - 13))) ^ ((B >>> 22) | (B << (32 - 22)))) - + ((C & D) | ((C | D) & B)); - E += t1; - A = t1 + t2; - int W8 = decodeBEInt(data, 4 * 0x8); - t1 = H + (((E >>> 6) | (E << (32 - 6))) ^ ((E >>> 11) - | (E << (32 - 11))) ^ ((E >>> 25) | (E << (32 - 25)))) - + (((F ^ G) & E) ^ G) + K[pcount + 0x8] + W8; - t2 = (((A >>> 2) | (A << (32 - 2))) ^ ((A >>> 13) - | (A << (32 - 13))) ^ ((A >>> 22) | (A << (32 - 22)))) - + ((B & C) | ((B | C) & A)); - D += t1; - H = t1 + t2; - int W9 = decodeBEInt(data, 4 * 0x9); - t1 = G + (((D >>> 6) | (D << (32 - 6))) ^ ((D >>> 11) - | (D << (32 - 11))) ^ ((D >>> 25) | (D << (32 - 25)))) - + (((E ^ F) & D) ^ F) + K[pcount + 0x9] + W9; - t2 = (((H >>> 2) | (H << (32 - 2))) ^ ((H >>> 13) - | (H << (32 - 13))) ^ ((H >>> 22) | (H << (32 - 22)))) - + ((A & B) | ((A | B) & H)); - C += t1; - G = t1 + t2; - int WA = decodeBEInt(data, 4 * 0xA); - t1 = F + (((C >>> 6) | (C << (32 - 6))) ^ ((C >>> 11) - | (C << (32 - 11))) ^ ((C >>> 25) | (C << (32 - 25)))) - + (((D ^ E) & C) ^ E) + K[pcount + 0xA] + WA; - t2 = (((G >>> 2) | (G << (32 - 2))) ^ ((G >>> 13) - | (G << (32 - 13))) ^ ((G >>> 22) | (G << (32 - 22)))) - + ((H & A) | ((H | A) & G)); - B += t1; - F = t1 + t2; - int WB = decodeBEInt(data, 4 * 0xB); - t1 = E + (((B >>> 6) | (B << (32 - 6))) ^ ((B >>> 11) - | (B << (32 - 11))) ^ ((B >>> 25) | (B << (32 - 25)))) - + (((C ^ D) & B) ^ D) + K[pcount + 0xB] + WB; - t2 = (((F >>> 2) | (F << (32 - 2))) ^ ((F >>> 13) - | (F << (32 - 13))) ^ ((F >>> 22) | (F << (32 - 22)))) - + ((G & H) | ((G | H) & F)); - A += t1; - E = t1 + t2; - int WC = decodeBEInt(data, 4 * 0xC); - t1 = D + (((A >>> 6) | (A << (32 - 6))) ^ ((A >>> 11) - | (A << (32 - 11))) ^ ((A >>> 25) | (A << (32 - 25)))) - + (((B ^ C) & A) ^ C) + K[pcount + 0xC] + WC; - t2 = (((E >>> 2) | (E << (32 - 2))) ^ ((E >>> 13) - | (E << (32 - 13))) ^ ((E >>> 22) | (E << (32 - 22)))) - + ((F & G) | ((F | G) & E)); - H += t1; - D = t1 + t2; - int WD = decodeBEInt(data, 4 * 0xD); - t1 = C + (((H >>> 6) | (H << (32 - 6))) ^ ((H >>> 11) - | (H << (32 - 11))) ^ ((H >>> 25) | (H << (32 - 25)))) - + (((A ^ B) & H) ^ B) + K[pcount + 0xD] + WD; - t2 = (((D >>> 2) | (D << (32 - 2))) ^ ((D >>> 13) - | (D << (32 - 13))) ^ ((D >>> 22) | (D << (32 - 22)))) - + ((E & F) | ((E | F) & D)); - G += t1; - C = t1 + t2; - int WE = decodeBEInt(data, 4 * 0xE); - t1 = B + (((G >>> 6) | (G << (32 - 6))) ^ ((G >>> 11) - | (G << (32 - 11))) ^ ((G >>> 25) | (G << (32 - 25)))) - + (((H ^ A) & G) ^ A) + K[pcount + 0xE] + WE; - t2 = (((C >>> 2) | (C << (32 - 2))) ^ ((C >>> 13) - | (C << (32 - 13))) ^ ((C >>> 22) | (C << (32 - 22)))) - + ((D & E) | ((D | E) & C)); - F += t1; - B = t1 + t2; - int WF = decodeBEInt(data, 4 * 0xF); - t1 = A + (((F >>> 6) | (F << (32 - 6))) ^ ((F >>> 11) - | (F << (32 - 11))) ^ ((F >>> 25) | (F << (32 - 25)))) - + (((G ^ H) & F) ^ H) + K[pcount + 0xF] + WF; - t2 = (((B >>> 2) | (B << (32 - 2))) ^ ((B >>> 13) - | (B << (32 - 13))) ^ ((B >>> 22) | (B << (32 - 22)))) - + ((C & D) | ((C | D) & B)); - E += t1; - A = t1 + t2; - for (pcount = 16; pcount < 64; pcount += 16) { - W0 += (((WE >>> 17) | (WE << (32 - 17))) ^ ((WE >>> 19) - | (WE << (32 - 19))) ^ (WE >>> 10)) + W9 - + (((W1 >>> 7) | (W1 << (32 - 7))) - ^ ((W1 >>> 18) | (W1 << (32 - 18))) - ^ (W1 >>> 3)); - t1 = H + (((E >>> 6) | (E << (32 - 6))) ^ ((E >>> 11) - | (E << (32 - 11))) ^ ((E >>> 25) - | (E << (32 - 25)))) + (((F ^ G) & E) ^ G) - + K[pcount + 0x0] + W0; - t2 = (((A >>> 2) | (A << (32 - 2))) ^ ((A >>> 13) - | (A << (32 - 13))) ^ ((A >>> 22) - | (A << (32 - 22)))) - + ((B & C) | ((B | C) & A)); - D += t1; - H = t1 + t2; - W1 += (((WF >>> 17) | (WF << (32 - 17))) ^ ((WF >>> 19) - | (WF << (32 - 19))) ^ (WF >>> 10)) + WA - + (((W2 >>> 7) | (W2 << (32 - 7))) - ^ ((W2 >>> 18) | (W2 << (32 - 18))) - ^ (W2 >>> 3)); - t1 = G + (((D >>> 6) | (D << (32 - 6))) ^ ((D >>> 11) - | (D << (32 - 11))) ^ ((D >>> 25) - | (D << (32 - 25)))) + (((E ^ F) & D) ^ F) - + K[pcount + 0x1] + W1; - t2 = (((H >>> 2) | (H << (32 - 2))) ^ ((H >>> 13) - | (H << (32 - 13))) ^ ((H >>> 22) - | (H << (32 - 22)))) - + ((A & B) | ((A | B) & H)); - C += t1; - G = t1 + t2; - W2 += (((W0 >>> 17) | (W0 << (32 - 17))) ^ ((W0 >>> 19) - | (W0 << (32 - 19))) ^ (W0 >>> 10)) + WB - + (((W3 >>> 7) | (W3 << (32 - 7))) - ^ ((W3 >>> 18) | (W3 << (32 - 18))) - ^ (W3 >>> 3)); - t1 = F + (((C >>> 6) | (C << (32 - 6))) ^ ((C >>> 11) - | (C << (32 - 11))) ^ ((C >>> 25) - | (C << (32 - 25)))) + (((D ^ E) & C) ^ E) - + K[pcount + 0x2] + W2; - t2 = (((G >>> 2) | (G << (32 - 2))) ^ ((G >>> 13) - | (G << (32 - 13))) ^ ((G >>> 22) - | (G << (32 - 22)))) - + ((H & A) | ((H | A) & G)); - B += t1; - F = t1 + t2; - W3 += (((W1 >>> 17) | (W1 << (32 - 17))) ^ ((W1 >>> 19) - | (W1 << (32 - 19))) ^ (W1 >>> 10)) + WC - + (((W4 >>> 7) | (W4 << (32 - 7))) - ^ ((W4 >>> 18) | (W4 << (32 - 18))) - ^ (W4 >>> 3)); - t1 = E + (((B >>> 6) | (B << (32 - 6))) ^ ((B >>> 11) - | (B << (32 - 11))) ^ ((B >>> 25) - | (B << (32 - 25)))) + (((C ^ D) & B) ^ D) - + K[pcount + 0x3] + W3; - t2 = (((F >>> 2) | (F << (32 - 2))) ^ ((F >>> 13) - | (F << (32 - 13))) ^ ((F >>> 22) - | (F << (32 - 22)))) - + ((G & H) | ((G | H) & F)); - A += t1; - E = t1 + t2; - W4 += (((W2 >>> 17) | (W2 << (32 - 17))) ^ ((W2 >>> 19) - | (W2 << (32 - 19))) ^ (W2 >>> 10)) + WD - + (((W5 >>> 7) | (W5 << (32 - 7))) - ^ ((W5 >>> 18) | (W5 << (32 - 18))) - ^ (W5 >>> 3)); - t1 = D + (((A >>> 6) | (A << (32 - 6))) ^ ((A >>> 11) - | (A << (32 - 11))) ^ ((A >>> 25) - | (A << (32 - 25)))) + (((B ^ C) & A) ^ C) - + K[pcount + 0x4] + W4; - t2 = (((E >>> 2) | (E << (32 - 2))) ^ ((E >>> 13) - | (E << (32 - 13))) ^ ((E >>> 22) - | (E << (32 - 22)))) - + ((F & G) | ((F | G) & E)); - H += t1; - D = t1 + t2; - W5 += (((W3 >>> 17) | (W3 << (32 - 17))) ^ ((W3 >>> 19) - | (W3 << (32 - 19))) ^ (W3 >>> 10)) + WE - + (((W6 >>> 7) | (W6 << (32 - 7))) - ^ ((W6 >>> 18) | (W6 << (32 - 18))) - ^ (W6 >>> 3)); - t1 = C + (((H >>> 6) | (H << (32 - 6))) ^ ((H >>> 11) - | (H << (32 - 11))) ^ ((H >>> 25) - | (H << (32 - 25)))) + (((A ^ B) & H) ^ B) - + K[pcount + 0x5] + W5; - t2 = (((D >>> 2) | (D << (32 - 2))) ^ ((D >>> 13) - | (D << (32 - 13))) ^ ((D >>> 22) - | (D << (32 - 22)))) - + ((E & F) | ((E | F) & D)); - G += t1; - C = t1 + t2; - W6 += (((W4 >>> 17) | (W4 << (32 - 17))) ^ ((W4 >>> 19) - | (W4 << (32 - 19))) ^ (W4 >>> 10)) + WF - + (((W7 >>> 7) | (W7 << (32 - 7))) - ^ ((W7 >>> 18) | (W7 << (32 - 18))) - ^ (W7 >>> 3)); - t1 = B + (((G >>> 6) | (G << (32 - 6))) ^ ((G >>> 11) - | (G << (32 - 11))) ^ ((G >>> 25) - | (G << (32 - 25)))) + (((H ^ A) & G) ^ A) - + K[pcount + 0x6] + W6; - t2 = (((C >>> 2) | (C << (32 - 2))) ^ ((C >>> 13) - | (C << (32 - 13))) ^ ((C >>> 22) - | (C << (32 - 22)))) - + ((D & E) | ((D | E) & C)); - F += t1; - B = t1 + t2; - W7 += (((W5 >>> 17) | (W5 << (32 - 17))) ^ ((W5 >>> 19) - | (W5 << (32 - 19))) ^ (W5 >>> 10)) + W0 - + (((W8 >>> 7) | (W8 << (32 - 7))) - ^ ((W8 >>> 18) | (W8 << (32 - 18))) - ^ (W8 >>> 3)); - t1 = A + (((F >>> 6) | (F << (32 - 6))) ^ ((F >>> 11) - | (F << (32 - 11))) ^ ((F >>> 25) - | (F << (32 - 25)))) + (((G ^ H) & F) ^ H) - + K[pcount + 0x7] + W7; - t2 = (((B >>> 2) | (B << (32 - 2))) ^ ((B >>> 13) - | (B << (32 - 13))) ^ ((B >>> 22) - | (B << (32 - 22)))) - + ((C & D) | ((C | D) & B)); - E += t1; - A = t1 + t2; - W8 += (((W6 >>> 17) | (W6 << (32 - 17))) ^ ((W6 >>> 19) - | (W6 << (32 - 19))) ^ (W6 >>> 10)) + W1 - + (((W9 >>> 7) | (W9 << (32 - 7))) - ^ ((W9 >>> 18) | (W9 << (32 - 18))) - ^ (W9 >>> 3)); - t1 = H + (((E >>> 6) | (E << (32 - 6))) ^ ((E >>> 11) - | (E << (32 - 11))) ^ ((E >>> 25) - | (E << (32 - 25)))) + (((F ^ G) & E) ^ G) - + K[pcount + 0x8] + W8; - t2 = (((A >>> 2) | (A << (32 - 2))) ^ ((A >>> 13) - | (A << (32 - 13))) ^ ((A >>> 22) - | (A << (32 - 22)))) - + ((B & C) | ((B | C) & A)); - D += t1; - H = t1 + t2; - W9 += (((W7 >>> 17) | (W7 << (32 - 17))) ^ ((W7 >>> 19) - | (W7 << (32 - 19))) ^ (W7 >>> 10)) + W2 - + (((WA >>> 7) | (WA << (32 - 7))) - ^ ((WA >>> 18) | (WA << (32 - 18))) - ^ (WA >>> 3)); - t1 = G + (((D >>> 6) | (D << (32 - 6))) ^ ((D >>> 11) - | (D << (32 - 11))) ^ ((D >>> 25) - | (D << (32 - 25)))) + (((E ^ F) & D) ^ F) - + K[pcount + 0x9] + W9; - t2 = (((H >>> 2) | (H << (32 - 2))) ^ ((H >>> 13) - | (H << (32 - 13))) ^ ((H >>> 22) - | (H << (32 - 22)))) - + ((A & B) | ((A | B) & H)); - C += t1; - G = t1 + t2; - WA += (((W8 >>> 17) | (W8 << (32 - 17))) ^ ((W8 >>> 19) - | (W8 << (32 - 19))) ^ (W8 >>> 10)) + W3 - + (((WB >>> 7) | (WB << (32 - 7))) - ^ ((WB >>> 18) | (WB << (32 - 18))) - ^ (WB >>> 3)); - t1 = F + (((C >>> 6) | (C << (32 - 6))) ^ ((C >>> 11) - | (C << (32 - 11))) ^ ((C >>> 25) - | (C << (32 - 25)))) + (((D ^ E) & C) ^ E) - + K[pcount + 0xA] + WA; - t2 = (((G >>> 2) | (G << (32 - 2))) ^ ((G >>> 13) - | (G << (32 - 13))) ^ ((G >>> 22) - | (G << (32 - 22)))) - + ((H & A) | ((H | A) & G)); - B += t1; - F = t1 + t2; - WB += (((W9 >>> 17) | (W9 << (32 - 17))) ^ ((W9 >>> 19) - | (W9 << (32 - 19))) ^ (W9 >>> 10)) + W4 - + (((WC >>> 7) | (WC << (32 - 7))) - ^ ((WC >>> 18) | (WC << (32 - 18))) - ^ (WC >>> 3)); - t1 = E + (((B >>> 6) | (B << (32 - 6))) ^ ((B >>> 11) - | (B << (32 - 11))) ^ ((B >>> 25) - | (B << (32 - 25)))) + (((C ^ D) & B) ^ D) - + K[pcount + 0xB] + WB; - t2 = (((F >>> 2) | (F << (32 - 2))) ^ ((F >>> 13) - | (F << (32 - 13))) ^ ((F >>> 22) - | (F << (32 - 22)))) - + ((G & H) | ((G | H) & F)); - A += t1; - E = t1 + t2; - WC += (((WA >>> 17) | (WA << (32 - 17))) ^ ((WA >>> 19) - | (WA << (32 - 19))) ^ (WA >>> 10)) + W5 - + (((WD >>> 7) | (WD << (32 - 7))) - ^ ((WD >>> 18) | (WD << (32 - 18))) - ^ (WD >>> 3)); - t1 = D + (((A >>> 6) | (A << (32 - 6))) ^ ((A >>> 11) - | (A << (32 - 11))) ^ ((A >>> 25) - | (A << (32 - 25)))) + (((B ^ C) & A) ^ C) - + K[pcount + 0xC] + WC; - t2 = (((E >>> 2) | (E << (32 - 2))) ^ ((E >>> 13) - | (E << (32 - 13))) ^ ((E >>> 22) - | (E << (32 - 22)))) - + ((F & G) | ((F | G) & E)); - H += t1; - D = t1 + t2; - WD += (((WB >>> 17) | (WB << (32 - 17))) ^ ((WB >>> 19) - | (WB << (32 - 19))) ^ (WB >>> 10)) + W6 - + (((WE >>> 7) | (WE << (32 - 7))) - ^ ((WE >>> 18) | (WE << (32 - 18))) - ^ (WE >>> 3)); - t1 = C + (((H >>> 6) | (H << (32 - 6))) ^ ((H >>> 11) - | (H << (32 - 11))) ^ ((H >>> 25) - | (H << (32 - 25)))) + (((A ^ B) & H) ^ B) - + K[pcount + 0xD] + WD; - t2 = (((D >>> 2) | (D << (32 - 2))) ^ ((D >>> 13) - | (D << (32 - 13))) ^ ((D >>> 22) - | (D << (32 - 22)))) - + ((E & F) | ((E | F) & D)); - G += t1; - C = t1 + t2; - WE += (((WC >>> 17) | (WC << (32 - 17))) ^ ((WC >>> 19) - | (WC << (32 - 19))) ^ (WC >>> 10)) + W7 - + (((WF >>> 7) | (WF << (32 - 7))) - ^ ((WF >>> 18) | (WF << (32 - 18))) - ^ (WF >>> 3)); - t1 = B + (((G >>> 6) | (G << (32 - 6))) ^ ((G >>> 11) - | (G << (32 - 11))) ^ ((G >>> 25) - | (G << (32 - 25)))) + (((H ^ A) & G) ^ A) - + K[pcount + 0xE] + WE; - t2 = (((C >>> 2) | (C << (32 - 2))) ^ ((C >>> 13) - | (C << (32 - 13))) ^ ((C >>> 22) - | (C << (32 - 22)))) - + ((D & E) | ((D | E) & C)); - F += t1; - B = t1 + t2; - WF += (((WD >>> 17) | (WD << (32 - 17))) ^ ((WD >>> 19) - | (WD << (32 - 19))) ^ (WD >>> 10)) + W8 - + (((W0 >>> 7) | (W0 << (32 - 7))) - ^ ((W0 >>> 18) | (W0 << (32 - 18))) - ^ (W0 >>> 3)); - t1 = A + (((F >>> 6) | (F << (32 - 6))) ^ ((F >>> 11) - | (F << (32 - 11))) ^ ((F >>> 25) - | (F << (32 - 25)))) + (((G ^ H) & F) ^ H) - + K[pcount + 0xF] + WF; - t2 = (((B >>> 2) | (B << (32 - 2))) ^ ((B >>> 13) - | (B << (32 - 13))) ^ ((B >>> 22) - | (B << (32 - 22)))) - + ((C & D) | ((C | D) & B)); - E += t1; - A = t1 + t2; - } + /* + * The version below unrolls 16 rounds and inlines + * rotations. It should avoid many array accesses + * (W[] is transformed into 16 local variables) and + * data routing (16 is a multiple of 8, so the + * big rotation of the eight words becomes trivial). + * Strangely enough, it yields only a very small + * performance gain (less than 10% on Intel x86 with + * Sun JDK 6, both in 32-bit and 64-bit modes). Since + * it also probably consumes much more L1 cache, the + * simpler version above is preferred. + * + int A = currentVal[0]; + int B = currentVal[1]; + int C = currentVal[2]; + int D = currentVal[3]; + int E = currentVal[4]; + int F = currentVal[5]; + int G = currentVal[6]; + int H = currentVal[7]; + int t1, t2; + int pcount = 0; + int W0 = decodeBEInt(data, 4 * 0x0); + t1 = H + (((E >>> 6) | (E << (32 - 6))) ^ ((E >>> 11) + | (E << (32 - 11))) ^ ((E >>> 25) | (E << (32 - 25)))) + + (((F ^ G) & E) ^ G) + K[pcount + 0x0] + W0; + t2 = (((A >>> 2) | (A << (32 - 2))) ^ ((A >>> 13) + | (A << (32 - 13))) ^ ((A >>> 22) | (A << (32 - 22)))) + + ((B & C) | ((B | C) & A)); + D += t1; + H = t1 + t2; + int W1 = decodeBEInt(data, 4 * 0x1); + t1 = G + (((D >>> 6) | (D << (32 - 6))) ^ ((D >>> 11) + | (D << (32 - 11))) ^ ((D >>> 25) | (D << (32 - 25)))) + + (((E ^ F) & D) ^ F) + K[pcount + 0x1] + W1; + t2 = (((H >>> 2) | (H << (32 - 2))) ^ ((H >>> 13) + | (H << (32 - 13))) ^ ((H >>> 22) | (H << (32 - 22)))) + + ((A & B) | ((A | B) & H)); + C += t1; + G = t1 + t2; + int W2 = decodeBEInt(data, 4 * 0x2); + t1 = F + (((C >>> 6) | (C << (32 - 6))) ^ ((C >>> 11) + | (C << (32 - 11))) ^ ((C >>> 25) | (C << (32 - 25)))) + + (((D ^ E) & C) ^ E) + K[pcount + 0x2] + W2; + t2 = (((G >>> 2) | (G << (32 - 2))) ^ ((G >>> 13) + | (G << (32 - 13))) ^ ((G >>> 22) | (G << (32 - 22)))) + + ((H & A) | ((H | A) & G)); + B += t1; + F = t1 + t2; + int W3 = decodeBEInt(data, 4 * 0x3); + t1 = E + (((B >>> 6) | (B << (32 - 6))) ^ ((B >>> 11) + | (B << (32 - 11))) ^ ((B >>> 25) | (B << (32 - 25)))) + + (((C ^ D) & B) ^ D) + K[pcount + 0x3] + W3; + t2 = (((F >>> 2) | (F << (32 - 2))) ^ ((F >>> 13) + | (F << (32 - 13))) ^ ((F >>> 22) | (F << (32 - 22)))) + + ((G & H) | ((G | H) & F)); + A += t1; + E = t1 + t2; + int W4 = decodeBEInt(data, 4 * 0x4); + t1 = D + (((A >>> 6) | (A << (32 - 6))) ^ ((A >>> 11) + | (A << (32 - 11))) ^ ((A >>> 25) | (A << (32 - 25)))) + + (((B ^ C) & A) ^ C) + K[pcount + 0x4] + W4; + t2 = (((E >>> 2) | (E << (32 - 2))) ^ ((E >>> 13) + | (E << (32 - 13))) ^ ((E >>> 22) | (E << (32 - 22)))) + + ((F & G) | ((F | G) & E)); + H += t1; + D = t1 + t2; + int W5 = decodeBEInt(data, 4 * 0x5); + t1 = C + (((H >>> 6) | (H << (32 - 6))) ^ ((H >>> 11) + | (H << (32 - 11))) ^ ((H >>> 25) | (H << (32 - 25)))) + + (((A ^ B) & H) ^ B) + K[pcount + 0x5] + W5; + t2 = (((D >>> 2) | (D << (32 - 2))) ^ ((D >>> 13) + | (D << (32 - 13))) ^ ((D >>> 22) | (D << (32 - 22)))) + + ((E & F) | ((E | F) & D)); + G += t1; + C = t1 + t2; + int W6 = decodeBEInt(data, 4 * 0x6); + t1 = B + (((G >>> 6) | (G << (32 - 6))) ^ ((G >>> 11) + | (G << (32 - 11))) ^ ((G >>> 25) | (G << (32 - 25)))) + + (((H ^ A) & G) ^ A) + K[pcount + 0x6] + W6; + t2 = (((C >>> 2) | (C << (32 - 2))) ^ ((C >>> 13) + | (C << (32 - 13))) ^ ((C >>> 22) | (C << (32 - 22)))) + + ((D & E) | ((D | E) & C)); + F += t1; + B = t1 + t2; + int W7 = decodeBEInt(data, 4 * 0x7); + t1 = A + (((F >>> 6) | (F << (32 - 6))) ^ ((F >>> 11) + | (F << (32 - 11))) ^ ((F >>> 25) | (F << (32 - 25)))) + + (((G ^ H) & F) ^ H) + K[pcount + 0x7] + W7; + t2 = (((B >>> 2) | (B << (32 - 2))) ^ ((B >>> 13) + | (B << (32 - 13))) ^ ((B >>> 22) | (B << (32 - 22)))) + + ((C & D) | ((C | D) & B)); + E += t1; + A = t1 + t2; + int W8 = decodeBEInt(data, 4 * 0x8); + t1 = H + (((E >>> 6) | (E << (32 - 6))) ^ ((E >>> 11) + | (E << (32 - 11))) ^ ((E >>> 25) | (E << (32 - 25)))) + + (((F ^ G) & E) ^ G) + K[pcount + 0x8] + W8; + t2 = (((A >>> 2) | (A << (32 - 2))) ^ ((A >>> 13) + | (A << (32 - 13))) ^ ((A >>> 22) | (A << (32 - 22)))) + + ((B & C) | ((B | C) & A)); + D += t1; + H = t1 + t2; + int W9 = decodeBEInt(data, 4 * 0x9); + t1 = G + (((D >>> 6) | (D << (32 - 6))) ^ ((D >>> 11) + | (D << (32 - 11))) ^ ((D >>> 25) | (D << (32 - 25)))) + + (((E ^ F) & D) ^ F) + K[pcount + 0x9] + W9; + t2 = (((H >>> 2) | (H << (32 - 2))) ^ ((H >>> 13) + | (H << (32 - 13))) ^ ((H >>> 22) | (H << (32 - 22)))) + + ((A & B) | ((A | B) & H)); + C += t1; + G = t1 + t2; + int WA = decodeBEInt(data, 4 * 0xA); + t1 = F + (((C >>> 6) | (C << (32 - 6))) ^ ((C >>> 11) + | (C << (32 - 11))) ^ ((C >>> 25) | (C << (32 - 25)))) + + (((D ^ E) & C) ^ E) + K[pcount + 0xA] + WA; + t2 = (((G >>> 2) | (G << (32 - 2))) ^ ((G >>> 13) + | (G << (32 - 13))) ^ ((G >>> 22) | (G << (32 - 22)))) + + ((H & A) | ((H | A) & G)); + B += t1; + F = t1 + t2; + int WB = decodeBEInt(data, 4 * 0xB); + t1 = E + (((B >>> 6) | (B << (32 - 6))) ^ ((B >>> 11) + | (B << (32 - 11))) ^ ((B >>> 25) | (B << (32 - 25)))) + + (((C ^ D) & B) ^ D) + K[pcount + 0xB] + WB; + t2 = (((F >>> 2) | (F << (32 - 2))) ^ ((F >>> 13) + | (F << (32 - 13))) ^ ((F >>> 22) | (F << (32 - 22)))) + + ((G & H) | ((G | H) & F)); + A += t1; + E = t1 + t2; + int WC = decodeBEInt(data, 4 * 0xC); + t1 = D + (((A >>> 6) | (A << (32 - 6))) ^ ((A >>> 11) + | (A << (32 - 11))) ^ ((A >>> 25) | (A << (32 - 25)))) + + (((B ^ C) & A) ^ C) + K[pcount + 0xC] + WC; + t2 = (((E >>> 2) | (E << (32 - 2))) ^ ((E >>> 13) + | (E << (32 - 13))) ^ ((E >>> 22) | (E << (32 - 22)))) + + ((F & G) | ((F | G) & E)); + H += t1; + D = t1 + t2; + int WD = decodeBEInt(data, 4 * 0xD); + t1 = C + (((H >>> 6) | (H << (32 - 6))) ^ ((H >>> 11) + | (H << (32 - 11))) ^ ((H >>> 25) | (H << (32 - 25)))) + + (((A ^ B) & H) ^ B) + K[pcount + 0xD] + WD; + t2 = (((D >>> 2) | (D << (32 - 2))) ^ ((D >>> 13) + | (D << (32 - 13))) ^ ((D >>> 22) | (D << (32 - 22)))) + + ((E & F) | ((E | F) & D)); + G += t1; + C = t1 + t2; + int WE = decodeBEInt(data, 4 * 0xE); + t1 = B + (((G >>> 6) | (G << (32 - 6))) ^ ((G >>> 11) + | (G << (32 - 11))) ^ ((G >>> 25) | (G << (32 - 25)))) + + (((H ^ A) & G) ^ A) + K[pcount + 0xE] + WE; + t2 = (((C >>> 2) | (C << (32 - 2))) ^ ((C >>> 13) + | (C << (32 - 13))) ^ ((C >>> 22) | (C << (32 - 22)))) + + ((D & E) | ((D | E) & C)); + F += t1; + B = t1 + t2; + int WF = decodeBEInt(data, 4 * 0xF); + t1 = A + (((F >>> 6) | (F << (32 - 6))) ^ ((F >>> 11) + | (F << (32 - 11))) ^ ((F >>> 25) | (F << (32 - 25)))) + + (((G ^ H) & F) ^ H) + K[pcount + 0xF] + WF; + t2 = (((B >>> 2) | (B << (32 - 2))) ^ ((B >>> 13) + | (B << (32 - 13))) ^ ((B >>> 22) | (B << (32 - 22)))) + + ((C & D) | ((C | D) & B)); + E += t1; + A = t1 + t2; + for (pcount = 16; pcount < 64; pcount += 16) { + W0 += (((WE >>> 17) | (WE << (32 - 17))) ^ ((WE >>> 19) + | (WE << (32 - 19))) ^ (WE >>> 10)) + W9 + + (((W1 >>> 7) | (W1 << (32 - 7))) + ^ ((W1 >>> 18) | (W1 << (32 - 18))) + ^ (W1 >>> 3)); + t1 = H + (((E >>> 6) | (E << (32 - 6))) ^ ((E >>> 11) + | (E << (32 - 11))) ^ ((E >>> 25) + | (E << (32 - 25)))) + (((F ^ G) & E) ^ G) + + K[pcount + 0x0] + W0; + t2 = (((A >>> 2) | (A << (32 - 2))) ^ ((A >>> 13) + | (A << (32 - 13))) ^ ((A >>> 22) + | (A << (32 - 22)))) + + ((B & C) | ((B | C) & A)); + D += t1; + H = t1 + t2; + W1 += (((WF >>> 17) | (WF << (32 - 17))) ^ ((WF >>> 19) + | (WF << (32 - 19))) ^ (WF >>> 10)) + WA + + (((W2 >>> 7) | (W2 << (32 - 7))) + ^ ((W2 >>> 18) | (W2 << (32 - 18))) + ^ (W2 >>> 3)); + t1 = G + (((D >>> 6) | (D << (32 - 6))) ^ ((D >>> 11) + | (D << (32 - 11))) ^ ((D >>> 25) + | (D << (32 - 25)))) + (((E ^ F) & D) ^ F) + + K[pcount + 0x1] + W1; + t2 = (((H >>> 2) | (H << (32 - 2))) ^ ((H >>> 13) + | (H << (32 - 13))) ^ ((H >>> 22) + | (H << (32 - 22)))) + + ((A & B) | ((A | B) & H)); + C += t1; + G = t1 + t2; + W2 += (((W0 >>> 17) | (W0 << (32 - 17))) ^ ((W0 >>> 19) + | (W0 << (32 - 19))) ^ (W0 >>> 10)) + WB + + (((W3 >>> 7) | (W3 << (32 - 7))) + ^ ((W3 >>> 18) | (W3 << (32 - 18))) + ^ (W3 >>> 3)); + t1 = F + (((C >>> 6) | (C << (32 - 6))) ^ ((C >>> 11) + | (C << (32 - 11))) ^ ((C >>> 25) + | (C << (32 - 25)))) + (((D ^ E) & C) ^ E) + + K[pcount + 0x2] + W2; + t2 = (((G >>> 2) | (G << (32 - 2))) ^ ((G >>> 13) + | (G << (32 - 13))) ^ ((G >>> 22) + | (G << (32 - 22)))) + + ((H & A) | ((H | A) & G)); + B += t1; + F = t1 + t2; + W3 += (((W1 >>> 17) | (W1 << (32 - 17))) ^ ((W1 >>> 19) + | (W1 << (32 - 19))) ^ (W1 >>> 10)) + WC + + (((W4 >>> 7) | (W4 << (32 - 7))) + ^ ((W4 >>> 18) | (W4 << (32 - 18))) + ^ (W4 >>> 3)); + t1 = E + (((B >>> 6) | (B << (32 - 6))) ^ ((B >>> 11) + | (B << (32 - 11))) ^ ((B >>> 25) + | (B << (32 - 25)))) + (((C ^ D) & B) ^ D) + + K[pcount + 0x3] + W3; + t2 = (((F >>> 2) | (F << (32 - 2))) ^ ((F >>> 13) + | (F << (32 - 13))) ^ ((F >>> 22) + | (F << (32 - 22)))) + + ((G & H) | ((G | H) & F)); + A += t1; + E = t1 + t2; + W4 += (((W2 >>> 17) | (W2 << (32 - 17))) ^ ((W2 >>> 19) + | (W2 << (32 - 19))) ^ (W2 >>> 10)) + WD + + (((W5 >>> 7) | (W5 << (32 - 7))) + ^ ((W5 >>> 18) | (W5 << (32 - 18))) + ^ (W5 >>> 3)); + t1 = D + (((A >>> 6) | (A << (32 - 6))) ^ ((A >>> 11) + | (A << (32 - 11))) ^ ((A >>> 25) + | (A << (32 - 25)))) + (((B ^ C) & A) ^ C) + + K[pcount + 0x4] + W4; + t2 = (((E >>> 2) | (E << (32 - 2))) ^ ((E >>> 13) + | (E << (32 - 13))) ^ ((E >>> 22) + | (E << (32 - 22)))) + + ((F & G) | ((F | G) & E)); + H += t1; + D = t1 + t2; + W5 += (((W3 >>> 17) | (W3 << (32 - 17))) ^ ((W3 >>> 19) + | (W3 << (32 - 19))) ^ (W3 >>> 10)) + WE + + (((W6 >>> 7) | (W6 << (32 - 7))) + ^ ((W6 >>> 18) | (W6 << (32 - 18))) + ^ (W6 >>> 3)); + t1 = C + (((H >>> 6) | (H << (32 - 6))) ^ ((H >>> 11) + | (H << (32 - 11))) ^ ((H >>> 25) + | (H << (32 - 25)))) + (((A ^ B) & H) ^ B) + + K[pcount + 0x5] + W5; + t2 = (((D >>> 2) | (D << (32 - 2))) ^ ((D >>> 13) + | (D << (32 - 13))) ^ ((D >>> 22) + | (D << (32 - 22)))) + + ((E & F) | ((E | F) & D)); + G += t1; + C = t1 + t2; + W6 += (((W4 >>> 17) | (W4 << (32 - 17))) ^ ((W4 >>> 19) + | (W4 << (32 - 19))) ^ (W4 >>> 10)) + WF + + (((W7 >>> 7) | (W7 << (32 - 7))) + ^ ((W7 >>> 18) | (W7 << (32 - 18))) + ^ (W7 >>> 3)); + t1 = B + (((G >>> 6) | (G << (32 - 6))) ^ ((G >>> 11) + | (G << (32 - 11))) ^ ((G >>> 25) + | (G << (32 - 25)))) + (((H ^ A) & G) ^ A) + + K[pcount + 0x6] + W6; + t2 = (((C >>> 2) | (C << (32 - 2))) ^ ((C >>> 13) + | (C << (32 - 13))) ^ ((C >>> 22) + | (C << (32 - 22)))) + + ((D & E) | ((D | E) & C)); + F += t1; + B = t1 + t2; + W7 += (((W5 >>> 17) | (W5 << (32 - 17))) ^ ((W5 >>> 19) + | (W5 << (32 - 19))) ^ (W5 >>> 10)) + W0 + + (((W8 >>> 7) | (W8 << (32 - 7))) + ^ ((W8 >>> 18) | (W8 << (32 - 18))) + ^ (W8 >>> 3)); + t1 = A + (((F >>> 6) | (F << (32 - 6))) ^ ((F >>> 11) + | (F << (32 - 11))) ^ ((F >>> 25) + | (F << (32 - 25)))) + (((G ^ H) & F) ^ H) + + K[pcount + 0x7] + W7; + t2 = (((B >>> 2) | (B << (32 - 2))) ^ ((B >>> 13) + | (B << (32 - 13))) ^ ((B >>> 22) + | (B << (32 - 22)))) + + ((C & D) | ((C | D) & B)); + E += t1; + A = t1 + t2; + W8 += (((W6 >>> 17) | (W6 << (32 - 17))) ^ ((W6 >>> 19) + | (W6 << (32 - 19))) ^ (W6 >>> 10)) + W1 + + (((W9 >>> 7) | (W9 << (32 - 7))) + ^ ((W9 >>> 18) | (W9 << (32 - 18))) + ^ (W9 >>> 3)); + t1 = H + (((E >>> 6) | (E << (32 - 6))) ^ ((E >>> 11) + | (E << (32 - 11))) ^ ((E >>> 25) + | (E << (32 - 25)))) + (((F ^ G) & E) ^ G) + + K[pcount + 0x8] + W8; + t2 = (((A >>> 2) | (A << (32 - 2))) ^ ((A >>> 13) + | (A << (32 - 13))) ^ ((A >>> 22) + | (A << (32 - 22)))) + + ((B & C) | ((B | C) & A)); + D += t1; + H = t1 + t2; + W9 += (((W7 >>> 17) | (W7 << (32 - 17))) ^ ((W7 >>> 19) + | (W7 << (32 - 19))) ^ (W7 >>> 10)) + W2 + + (((WA >>> 7) | (WA << (32 - 7))) + ^ ((WA >>> 18) | (WA << (32 - 18))) + ^ (WA >>> 3)); + t1 = G + (((D >>> 6) | (D << (32 - 6))) ^ ((D >>> 11) + | (D << (32 - 11))) ^ ((D >>> 25) + | (D << (32 - 25)))) + (((E ^ F) & D) ^ F) + + K[pcount + 0x9] + W9; + t2 = (((H >>> 2) | (H << (32 - 2))) ^ ((H >>> 13) + | (H << (32 - 13))) ^ ((H >>> 22) + | (H << (32 - 22)))) + + ((A & B) | ((A | B) & H)); + C += t1; + G = t1 + t2; + WA += (((W8 >>> 17) | (W8 << (32 - 17))) ^ ((W8 >>> 19) + | (W8 << (32 - 19))) ^ (W8 >>> 10)) + W3 + + (((WB >>> 7) | (WB << (32 - 7))) + ^ ((WB >>> 18) | (WB << (32 - 18))) + ^ (WB >>> 3)); + t1 = F + (((C >>> 6) | (C << (32 - 6))) ^ ((C >>> 11) + | (C << (32 - 11))) ^ ((C >>> 25) + | (C << (32 - 25)))) + (((D ^ E) & C) ^ E) + + K[pcount + 0xA] + WA; + t2 = (((G >>> 2) | (G << (32 - 2))) ^ ((G >>> 13) + | (G << (32 - 13))) ^ ((G >>> 22) + | (G << (32 - 22)))) + + ((H & A) | ((H | A) & G)); + B += t1; + F = t1 + t2; + WB += (((W9 >>> 17) | (W9 << (32 - 17))) ^ ((W9 >>> 19) + | (W9 << (32 - 19))) ^ (W9 >>> 10)) + W4 + + (((WC >>> 7) | (WC << (32 - 7))) + ^ ((WC >>> 18) | (WC << (32 - 18))) + ^ (WC >>> 3)); + t1 = E + (((B >>> 6) | (B << (32 - 6))) ^ ((B >>> 11) + | (B << (32 - 11))) ^ ((B >>> 25) + | (B << (32 - 25)))) + (((C ^ D) & B) ^ D) + + K[pcount + 0xB] + WB; + t2 = (((F >>> 2) | (F << (32 - 2))) ^ ((F >>> 13) + | (F << (32 - 13))) ^ ((F >>> 22) + | (F << (32 - 22)))) + + ((G & H) | ((G | H) & F)); + A += t1; + E = t1 + t2; + WC += (((WA >>> 17) | (WA << (32 - 17))) ^ ((WA >>> 19) + | (WA << (32 - 19))) ^ (WA >>> 10)) + W5 + + (((WD >>> 7) | (WD << (32 - 7))) + ^ ((WD >>> 18) | (WD << (32 - 18))) + ^ (WD >>> 3)); + t1 = D + (((A >>> 6) | (A << (32 - 6))) ^ ((A >>> 11) + | (A << (32 - 11))) ^ ((A >>> 25) + | (A << (32 - 25)))) + (((B ^ C) & A) ^ C) + + K[pcount + 0xC] + WC; + t2 = (((E >>> 2) | (E << (32 - 2))) ^ ((E >>> 13) + | (E << (32 - 13))) ^ ((E >>> 22) + | (E << (32 - 22)))) + + ((F & G) | ((F | G) & E)); + H += t1; + D = t1 + t2; + WD += (((WB >>> 17) | (WB << (32 - 17))) ^ ((WB >>> 19) + | (WB << (32 - 19))) ^ (WB >>> 10)) + W6 + + (((WE >>> 7) | (WE << (32 - 7))) + ^ ((WE >>> 18) | (WE << (32 - 18))) + ^ (WE >>> 3)); + t1 = C + (((H >>> 6) | (H << (32 - 6))) ^ ((H >>> 11) + | (H << (32 - 11))) ^ ((H >>> 25) + | (H << (32 - 25)))) + (((A ^ B) & H) ^ B) + + K[pcount + 0xD] + WD; + t2 = (((D >>> 2) | (D << (32 - 2))) ^ ((D >>> 13) + | (D << (32 - 13))) ^ ((D >>> 22) + | (D << (32 - 22)))) + + ((E & F) | ((E | F) & D)); + G += t1; + C = t1 + t2; + WE += (((WC >>> 17) | (WC << (32 - 17))) ^ ((WC >>> 19) + | (WC << (32 - 19))) ^ (WC >>> 10)) + W7 + + (((WF >>> 7) | (WF << (32 - 7))) + ^ ((WF >>> 18) | (WF << (32 - 18))) + ^ (WF >>> 3)); + t1 = B + (((G >>> 6) | (G << (32 - 6))) ^ ((G >>> 11) + | (G << (32 - 11))) ^ ((G >>> 25) + | (G << (32 - 25)))) + (((H ^ A) & G) ^ A) + + K[pcount + 0xE] + WE; + t2 = (((C >>> 2) | (C << (32 - 2))) ^ ((C >>> 13) + | (C << (32 - 13))) ^ ((C >>> 22) + | (C << (32 - 22)))) + + ((D & E) | ((D | E) & C)); + F += t1; + B = t1 + t2; + WF += (((WD >>> 17) | (WD << (32 - 17))) ^ ((WD >>> 19) + | (WD << (32 - 19))) ^ (WD >>> 10)) + W8 + + (((W0 >>> 7) | (W0 << (32 - 7))) + ^ ((W0 >>> 18) | (W0 << (32 - 18))) + ^ (W0 >>> 3)); + t1 = A + (((F >>> 6) | (F << (32 - 6))) ^ ((F >>> 11) + | (F << (32 - 11))) ^ ((F >>> 25) + | (F << (32 - 25)))) + (((G ^ H) & F) ^ H) + + K[pcount + 0xF] + WF; + t2 = (((B >>> 2) | (B << (32 - 2))) ^ ((B >>> 13) + | (B << (32 - 13))) ^ ((B >>> 22) + | (B << (32 - 22)))) + + ((C & D) | ((C | D) & B)); + E += t1; + A = t1 + t2; + } - currentVal[0] += A; - currentVal[1] += B; - currentVal[2] += C; - currentVal[3] += D; - currentVal[4] += E; - currentVal[5] += F; - currentVal[6] += G; - currentVal[7] += H; - */ - } + currentVal[0] += A; + currentVal[1] += B; + currentVal[2] += C; + currentVal[3] += D; + currentVal[4] += E; + currentVal[5] += F; + currentVal[6] += G; + currentVal[7] += H; + */ + } - /** @see Digest */ - public String toString() - { - return "SHA-" + (getDigestLength() << 3); - } + /** @see Digest */ + public String toString() { + return "SHA-" + (getDigestLength() << 3); + } } diff --git a/jami-nameserver/src/main/java/net/jami/jams/nameserver/LocalNameServer.java b/jami-nameserver/src/main/java/net/jami/jams/nameserver/LocalNameServer.java index 08acf7876155847de434256079c6f5aad2802329..ce44aa428be7f1a41413e26f87aa3236c00eb74b 100644 --- a/jami-nameserver/src/main/java/net/jami/jams/nameserver/LocalNameServer.java +++ b/jami-nameserver/src/main/java/net/jami/jams/nameserver/LocalNameServer.java @@ -1,28 +1,29 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.nameserver; import lombok.extern.slf4j.Slf4j; + import net.jami.datastore.main.DataStore; import net.jami.jams.common.authmodule.AuthModuleKey; import net.jami.jams.common.authmodule.AuthenticationModule; @@ -46,13 +47,14 @@ public class LocalNameServer implements NameServer { private final String nameserverURI; private final AuthenticationModule authenticationModule; - public LocalNameServer(DataStore dataStore, AuthenticationModule authenticationModule, String nameserverURI) { + public LocalNameServer( + DataStore dataStore, AuthenticationModule authenticationModule, String nameserverURI) { this.dataStore = dataStore; this.nameserverURI = nameserverURI; this.authenticationModule = authenticationModule; } - //This always returns 200, for obvious reasons. + // This always returns 200, for obvious reasons. @Override public Integer registerName(String username, NameRegistrationRequest nameRegistrationRequest) { return 200; @@ -62,28 +64,31 @@ public class LocalNameServer implements NameServer { public NameLookupResponse getAddressFromName(String username) { NameLookupResponse nameLookupResponse = null; StatementList statementList = new StatementList(); - StatementElement statementElement = new StatementElement("username","=",username,""); + StatementElement statementElement = new StatementElement("username", "=", username, ""); statementList.addStatement(statementElement); List<User> results = dataStore.getUserDao().getObjects(statementList); - if(results.size() == 0){ - //Reattempt resolution via directory lookups. + if (results.size() == 0) { + // Reattempt resolution via directory lookups. final User user = new User(); - for(AuthModuleKey key : authenticationModule.getAuthSources().keySet()){ - UserProfile profile = authenticationModule.getAuthSources().get(key).getUserProfile(username); - if(profile != null){ - //Use the username from the profile, not the one supplied otherwise phantom users will be created. + for (AuthModuleKey key : authenticationModule.getAuthSources().keySet()) { + UserProfile profile = + authenticationModule.getAuthSources().get(key).getUserProfile(username); + if (profile != null) { + // Use the username from the profile, not the one supplied otherwise phantom + // users will be created. user.setUsername(profile.getUsername()); user.setRealm(key.getRealm()); user.setUserType(key.getType()); user.setAccessLevel(AccessLevel.USER); - authenticationModule.createUser(user.getUserType(),user.getRealm(),this,user); + authenticationModule.createUser( + user.getUserType(), user.getRealm(), this, user); break; } } - if(user.getUsername() == null) return null; - //resolve again in the database to be sure. + if (user.getUsername() == null) return null; + // resolve again in the database to be sure. results = dataStore.getUserDao().getObjects(statementList); - if(results.size() == 0) return null; + if (results.size() == 0) return null; } nameLookupResponse = new NameLookupResponse(); nameLookupResponse.setName(results.get(0).getUsername()); @@ -94,10 +99,10 @@ public class LocalNameServer implements NameServer { @Override public String getNameFromAddress(String address) { StatementList statementList = new StatementList(); - StatementElement statementElement = new StatementElement("jamiId","=",address,""); + StatementElement statementElement = new StatementElement("jamiId", "=", address, ""); statementList.addStatement(statementElement); List<User> results = dataStore.getUserDao().getObjects(statementList); - if(results.size() == 0) return null; + if (results.size() == 0) return null; return results.get(0).getUsername(); } diff --git a/jami-nameserver/src/main/java/net/jami/jams/nameserver/PublicNameServer.java b/jami-nameserver/src/main/java/net/jami/jams/nameserver/PublicNameServer.java index 5fcabed9d2fe8c5f3a4946b5045509150d9a7547..6ca4e51a73dca3354112a9dce3c8e863585a2428 100644 --- a/jami-nameserver/src/main/java/net/jami/jams/nameserver/PublicNameServer.java +++ b/jami-nameserver/src/main/java/net/jami/jams/nameserver/PublicNameServer.java @@ -1,30 +1,32 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.nameserver; import com.jsoniter.JsonIterator; import com.jsoniter.output.JsonStream; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.jami.NameLookupResponse; import net.jami.jams.common.jami.NameRegistrationRequest; import net.jami.jams.common.jami.NameServer; @@ -46,14 +48,13 @@ public class PublicNameServer implements NameServer { @Override public Integer registerName(String username, NameRegistrationRequest nameRegistrationRequest) { try { - URL url = new URL(nameserverURI+"/name/" + username); + URL url = new URL(nameserverURI + "/name/" + username); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); con.getOutputStream().write(JsonStream.serialize(nameRegistrationRequest).getBytes()); return con.getResponseCode(); - } - catch (Exception e) { + } catch (Exception e) { return 500; } } @@ -61,10 +62,10 @@ public class PublicNameServer implements NameServer { @Override public NameLookupResponse getAddressFromName(String username) { try { - URL url = new URL(nameserverURI+"/name/" + username); + URL url = new URL(nameserverURI + "/name/" + username); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); - if(con.getResponseCode() == 200) { + if (con.getResponseCode() == 200) { StringBuilder responseData = new StringBuilder(); int respSize = Integer.parseInt(con.getHeaderField("Content-Length")); int currentSize = 0; @@ -72,12 +73,11 @@ public class PublicNameServer implements NameServer { responseData.append((char) con.getInputStream().read()); currentSize++; } - log.info("Response received from public nameserver {} ", responseData.toString()); - return JsonIterator.deserialize(responseData.toString(),NameLookupResponse.class); + log.info("Response received from public nameserver {} ", responseData); + return JsonIterator.deserialize(responseData.toString(), NameLookupResponse.class); } return null; - } - catch (Exception e){ + } catch (Exception e) { log.info("An error occurred while querying the public nameserver {} ", e.toString()); return null; } @@ -86,10 +86,10 @@ public class PublicNameServer implements NameServer { @Override public String getNameFromAddress(String address) { try { - URL url = new URL(nameserverURI+"/addr/" + address); + URL url = new URL(nameserverURI + "/addr/" + address); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); - if(con.getResponseCode() == 200) { + if (con.getResponseCode() == 200) { StringBuilder responseData = new StringBuilder(); int respSize = Integer.parseInt(con.getHeaderField("Content-Length")); int currentSize = 0; @@ -97,15 +97,14 @@ public class PublicNameServer implements NameServer { responseData.append((char) con.getInputStream().read()); currentSize++; } - log.info("Response received from public nameserver {} ",responseData.toString()); + log.info("Response received from public nameserver {} ", responseData); JSONParser parser = new JSONParser(); JSONObject json = (JSONObject) parser.parse(responseData.toString()); return json.getAsString("name"); } return null; - } - catch (Exception e){ - log.info("An error occurred while querying the public nameserver {} ",e.toString()); + } catch (Exception e) { + log.info("An error occurred while querying the public nameserver {} ", e.toString()); return null; } } diff --git a/jams-ca/src/main/java/net/jami/jams/ca/JamsCA.java b/jams-ca/src/main/java/net/jami/jams/ca/JamsCA.java index 317b1b0a3e10240361dc641dafe34fc67fa69f3f..a80cb58aa4e5ae1f51259654133a3f7373b4b994 100644 --- a/jams-ca/src/main/java/net/jami/jams/ca/JamsCA.java +++ b/jams-ca/src/main/java/net/jami/jams/ca/JamsCA.java @@ -1,29 +1,31 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.ca; import com.jsoniter.JsonIterator; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.ca.workers.crl.CRLWorker; import net.jami.jams.ca.workers.csr.CertificateWorker; import net.jami.jams.ca.workers.ocsp.OCSPWorker; @@ -34,11 +36,11 @@ import net.jami.jams.common.objects.requests.RevocationRequest; import net.jami.jams.common.objects.system.SystemAccount; import net.jami.jams.common.objects.user.User; import net.jami.jams.common.serialization.JsoniterRegistry; + import org.bouncycastle.cert.X509CRLHolder; import org.bouncycastle.cert.ocsp.OCSPException; import org.bouncycastle.cert.ocsp.OCSPReq; import org.bouncycastle.cert.ocsp.OCSPResp; -import org.bouncycastle.jcajce.provider.asymmetric.X509; import org.bouncycastle.jce.provider.BouncyCastleProvider; import java.security.PrivateKey; @@ -50,20 +52,19 @@ import java.util.concurrent.atomic.AtomicReference; @Slf4j public class JamsCA implements CertificateAuthority { - - //These are the workers which are responsible for CRL/OCSP, they have an odd relationship. + // These are the workers which are responsible for CRL/OCSP, they have an odd relationship. private static CRLWorker crlWorker; private static OCSPWorker ocspWorker; public static volatile String serverDomain; - //The default value is SHA512WITHRSA, this can be changed in the config file. + // The default value is SHA512WITHRSA, this can be changed in the config file. public static volatile String signingAlgorithm = "SHA512WITHRSA"; - //Various times + // Various times public static long crlLifetime = 360_000_000; public static long userLifetime = 360_000_000; public static long deviceLifetime = 360_000_000; - //CA certificate & OCSP Certificates, because they are often used. + // CA certificate & OCSP Certificates, because they are often used. public static SystemAccount CA; public static SystemAccount OCSP; @@ -74,7 +75,8 @@ public class JamsCA implements CertificateAuthority { @Override public void init(String settings, SystemAccount ca, SystemAccount ocsp) { - CertificateAuthorityConfig config = JsonIterator.deserialize(settings, CertificateAuthorityConfig.class); + CertificateAuthorityConfig config = + JsonIterator.deserialize(settings, CertificateAuthorityConfig.class); CA = ca; OCSP = ca; serverDomain = config.getServerDomain(); @@ -82,7 +84,7 @@ public class JamsCA implements CertificateAuthority { crlLifetime = config.getCrlLifetime(); userLifetime = config.getUserLifetime(); deviceLifetime = config.getDeviceLifetime(); - if(ca != null && ocsp != null) { + if (ca != null && ocsp != null) { crlWorker = new CRLWorker(CA.getPrivateKey(), CA.getCertificate()); try { ocspWorker = new OCSPWorker(OCSP.getPrivateKey(), OCSP.getCertificate(), crlWorker); @@ -129,14 +131,18 @@ public class JamsCA implements CertificateAuthority { public String getLatestCRLPEMEncoded() { try { return Base64.getEncoder().encodeToString(getLatestCRL().get().getEncoded()); - } - catch (Exception e){ + } catch (Exception e) { log.error("Could not return a valid CRL!"); return null; } } - public static OCSPResp getOCSPResponse(OCSPReq ocspRequest, X509Certificate certificate, PrivateKey privateKey, Boolean unknown) throws OCSPException { + public static OCSPResp getOCSPResponse( + OCSPReq ocspRequest, + X509Certificate certificate, + PrivateKey privateKey, + Boolean unknown) + throws OCSPException { return ocspWorker.getOCSPResponse(ocspRequest, certificate, privateKey, unknown); } @@ -147,11 +153,11 @@ public class JamsCA implements CertificateAuthority { @Override public boolean shutdownThreads() { - //Unsafe but acceptable. + // Unsafe but acceptable. crlWorker.getStop().set(true); crlWorker.interrupt(); Thread.State state = crlWorker.getState(); - while(!state.equals(Thread.State.TERMINATED)){ + while (!state.equals(Thread.State.TERMINATED)) { state = crlWorker.getState(); } crlWorker = null; diff --git a/jams-ca/src/main/java/net/jami/jams/ca/workers/X509Worker.java b/jams-ca/src/main/java/net/jami/jams/ca/workers/X509Worker.java index f09fda04757a466769e141344a16bf7a3a9e06c9..b82659b2e3ef03bcff1b2673434c3494598fe681 100644 --- a/jams-ca/src/main/java/net/jami/jams/ca/workers/X509Worker.java +++ b/jams-ca/src/main/java/net/jami/jams/ca/workers/X509Worker.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.ca.workers; import lombok.Getter; @@ -33,7 +33,7 @@ import java.util.concurrent.ConcurrentLinkedQueue; @Getter @Setter @Slf4j -public abstract class X509Worker<T> extends Thread{ +public abstract class X509Worker<T> extends Thread { private ConcurrentLinkedQueue<T> input = new ConcurrentLinkedQueue<>(); private PrivateKey signingKey; diff --git a/jams-ca/src/main/java/net/jami/jams/ca/workers/crl/CRLFileStorage.java b/jams-ca/src/main/java/net/jami/jams/ca/workers/crl/CRLFileStorage.java index b8f24fc7baa304e7676e6bef0938c8c56c3c2c33..14a08c967668d85860a72e1253ebc06dc0f1c6bf 100644 --- a/jams-ca/src/main/java/net/jami/jams/ca/workers/crl/CRLFileStorage.java +++ b/jams-ca/src/main/java/net/jami/jams/ca/workers/crl/CRLFileStorage.java @@ -1,28 +1,29 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.ca.workers.crl; import net.jami.jams.common.serialization.fs.FileStorage; + import org.bouncycastle.cert.X509CRLHolder; public class CRLFileStorage extends FileStorage<X509CRLHolder> { @@ -32,7 +33,7 @@ public class CRLFileStorage extends FileStorage<X509CRLHolder> { } @Override - public X509CRLHolder getObject(byte[] bytes) throws Exception{ + public X509CRLHolder getObject(byte[] bytes) throws Exception { return new X509CRLHolder(bytes); } diff --git a/jams-ca/src/main/java/net/jami/jams/ca/workers/crl/CRLWorker.java b/jams-ca/src/main/java/net/jami/jams/ca/workers/crl/CRLWorker.java index d215d0fdee0c95edf0a6848aeb0bf5c707945165..46d01b87f4fb219e092ad70951897f47809db04d 100644 --- a/jams-ca/src/main/java/net/jami/jams/ca/workers/crl/CRLWorker.java +++ b/jams-ca/src/main/java/net/jami/jams/ca/workers/crl/CRLWorker.java @@ -1,33 +1,35 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.ca.workers.crl; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; + import net.jami.jams.ca.JamsCA; import net.jami.jams.ca.workers.X509Worker; import net.jami.jams.common.objects.requests.RevocationRequest; + import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.CRLReason; import org.bouncycastle.cert.X509CRLHolder; @@ -44,29 +46,33 @@ import java.util.concurrent.atomic.AtomicReference; @Slf4j public class CRLWorker extends X509Worker<RevocationRequest> { - @Getter - private final AtomicReference<X509CRLHolder> existingCRL = new AtomicReference<>(); + @Getter private final AtomicReference<X509CRLHolder> existingCRL = new AtomicReference<>(); @Getter - private final CRLFileStorage crlFileStorage = new CRLFileStorage(System.getProperty("user.dir") + File.separator + "crl.pem"); + private final CRLFileStorage crlFileStorage = + new CRLFileStorage(System.getProperty("user.dir") + File.separator + "crl.pem"); - @Getter @Setter - private AtomicBoolean stop = new AtomicBoolean(false); + @Getter @Setter private AtomicBoolean stop = new AtomicBoolean(false); public CRLWorker(PrivateKey privateKey, X509Certificate certificate) { super(privateKey, certificate); - try{ + try { existingCRL.set(crlFileStorage.getData()); - } - catch (Exception e){ - log.warn("Could not find existing CRL file, if this is the first" + - " time you are starting the server or no CRL existed, this is fine"); - X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(new X500Name((getCertificate()).getSubjectDN().getName()), new Date()); + } catch (Exception e) { + log.warn( + "Could not find existing CRL file, if this is the first" + + " time you are starting the server or no CRL existed, this is fine"); + X509v2CRLBuilder crlBuilder = + new X509v2CRLBuilder( + new X500Name((getCertificate()).getSubjectDN().getName()), new Date()); try { - existingCRL.set(crlBuilder.build(new JcaContentSignerBuilder("SHA512WITHRSA").setProvider("BC").build(getSigningKey()))); + existingCRL.set( + crlBuilder.build( + new JcaContentSignerBuilder("SHA512WITHRSA") + .setProvider("BC") + .build(getSigningKey()))); crlFileStorage.storeData(existingCRL.get()); - } - catch (Exception e1){ + } catch (Exception e1) { log.error("Could not create blank CRL!"); } } @@ -75,56 +81,64 @@ public class CRLWorker extends X509Worker<RevocationRequest> { log.info("Instantiated & started a CRL Worker..."); } - //Basically we just publish it in the CRL. - private void revokeCertificate(RevocationRequest revocationRequest){ + // Basically we just publish it in the CRL. + private void revokeCertificate(RevocationRequest revocationRequest) { try { - X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(new X500Name((getCertificate()).getSubjectDN().getName()), new Date()); - if(revocationRequest != null) { - crlBuilder.addCRLEntry(revocationRequest.getIdentifier(), new Date(), CRLReason.privilegeWithdrawn); + X509v2CRLBuilder crlBuilder = + new X509v2CRLBuilder( + new X500Name((getCertificate()).getSubjectDN().getName()), new Date()); + if (revocationRequest != null) { + crlBuilder.addCRLEntry( + revocationRequest.getIdentifier(), + new Date(), + CRLReason.privilegeWithdrawn); } crlBuilder.addCRL(existingCRL.get()); - existingCRL.set(crlBuilder.build(new JcaContentSignerBuilder("SHA512WITHRSA").setProvider("BC").build(getSigningKey()))); + existingCRL.set( + crlBuilder.build( + new JcaContentSignerBuilder("SHA512WITHRSA") + .setProvider("BC") + .build(getSigningKey()))); boolean failedWrite = true; - while(failedWrite){ - try{ + while (failedWrite) { + try { crlFileStorage.storeData(existingCRL.get()); failedWrite = false; - } - catch (Exception e){ + } catch (Exception e) { log.warn("Failed to write file, trying again!"); } } log.info("Successfully ran revocation routine"); - } - catch (Exception e){ - log.error("Failed to sign a CRL with error " + e.toString()); + } catch (Exception e) { + log.error("Failed to sign a CRL with error " + e); } } @Override public void run() { boolean needsRefresh = false; - while(!stop.get()){ - try{ - while(getInput().isEmpty()){ - if(needsRefresh){ + while (!stop.get()) { + try { + while (getInput().isEmpty()) { + if (needsRefresh) { revokeCertificate(null); needsRefresh = false; } - synchronized (getInput()){ + synchronized (getInput()) { getInput().wait(JamsCA.crlLifetime - 10_000); needsRefresh = true; } } - while(!getInput().isEmpty()) { + while (!getInput().isEmpty()) { RevocationRequest revocationRequest = getInput().poll(); revokeCertificate(revocationRequest); needsRefresh = false; - log.info("Successfully revoked the certificated with ID " + revocationRequest.getIdentifier()); + log.info( + "Successfully revoked the certificated with ID " + + revocationRequest.getIdentifier()); } - } - catch (Exception e){ - log.error("An error has occured in the CRL signing thread: " + e.toString()); + } catch (Exception e) { + log.error("An error has occured in the CRL signing thread: " + e); } } log.info("Stopped CRL Worker Thread..."); diff --git a/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/CertificateWorker.java b/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/CertificateWorker.java index 845ac79326dac47e1007695724382ff95edf956b..8e5f27dacadf7c6bdf42fdb48786bdc7a4f19a66 100644 --- a/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/CertificateWorker.java +++ b/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/CertificateWorker.java @@ -1,28 +1,29 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.ca.workers.csr; import lombok.extern.slf4j.Slf4j; + import net.jami.jams.ca.workers.csr.builders.DeviceBuilder; import net.jami.jams.ca.workers.csr.builders.SystemAccountBuilder; import net.jami.jams.ca.workers.csr.builders.UserBuilder; @@ -35,24 +36,27 @@ public class CertificateWorker { public static final long SHIFT = 43200000L; - //The CSR here is null because we generate a certificate and keypair. + // The CSR here is null because we generate a certificate and keypair. public static SystemAccount getSignedCertificate(SystemAccount systemAccount) { - switch (systemAccount.getSystemAccountType()){ - case CA: return SystemAccountBuilder.generateCA(systemAccount); - case OCSP: return SystemAccountBuilder.generateOCSP(systemAccount); - default: return null; + switch (systemAccount.getSystemAccountType()) { + case CA: + return SystemAccountBuilder.generateCA(systemAccount); + case OCSP: + return SystemAccountBuilder.generateOCSP(systemAccount); + default: + return null; } } - public static User getSignedCertificate(User user){ + public static User getSignedCertificate(User user) { return UserBuilder.generateUser(user); } - public static User getRefreshedCertificate(User user){ + public static User getRefreshedCertificate(User user) { return UserBuilder.refreshUser(user); } - public static Device getSignedCertificate(User user, Device device){ - return DeviceBuilder.generateDevice(user,device); + public static Device getSignedCertificate(User user, Device device) { + return DeviceBuilder.generateDevice(user, device); } } diff --git a/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/builders/DeviceBuilder.java b/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/builders/DeviceBuilder.java index 8f54fdce131471237204622a1ea2e6a097a83bf2..21da15b7ba28038b3e82bb7253a019601b42e907 100644 --- a/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/builders/DeviceBuilder.java +++ b/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/builders/DeviceBuilder.java @@ -1,34 +1,41 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.ca.workers.csr.builders; +import static net.jami.jams.ca.workers.csr.CertificateWorker.SHIFT; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.ca.JamsCA; import net.jami.jams.ca.workers.csr.utils.CertificateSigner; import net.jami.jams.ca.workers.csr.utils.ExtensionLibrary; import net.jami.jams.common.objects.devices.Device; import net.jami.jams.common.objects.user.User; + import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.x509.AccessDescription; +import org.bouncycastle.asn1.x509.AuthorityInformationAccess; +import org.bouncycastle.asn1.x509.Extension; import org.bouncycastle.asn1.x509.GeneralName; import org.bouncycastle.cert.X509v3CertificateBuilder; import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; @@ -37,64 +44,80 @@ import java.math.BigInteger; import java.security.SecureRandom; import java.util.Date; -import org.bouncycastle.asn1.x509.GeneralName; -import org.bouncycastle.asn1.x509.AccessDescription; -import org.bouncycastle.asn1.x509.AuthorityInformationAccess; -import org.bouncycastle.asn1.x509.Extension; - -import static net.jami.jams.ca.workers.csr.CertificateWorker.SHIFT; - @Slf4j public class DeviceBuilder { - private static final ASN1ObjectIdentifier DEVICE_ID_FIELD = new ASN1ObjectIdentifier("0.9.2342.19200300.100.1.1"); + private static final ASN1ObjectIdentifier DEVICE_ID_FIELD = + new ASN1ObjectIdentifier("0.9.2342.19200300.100.1.1"); private static final ASN1ObjectIdentifier DEVICE_CN = new ASN1ObjectIdentifier("2.5.4.3"); - public static Device generateDevice(User user, Device device){ + public static Device generateDevice(User user, Device device) { try { long now = System.currentTimeMillis(); - X509v3CertificateBuilder builder = new X509v3CertificateBuilder( - new JcaX509CertificateHolder(user.getCertificate()).getSubject(), - new BigInteger(256, new SecureRandom()), - new Date(now - SHIFT), - new Date(now + JamsCA.deviceLifetime), - device.getCertificationRequest().getSubject(), - device.getCertificationRequest().getSubjectPublicKeyInfo() - ); + X509v3CertificateBuilder builder = + new X509v3CertificateBuilder( + new JcaX509CertificateHolder(user.getCertificate()).getSubject(), + new BigInteger(256, new SecureRandom()), + new Date(now - SHIFT), + new Date(now + JamsCA.deviceLifetime), + device.getCertificationRequest().getSubject(), + device.getCertificationRequest().getSubjectPublicKeyInfo()); /* - * - * This extension library configuration is done at this point in order to add the issuer id (here the jami Id) - * to the certificate to help retrieve the device certificate issuer in more suitable manner during the call to the OCSP endpoint - * - * */ + * + * This extension library configuration is done at this point in order to add the issuer id (here the jami Id) + * to the certificate to help retrieve the device certificate issuer in more suitable manner during the call to the OCSP endpoint + * + * */ - //Pre-Define the AIA Point - AccessDescription accessDescription = new AccessDescription( - AccessDescription.id_ad_ocsp, - new GeneralName(GeneralName.uniformResourceIdentifier, JamsCA.serverDomain + "/api/ocsp/" + user.getJamiId()) - ); + // Pre-Define the AIA Point + AccessDescription accessDescription = + new AccessDescription( + AccessDescription.id_ad_ocsp, + new GeneralName( + GeneralName.uniformResourceIdentifier, + JamsCA.serverDomain + "/api/ocsp/" + user.getJamiId())); - ExtensionLibrary.deviceExtensions.getExtensions().set(3, new Object[]{Extension.authorityInfoAccess, false, new AuthorityInformationAccess(accessDescription)}); + ExtensionLibrary.deviceExtensions + .getExtensions() + .set( + 3, + new Object[] { + Extension.authorityInfoAccess, + false, + new AuthorityInformationAccess(accessDescription) + }); - device.setCertificate(CertificateSigner.signCertificate(user.getPrivateKey(),builder, ExtensionLibrary.deviceExtensions)); + device.setCertificate( + CertificateSigner.signCertificate( + user.getPrivateKey(), builder, ExtensionLibrary.deviceExtensions)); boolean deviceIdDetected = false; - for(int i=0; i < device.getCertificationRequest().getSubject().getRDNs().length;i++) { - if(device.getCertificationRequest().getSubject().getRDNs()[i].getFirst().getType().equals(DEVICE_ID_FIELD)){ - device.setDeviceId(device.getCertificationRequest().getSubject().getRDNs()[i].getFirst().getValue().toString()); + for (int i = 0; + i < device.getCertificationRequest().getSubject().getRDNs().length; + i++) { + if (device.getCertificationRequest() + .getSubject() + .getRDNs()[i] + .getFirst() + .getType() + .equals(DEVICE_ID_FIELD)) { + device.setDeviceId( + device.getCertificationRequest() + .getSubject() + .getRDNs()[i] + .getFirst() + .getValue() + .toString()); deviceIdDetected = true; } } - if(!deviceIdDetected) return null; - //kill off the certification request it's useless. + if (!deviceIdDetected) return null; + // kill off the certification request it's useless. device.setCertificationRequest(null); return device; - } - catch (Exception e){ - log.error("Could not generate a user certificate: " + e.toString()); + } catch (Exception e) { + log.error("Could not generate a user certificate: " + e); return null; } } - - } diff --git a/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/builders/SystemAccountBuilder.java b/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/builders/SystemAccountBuilder.java index 395ca189ec69fca721abdd5a95b1c0d417be22e6..378c46c530627097d11bce7bd2162ede70eed12f 100644 --- a/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/builders/SystemAccountBuilder.java +++ b/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/builders/SystemAccountBuilder.java @@ -1,32 +1,34 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.ca.workers.csr.builders; import lombok.extern.slf4j.Slf4j; + import net.jami.jams.ca.JamsCA; import net.jami.jams.ca.workers.csr.utils.CertificateSigner; import net.jami.jams.ca.workers.csr.utils.ExtensionLibrary; import net.jami.jams.common.objects.system.SystemAccount; + import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.cert.X509v3CertificateBuilder; @@ -41,53 +43,58 @@ import java.util.Date; @Slf4j public class SystemAccountBuilder { - //Self-signed because it is a CA - public static SystemAccount generateCA(SystemAccount systemAccount){ + // Self-signed because it is a CA + public static SystemAccount generateCA(SystemAccount systemAccount) { try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(4096); KeyPair keyPair = keyPairGenerator.generateKeyPair(); - X509v3CertificateBuilder builder = new X509v3CertificateBuilder( - new X500Name(systemAccount.getX509Fields().getDN()), - new BigInteger(256, new SecureRandom()), - new Date(System.currentTimeMillis()), - new Date(System.currentTimeMillis() + systemAccount.getX509Fields().getLifetime()), - new X500Name(systemAccount.getX509Fields().getDN()), - SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()) - ); + X509v3CertificateBuilder builder = + new X509v3CertificateBuilder( + new X500Name(systemAccount.getX509Fields().getDN()), + new BigInteger(256, new SecureRandom()), + new Date(System.currentTimeMillis()), + new Date( + System.currentTimeMillis() + + systemAccount.getX509Fields().getLifetime()), + new X500Name(systemAccount.getX509Fields().getDN()), + SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded())); systemAccount.setPrivateKey(keyPair.getPrivate()); - systemAccount.setCertificate(CertificateSigner.signCertificate(keyPair.getPrivate(),builder, ExtensionLibrary.caExtensions)); + systemAccount.setCertificate( + CertificateSigner.signCertificate( + keyPair.getPrivate(), builder, ExtensionLibrary.caExtensions)); return systemAccount; - } - catch (Exception e){ - log.error("Could not generate the system's CA: " + e.toString()); + } catch (Exception e) { + log.error("Could not generate the system's CA: " + e); return null; } } - //This is signed by the CA, the OCSP certificate has the same lifetime as the CA by default. - //someday this could change. - public static SystemAccount generateOCSP(SystemAccount systemAccount){ + // This is signed by the CA, the OCSP certificate has the same lifetime as the CA by default. + // someday this could change. + public static SystemAccount generateOCSP(SystemAccount systemAccount) { try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(4096); KeyPair keyPair = keyPairGenerator.generateKeyPair(); - X509v3CertificateBuilder builder = new X509v3CertificateBuilder( - new JcaX509CertificateHolder(JamsCA.CA.getCertificate()).getSubject(), - new BigInteger(256, new SecureRandom()), - new Date(System.currentTimeMillis()), - new Date(System.currentTimeMillis() + systemAccount.getX509Fields().getLifetime()), - new X500Name("CN=" + systemAccount.getX509Fields().getDN()), - SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()) - ); + X509v3CertificateBuilder builder = + new X509v3CertificateBuilder( + new JcaX509CertificateHolder(JamsCA.CA.getCertificate()).getSubject(), + new BigInteger(256, new SecureRandom()), + new Date(System.currentTimeMillis()), + new Date( + System.currentTimeMillis() + + systemAccount.getX509Fields().getLifetime()), + new X500Name("CN=" + systemAccount.getX509Fields().getDN()), + SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded())); systemAccount.setPrivateKey(keyPair.getPrivate()); - systemAccount.setCertificate(CertificateSigner.signCertificate(JamsCA.CA.getPrivateKey(), builder, ExtensionLibrary.caExtensions)); + systemAccount.setCertificate( + CertificateSigner.signCertificate( + JamsCA.CA.getPrivateKey(), builder, ExtensionLibrary.caExtensions)); return systemAccount; - } - catch (Exception e){ - log.error("Could not generate the system's OCSP: " + e.toString()); + } catch (Exception e) { + log.error("Could not generate the system's OCSP: " + e); return null; } } - } diff --git a/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/builders/UserBuilder.java b/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/builders/UserBuilder.java index c326ef46771716f37aca99ffe79ea33f01406c63..d176275bbf3b8af3557a05e4259edaabe4bf6315 100644 --- a/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/builders/UserBuilder.java +++ b/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/builders/UserBuilder.java @@ -1,33 +1,39 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.ca.workers.csr.builders; +import static net.jami.jams.ca.workers.csr.CertificateWorker.SHIFT; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.ca.JamsCA; import net.jami.jams.ca.workers.csr.utils.CertificateSigner; import net.jami.jams.ca.workers.csr.utils.ExtensionLibrary; import net.jami.jams.common.objects.roots.X509Fields; import net.jami.jams.common.objects.user.User; + +import org.apache.commons.codec.binary.Hex; +import org.apache.commons.codec.digest.MessageDigestAlgorithms; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.cert.X509v3CertificateBuilder; @@ -40,12 +46,6 @@ import java.security.MessageDigest; import java.security.SecureRandom; import java.util.Date; -import static net.jami.jams.ca.workers.csr.CertificateWorker.SHIFT; - -import org.apache.commons.codec.binary.Hex; -import org.apache.commons.codec.digest.MessageDigestAlgorithms; - - @Slf4j public class UserBuilder { @@ -56,23 +56,31 @@ public class UserBuilder { keyPairGenerator.initialize(4096); KeyPair keyPair = keyPairGenerator.generateKeyPair(); - user.getX509Fields().setUid(Hex.encodeHexString(MessageDigest.getInstance(MessageDigestAlgorithms.SHA_1).digest(keyPair.getPublic().getEncoded()))); + user.getX509Fields() + .setUid( + Hex.encodeHexString( + MessageDigest.getInstance(MessageDigestAlgorithms.SHA_1) + .digest(keyPair.getPublic().getEncoded()))); - X509v3CertificateBuilder builder = new X509v3CertificateBuilder( - new JcaX509CertificateHolder(JamsCA.CA.getCertificate()).getSubject(), - new BigInteger(128, new SecureRandom()), - new Date(now - SHIFT), - new Date(now + JamsCA.userLifetime), - new X500Name(user.getX509Fields().getDN()), - SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()) - ); + X509v3CertificateBuilder builder = + new X509v3CertificateBuilder( + new JcaX509CertificateHolder(JamsCA.CA.getCertificate()).getSubject(), + new BigInteger(128, new SecureRandom()), + new Date(now - SHIFT), + new Date(now + JamsCA.userLifetime), + new X500Name(user.getX509Fields().getDN()), + SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded())); user.setPrivateKey(keyPair.getPrivate()); - user.setCertificate(CertificateSigner.signCertificate(JamsCA.CA.getPrivateKey(), builder, ExtensionLibrary.userExtensions)); - log.info("New user certificate: Not valid after: " + user.getCertificate().getNotAfter()); + user.setCertificate( + CertificateSigner.signCertificate( + JamsCA.CA.getPrivateKey(), builder, ExtensionLibrary.userExtensions)); + log.info( + "New user certificate: Not valid after: " + + user.getCertificate().getNotAfter()); return user; } catch (Exception e) { - log.error("Could not generate a user certificate: " + e.toString()); + log.error("Could not generate a user certificate: " + e); return null; } } @@ -89,20 +97,25 @@ public class UserBuilder { user.getX509Fields().setCommonName(user.getUsername()); user.getX509Fields().setUid(user.getJamiId()); - X509v3CertificateBuilder builder = new X509v3CertificateBuilder( - new JcaX509CertificateHolder(JamsCA.CA.getCertificate()).getSubject(), - new BigInteger(128, new SecureRandom()), - new Date(now - SHIFT), - new Date(now + userLifeTime), - new X500Name(user.getX509Fields().getDN()), - new JcaX509CertificateHolder(user.getCertificate()).getSubjectPublicKeyInfo() - ); - user.setCertificate(CertificateSigner.signCertificate(JamsCA.CA.getPrivateKey(), builder, ExtensionLibrary.userExtensions)); - log.info("Refreshed user certificate: Not valid after: " + user.getCertificate().getNotAfter()); + X509v3CertificateBuilder builder = + new X509v3CertificateBuilder( + new JcaX509CertificateHolder(JamsCA.CA.getCertificate()).getSubject(), + new BigInteger(128, new SecureRandom()), + new Date(now - SHIFT), + new Date(now + userLifeTime), + new X500Name(user.getX509Fields().getDN()), + new JcaX509CertificateHolder(user.getCertificate()) + .getSubjectPublicKeyInfo()); + user.setCertificate( + CertificateSigner.signCertificate( + JamsCA.CA.getPrivateKey(), builder, ExtensionLibrary.userExtensions)); + log.info( + "Refreshed user certificate: Not valid after: " + + user.getCertificate().getNotAfter()); return user; } catch (Exception e) { - log.error("Could not refresh user certificate: " + e.toString()); + log.error("Could not refresh user certificate: " + e); return null; } } diff --git a/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/utils/CertificateExtendedData.java b/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/utils/CertificateExtendedData.java index 0ed680860fec554d7223a9db4fad880839f31987..8ec72ac7f989113f453178a2d2272144af269149 100644 --- a/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/utils/CertificateExtendedData.java +++ b/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/utils/CertificateExtendedData.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.ca.workers.csr.utils; import lombok.Getter; @@ -33,5 +33,3 @@ import java.util.List; public class CertificateExtendedData { private List<Object[]> extensions = new ArrayList<>(); } - - diff --git a/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/utils/CertificateSigner.java b/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/utils/CertificateSigner.java index 22876a3acd90b14f904c6183dcbd3c85da52be7d..18878df5f1ca8684e19a2438e68841e41d28e4bc 100644 --- a/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/utils/CertificateSigner.java +++ b/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/utils/CertificateSigner.java @@ -1,29 +1,31 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.ca.workers.csr.utils; import lombok.extern.slf4j.Slf4j; + import net.jami.jams.ca.JamsCA; + import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; @@ -44,27 +46,38 @@ import java.security.cert.X509Certificate; @Slf4j public class CertificateSigner { - public static X509Certificate signCertificate(PrivateKey privateKey, X509v3CertificateBuilder certificateBuilder, - CertificateExtendedData certificateExtendedData){ + public static X509Certificate signCertificate( + PrivateKey privateKey, + X509v3CertificateBuilder certificateBuilder, + CertificateExtendedData certificateExtendedData) { try { - //Appose the extended data from the template. - for(Object[] extensions : certificateExtendedData.getExtensions()){ - certificateBuilder.addExtension((ASN1ObjectIdentifier) extensions[0],(boolean) extensions[1],(ASN1Encodable) extensions[2]); + // Appose the extended data from the template. + for (Object[] extensions : certificateExtendedData.getExtensions()) { + certificateBuilder.addExtension( + (ASN1ObjectIdentifier) extensions[0], + (boolean) extensions[1], + (ASN1Encodable) extensions[2]); } - //Initialize the signing. - AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(JamsCA.signingAlgorithm); - AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); - AsymmetricKeyParameter asymmetricKeyParameter = PrivateKeyFactory.createKey(privateKey.getEncoded()); - //Sign the certificate. - ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(asymmetricKeyParameter); - Certificate eeX509CertificateStructure = certificateBuilder.build(sigGen).toASN1Structure(); - return (X509Certificate) new CertificateFactory().engineGenerateCertificate(new ByteArrayInputStream(eeX509CertificateStructure.getEncoded())); - } - catch (Exception e){ - log.error("Could not sign a certificate with error: " + e.toString()); + // Initialize the signing. + AlgorithmIdentifier sigAlgId = + new DefaultSignatureAlgorithmIdentifierFinder().find(JamsCA.signingAlgorithm); + AlgorithmIdentifier digAlgId = + new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); + AsymmetricKeyParameter asymmetricKeyParameter = + PrivateKeyFactory.createKey(privateKey.getEncoded()); + // Sign the certificate. + ContentSigner sigGen = + new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(asymmetricKeyParameter); + Certificate eeX509CertificateStructure = + certificateBuilder.build(sigGen).toASN1Structure(); + return (X509Certificate) + new CertificateFactory() + .engineGenerateCertificate( + new ByteArrayInputStream( + eeX509CertificateStructure.getEncoded())); + } catch (Exception e) { + log.error("Could not sign a certificate with error: " + e); return null; } } - - } diff --git a/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/utils/ExtensionLibrary.java b/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/utils/ExtensionLibrary.java index fca44100a99d68b81ef283656f915ddfbb286988..12aaaff8e83cadf696eedbace7d1439ff1fdb54b 100644 --- a/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/utils/ExtensionLibrary.java +++ b/jams-ca/src/main/java/net/jami/jams/ca/workers/csr/utils/ExtensionLibrary.java @@ -1,28 +1,29 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.ca.workers.csr.utils; import net.jami.jams.ca.JamsCA; + import org.bouncycastle.asn1.x509.AccessDescription; import org.bouncycastle.asn1.x509.AuthorityInformationAccess; import org.bouncycastle.asn1.x509.BasicConstraints; @@ -46,40 +47,116 @@ public class ExtensionLibrary { private static final int SCHEMA = GeneralName.uniformResourceIdentifier; static { - //Pre-Define the CRL Distribution Point + // Pre-Define the CRL Distribution Point DistributionPoint[] distPoints = new DistributionPoint[1]; - distPoints[0] = new DistributionPoint(new DistributionPointName( - new GeneralNames(new GeneralName(SCHEMA, JamsCA.serverDomain + "/api/auth/crl"))) - , null, null - ); + distPoints[0] = + new DistributionPoint( + new DistributionPointName( + new GeneralNames( + new GeneralName( + SCHEMA, JamsCA.serverDomain + "/api/auth/crl"))), + null, + null); - //Pre-Define the AIA Point - AccessDescription accessDescription = new AccessDescription( - AccessDescription.id_ad_ocsp, - new GeneralName(SCHEMA, JamsCA.serverDomain + "/api/ocsp") - ); + // Pre-Define the AIA Point + AccessDescription accessDescription = + new AccessDescription( + AccessDescription.id_ad_ocsp, + new GeneralName(SCHEMA, JamsCA.serverDomain + "/api/ocsp")); - //CA Extensions. - caExtensions.getExtensions().add(new Object[]{Extension.basicConstraints, true, new BasicConstraints(10)}); - caExtensions.getExtensions().add(new Object[]{Extension.keyUsage, false, new KeyUsage(KeyUsage.cRLSign | KeyUsage.keyCertSign)}); + // CA Extensions. + caExtensions + .getExtensions() + .add(new Object[] {Extension.basicConstraints, true, new BasicConstraints(10)}); + caExtensions + .getExtensions() + .add( + new Object[] { + Extension.keyUsage, + false, + new KeyUsage(KeyUsage.cRLSign | KeyUsage.keyCertSign) + }); - //OCSP Extensions. - ocspExtensions.getExtensions().add(new Object[]{Extension.basicConstraints, true, new BasicConstraints(false)}); - ocspExtensions.getExtensions().add(new Object[]{Extension.extendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_OCSPSigning)}); - ocspExtensions.getExtensions().add(new Object[]{Extension.keyUsage, false, new KeyUsage(KeyUsage.nonRepudiation | KeyUsage.digitalSignature | KeyUsage.keyEncipherment)}); + // OCSP Extensions. + ocspExtensions + .getExtensions() + .add(new Object[] {Extension.basicConstraints, true, new BasicConstraints(false)}); + ocspExtensions + .getExtensions() + .add( + new Object[] { + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage(KeyPurposeId.id_kp_OCSPSigning) + }); + ocspExtensions + .getExtensions() + .add( + new Object[] { + Extension.keyUsage, + false, + new KeyUsage( + KeyUsage.nonRepudiation + | KeyUsage.digitalSignature + | KeyUsage.keyEncipherment) + }); - //User extensions (the user is a sub-CA) - userExtensions.getExtensions().add(new Object[]{Extension.basicConstraints, true, new BasicConstraints(10)}); - userExtensions.getExtensions().add(new Object[]{Extension.keyUsage, false, new KeyUsage(KeyUsage.cRLSign | KeyUsage.keyCertSign)}); - userExtensions.getExtensions().add(new Object[]{Extension.cRLDistributionPoints, false, new CRLDistPoint(distPoints)}); - userExtensions.getExtensions().add(new Object[]{Extension.authorityInfoAccess, false, new AuthorityInformationAccess(accessDescription)}); + // User extensions (the user is a sub-CA) + userExtensions + .getExtensions() + .add(new Object[] {Extension.basicConstraints, true, new BasicConstraints(10)}); + userExtensions + .getExtensions() + .add( + new Object[] { + Extension.keyUsage, + false, + new KeyUsage(KeyUsage.cRLSign | KeyUsage.keyCertSign) + }); + userExtensions + .getExtensions() + .add( + new Object[] { + Extension.cRLDistributionPoints, false, new CRLDistPoint(distPoints) + }); + userExtensions + .getExtensions() + .add( + new Object[] { + Extension.authorityInfoAccess, + false, + new AuthorityInformationAccess(accessDescription) + }); - //Device extensions - deviceExtensions.getExtensions().add(new Object[]{Extension.basicConstraints, true, new BasicConstraints(false)}); - deviceExtensions.getExtensions().add(new Object[]{Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation)}); - deviceExtensions.getExtensions().add(new Object[]{Extension.cRLDistributionPoints, false, new CRLDistPoint(distPoints)}); - deviceExtensions.getExtensions().add(new Object[]{Extension.authorityInfoAccess, false, new AuthorityInformationAccess(accessDescription)}); + // Device extensions + deviceExtensions + .getExtensions() + .add(new Object[] {Extension.basicConstraints, true, new BasicConstraints(false)}); + deviceExtensions + .getExtensions() + .add( + new Object[] { + Extension.keyUsage, + false, + new KeyUsage( + KeyUsage.digitalSignature + | KeyUsage.dataEncipherment + | KeyUsage.keyAgreement + | KeyUsage.nonRepudiation) + }); + deviceExtensions + .getExtensions() + .add( + new Object[] { + Extension.cRLDistributionPoints, false, new CRLDistPoint(distPoints) + }); + deviceExtensions + .getExtensions() + .add( + new Object[] { + Extension.authorityInfoAccess, + false, + new AuthorityInformationAccess(accessDescription) + }); } - - } diff --git a/jams-ca/src/main/java/net/jami/jams/ca/workers/ocsp/OCSPWorker.java b/jams-ca/src/main/java/net/jami/jams/ca/workers/ocsp/OCSPWorker.java index b77ea1885a6860710506270ef0c1a6d3de1b20f6..3b064f6aac7008cca130657d06b9daeb9c3bf60a 100644 --- a/jams-ca/src/main/java/net/jami/jams/ca/workers/ocsp/OCSPWorker.java +++ b/jams-ca/src/main/java/net/jami/jams/ca/workers/ocsp/OCSPWorker.java @@ -1,35 +1,37 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.ca.workers.ocsp; +import static net.jami.jams.ca.JamsCA.*; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.ca.workers.X509Worker; import net.jami.jams.ca.workers.crl.CRLWorker; import net.jami.jams.common.cryptoengineapi.ocsp.CertificateStatus; import net.jami.jams.common.cryptoengineapi.ocsp.CertificateSummary; import net.jami.jams.common.cryptoengineapi.ocsp.OCSPCertificateStatusMapper; -import net.jami.jams.common.objects.devices.Device; -import net.jami.jams.common.objects.user.User; + import org.bouncycastle.asn1.ocsp.OCSPObjectIdentifiers; import org.bouncycastle.asn1.x509.Extension; import org.bouncycastle.asn1.x509.Extensions; @@ -54,102 +56,132 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Date; -import static net.jami.jams.ca.JamsCA.*; - @Slf4j public class OCSPWorker extends X509Worker<String> { private final CRLWorker crlWorker; private final RespID responderID; private final ContentSigner contentSigner; - private final JcaContentVerifierProviderBuilder contentVerifierProvider = new JcaContentVerifierProviderBuilder().setProvider("BC"); + private final JcaContentVerifierProviderBuilder contentVerifierProvider = + new JcaContentVerifierProviderBuilder().setProvider("BC"); - //To process OCSP requests we need access to the CRL, hence we might as well just pass it here. - public OCSPWorker(PrivateKey privateKey, X509Certificate certificate, CRLWorker crlWorker) throws Exception { + // To process OCSP requests we need access to the CRL, hence we might as well just pass it here. + public OCSPWorker(PrivateKey privateKey, X509Certificate certificate, CRLWorker crlWorker) + throws Exception { super(privateKey, certificate); this.crlWorker = crlWorker; - DigestCalculatorProvider digestCalculatorProvider = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(); + DigestCalculatorProvider digestCalculatorProvider = + new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(); // only SHA-1 is supported for responder IDs. - this.responderID = new RespID(SubjectPublicKeyInfo.getInstance(CA.getCertificate().getPublicKey().getEncoded()), digestCalculatorProvider.get(new DefaultDigestAlgorithmIdentifierFinder().find ("SHA-1"))); - this.contentSigner = new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build(CA.getPrivateKey()); + this.responderID = + new RespID( + SubjectPublicKeyInfo.getInstance( + CA.getCertificate().getPublicKey().getEncoded()), + digestCalculatorProvider.get( + new DefaultDigestAlgorithmIdentifierFinder().find("SHA-1"))); + this.contentSigner = + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider("BC") + .build(CA.getPrivateKey()); log.info("Instantiated OCSP Worker..."); } - public OCSPResp getOCSPResponse(OCSPReq ocspRequest, X509Certificate certificate, PrivateKey privateKey, Boolean unknown) throws OCSPException { + public OCSPResp getOCSPResponse( + OCSPReq ocspRequest, + X509Certificate certificate, + PrivateKey privateKey, + Boolean unknown) + throws OCSPException { try { - if(validateRequest(ocspRequest) != null) throw new OCSPException("Request is not valid"); //this means the request is invalid and we should notify the client. - //If the request was valid, we move on to other things. + if (validateRequest(ocspRequest) != null) + throw new OCSPException( + "Request is not valid"); // this means the request is invalid and we should + // notify the client. + // If the request was valid, we move on to other things. BasicOCSPRespBuilder responseBuilder = new BasicOCSPRespBuilder(responderID); // Add appropriate extensions Collection<Extension> responseExtensions = new ArrayList<>(); // nonce - Extension nonceExtension = ocspRequest.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); + Extension nonceExtension = + ocspRequest.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); if (nonceExtension != null) responseExtensions.add(nonceExtension); - Extension[] extensions = responseExtensions.toArray(new Extension[responseExtensions.size()]); + Extension[] extensions = + responseExtensions.toArray(new Extension[responseExtensions.size()]); responseBuilder.setResponseExtensions(new Extensions(extensions)); for (Req request : ocspRequest.getRequestList()) addResponse(responseBuilder, request, unknown); - BasicOCSPResp basicResponse = responseBuilder.build( - new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build(privateKey), - new X509CertificateHolder[]{new JcaX509CertificateHolder(certificate)}, - new Date() - ); + BasicOCSPResp basicResponse = + responseBuilder.build( + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider("BC") + .build(privateKey), + new X509CertificateHolder[] {new JcaX509CertificateHolder(certificate)}, + new Date()); return new OCSPRespBuilder().build(OCSPRespBuilder.SUCCESSFUL, basicResponse); - } - catch (Exception e){ - log.error("Could not verify the signature on the OCSP request with error {}",e.getMessage()); + } catch (Exception e) { + log.error( + "Could not verify the signature on the OCSP request with error {}", + e.getMessage()); return null; } } private OCSPResp validateRequest(OCSPReq ocspRequest) throws Exception { - if (ocspRequest == null || (ocspRequest.isSigned() && - !ocspRequest.isSignatureValid(contentVerifierProvider.build(ocspRequest.getCerts()[0])))) { + if (ocspRequest == null + || (ocspRequest.isSigned() + && !ocspRequest.isSignatureValid( + contentVerifierProvider.build(ocspRequest.getCerts()[0])))) { return new OCSPRespBuilder().build(OCSPRespBuilder.MALFORMED_REQUEST, null); } return null; } - private CertificateSummary getCertificateSummary(BigInteger serial, Boolean unknown) { - if(unknown) { + if (unknown) { return CertificateSummary.newBuilder() .withStatus(CertificateStatus.UNKNOWN) .withSerialNumber(serial) .build(); } - X509CRLEntryHolder x509CRLEntryHolder = crlWorker.getExistingCRL().get().getRevokedCertificate(serial); + X509CRLEntryHolder x509CRLEntryHolder = + crlWorker.getExistingCRL().get().getRevokedCertificate(serial); - if(x509CRLEntryHolder != null) return CertificateSummary.newBuilder() - .withStatus(CertificateStatus.REVOKED) - .withSerialNumber(serial) - .withRevocationTime(LocalDateTime.ofInstant(x509CRLEntryHolder.getRevocationDate().toInstant(), ZoneId.systemDefault())) - .build(); - return CertificateSummary.newBuilder() - .withStatus(CertificateStatus.VALID) + if (x509CRLEntryHolder != null) + return CertificateSummary.newBuilder() + .withStatus(CertificateStatus.REVOKED) .withSerialNumber(serial) + .withRevocationTime( + LocalDateTime.ofInstant( + x509CRLEntryHolder.getRevocationDate().toInstant(), + ZoneId.systemDefault())) .build(); + return CertificateSummary.newBuilder() + .withStatus(CertificateStatus.VALID) + .withSerialNumber(serial) + .build(); } - - private void addResponse(BasicOCSPRespBuilder responseBuilder, Req request, Boolean unknown) throws OCSPException{ + private void addResponse(BasicOCSPRespBuilder responseBuilder, Req request, Boolean unknown) + throws OCSPException { CertificateID certificateID = request.getCertID(); // Build Extensions - Extensions extensions = new Extensions(new Extension[]{}); + Extensions extensions = new Extensions(new Extension[] {}); Extensions requestExtensions = request.getSingleRequestExtensions(); if (requestExtensions != null) { - Extension nonceExtension = requestExtensions.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); + Extension nonceExtension = + requestExtensions.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); if (nonceExtension != null) extensions = new Extensions(nonceExtension); } - responseBuilder.addResponse(certificateID, - OCSPCertificateStatusMapper.getStatus(getCertificateSummary(request.getCertID().getSerialNumber(), unknown)), + responseBuilder.addResponse( + certificateID, + OCSPCertificateStatusMapper.getStatus( + getCertificateSummary(request.getCertID().getSerialNumber(), unknown)), new Date(), new Date(new Date().getTime() + crlLifetime), extensions); } - } diff --git a/jams-ca/src/test/java/net/jami/jams/ca/workers/csr/builders/SystemAccountBuilderTest.java b/jams-ca/src/test/java/net/jami/jams/ca/workers/csr/builders/SystemAccountBuilderTest.java index 9023c1420c51f7ac3ed5c5f804d13d59018c8894..cfa68ad680c88ad603f5391962467150950989e0 100644 --- a/jams-ca/src/test/java/net/jami/jams/ca/workers/csr/builders/SystemAccountBuilderTest.java +++ b/jams-ca/src/test/java/net/jami/jams/ca/workers/csr/builders/SystemAccountBuilderTest.java @@ -1,28 +1,31 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.ca.workers.csr.builders; +import static org.junit.jupiter.api.Assertions.fail; + import com.jsoniter.output.JsonStream; + import net.jami.jams.ca.JamsCA; import net.jami.jams.common.authentication.AuthenticationSourceType; import net.jami.jams.common.cryptoengineapi.CertificateAuthorityConfig; @@ -34,6 +37,7 @@ import net.jami.jams.common.objects.system.SystemAccount; import net.jami.jams.common.objects.system.SystemAccountType; import net.jami.jams.common.objects.user.User; import net.jami.jams.common.utils.X509Utils; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -44,15 +48,13 @@ import java.io.InputStream; import java.math.BigInteger; import java.util.HashMap; -import static org.junit.jupiter.api.Assertions.fail; - class SystemAccountBuilderTest { private static String strPkcs10Request; @BeforeAll - static void setUp() throws Exception{ - //Delete the crl.pem file if it exists. + static void setUp() throws Exception { + // Delete the crl.pem file if it exists. File file = new File(System.getProperty("user.dir") + File.separator + "crl.pem"); file.delete(); InputStream path; @@ -70,47 +72,46 @@ class SystemAccountBuilderTest { caAccount.getX509Fields().setCountry("FR"); caAccount.getX509Fields().setLifetime(10000000L); caAccount = SystemAccountBuilder.generateCA(caAccount); - Assertions.assertNotNull(caAccount.getCertificate(),"CA Certificate was not generated!"); + Assertions.assertNotNull(caAccount.getCertificate(), "CA Certificate was not generated!"); JamsCA.CA = caAccount; - //Generate OCSP + // Generate OCSP SystemAccount ocspAccount = new SystemAccount(); ocspAccount.setSystemAccountType(SystemAccountType.OCSP); ocspAccount.setX509Fields(new X509Fields()); ocspAccount.getX509Fields().setCommonName("OCSP Server"); ocspAccount.getX509Fields().setLifetime(10000000L); ocspAccount = SystemAccountBuilder.generateOCSP(ocspAccount); - Assertions.assertNotNull(ocspAccount.getCertificate(),"OCSP Certificate was not generated!"); + Assertions.assertNotNull( + ocspAccount.getCertificate(), "OCSP Certificate was not generated!"); - //Generate User. + // Generate User. User user = new User(); user.setUserType(AuthenticationSourceType.LOCAL); user.setX509Fields(new X509Fields()); user.getX509Fields().setCommonName("Felix's Personal Certificate"); user = UserBuilder.generateUser(user); - Assertions.assertNotNull(user.getCertificate(),"User Certificate was not generated!"); + Assertions.assertNotNull(user.getCertificate(), "User Certificate was not generated!"); - //Generate a device + // Generate a device Device device = new Device(); device.setOwner("00000"); device.setCertificationRequest(X509Utils.getCSRFromString(strPkcs10Request)); - device = DeviceBuilder.generateDevice(user,device); - Assertions.assertNotNull(device.getCertificate(),"Device certificate was not generated!"); - //Check that we can decode the rdn. + device = DeviceBuilder.generateDevice(user, device); + Assertions.assertNotNull(device.getCertificate(), "Device certificate was not generated!"); + // Check that we can decode the rdn. try { - HashMap<String,String> data = X509Utils.extractDNFromCertificate(device.getCertificate()); - Assertions.assertEquals(2,data.size()); - } - catch (Exception e){ + HashMap<String, String> data = + X509Utils.extractDNFromCertificate(device.getCertificate()); + Assertions.assertEquals(2, data.size()); + } catch (Exception e) { fail(); } - - } @Test - void testCRLGeneration() throws Exception{ + void testCRLGeneration() throws Exception { SystemAccount caAccount = new SystemAccount(); caAccount.setSystemAccountType(SystemAccountType.CA); caAccount.setX509Fields(new X509Fields()); @@ -118,7 +119,7 @@ class SystemAccountBuilderTest { caAccount.getX509Fields().setCountry("FR"); caAccount.getX509Fields().setLifetime(10000000L); caAccount = SystemAccountBuilder.generateCA(caAccount); - Assertions.assertNotNull(caAccount.getCertificate(),"CA Certificate was not generated!"); + Assertions.assertNotNull(caAccount.getCertificate(), "CA Certificate was not generated!"); CertificateAuthorityConfig config = new CertificateAuthorityConfig(); config.setUserLifetime(1000L); config.setSigningAlgorithm("SHA512WITHRSA"); @@ -126,28 +127,33 @@ class SystemAccountBuilderTest { config.setCrlLifetime(1000000L); config.setDeviceLifetime(1000L); - JamsCA jamsCA = new JamsCA(); - jamsCA.init(JsonStream.serialize(config),caAccount,caAccount); + jamsCA.init(JsonStream.serialize(config), caAccount, caAccount); RevocationRequest revocationRequest = new RevocationRequest(); revocationRequest.setIdentifier(new BigInteger("91828882")); revocationRequest.setRevocationType(RevocationType.USER); jamsCA.revokeCertificate(revocationRequest); - synchronized (this){ + synchronized (this) { this.wait(2_000); } Assertions.assertNotNull(jamsCA.getLatestCRL()); - Assertions.assertEquals(1,jamsCA.getLatestCRL().get().getRevokedCertificates().toArray().length,"Expected only 1 certificate!"); + Assertions.assertEquals( + 1, + jamsCA.getLatestCRL().get().getRevokedCertificates().toArray().length, + "Expected only 1 certificate!"); revocationRequest = new RevocationRequest(); revocationRequest.setIdentifier(new BigInteger("17262653")); revocationRequest.setRevocationType(RevocationType.USER); jamsCA.revokeCertificate(revocationRequest); - synchronized (this){ + synchronized (this) { this.wait(2_000); } Assertions.assertNotNull(jamsCA.getLatestCRL()); - Assertions.assertEquals(2,jamsCA.getLatestCRL().get().getRevokedCertificates().toArray().length,"Expected only 2 certificates!"); + Assertions.assertEquals( + 2, + jamsCA.getLatestCRL().get().getRevokedCertificates().toArray().length, + "Expected only 2 certificates!"); } @AfterAll @@ -155,4 +161,4 @@ class SystemAccountBuilderTest { File file = new File(System.getProperty("user.dir") + File.separator + "crl.pem"); file.delete(); } -} \ No newline at end of file +} diff --git a/jams-ca/src/test/java/net/jami/jams/ca/workers/csr/builders/UserBuilderTest.java b/jams-ca/src/test/java/net/jami/jams/ca/workers/csr/builders/UserBuilderTest.java index 468a9b4ee5cb7e4652ceec3cc738fada07f18319..219ced4f3a026cd33ea40cdd0b8c2fa8567dc6bb 100644 --- a/jams-ca/src/test/java/net/jami/jams/ca/workers/csr/builders/UserBuilderTest.java +++ b/jams-ca/src/test/java/net/jami/jams/ca/workers/csr/builders/UserBuilderTest.java @@ -1,36 +1,22 @@ package net.jami.jams.ca.workers.csr.builders; -import net.jami.jams.ca.JamsCA; +import static org.junit.jupiter.api.Assertions.*; + import lombok.extern.slf4j.Slf4j; import net.jami.jams.common.authentication.AuthenticationSourceType; import net.jami.jams.common.objects.roots.X509Fields; -import net.jami.jams.common.objects.user.AccessLevel; import net.jami.jams.common.objects.user.User; -import net.jami.jams.common.utils.X509Utils; -import org.bouncycastle.openssl.jcajce.JcaPEMWriter; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.security.PrivateKey; -import java.security.cert.X509Certificate; -import java.util.Arrays; -import java.util.Base64; -import java.util.Date; - -import static org.junit.jupiter.api.Assertions.*; +import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; -import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; +import java.security.cert.X509Certificate; @Slf4j class UserBuilderTest { - @Test void generateUserCertificate() { @@ -41,7 +27,7 @@ class UserBuilderTest { user.getX509Fields().setCommonName("TestUser's Personal Certificate"); user = UserBuilder.generateUser(user); - Assertions.assertNotNull(user.getCertificate(),"User Certificate was not generated!"); + Assertions.assertNotNull(user.getCertificate(), "User Certificate was not generated!"); } @Test @@ -49,32 +35,39 @@ class UserBuilderTest { User user = new User(); user.setUsername("TestUser"); - //user.setJamiId(""); + // user.setJamiId(""); user.setUserType(AuthenticationSourceType.LOCAL); user.setX509Fields(new X509Fields()); user.getX509Fields().setCommonName("TestUser's Personal Certificate"); user = UserBuilder.generateUser(user); - Assertions.assertNotNull(user,"User was not generated!"); + Assertions.assertNotNull(user, "User was not generated!"); X509Certificate cert = user.getCertificate(); - Assertions.assertNotNull(cert,"User Certificate was not generated!"); + Assertions.assertNotNull(cert, "User Certificate was not generated!"); User refreshedUser = UserBuilder.refreshUser(user, 465_000_000); - Assertions.assertNotNull(refreshedUser,"User was not generated!"); + Assertions.assertNotNull(refreshedUser, "User was not generated!"); X509Certificate new_cert = refreshedUser.getCertificate(); - Assertions.assertArrayEquals(cert.getPublicKey().getEncoded(), new_cert.getPublicKey().getEncoded(), "PK is different"); + Assertions.assertArrayEquals( + cert.getPublicKey().getEncoded(), + new_cert.getPublicKey().getEncoded(), + "PK is different"); - Assertions.assertNotNull(new_cert,"User Certificate was not updated!"); - Assertions.assertEquals(user.getAddress(), refreshedUser.getAddress(), "User address is different"); + Assertions.assertNotNull(new_cert, "User Certificate was not updated!"); + Assertions.assertEquals( + user.getAddress(), refreshedUser.getAddress(), "User address is different"); Assertions.assertNotEquals(cert.getNotAfter(), new_cert.getNotAfter()); try { - Assertions.assertEquals(new JcaX509CertificateHolder(cert).getSubjectPublicKeyInfo().getPublicKey(), - new JcaX509CertificateHolder(new_cert).getSubjectPublicKeyInfo().getPublicKey()); + Assertions.assertEquals( + new JcaX509CertificateHolder(cert).getSubjectPublicKeyInfo().getPublicKey(), + new JcaX509CertificateHolder(new_cert) + .getSubjectPublicKeyInfo() + .getPublicKey()); } catch (Exception e) { log.error("Error comparing two public keys information: ", e.getMessage()); } } -} \ No newline at end of file +} diff --git a/jams-common/src/main/java/net/jami/jams/common/annotations/JsonContent.java b/jams-common/src/main/java/net/jami/jams/common/annotations/JsonContent.java index 16288803e02b752d01c007396186c80d2e145b0e..8ddb9f3397aa0da3b6c58ba0abf5b116ea6caa35 100644 --- a/jams-common/src/main/java/net/jami/jams/common/annotations/JsonContent.java +++ b/jams-common/src/main/java/net/jami/jams/common/annotations/JsonContent.java @@ -1,4 +1,3 @@ package net.jami.jams.common.annotations; -public @interface JsonContent { -} +public @interface JsonContent {} diff --git a/jams-common/src/main/java/net/jami/jams/common/annotations/PackageScanner.java b/jams-common/src/main/java/net/jami/jams/common/annotations/PackageScanner.java index 5204358e45dd3cad6e9ec6831b78964a7c476812..f775782a400fcf3d8c77cd978be3b4a98ab67557 100644 --- a/jams-common/src/main/java/net/jami/jams/common/annotations/PackageScanner.java +++ b/jams-common/src/main/java/net/jami/jams/common/annotations/PackageScanner.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.annotations; import java.io.File; @@ -32,7 +32,10 @@ public class PackageScanner { public static ArrayList<String> getClasses(String jarFile) throws Exception { ArrayList<String> classNames = new ArrayList<>(); - ZipInputStream zip = new ZipInputStream(new FileInputStream(System.getProperty("user.dir") + File.separator + jarFile)); + ZipInputStream zip = + new ZipInputStream( + new FileInputStream( + System.getProperty("user.dir") + File.separator + jarFile)); for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { if (!entry.isDirectory() && entry.getName().endsWith(".class")) { // This ZipEntry represents a class. Now, what class does it represent? diff --git a/jams-common/src/main/java/net/jami/jams/common/annotations/ScopedServletAnnotationScanner.java b/jams-common/src/main/java/net/jami/jams/common/annotations/ScopedServletAnnotationScanner.java index cd2eef1191a1f9559fca38cd1a1f434bdb1eccf1..85e4ad6d40ac07b60fadfde5d1843f3a311e8cb4 100644 --- a/jams-common/src/main/java/net/jami/jams/common/annotations/ScopedServletAnnotationScanner.java +++ b/jams-common/src/main/java/net/jami/jams/common/annotations/ScopedServletAnnotationScanner.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.annotations; import javassist.ClassPool; @@ -29,19 +29,20 @@ import javassist.bytecode.AnnotationsAttribute; import javassist.bytecode.AttributeInfo; import javassist.bytecode.MethodInfo; import javassist.bytecode.annotation.Annotation; + import lombok.extern.slf4j.Slf4j; import java.util.ArrayList; @Slf4j public class ScopedServletAnnotationScanner { - public void processClasses(String jarFile){ + public void processClasses(String jarFile) { try { ArrayList<String> classNames = PackageScanner.getClasses(jarFile); classNames.parallelStream().forEach(this::processClass); } catch (Exception e) { - log.info("Could not modify a target class with error {}",e.getMessage()); + log.info("Could not modify a target class with error {}", e.getMessage()); } } @@ -54,20 +55,25 @@ public class ScopedServletAnnotationScanner { boolean classChanged = false; for (int i = 0; i < ctMethods.length; i++) { MethodInfo minfo = ctMethods[i].getMethodInfo(); - for(AttributeInfo ai : minfo.getAttributes()) { + for (AttributeInfo ai : minfo.getAttributes()) { if (ai.getClass().getName().contains("AnnotationsAttribute")) { AnnotationsAttribute aa = (AnnotationsAttribute) ai; for (Annotation a : aa.getAnnotations()) { if (a.getTypeName().equals(JsonContent.class.getName())) { - log.info("[{}] has secured method {}, modifying method... ", cc.getSimpleName(), ctMethods[i].getName()); - //Build the code block that enforces security. - StringBuilder sb = new StringBuilder(); - sb.append("{\n"); - //So this does not play nice when trying to use hash sets... - sb.append("resp.setContentType(\"application/json\");\n"); - sb.append("}\n"); - ctMethods[i].insertBefore(sb.toString()); + log.info( + "[{}] has secured method {}, modifying method... ", + cc.getSimpleName(), + ctMethods[i].getName()); + // Build the code block that enforces security. + String sb = + "{\n" + + + // So this does not play nice when trying to use + // hash sets... + "resp.setContentType(\"application/json\");\n" + + "}\n"; + ctMethods[i].insertBefore(sb); classChanged = true; } } @@ -75,11 +81,12 @@ public class ScopedServletAnnotationScanner { } } - if(classChanged) { + if (classChanged) { if (cc.isFrozen()) cc.defrost(); cc.toClass(); } - } catch (Exception e) {} + } catch (Exception e) { + } } } diff --git a/jams-common/src/main/java/net/jami/jams/common/annotations/ScopedServletMethod.java b/jams-common/src/main/java/net/jami/jams/common/annotations/ScopedServletMethod.java index 2428eddebaa0705b917ee7e47b7e074593012783..9cdab5857d5240a4a591d77fafc056f5c54abed6 100644 --- a/jams-common/src/main/java/net/jami/jams/common/annotations/ScopedServletMethod.java +++ b/jams-common/src/main/java/net/jami/jams/common/annotations/ScopedServletMethod.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.annotations; import net.jami.jams.common.objects.user.AccessLevel; @@ -32,5 +32,5 @@ import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.SOURCE) public @interface ScopedServletMethod { - public AccessLevel[] securityGroups(); + AccessLevel[] securityGroups(); } diff --git a/jams-common/src/main/java/net/jami/jams/common/annotations/ScopedServletProcessor.java b/jams-common/src/main/java/net/jami/jams/common/annotations/ScopedServletProcessor.java index f044f4b109dc6561d5f8e5cfb93730bf43ab8669..afb156e795a3523f179de5bb35c8fcba6aeff7d2 100644 --- a/jams-common/src/main/java/net/jami/jams/common/annotations/ScopedServletProcessor.java +++ b/jams-common/src/main/java/net/jami/jams/common/annotations/ScopedServletProcessor.java @@ -1,33 +1,41 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.annotations; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.LoaderClassPath; + import net.jami.jams.common.objects.user.AccessLevel; +import java.io.File; +import java.io.FileInputStream; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.HashMap; +import java.util.Set; + import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; @@ -37,56 +45,83 @@ import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic; -import java.io.File; -import java.io.FileInputStream; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.HashMap; -import java.util.Set; @SupportedAnnotationTypes("net.jami.jams.common.annotations.ScopedServletMethod") @SupportedSourceVersion(SourceVersion.RELEASE_11) -@SupportedOptions({"moduleDir","parentDir"}) -//This is a bit of hack to modify already compiled sources at compilation time +@SupportedOptions({"moduleDir", "parentDir"}) +// This is a bit of hack to modify already compiled sources at compilation time public class ScopedServletProcessor extends AbstractProcessor { private String moduleDirectory = null; private String parentDirectory = null; public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { - //Get the current project working directory: + // Get the current project working directory: moduleDirectory = processingEnv.getOptions().get("moduleDir"); parentDirectory = processingEnv.getOptions().get("parentDir"); - processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Project Directory: " + moduleDirectory); + processingEnv + .getMessager() + .printMessage(Diagnostic.Kind.NOTE, "Project Directory: " + moduleDirectory); if (roundEnv.processingOver()) { return false; } - processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE,"Working in directory: " + System.getProperty("user.dir")); - Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(ScopedServletMethod.class); - //Inside each annotation, we have a list of stuff. - HashMap<String, HashMap<String,AccessLevel[]>> annList = new HashMap<>(); - annotatedElements.forEach(element -> { - processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Found class: " + element.getEnclosingElement().toString()); - processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Found method: " + element.toString()); - processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE,"Found " + element.getAnnotation(ScopedServletMethod.class).securityGroups().length + " groups"); - String clsName = element.getEnclosingElement().toString(); - String mthName = element.toString(); - AccessLevel[] levels = element.getAnnotation(ScopedServletMethod.class).securityGroups(); - annList.putIfAbsent(clsName,new HashMap<>()); - annList.get(clsName).putIfAbsent(mthName,levels); - }); + processingEnv + .getMessager() + .printMessage( + Diagnostic.Kind.NOTE, + "Working in directory: " + System.getProperty("user.dir")); + Set<? extends Element> annotatedElements = + roundEnv.getElementsAnnotatedWith(ScopedServletMethod.class); + // Inside each annotation, we have a list of stuff. + HashMap<String, HashMap<String, AccessLevel[]>> annList = new HashMap<>(); + annotatedElements.forEach( + element -> { + processingEnv + .getMessager() + .printMessage( + Diagnostic.Kind.NOTE, + "Found class: " + element.getEnclosingElement().toString()); + processingEnv + .getMessager() + .printMessage(Diagnostic.Kind.NOTE, "Found method: " + element); + processingEnv + .getMessager() + .printMessage( + Diagnostic.Kind.NOTE, + "Found " + + element.getAnnotation(ScopedServletMethod.class) + .securityGroups() + .length + + " groups"); + String clsName = element.getEnclosingElement().toString(); + String mthName = element.toString(); + AccessLevel[] levels = + element.getAnnotation(ScopedServletMethod.class).securityGroups(); + annList.putIfAbsent(clsName, new HashMap<>()); + annList.get(clsName).putIfAbsent(mthName, levels); + }); annList.forEach(this::processClass); return true; } - private void processClass(String classname,HashMap<String,AccessLevel[]> methodNames) { + private void processClass(String classname, HashMap<String, AccessLevel[]> methodNames) { try { - URL cpUrl1 = new URL("jar:file:" + parentDirectory + File.separator + "compile-libs/tomcat-embed-core-10.0.0-M5.jar!/"); - URL cpUrl3 = new URL("jar:file:" + parentDirectory + File.separator + "compile-libs/tomcat-annotations-api-10.0.0-M5.jar!/"); + URL cpUrl1 = + new URL( + "jar:file:" + + parentDirectory + + File.separator + + "compile-libs/tomcat-embed-core-10.0.0-M5.jar!/"); + URL cpUrl3 = + new URL( + "jar:file:" + + parentDirectory + + File.separator + + "compile-libs/tomcat-annotations-api-10.0.0-M5.jar!/"); - URLClassLoader cpUrlLoader = new URLClassLoader(new URL[]{cpUrl1,cpUrl3}); + URLClassLoader cpUrlLoader = new URLClassLoader(new URL[] {cpUrl1, cpUrl3}); StringBuilder path = new StringBuilder(); path.append(moduleDirectory); @@ -95,32 +130,47 @@ public class ScopedServletProcessor extends AbstractProcessor { path.append(File.separator); path.append("classes"); path.append(File.separator); - path.append(classname.replaceAll("\\.",File.separator)); + path.append(classname.replaceAll("\\.", File.separator)); path.append(".class"); - processingEnv.getMessager().printMessage(Diagnostic.Kind.MANDATORY_WARNING,"Now processing: " + path.toString()); + processingEnv + .getMessager() + .printMessage(Diagnostic.Kind.MANDATORY_WARNING, "Now processing: " + path); ClassPool pool = ClassPool.getDefault(); - //Load tomcat & commons classpath.. + // Load tomcat & commons classpath.. pool.insertClassPath(new LoaderClassPath(cpUrlLoader)); - pool.makeClass(new FileInputStream(parentDirectory+"/jams-common/target/classes/net/jami/jams/common/objects/user/AccessLevel.class")); - pool.makeClass(new FileInputStream(parentDirectory+"/jams-common/target/classes/net/jami/jams/common/serialization/tomcat/TomcatCustomErrorHandler.class")); + pool.makeClass( + new FileInputStream( + parentDirectory + + "/jams-common/target/classes/net/jami/jams/common/objects/user/AccessLevel.class")); + pool.makeClass( + new FileInputStream( + parentDirectory + + "/jams-common/target/classes/net/jami/jams/common/serialization/tomcat/TomcatCustomErrorHandler.class")); CtClass ctClass = pool.makeClass(new FileInputStream(path.toString())); - processingEnv.getMessager().printMessage(Diagnostic.Kind.MANDATORY_WARNING,ctClass.getName()); - //Now that we have the CtClass we copy past - for(String rawmethodName : methodNames.keySet()) { + processingEnv + .getMessager() + .printMessage(Diagnostic.Kind.MANDATORY_WARNING, ctClass.getName()); + // Now that we have the CtClass we copy past + for (String rawmethodName : methodNames.keySet()) { String methodName = rawmethodName.split("\\(")[0]; for (int i = 0; i < ctClass.getMethods().length; i++) { CtMethod method = ctClass.getMethods()[i]; if (method.getName().equals(methodName)) { - //Insert code. + // Insert code. StringBuilder sb = new StringBuilder(); sb.append("{\n"); sb.append("boolean allowed = false;\n"); - sb.append("net.jami.jams.common.objects.user.AccessLevel level = (net.jami.jams.common.objects.user.AccessLevel) req.getAttribute(\"accessLevel\");\n"); - for(int j=0; j<methodNames.get(rawmethodName).length; j++) { - sb.append("if(level == net.jami.jams.common.objects.user.AccessLevel.valueOf(\"").append(methodNames.get(rawmethodName)[j].toString()).append("\")) allowed = true;\n"); + sb.append( + "net.jami.jams.common.objects.user.AccessLevel level = (net.jami.jams.common.objects.user.AccessLevel) req.getAttribute(\"accessLevel\");\n"); + for (int j = 0; j < methodNames.get(rawmethodName).length; j++) { + sb.append( + "if(level == net.jami.jams.common.objects.user.AccessLevel.valueOf(\"") + .append(methodNames.get(rawmethodName)[j].toString()) + .append("\")) allowed = true;\n"); } sb.append("if(!allowed){\n"); - sb.append("net.jami.jams.common.serialization.tomcat.TomcatCustomErrorHandler.sendCustomError(resp,403,\"You do not have sufficient permissions to access this resource!\");\n"); + sb.append( + "net.jami.jams.common.serialization.tomcat.TomcatCustomErrorHandler.sendCustomError(resp,403,\"You do not have sufficient permissions to access this resource!\");\n"); sb.append("return;\n"); sb.append("}\n"); sb.append("}\n"); @@ -128,7 +178,7 @@ public class ScopedServletProcessor extends AbstractProcessor { } } } - //Perist the class before it gets copied into the binary. + // Perist the class before it gets copied into the binary. path = new StringBuilder(); path.append(moduleDirectory); path.append(File.separator); @@ -138,8 +188,8 @@ public class ScopedServletProcessor extends AbstractProcessor { ctClass.writeFile(path.toString()); processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Saved the class..."); } catch (Exception e) { - processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,e.getMessage()); + processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage()); } } - //The only way to modify a file at this point would be to read it, and do a LOT of regex. + // The only way to modify a file at this point would be to read it, and do a LOT of regex. } diff --git a/jams-common/src/main/java/net/jami/jams/common/authentication/AuthenticationSource.java b/jams-common/src/main/java/net/jami/jams/common/authentication/AuthenticationSource.java index bf01d7edd58b8e7759dfc4768589e9b8a0d79e16..6e40ae93c377d9d21f6005a9213370d1b338c239 100644 --- a/jams-common/src/main/java/net/jami/jams/common/authentication/AuthenticationSource.java +++ b/jams-common/src/main/java/net/jami/jams/common/authentication/AuthenticationSource.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.authentication; import net.jami.jams.common.objects.user.User; @@ -31,12 +31,18 @@ import java.util.Optional; public interface AuthenticationSource { boolean createUser(User user); + List<UserProfile> searchUserProfiles(String queryString, String field, Optional<Integer> page); + UserProfile getUserProfile(String username); + boolean setUserProfile(UserProfile userProfile); + boolean authenticate(String username, String password); + AuthenticationSourceInfo getInfo(); + boolean test(); - boolean updatePassword(User user, String password); + boolean updatePassword(User user, String password); } diff --git a/jams-common/src/main/java/net/jami/jams/common/authentication/AuthenticationSourceInfo.java b/jams-common/src/main/java/net/jami/jams/common/authentication/AuthenticationSourceInfo.java index 81e8b8b395843d4eaec5d23ae8f065bbda080e7c..6c48dc5aa5e7045c1e74fe142a1d859f8df400f6 100644 --- a/jams-common/src/main/java/net/jami/jams/common/authentication/AuthenticationSourceInfo.java +++ b/jams-common/src/main/java/net/jami/jams/common/authentication/AuthenticationSourceInfo.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.authentication; import lombok.AllArgsConstructor; @@ -35,5 +35,4 @@ public class AuthenticationSourceInfo { private String realm; private AuthenticationSourceType authenticationSourceType; - } diff --git a/jams-common/src/main/java/net/jami/jams/common/authentication/AuthenticationSourceType.java b/jams-common/src/main/java/net/jami/jams/common/authentication/AuthenticationSourceType.java index b01fb44d302271aad6cc2dba5485cd819b94e79d..560c946991eaba573c28200ebf70de0e2b08e697 100644 --- a/jams-common/src/main/java/net/jami/jams/common/authentication/AuthenticationSourceType.java +++ b/jams-common/src/main/java/net/jami/jams/common/authentication/AuthenticationSourceType.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.authentication; public enum AuthenticationSourceType { @@ -27,11 +27,10 @@ public enum AuthenticationSourceType { LDAP, LOCAL; - public static AuthenticationSourceType fromString(String str){ - if(str.equals("AD")) return AD; - if(str.equals("LDAP")) return LDAP; - if(str.equals("LOCAL")) return LOCAL; + public static AuthenticationSourceType fromString(String str) { + if (str.equals("AD")) return AD; + if (str.equals("LDAP")) return LDAP; + if (str.equals("LOCAL")) return LOCAL; return null; } - } diff --git a/jams-common/src/main/java/net/jami/jams/common/authentication/activedirectory/ActiveDirectorySettings.java b/jams-common/src/main/java/net/jami/jams/common/authentication/activedirectory/ActiveDirectorySettings.java index 6eb375211d0e3cf4d6853bed1c19d0b19c05760d..9ae698ed2f8c3bf6a5c570b0f36f6584e03477ee 100644 --- a/jams-common/src/main/java/net/jami/jams/common/authentication/activedirectory/ActiveDirectorySettings.java +++ b/jams-common/src/main/java/net/jami/jams/common/authentication/activedirectory/ActiveDirectorySettings.java @@ -1,31 +1,30 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.authentication.activedirectory; import lombok.Getter; import lombok.Setter; -import java.util.HashMap; import java.util.concurrent.ConcurrentHashMap; @Getter @@ -33,11 +32,10 @@ import java.util.concurrent.ConcurrentHashMap; public class ActiveDirectorySettings { private Boolean isSSL; - private int port; - private String realm; - private String host; - private String username; - private String password; - private ConcurrentHashMap<String,String> fieldMappings; - + private int port; + private String realm; + private String host; + private String username; + private String password; + private ConcurrentHashMap<String, String> fieldMappings; } diff --git a/jams-common/src/main/java/net/jami/jams/common/authentication/ldap/LDAPSettings.java b/jams-common/src/main/java/net/jami/jams/common/authentication/ldap/LDAPSettings.java index 96d5654e18f5214eb2718b3657214cca01ab8d6c..5b31861f6ea6b06791a9af9dc233a0871853482e 100644 --- a/jams-common/src/main/java/net/jami/jams/common/authentication/ldap/LDAPSettings.java +++ b/jams-common/src/main/java/net/jami/jams/common/authentication/ldap/LDAPSettings.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.authentication.ldap; import lombok.Getter; @@ -32,12 +32,11 @@ import java.util.HashMap; public class LDAPSettings { private Boolean useStartTLS; - private String realm; - private String baseDN; - private String host; - private String username; - private String password; - private String usernameField; - private HashMap<String,String> fieldMappings; - + private String realm; + private String baseDN; + private String host; + private String username; + private String password; + private String usernameField; + private HashMap<String, String> fieldMappings; } diff --git a/jams-common/src/main/java/net/jami/jams/common/authentication/local/LocalAuthSettings.java b/jams-common/src/main/java/net/jami/jams/common/authentication/local/LocalAuthSettings.java index 96dc5b16807947cd4604cea9fbd1a8fe20b298d2..3988f2b39b8e04e52cde7d883413769947fe0cf2 100644 --- a/jams-common/src/main/java/net/jami/jams/common/authentication/local/LocalAuthSettings.java +++ b/jams-common/src/main/java/net/jami/jams/common/authentication/local/LocalAuthSettings.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.authentication.local; import lombok.Getter; @@ -29,5 +29,5 @@ import lombok.Setter; @Setter public class LocalAuthSettings { private Boolean publicNames; - private String publicNameServer; + private String publicNameServer; } diff --git a/jams-common/src/main/java/net/jami/jams/common/authmodule/AuthModuleKey.java b/jams-common/src/main/java/net/jami/jams/common/authmodule/AuthModuleKey.java index 3e042386b010689773daf82e0e99f46009e7ceef..6e5936394630e0d7581e9ea570770346c29417f2 100644 --- a/jams-common/src/main/java/net/jami/jams/common/authmodule/AuthModuleKey.java +++ b/jams-common/src/main/java/net/jami/jams/common/authmodule/AuthModuleKey.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.authmodule; import lombok.AllArgsConstructor; @@ -27,6 +27,7 @@ import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; + import net.jami.jams.common.authentication.AuthenticationSourceType; @Getter @@ -38,5 +39,4 @@ public class AuthModuleKey { private String realm; private AuthenticationSourceType type; - } diff --git a/jams-common/src/main/java/net/jami/jams/common/authmodule/AuthTokenResponse.java b/jams-common/src/main/java/net/jami/jams/common/authmodule/AuthTokenResponse.java index 854e4df5387aebd15ea14129161df432c4b6d8b5..94d2562674c7a255f5318775237da42a791261b1 100644 --- a/jams-common/src/main/java/net/jami/jams/common/authmodule/AuthTokenResponse.java +++ b/jams-common/src/main/java/net/jami/jams/common/authmodule/AuthTokenResponse.java @@ -1,36 +1,37 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.authmodule; import lombok.Getter; import lombok.Setter; + import net.jami.jams.common.objects.user.AccessLevel; @Getter @Setter public class AuthTokenResponse { - private String token_type; - private String access_token; - private Long expires_in; + private String token_type; + private String access_token; + private Long expires_in; private AccessLevel scope; } diff --git a/jams-common/src/main/java/net/jami/jams/common/authmodule/AuthenticationModule.java b/jams-common/src/main/java/net/jami/jams/common/authmodule/AuthenticationModule.java index 043271ff9a5fa6515fe2f6f5f1b90f6e751136a3..ee354eebf8f0c8fe38211dafaa48306dbfa697fc 100644 --- a/jams-common/src/main/java/net/jami/jams/common/authmodule/AuthenticationModule.java +++ b/jams-common/src/main/java/net/jami/jams/common/authmodule/AuthenticationModule.java @@ -1,32 +1,34 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.authmodule; import com.nimbusds.jwt.SignedJWT; + import net.jami.jams.common.authentication.AuthenticationSource; import net.jami.jams.common.authentication.AuthenticationSourceType; import net.jami.jams.common.jami.NameServer; import net.jami.jams.common.objects.user.User; + import org.bouncycastle.cert.X509CRLHolder; import java.security.cert.X509Certificate; @@ -36,14 +38,24 @@ import java.util.concurrent.ConcurrentHashMap; public interface AuthenticationModule { void attachAuthSource(AuthenticationSourceType type, String settings); + AuthTokenResponse authenticateUser(String username, String password); - AuthTokenResponse authenticateUser(X509Certificate[] certificates, X509CRLHolder crl, X509Certificate ca); + + AuthTokenResponse authenticateUser( + X509Certificate[] certificates, X509CRLHolder crl, X509Certificate ca); + ConcurrentHashMap<AuthModuleKey, AuthenticationSource> getAuthSources(); + boolean testModuleConfiguration(AuthenticationSourceType type, String configuration); - boolean createUser(AuthenticationSourceType type, String realm, NameServer nameServer, User user); + + boolean createUser( + AuthenticationSourceType type, String realm, NameServer nameServer, User user); + RSAPublicKey getAuthModulePubKey(); + char[] getOTP(String username); - //In both cases, the tokens are signed, we can + // In both cases, the tokens are signed, we can boolean verifyToken(SignedJWT token); + void deleteToken(SignedJWT token); } diff --git a/jams-common/src/main/java/net/jami/jams/common/authmodule/AuthenticationResult.java b/jams-common/src/main/java/net/jami/jams/common/authmodule/AuthenticationResult.java index 4b224b9ba7d17ac1158fcbf32632e2ba13d091de..c0c52434195cd6e10269bf2e38cec41fe98091b5 100644 --- a/jams-common/src/main/java/net/jami/jams/common/authmodule/AuthenticationResult.java +++ b/jams-common/src/main/java/net/jami/jams/common/authmodule/AuthenticationResult.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.authmodule; import lombok.Getter; @@ -32,12 +32,12 @@ import lombok.Setter; public class AuthenticationResult { private Boolean authenticated; - private String token; - private Long expires; + private String token; + private Long expires; public AuthenticationResult(Boolean authenticated, String token) { this.authenticated = authenticated; this.token = token; - this.expires = System.currentTimeMillis() + 15*60*1_000; + this.expires = System.currentTimeMillis() + 15 * 60 * 1_000; } } diff --git a/jams-common/src/main/java/net/jami/jams/common/cryptoengineapi/CertificateAuthority.java b/jams-common/src/main/java/net/jami/jams/common/cryptoengineapi/CertificateAuthority.java index a8de02acd58ec763ca5235a1371d1b38b67b2f83..e791e67ea14418a8e0d0849c0f100343c04b6c68 100644 --- a/jams-common/src/main/java/net/jami/jams/common/cryptoengineapi/CertificateAuthority.java +++ b/jams-common/src/main/java/net/jami/jams/common/cryptoengineapi/CertificateAuthority.java @@ -1,49 +1,56 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.cryptoengineapi; import net.jami.jams.common.objects.devices.Device; import net.jami.jams.common.objects.requests.RevocationRequest; import net.jami.jams.common.objects.system.SystemAccount; import net.jami.jams.common.objects.user.User; + import org.bouncycastle.cert.X509CRLHolder; -import org.bouncycastle.cert.ocsp.OCSPReq; -import org.bouncycastle.cert.ocsp.OCSPResp; import java.security.cert.X509Certificate; import java.util.concurrent.atomic.AtomicReference; public interface CertificateAuthority { - //Return a signed X509 certificate based on various constraints. + // Return a signed X509 certificate based on various constraints. void init(String settings, SystemAccount ca, SystemAccount ocsp); + User getSignedCertificate(User user); + User getRefreshedCertificate(User user); + Device getSignedCertificate(User user, Device device); + SystemAccount getSignedCertificate(SystemAccount systemAccount); + void revokeCertificate(RevocationRequest revocationRequest); + AtomicReference<X509CRLHolder> getLatestCRL(); + String getLatestCRLPEMEncoded(); + X509Certificate getCA(); - boolean shutdownThreads(); + boolean shutdownThreads(); } diff --git a/jams-common/src/main/java/net/jami/jams/common/cryptoengineapi/CertificateAuthorityConfig.java b/jams-common/src/main/java/net/jami/jams/common/cryptoengineapi/CertificateAuthorityConfig.java index 43fd113b5d98564fb540d7730c1709f9eb973b8d..63727a1773938d9c3e46daaa9827b8524ab4bfd0 100644 --- a/jams-common/src/main/java/net/jami/jams/common/cryptoengineapi/CertificateAuthorityConfig.java +++ b/jams-common/src/main/java/net/jami/jams/common/cryptoengineapi/CertificateAuthorityConfig.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.cryptoengineapi; import lombok.Getter; @@ -28,9 +28,9 @@ import lombok.Setter; @Getter @Setter public class CertificateAuthorityConfig { - private String serverDomain; - private String signingAlgorithm; - private Long crlLifetime; - private Long userLifetime; - private Long deviceLifetime; + private String serverDomain; + private String signingAlgorithm; + private Long crlLifetime; + private Long userLifetime; + private Long deviceLifetime; } diff --git a/jams-common/src/main/java/net/jami/jams/common/cryptoengineapi/ocsp/CertificateStatus.java b/jams-common/src/main/java/net/jami/jams/common/cryptoengineapi/ocsp/CertificateStatus.java index 07df4b9fcf1b4cdbf09e3b58cc985c5aa0e397cc..fcd97fc560c325845b23977452ee420d65e9085f 100644 --- a/jams-common/src/main/java/net/jami/jams/common/cryptoengineapi/ocsp/CertificateStatus.java +++ b/jams-common/src/main/java/net/jami/jams/common/cryptoengineapi/ocsp/CertificateStatus.java @@ -1,33 +1,36 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.cryptoengineapi.ocsp; public enum CertificateStatus { - VALID, /** The certificate is valid **/ - REVOKED, /** The certificate has been revoked **/ - EXPIRED, /** The certificate is expired **/ - UNKNOWN; /** The certificate is unknown **/ - + VALID, + /** The certificate is valid **/ + REVOKED, + /** The certificate has been revoked **/ + EXPIRED, + /** The certificate is expired **/ + UNKNOWN; + /** The certificate is unknown **/ public static CertificateStatus fromString(String status) { switch (status) { case "V": diff --git a/jams-common/src/main/java/net/jami/jams/common/cryptoengineapi/ocsp/CertificateSummary.java b/jams-common/src/main/java/net/jami/jams/common/cryptoengineapi/ocsp/CertificateSummary.java index d1f39b613c9c0891df227682f02400721b197303..5dbb9ce51a70101bc93fc9a46c345d48c41ce23d 100644 --- a/jams-common/src/main/java/net/jami/jams/common/cryptoengineapi/ocsp/CertificateSummary.java +++ b/jams-common/src/main/java/net/jami/jams/common/cryptoengineapi/ocsp/CertificateSummary.java @@ -1,45 +1,44 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.cryptoengineapi.ocsp; import lombok.AllArgsConstructor; import lombok.Getter; -import lombok.NoArgsConstructor; import lombok.Setter; -import javax.security.auth.x500.X500Principal; import java.math.BigInteger; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; -import java.util.Arrays; -import java.util.List; + +import javax.security.auth.x500.X500Principal; @Getter @Setter @AllArgsConstructor public class CertificateSummary { - public static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyMMddHHmmssZ"); + public static final DateTimeFormatter DATE_TIME_FORMATTER = + DateTimeFormatter.ofPattern("yyMMddHHmmssZ"); private final CertificateStatus status; private final LocalDateTime expirationTime; @@ -91,7 +90,8 @@ public class CertificateSummary { serialNumber = builder.serialNumber; fileName = builder.fileName; subjectDN = builder.subjectDN; - thisUpdateTime = builder.thisUpdateTime == null ? LocalDateTime.now() : builder.thisUpdateTime; + thisUpdateTime = + builder.thisUpdateTime == null ? LocalDateTime.now() : builder.thisUpdateTime; } public static Builder newBuilder() { @@ -109,8 +109,7 @@ public class CertificateSummary { private LocalDateTime thisUpdateTime = null; - private Builder() { - } + private Builder() {} public Builder withStatus(CertificateStatus val) { status = val; diff --git a/jams-common/src/main/java/net/jami/jams/common/cryptoengineapi/ocsp/OCSPCertificateStatusMapper.java b/jams-common/src/main/java/net/jami/jams/common/cryptoengineapi/ocsp/OCSPCertificateStatusMapper.java index 2e207e1969850effd184f4910cb1ebcbe93b569f..4cc8a821f1975aec5add05674f1adef816b117d8 100644 --- a/jams-common/src/main/java/net/jami/jams/common/cryptoengineapi/ocsp/OCSPCertificateStatusMapper.java +++ b/jams-common/src/main/java/net/jami/jams/common/cryptoengineapi/ocsp/OCSPCertificateStatusMapper.java @@ -1,27 +1,30 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.cryptoengineapi.ocsp; +import static net.jami.jams.common.cryptoengineapi.ocsp.RevocationReason.PRIVILEGE_WITHDRAWN; +import static net.jami.jams.common.cryptoengineapi.ocsp.RevocationReason.SUPERSEDED; + import org.bouncycastle.cert.ocsp.CertificateStatus; import org.bouncycastle.cert.ocsp.RevokedStatus; import org.bouncycastle.cert.ocsp.UnknownStatus; @@ -29,25 +32,33 @@ import org.bouncycastle.cert.ocsp.UnknownStatus; import java.time.ZoneId; import java.util.Date; -import static net.jami.jams.common.cryptoengineapi.ocsp.RevocationReason.PRIVILEGE_WITHDRAWN; -import static net.jami.jams.common.cryptoengineapi.ocsp.RevocationReason.SUPERSEDED; - public class OCSPCertificateStatusMapper { - public static CertificateStatus getStatus(CertificateSummary certificateSummary){ + public static CertificateStatus getStatus(CertificateSummary certificateSummary) { switch (certificateSummary.getStatus()) { case VALID: return CertificateStatus.GOOD; case REVOKED: - return new RevokedStatus(Date.from(certificateSummary.getRevocationTime().atZone(ZoneId.systemDefault()).toInstant()), PRIVILEGE_WITHDRAWN.getCode()); + return new RevokedStatus( + Date.from( + certificateSummary + .getRevocationTime() + .atZone(ZoneId.systemDefault()) + .toInstant()), + PRIVILEGE_WITHDRAWN.getCode()); case EXPIRED: - return new RevokedStatus(Date.from(certificateSummary.getExpirationTime().atZone(ZoneId.systemDefault()).toInstant()), SUPERSEDED.getCode()); + return new RevokedStatus( + Date.from( + certificateSummary + .getExpirationTime() + .atZone(ZoneId.systemDefault()) + .toInstant()), + SUPERSEDED.getCode()); case UNKNOWN: return new UnknownStatus(); default: - throw new IllegalArgumentException("Unknown status! " + certificateSummary.getStatus().name()); + throw new IllegalArgumentException( + "Unknown status! " + certificateSummary.getStatus().name()); } } - - } diff --git a/jams-common/src/main/java/net/jami/jams/common/cryptoengineapi/ocsp/RevocationReason.java b/jams-common/src/main/java/net/jami/jams/common/cryptoengineapi/ocsp/RevocationReason.java index f5b512c28ad7eac090bcd5afb0b810bb42c1141e..8769812c83549993038d74733da862636e8b4d04 100644 --- a/jams-common/src/main/java/net/jami/jams/common/cryptoengineapi/ocsp/RevocationReason.java +++ b/jams-common/src/main/java/net/jami/jams/common/cryptoengineapi/ocsp/RevocationReason.java @@ -1,41 +1,37 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.cryptoengineapi.ocsp; import java.util.HashMap; - /** * Enumeration of certificate revocation reasons * * @author wdawson * @see java.security.cert.CRLReason */ - - public enum RevocationReason { - /** * Code = 0, Name = unspecified * <p> @@ -141,8 +137,8 @@ public enum RevocationReason { private static final int NUM_CODES = 11; - private int code; - private String name; + private final int code; + private final String name; RevocationReason(int code, String name) { this.code = code; @@ -158,7 +154,7 @@ public enum RevocationReason { } // Map for quick lookups by name. - private static HashMap<String, RevocationReason> nameToReason = new HashMap<>(); + private static final HashMap<String, RevocationReason> nameToReason = new HashMap<>(); /** * Return the RevocationReason with the given code. diff --git a/jams-common/src/main/java/net/jami/jams/common/dao/DeleteStatementBuilder.java b/jams-common/src/main/java/net/jami/jams/common/dao/DeleteStatementBuilder.java index 46be13b6a5b031d20aff0b0d66ca9f6800a72e9d..b89eb731ba9a7d819a416300cfb2fdf109f129b9 100644 --- a/jams-common/src/main/java/net/jami/jams/common/dao/DeleteStatementBuilder.java +++ b/jams-common/src/main/java/net/jami/jams/common/dao/DeleteStatementBuilder.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.dao; import net.jami.jams.common.dao.connectivity.SQLConnection; @@ -28,23 +28,24 @@ import java.sql.PreparedStatement; public class DeleteStatementBuilder { - public static PreparedStatement buildStatement(String table, StatementList statementElements, - SQLConnection connection) throws Exception { + public static PreparedStatement buildStatement( + String table, StatementList statementElements, SQLConnection connection) + throws Exception { PreparedStatement ps = null; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("DELETE FROM ").append(table); - if(statementElements != null) { + if (statementElements != null) { stringBuilder.append(" WHERE "); for (StatementElement statementElement : statementElements.getStatements()) { stringBuilder - .append(statementElement.getColumn()) - .append(" ") - .append(statementElement.getOperator()) - .append(" ") - .append("?") - .append(" ") - .append(statementElement.getNextStatementRelation()) - .append(" "); + .append(statementElement.getColumn()) + .append(" ") + .append(statementElement.getOperator()) + .append(" ") + .append("?") + .append(" ") + .append(statementElement.getNextStatementRelation()) + .append(" "); } ps = connection.getConnection().prepareStatement(stringBuilder.toString()); int i = 1; @@ -52,8 +53,7 @@ public class DeleteStatementBuilder { ps.setString(i, statementElement.getValue()); i++; } - } - else{ + } else { ps = connection.getConnection().prepareStatement(stringBuilder.toString()); } return ps; diff --git a/jams-common/src/main/java/net/jami/jams/common/dao/SelectStatementBuilder.java b/jams-common/src/main/java/net/jami/jams/common/dao/SelectStatementBuilder.java index ca0b3ffb908542473dad37e58cb94818b2ff7129..cd591e9c794b086550405c7116e30b73cee653c0 100644 --- a/jams-common/src/main/java/net/jami/jams/common/dao/SelectStatementBuilder.java +++ b/jams-common/src/main/java/net/jami/jams/common/dao/SelectStatementBuilder.java @@ -28,25 +28,28 @@ import java.sql.PreparedStatement; public class SelectStatementBuilder { - public static PreparedStatement buildStatement(String table, StatementList statementElements, - StatementConstraints statementConstraints, - SQLConnection connection) throws Exception - { + public static PreparedStatement buildStatement( + String table, + StatementList statementElements, + StatementConstraints statementConstraints, + SQLConnection connection) + throws Exception { PreparedStatement ps = null; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("SELECT * FROM ").append(table); - if(statementElements != null) { + if (statementElements != null) { stringBuilder.append(" WHERE "); for (StatementElement statementElement : statementElements.getStatements()) { - stringBuilder.append("lower(" + statementElement.getColumn() + ")") - .append(" ") - .append(statementElement.getOperator()) - .append(" ") - .append("?") - .append(" ") - .append(statementElement.getNextStatementRelation()) - .append(" "); + stringBuilder + .append("lower(" + statementElement.getColumn() + ")") + .append(" ") + .append(statementElement.getOperator()) + .append(" ") + .append("?") + .append(" ") + .append(statementElement.getNextStatementRelation()) + .append(" "); } ps = connection.getConnection().prepareStatement(stringBuilder.toString()); int i = 1; @@ -54,16 +57,16 @@ public class SelectStatementBuilder { ps.setString(i, (statementElement.getValue()).toLowerCase()); i++; } - } - else{ - if(statementConstraints != null){ - stringBuilder.append(" LIMIT ").append(statementConstraints.getRowCount()) - .append(" OFFSET ").append(statementConstraints.getOffset()); + } else { + if (statementConstraints != null) { + stringBuilder + .append(" LIMIT ") + .append(statementConstraints.getRowCount()) + .append(" OFFSET ") + .append(statementConstraints.getOffset()); } ps = connection.getConnection().prepareStatement(stringBuilder.toString()); } return ps; } - - } diff --git a/jams-common/src/main/java/net/jami/jams/common/dao/StatementConstraints.java b/jams-common/src/main/java/net/jami/jams/common/dao/StatementConstraints.java index cd7bc6563d9e42c949c6a3371bef42ea309f3c63..f2f2294c1c1871f3b976f6397c45bbefc602b109 100644 --- a/jams-common/src/main/java/net/jami/jams/common/dao/StatementConstraints.java +++ b/jams-common/src/main/java/net/jami/jams/common/dao/StatementConstraints.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.dao; import lombok.Getter; diff --git a/jams-common/src/main/java/net/jami/jams/common/dao/StatementElement.java b/jams-common/src/main/java/net/jami/jams/common/dao/StatementElement.java index f788a6c764fef0409cdc15b9ea98e0fa661148de..6e1446b2bace8e0f66368d199a22f51d4f18c693 100644 --- a/jams-common/src/main/java/net/jami/jams/common/dao/StatementElement.java +++ b/jams-common/src/main/java/net/jami/jams/common/dao/StatementElement.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.dao; import lombok.AllArgsConstructor; diff --git a/jams-common/src/main/java/net/jami/jams/common/dao/StatementList.java b/jams-common/src/main/java/net/jami/jams/common/dao/StatementList.java index bee93a200b53a65ef44bf614990faea0f3ed417c..8767fda06cd9d49eefa355534e4273028cb7d093 100644 --- a/jams-common/src/main/java/net/jami/jams/common/dao/StatementList.java +++ b/jams-common/src/main/java/net/jami/jams/common/dao/StatementList.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.dao; import lombok.Getter; @@ -34,8 +34,7 @@ public class StatementList { private List<StatementElement> statements = new ArrayList<>(); - public void addStatement(StatementElement statementElement){ + public void addStatement(StatementElement statementElement) { statements.add(statementElement); } - } diff --git a/jams-common/src/main/java/net/jami/jams/common/dao/UpdateStatementBuilder.java b/jams-common/src/main/java/net/jami/jams/common/dao/UpdateStatementBuilder.java index a80161771067daeacf52b2bab0e8521d2fa37159..8743e00efc85c9704959e15bec92be9c62cee0f5 100644 --- a/jams-common/src/main/java/net/jami/jams/common/dao/UpdateStatementBuilder.java +++ b/jams-common/src/main/java/net/jami/jams/common/dao/UpdateStatementBuilder.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.dao; import net.jami.jams.common.dao.connectivity.SQLConnection; @@ -27,18 +27,18 @@ import net.jami.jams.common.dao.connectivity.SQLConnection; import java.sql.PreparedStatement; public class UpdateStatementBuilder { - public static PreparedStatement buildStatement(String table, StatementList updateElements, - StatementList conditionalElements, - SQLConnection connection) throws Exception { + public static PreparedStatement buildStatement( + String table, + StatementList updateElements, + StatementList conditionalElements, + SQLConnection connection) + throws Exception { PreparedStatement ps = null; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("UPDATE ").append(table).append(" SET "); for (int i = 0; i < updateElements.getStatements().size(); i++) { StatementElement statementElement = updateElements.getStatements().get(i); - stringBuilder - .append(statementElement.getColumn()) - .append(" = ") - .append("?"); + stringBuilder.append(statementElement.getColumn()).append(" = ").append("?"); if (i != updateElements.getStatements().size() - 1) stringBuilder.append(","); } stringBuilder.append(" WHERE "); @@ -53,7 +53,7 @@ public class UpdateStatementBuilder { .append(statementElement.getNextStatementRelation()); } ps = connection.getConnection().prepareStatement(stringBuilder.toString()); - //Now we have to feed this all the elements it should have. + // Now we have to feed this all the elements it should have. updateElements.getStatements().addAll(conditionalElements.getStatements()); int i = 1; for (StatementElement statementElement : updateElements.getStatements()) { diff --git a/jams-common/src/main/java/net/jami/jams/common/dao/connectivity/ConnectionPool.java b/jams-common/src/main/java/net/jami/jams/common/dao/connectivity/ConnectionPool.java index efafce105d7a33ba583a0bf6b513636fe2269700..bfc1cc80b7de891b9dc80b5ac68815eed6a99302 100644 --- a/jams-common/src/main/java/net/jami/jams/common/dao/connectivity/ConnectionPool.java +++ b/jams-common/src/main/java/net/jami/jams/common/dao/connectivity/ConnectionPool.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.dao.connectivity; import lombok.extern.slf4j.Slf4j; @@ -33,7 +33,7 @@ public class ConnectionPool { private final ConcurrentLinkedQueue<SQLConnection> connections = new ConcurrentLinkedQueue<>(); private String connectionURI; - //Load Derby class. + // Load Derby class. public ConnectionPool(String connectionURI) { try { @@ -43,39 +43,37 @@ public class ConnectionPool { try { connections.add(new SQLConnection(DriverManager.getConnection(connectionURI))); } catch (Exception e) { - log.error("Could not create a link with the database: " + e.toString()); + log.error("Could not create a link with the database: " + e); } } - } - catch (Exception e){ - log.error("Could not load ApacheDerby class driver: " + e.toString()); + } catch (Exception e) { + log.error("Could not load ApacheDerby class driver: " + e); } } - public SQLConnection getConnection(){ + public SQLConnection getConnection() { try { SQLConnection sqlConnection = null; while (sqlConnection == null) { sqlConnection = connections.poll(); } - if (sqlConnection.isStale()) sqlConnection = new SQLConnection(DriverManager.getConnection(connectionURI)); + if (sqlConnection.isStale()) + sqlConnection = new SQLConnection(DriverManager.getConnection(connectionURI)); return sqlConnection; - } - catch (Exception e){ - log.info("A connection could not be obtained with error " + e.toString()); + } catch (Exception e) { + log.info("A connection could not be obtained with error " + e); return null; } } - public void returnConnection(SQLConnection sqlConnection){ + public void returnConnection(SQLConnection sqlConnection) { try { - if (sqlConnection.isStale()){ + if (sqlConnection.isStale()) { sqlConnection.getConnection().close(); sqlConnection = new SQLConnection(DriverManager.getConnection(connectionURI)); } connections.add(sqlConnection); - } - catch (Exception e){ + } catch (Exception e) { log.error("Could not return a connection!"); } } diff --git a/jams-common/src/main/java/net/jami/jams/common/dao/connectivity/SQLConnection.java b/jams-common/src/main/java/net/jami/jams/common/dao/connectivity/SQLConnection.java index b519c8b9fe06a111fbbbd507cdb242b2d2979e2c..9c2b72d48d6051dae777d63112b60f4a79858008 100644 --- a/jams-common/src/main/java/net/jami/jams/common/dao/connectivity/SQLConnection.java +++ b/jams-common/src/main/java/net/jami/jams/common/dao/connectivity/SQLConnection.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.dao.connectivity; import lombok.Getter; @@ -40,8 +40,7 @@ public class SQLConnection { this.creationTimestamp = System.currentTimeMillis(); } - public boolean isStale(){ + public boolean isStale() { return (System.currentTimeMillis() - creationTimestamp > TIMEOUT); } - } diff --git a/jams-common/src/main/java/net/jami/jams/common/jami/AddrLookupResponse.java b/jams-common/src/main/java/net/jami/jams/common/jami/AddrLookupResponse.java index 20f72c30507240be48fc11f3cde4c78c05b4a071..37b3b26b25e45a2d35f554676d846b14864d5b6d 100644 --- a/jams-common/src/main/java/net/jami/jams/common/jami/AddrLookupResponse.java +++ b/jams-common/src/main/java/net/jami/jams/common/jami/AddrLookupResponse.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.jami; import lombok.AllArgsConstructor; diff --git a/jams-common/src/main/java/net/jami/jams/common/jami/NameLookupResponse.java b/jams-common/src/main/java/net/jami/jams/common/jami/NameLookupResponse.java index 1d2bbf43b73da9397e759f0fb80956b3557ed8a8..0a2ab00a3222a5204da0b109136318edcbfacb37 100644 --- a/jams-common/src/main/java/net/jami/jams/common/jami/NameLookupResponse.java +++ b/jams-common/src/main/java/net/jami/jams/common/jami/NameLookupResponse.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.jami; import lombok.Getter; diff --git a/jams-common/src/main/java/net/jami/jams/common/jami/NameRegistrationRequest.java b/jams-common/src/main/java/net/jami/jams/common/jami/NameRegistrationRequest.java index 3f7187a438331bb6db031f270a24e3742cb07c32..649db728e190afc376ae6e635e62a916f4bc4069 100644 --- a/jams-common/src/main/java/net/jami/jams/common/jami/NameRegistrationRequest.java +++ b/jams-common/src/main/java/net/jami/jams/common/jami/NameRegistrationRequest.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.jami; import lombok.Getter; diff --git a/jams-common/src/main/java/net/jami/jams/common/jami/NameServer.java b/jams-common/src/main/java/net/jami/jams/common/jami/NameServer.java index 11c8e16bfdfa593c74c97532fd6e122948087ae1..e86b592f61f30ad0cf3de9cb538b849b03d2d8a4 100644 --- a/jams-common/src/main/java/net/jami/jams/common/jami/NameServer.java +++ b/jams-common/src/main/java/net/jami/jams/common/jami/NameServer.java @@ -1,30 +1,33 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.jami; public interface NameServer { Integer registerName(String username, NameRegistrationRequest nameRegistrationRequest); + NameLookupResponse getAddressFromName(String username); + String getNameFromAddress(String address); + String getURI(); } diff --git a/jams-common/src/main/java/net/jami/jams/common/objects/contacts/Contact.java b/jams-common/src/main/java/net/jami/jams/common/objects/contacts/Contact.java index b7d71c16361f9a3b63ed0f0cf05bfb62f7cfb7c5..de2126166fa2781e58792ce4caef71fcbce1e4ba 100644 --- a/jams-common/src/main/java/net/jami/jams/common/objects/contacts/Contact.java +++ b/jams-common/src/main/java/net/jami/jams/common/objects/contacts/Contact.java @@ -24,10 +24,12 @@ package net.jami.jams.common.objects.contacts; import com.jsoniter.annotation.JsonIgnore; + import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; + import net.jami.jams.common.serialization.database.DatabaseObject; import java.sql.PreparedStatement; @@ -39,12 +41,12 @@ import java.sql.ResultSet; @EqualsAndHashCode public class Contact implements DatabaseObject { - @JsonIgnore //Ignore the owner because he is irrelevant. + @JsonIgnore // Ignore the owner because he is irrelevant. private String owner; private String uri; private String displayName; private Long timestamp; - private Character status; //A = added, D = deleted. + private Character status; // A = added, D = deleted. private Boolean banned = false; private Boolean confirmed = false; private String conversationId; @@ -64,12 +66,12 @@ public class Contact implements DatabaseObject { public PreparedStatement getInsert(PreparedStatement ps) throws Exception { ps.setString(1, owner); ps.setString(2, uri); - if(displayName != null) ps.setString(3, displayName); + if (displayName != null) ps.setString(3, displayName); else ps.setString(3, ""); - ps.setLong(4,timestamp); - ps.setInt(5,status); - ps.setBoolean(6,banned); - ps.setBoolean(7,confirmed); + ps.setLong(4, timestamp); + ps.setInt(5, status); + ps.setBoolean(6, banned); + ps.setBoolean(7, confirmed); ps.setString(8, conversationId); return ps; } diff --git a/jams-common/src/main/java/net/jami/jams/common/objects/devices/Device.java b/jams-common/src/main/java/net/jami/jams/common/objects/devices/Device.java index 888018467f2f9170b10b5945a47fd007c184a9c5..33b18480705fd0c28a10b317b52d78d38e5c49fc 100644 --- a/jams-common/src/main/java/net/jami/jams/common/objects/devices/Device.java +++ b/jams-common/src/main/java/net/jami/jams/common/objects/devices/Device.java @@ -1,32 +1,34 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.objects.devices; import com.jsoniter.annotation.JsonIgnore; + import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; + import net.jami.jams.common.objects.roots.X509Entity; import net.jami.jams.common.serialization.database.DatabaseObject; import net.jami.jams.common.utils.X509Utils; @@ -41,8 +43,7 @@ import java.sql.ResultSet; public class Device extends X509Entity implements DatabaseObject { private String deviceId; - @JsonIgnore - private String owner; + @JsonIgnore private String owner; private String displayName; public Device(ResultSet rs) throws Exception { @@ -57,9 +58,9 @@ public class Device extends X509Entity implements DatabaseObject { public PreparedStatement getInsert(PreparedStatement ps) throws Exception { ps.setString(1, deviceId); ps.setString(2, owner); - ps.setString(3,displayName); + ps.setString(3, displayName); ps.setString(4, X509Utils.getPEMStringFromCertificate(this.getCertificate())); - //Devices do not have private keys exposed. + // Devices do not have private keys exposed. ps.setString(5, ""); return ps; } diff --git a/jams-common/src/main/java/net/jami/jams/common/objects/requests/CreateAuthSourceRequest.java b/jams-common/src/main/java/net/jami/jams/common/objects/requests/CreateAuthSourceRequest.java index 8ba85d6a50de2e1e7609953b25707e79aff8a704..721415904377a8aa915c48edd8bd0fd11a4078b2 100644 --- a/jams-common/src/main/java/net/jami/jams/common/objects/requests/CreateAuthSourceRequest.java +++ b/jams-common/src/main/java/net/jami/jams/common/objects/requests/CreateAuthSourceRequest.java @@ -1,29 +1,30 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.objects.requests; import lombok.Getter; import lombok.Setter; + import net.jami.jams.common.authentication.AuthenticationSourceType; import net.jami.jams.common.authentication.activedirectory.ActiveDirectorySettings; import net.jami.jams.common.authentication.ldap.LDAPSettings; @@ -37,5 +38,4 @@ public class CreateAuthSourceRequest { private LDAPSettings ldapSettings; private ActiveDirectorySettings activeDirectorySettings; private LocalAuthSettings localAuthSettings; - } diff --git a/jams-common/src/main/java/net/jami/jams/common/objects/requests/CreateCARequest.java b/jams-common/src/main/java/net/jami/jams/common/objects/requests/CreateCARequest.java index 18f9542646d3d47f5e073365e06c793f869b9eb7..b0c024b1b64c209d2b2b0e37a9ce91f9ca591e82 100644 --- a/jams-common/src/main/java/net/jami/jams/common/objects/requests/CreateCARequest.java +++ b/jams-common/src/main/java/net/jami/jams/common/objects/requests/CreateCARequest.java @@ -1,29 +1,30 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.objects.requests; import lombok.Getter; import lombok.Setter; + import net.jami.jams.common.objects.roots.X509Fields; import java.security.PrivateKey; diff --git a/jams-common/src/main/java/net/jami/jams/common/objects/requests/CredentialsRequest.java b/jams-common/src/main/java/net/jami/jams/common/objects/requests/CredentialsRequest.java index 7cc17cb437a713a6edb8cc41948a1aeb90252d7a..02807f207c3b900d235dedfea4eb6d908d0d82f2 100644 --- a/jams-common/src/main/java/net/jami/jams/common/objects/requests/CredentialsRequest.java +++ b/jams-common/src/main/java/net/jami/jams/common/objects/requests/CredentialsRequest.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.objects.requests; import lombok.Getter; @@ -31,5 +31,4 @@ public class CredentialsRequest { private String username; private String password; - } diff --git a/jams-common/src/main/java/net/jami/jams/common/objects/requests/DeviceRegistrationRequest.java b/jams-common/src/main/java/net/jami/jams/common/objects/requests/DeviceRegistrationRequest.java index 521666f1f8e2f299eb5263e0d584c4208c7c0c9e..86781b0f67c6a130c27fa14fe66f1a3d3438616d 100644 --- a/jams-common/src/main/java/net/jami/jams/common/objects/requests/DeviceRegistrationRequest.java +++ b/jams-common/src/main/java/net/jami/jams/common/objects/requests/DeviceRegistrationRequest.java @@ -1,29 +1,30 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.objects.requests; import lombok.Getter; import lombok.Setter; + import org.bouncycastle.pkcs.PKCS10CertificationRequest; @Getter @@ -32,5 +33,4 @@ public class DeviceRegistrationRequest { private PKCS10CertificationRequest csr; private String deviceName; - } diff --git a/jams-common/src/main/java/net/jami/jams/common/objects/requests/DeviceRevocationRequest.java b/jams-common/src/main/java/net/jami/jams/common/objects/requests/DeviceRevocationRequest.java index d33899e03c38711893f94aa28173c0ff5927bff3..21a1b903f8bf3e846e04644250ce680d8c26aa4c 100644 --- a/jams-common/src/main/java/net/jami/jams/common/objects/requests/DeviceRevocationRequest.java +++ b/jams-common/src/main/java/net/jami/jams/common/objects/requests/DeviceRevocationRequest.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.objects.requests; import lombok.Getter; diff --git a/jams-common/src/main/java/net/jami/jams/common/objects/requests/RevocationRequest.java b/jams-common/src/main/java/net/jami/jams/common/objects/requests/RevocationRequest.java index 671e52ae2193de4486cb9afe2c9ac587978d7a5d..051a30af66591838073019681821643e359dca45 100644 --- a/jams-common/src/main/java/net/jami/jams/common/objects/requests/RevocationRequest.java +++ b/jams-common/src/main/java/net/jami/jams/common/objects/requests/RevocationRequest.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.objects.requests; import lombok.AllArgsConstructor; diff --git a/jams-common/src/main/java/net/jami/jams/common/objects/requests/RevocationType.java b/jams-common/src/main/java/net/jami/jams/common/objects/requests/RevocationType.java index 98717813247dfc6941e190fd331905293c3636ae..4bb0a53755acee3ea9d69040efe9e00dce41526f 100644 --- a/jams-common/src/main/java/net/jami/jams/common/objects/requests/RevocationType.java +++ b/jams-common/src/main/java/net/jami/jams/common/objects/requests/RevocationType.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.objects.requests; public enum RevocationType { diff --git a/jams-common/src/main/java/net/jami/jams/common/objects/responses/DeviceRegistrationResponse.java b/jams-common/src/main/java/net/jami/jams/common/objects/responses/DeviceRegistrationResponse.java index f4f87ca13d64b85d296518f2a91760d15f4c4d41..7f9eb5121b504dd145ca27ff4d2d3505b1e59dc8 100644 --- a/jams-common/src/main/java/net/jami/jams/common/objects/responses/DeviceRegistrationResponse.java +++ b/jams-common/src/main/java/net/jami/jams/common/objects/responses/DeviceRegistrationResponse.java @@ -1,30 +1,32 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.objects.responses; import com.jsoniter.JsonIterator; + import lombok.Getter; import lombok.Setter; + import net.jami.jams.common.objects.user.PolicyData; import net.jami.jams.common.utils.X509Utils; @@ -40,16 +42,16 @@ public class DeviceRegistrationResponse { private String deviceReceipt; private String receiptSignature; private String userPhoto; - //Backward compatibility fix so all the fields are included here. + // Backward compatibility fix so all the fields are included here. private Boolean publicInCalls; private Boolean proxyEnabled; - private String dhtProxyListUrl; - private String proxyServer; + private String dhtProxyListUrl; + private String proxyServer; private Boolean accountPublish; private Boolean autoAnswer; - private String turnServer; - private String turnServerUserName; - private String turnServerPassword; + private String turnServer; + private String turnServerUserName; + private String turnServerPassword; private Boolean videoEnabled; private Boolean turnEnabled; private Boolean accountDiscovery; @@ -59,18 +61,20 @@ public class DeviceRegistrationResponse { private String defaultModerators; private String uiCustomization; - public void setCertificateChain(X509Certificate[] certificateChain){ + public void setCertificateChain(X509Certificate[] certificateChain) { StringBuilder stringBuilder = new StringBuilder(); - for(int i=certificateChain.length-1;i > -1;i--){ - stringBuilder.append(X509Utils.getPEMStringFromCertificate(certificateChain[i])).append("\n"); + for (int i = certificateChain.length - 1; i > -1; i--) { + stringBuilder + .append(X509Utils.getPEMStringFromCertificate(certificateChain[i])) + .append("\n"); } - //remove the last \n because it's useless. - stringBuilder.deleteCharAt(stringBuilder.length()-1); + // remove the last \n because it's useless. + stringBuilder.deleteCharAt(stringBuilder.length() - 1); this.certificateChain = stringBuilder.toString(); } - public void setPolicyData(String policyData){ - PolicyData policy = JsonIterator.deserialize(policyData,PolicyData.class); + public void setPolicyData(String policyData) { + PolicyData policy = JsonIterator.deserialize(policyData, PolicyData.class); this.publicInCalls = policy.getPublicInCalls(); this.proxyEnabled = policy.getProxyEnabled(); this.dhtProxyListUrl = policy.getDhtProxyListUrl(); @@ -89,6 +93,4 @@ public class DeviceRegistrationResponse { this.defaultModerators = policy.getDefaultModerators(); this.uiCustomization = policy.getUiCustomization(); } - - } diff --git a/jams-common/src/main/java/net/jami/jams/common/objects/responses/DeviceRevocationResponse.java b/jams-common/src/main/java/net/jami/jams/common/objects/responses/DeviceRevocationResponse.java index 060f7c79e26d6dc752109cc46a92be4a8881dbd3..bbab6eea61d5946ae7fd4eadc06e67c17bd04270 100644 --- a/jams-common/src/main/java/net/jami/jams/common/objects/responses/DeviceRevocationResponse.java +++ b/jams-common/src/main/java/net/jami/jams/common/objects/responses/DeviceRevocationResponse.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.objects.responses; import lombok.Getter; @@ -32,10 +32,9 @@ import java.util.Date; @Setter public class DeviceRevocationResponse { - private boolean success; private String errorDetails; - private static final SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss'Z'X"); - private String timestamp = dateFormatter.format(new Date()); - + private static final SimpleDateFormat dateFormatter = + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss'Z'X"); + private String timestamp = dateFormatter.format(new Date()); } diff --git a/jams-common/src/main/java/net/jami/jams/common/objects/responses/SubscriptionStatusResponse.java b/jams-common/src/main/java/net/jami/jams/common/objects/responses/SubscriptionStatusResponse.java index 6274841f041d6df5fef2b75f7c4add1d796b312d..e462cbaa0a6abda3e2c2e2526fc92a74f88f2d3a 100644 --- a/jams-common/src/main/java/net/jami/jams/common/objects/responses/SubscriptionStatusResponse.java +++ b/jams-common/src/main/java/net/jami/jams/common/objects/responses/SubscriptionStatusResponse.java @@ -1,29 +1,30 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.objects.responses; import lombok.Getter; import lombok.Setter; + import net.jami.jams.common.updater.subscription.LicenseInformation; @Getter diff --git a/jams-common/src/main/java/net/jami/jams/common/objects/roots/BlockchainEntity.java b/jams-common/src/main/java/net/jami/jams/common/objects/roots/BlockchainEntity.java index 4c4e69bf6c8ab0b1560f2c76c5888097ffb96d44..1b4f9d906c3039f76a136f08a2490207dd7f7eca 100644 --- a/jams-common/src/main/java/net/jami/jams/common/objects/roots/BlockchainEntity.java +++ b/jams-common/src/main/java/net/jami/jams/common/objects/roots/BlockchainEntity.java @@ -1,30 +1,33 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.objects.roots; public interface BlockchainEntity { String getAddress(); - void setAddress(String address); + + void setAddress(String address); + String getKey(); - void setKey(String key); + + void setKey(String key); } diff --git a/jams-common/src/main/java/net/jami/jams/common/objects/roots/X509Entity.java b/jams-common/src/main/java/net/jami/jams/common/objects/roots/X509Entity.java index 8398a9aedbe23e45d5fef2170b34c0c4b2519170..1898d0937d7dcf69dd7d26ad840a0bcce259e965 100644 --- a/jams-common/src/main/java/net/jami/jams/common/objects/roots/X509Entity.java +++ b/jams-common/src/main/java/net/jami/jams/common/objects/roots/X509Entity.java @@ -1,29 +1,30 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.objects.roots; import lombok.Getter; import lombok.Setter; + import org.bouncycastle.pkcs.PKCS10CertificationRequest; import java.security.PrivateKey; @@ -34,7 +35,7 @@ import java.security.cert.X509Certificate; public class X509Entity { private X509Certificate certificate; private PrivateKey privateKey; - //These can be null because they are only used if this is a request. + // These can be null because they are only used if this is a request. private X509Fields x509Fields; private PKCS10CertificationRequest certificationRequest; private Boolean revoked; diff --git a/jams-common/src/main/java/net/jami/jams/common/objects/roots/X509Fields.java b/jams-common/src/main/java/net/jami/jams/common/objects/roots/X509Fields.java index ee03a0376c7fb8e715b10fcbfb78603842b51220..6c7918285b9e795cdffa8f75cf05b4c1c41eb37d 100644 --- a/jams-common/src/main/java/net/jami/jams/common/objects/roots/X509Fields.java +++ b/jams-common/src/main/java/net/jami/jams/common/objects/roots/X509Fields.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.objects.roots; import lombok.Getter; @@ -35,22 +35,22 @@ public class X509Fields { private String state; private String organization; private String organizationUnit; - private Long lifetime; + private Long lifetime; - public String getDN(){ + public String getDN() { StringBuilder stringBuilder = new StringBuilder(); - //This makes no sense without a Common Name; - if(commonName != null) { + // This makes no sense without a Common Name; + if (commonName != null) { stringBuilder.append("CN=").append(commonName); } else return null; - if(uid !=null) { + if (uid != null) { stringBuilder.append(",").append("UID=").append(uid); } - if(country != null) stringBuilder.append(",").append("C=").append(country); - if(state != null) stringBuilder.append(",").append("ST=").append(state); - if(organization != null) stringBuilder.append(",").append("O=").append(organization); - if(organizationUnit != null) stringBuilder.append(",").append("OU=").append(organizationUnit); + if (country != null) stringBuilder.append(",").append("C=").append(country); + if (state != null) stringBuilder.append(",").append("ST=").append(state); + if (organization != null) stringBuilder.append(",").append("O=").append(organization); + if (organizationUnit != null) + stringBuilder.append(",").append("OU=").append(organizationUnit); return stringBuilder.toString(); } - } diff --git a/jams-common/src/main/java/net/jami/jams/common/objects/system/SystemAccount.java b/jams-common/src/main/java/net/jami/jams/common/objects/system/SystemAccount.java index d64b2565cd8bc6b3713e8f4c9892256955745c58..136b31b1c913eb13a592fdd1032cbd37eaaf89dd 100644 --- a/jams-common/src/main/java/net/jami/jams/common/objects/system/SystemAccount.java +++ b/jams-common/src/main/java/net/jami/jams/common/objects/system/SystemAccount.java @@ -1,30 +1,31 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.objects.system; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; + import net.jami.jams.common.objects.roots.X509Entity; import net.jami.jams.common.serialization.database.DatabaseObject; import net.jami.jams.common.utils.X509Utils; @@ -49,7 +50,7 @@ public class SystemAccount extends X509Entity implements DatabaseObject { public PreparedStatement getInsert(PreparedStatement ps) throws Exception { ps.setString(1, systemAccountType.toString()); ps.setString(2, X509Utils.getPEMStringFromCertificate(this.getCertificate())); - ps.setString(3,X509Utils.getPEMStringFromPrivateKey(this.getPrivateKey())); + ps.setString(3, X509Utils.getPEMStringFromPrivateKey(this.getPrivateKey())); return ps; } diff --git a/jams-common/src/main/java/net/jami/jams/common/objects/system/SystemAccountType.java b/jams-common/src/main/java/net/jami/jams/common/objects/system/SystemAccountType.java index 2825edac091bc1e5fd6040d10c18b9f9feef9f37..252c792ced7647ca9efe137ce3ee255b3f467eb6 100644 --- a/jams-common/src/main/java/net/jami/jams/common/objects/system/SystemAccountType.java +++ b/jams-common/src/main/java/net/jami/jams/common/objects/system/SystemAccountType.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.objects.system; public enum SystemAccountType { diff --git a/jams-common/src/main/java/net/jami/jams/common/objects/user/AccessLevel.java b/jams-common/src/main/java/net/jami/jams/common/objects/user/AccessLevel.java index 10ee9cbbb5a11bd8f4c51d17a9fa777afcaf4919..587bb842ea8e3675cd472dd53de0c0d5b48c6d6b 100644 --- a/jams-common/src/main/java/net/jami/jams/common/objects/user/AccessLevel.java +++ b/jams-common/src/main/java/net/jami/jams/common/objects/user/AccessLevel.java @@ -1,28 +1,28 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.objects.user; -public enum AccessLevel { +public enum AccessLevel { ADMIN, USER, DEVICE diff --git a/jams-common/src/main/java/net/jami/jams/common/objects/user/Group.java b/jams-common/src/main/java/net/jami/jams/common/objects/user/Group.java index a77b95c193f512e6c444b1b7145a17197db5e9b8..eef0555a398a25b27a24e6d6d0f2490d2d8fddff 100644 --- a/jams-common/src/main/java/net/jami/jams/common/objects/user/Group.java +++ b/jams-common/src/main/java/net/jami/jams/common/objects/user/Group.java @@ -4,13 +4,12 @@ import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; + import net.jami.jams.common.serialization.database.DatabaseObject; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; @AllArgsConstructor @NoArgsConstructor @@ -46,12 +45,10 @@ public class Group implements DatabaseObject { } public boolean isEmpty() { - if(this.id == null && this.name == null) return true; - return false; + return this.id == null && this.name == null; } public boolean hasBlueprint() { - if(this.blueprint == null || this.blueprint.equals("")) return false; - return true; + return this.blueprint != null && !this.blueprint.equals(""); } } diff --git a/jams-common/src/main/java/net/jami/jams/common/objects/user/Policy.java b/jams-common/src/main/java/net/jami/jams/common/objects/user/Policy.java index b25f79e32f186a3cf02353072df23fa30e89c586..55577824c23d7343ba7ad3150dfe50be266ccd6f 100644 --- a/jams-common/src/main/java/net/jami/jams/common/objects/user/Policy.java +++ b/jams-common/src/main/java/net/jami/jams/common/objects/user/Policy.java @@ -4,6 +4,7 @@ import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; + import net.jami.jams.common.serialization.database.DatabaseObject; import java.sql.PreparedStatement; diff --git a/jams-common/src/main/java/net/jami/jams/common/objects/user/PolicyData.java b/jams-common/src/main/java/net/jami/jams/common/objects/user/PolicyData.java index 94b688cbcda8eb5b87cb659af8506b69b0637cd0..7df781a63462f9121a9044394eee5df2597c2111 100644 --- a/jams-common/src/main/java/net/jami/jams/common/objects/user/PolicyData.java +++ b/jams-common/src/main/java/net/jami/jams/common/objects/user/PolicyData.java @@ -9,7 +9,7 @@ public class PolicyData { private Boolean publicInCalls; private Boolean proxyEnabled; - private String dhtProxyListUrl; + private String dhtProxyListUrl; private String proxyServer; private Boolean accountPublish; private Boolean autoAnswer; diff --git a/jams-common/src/main/java/net/jami/jams/common/objects/user/User.java b/jams-common/src/main/java/net/jami/jams/common/objects/user/User.java index 3001e88ab4995513efb027c96b63708bd1bf2c18..1f305afcdbd78b9d9d576f572b6e0d97cc9ed1a3 100644 --- a/jams-common/src/main/java/net/jami/jams/common/objects/user/User.java +++ b/jams-common/src/main/java/net/jami/jams/common/objects/user/User.java @@ -1,31 +1,32 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.objects.user; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; + import net.jami.jams.common.authentication.AuthenticationSourceType; import net.jami.jams.common.objects.roots.BlockchainEntity; import net.jami.jams.common.objects.roots.X509Entity; @@ -35,7 +36,6 @@ import net.jami.jams.common.utils.X509Utils; import java.sql.PreparedStatement; import java.sql.ResultSet; - @AllArgsConstructor @NoArgsConstructor @Getter @@ -45,7 +45,7 @@ public class User extends X509Entity implements BlockchainEntity, DatabaseObject private String username; private String password; private AuthenticationSourceType userType; - private String realm; //sort of the domain. + private String realm; // sort of the domain. private AccessLevel accessLevel = AccessLevel.USER; private Boolean needsPasswordReset = false; private String salt; @@ -65,10 +65,10 @@ public class User extends X509Entity implements BlockchainEntity, DatabaseObject this.ethAddress = rs.getString("ethAddress"); this.ethKey = rs.getString("ethKey"); this.jamiId = rs.getString("jamiId"); - if(rs.getString("certificate") != null && !rs.getString("certificate").isBlank()) { + if (rs.getString("certificate") != null && !rs.getString("certificate").isBlank()) { this.setCertificate(X509Utils.getCertificateFromPEMString(rs.getString("certificate"))); } - if(rs.getString("privatekey") != null && !rs.getString("privatekey").isBlank()) { + if (rs.getString("privatekey") != null && !rs.getString("privatekey").isBlank()) { this.setPrivateKey(X509Utils.getKeyFromPEMString(rs.getString("privatekey"))); } } @@ -100,10 +100,11 @@ public class User extends X509Entity implements BlockchainEntity, DatabaseObject @Override public PreparedStatement getInsert(PreparedStatement ps) throws Exception { ps.setString(1, username); - //We don't store the user's password if he is remote. - if(userType != null && userType.equals(AuthenticationSourceType.LOCAL)) ps.setString(2, password); + // We don't store the user's password if he is remote. + if (userType != null && userType.equals(AuthenticationSourceType.LOCAL)) + ps.setString(2, password); else ps.setString(2, null); - if(userType != null) ps.setString(3, userType.toString()); + if (userType != null) ps.setString(3, userType.toString()); else ps.setString(3, null); ps.setString(4, realm); ps.setString(5, ethAddress); @@ -119,9 +120,9 @@ public class User extends X509Entity implements BlockchainEntity, DatabaseObject } else { ps.setString(9, ""); } - ps.setString(10,accessLevel.toString()); - ps.setString(11,needsPasswordReset.toString()); - ps.setString(12,salt); + ps.setString(10, accessLevel.toString()); + ps.setString(11, needsPasswordReset.toString()); + ps.setString(12, salt); return ps; } @@ -135,11 +136,11 @@ public class User extends X509Entity implements BlockchainEntity, DatabaseObject return null; } - public void setPassword(char[] password){ + public void setPassword(char[] password) { this.password = new String(password); } - public void setPassword(String password){ + public void setPassword(String password) { this.password = password; } } diff --git a/jams-common/src/main/java/net/jami/jams/common/objects/user/UserGroupMapping.java b/jams-common/src/main/java/net/jami/jams/common/objects/user/UserGroupMapping.java index 2925ebd6574128af58fca49d8ab1602809272f17..380d2eaead3ae72ac88294efc0789f3e6c603e26 100644 --- a/jams-common/src/main/java/net/jami/jams/common/objects/user/UserGroupMapping.java +++ b/jams-common/src/main/java/net/jami/jams/common/objects/user/UserGroupMapping.java @@ -4,6 +4,7 @@ import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; + import net.jami.jams.common.serialization.database.DatabaseObject; import java.sql.PreparedStatement; diff --git a/jams-common/src/main/java/net/jami/jams/common/objects/user/UserProfile.java b/jams-common/src/main/java/net/jami/jams/common/objects/user/UserProfile.java index 23e56b572372e83cfb0d8a4a2fc289ca7f259f88..609fa345c2de89aff70b1105218191b3417c9a19 100644 --- a/jams-common/src/main/java/net/jami/jams/common/objects/user/UserProfile.java +++ b/jams-common/src/main/java/net/jami/jams/common/objects/user/UserProfile.java @@ -1,29 +1,29 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.objects.user; import com.jsoniter.annotation.JsonIgnore; -import com.jsoniter.output.JsonStream; + import ezvcard.Ezvcard; import ezvcard.VCard; import ezvcard.VCardVersion; @@ -32,11 +32,14 @@ import ezvcard.parameter.ImageType; import ezvcard.parameter.TelephoneType; import ezvcard.property.Photo; import ezvcard.property.StructuredName; + import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; + import net.jami.jams.common.serialization.database.DatabaseObject; + import org.bouncycastle.util.encoders.Base64; import java.lang.reflect.Method; @@ -44,10 +47,7 @@ import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.sql.PreparedStatement; import java.sql.ResultSet; -import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; -import java.util.List; @AllArgsConstructor @NoArgsConstructor @@ -63,7 +63,8 @@ public class UserProfile implements DatabaseObject { } } - //We sort of need the username here, because it's our only way of creating users which never existed. + // We sort of need the username here, because it's our only way of creating users which never + // existed. private String username; private String firstName; private String lastName; @@ -90,25 +91,28 @@ public class UserProfile implements DatabaseObject { } @JsonIgnore - //Ignore this if we pass through JSON iterator. - public String getAsVCard(){ + // Ignore this if we pass through JSON iterator. + public String getAsVCard() { VCard vCard = new VCard(); - //We assume these always exist... + // We assume these always exist... StructuredName structuredName = new StructuredName(); structuredName.setFamily(URLEncoder.encode(this.getLastName(), StandardCharsets.UTF_8)); structuredName.setGiven(URLEncoder.encode(this.getFirstName(), StandardCharsets.UTF_8)); vCard.setStructuredName(structuredName); - if(this.getPhoneNumber() != null) vCard.addTelephoneNumber(this.getPhoneNumber(), TelephoneType.WORK); - if(this.getMobileNumber() != null) vCard.addTelephoneNumber(this.getMobileNumber(),TelephoneType.CELL); - if(this.getFaxNumber() != null) vCard.addTelephoneNumber(this.getFaxNumber(), TelephoneType.FAX); - if(this.getEmail() != null) vCard.addEmail(this.getEmail(), EmailType.WORK); - if(this.getOrganization() != null) vCard.setOrganization(this.getOrganization()); - if(this.getId() != null) vCard.setExtendedProperty("id",this.id); + if (this.getPhoneNumber() != null) + vCard.addTelephoneNumber(this.getPhoneNumber(), TelephoneType.WORK); + if (this.getMobileNumber() != null) + vCard.addTelephoneNumber(this.getMobileNumber(), TelephoneType.CELL); + if (this.getFaxNumber() != null) + vCard.addTelephoneNumber(this.getFaxNumber(), TelephoneType.FAX); + if (this.getEmail() != null) vCard.addEmail(this.getEmail(), EmailType.WORK); + if (this.getOrganization() != null) vCard.setOrganization(this.getOrganization()); + if (this.getId() != null) vCard.setExtendedProperty("id", this.id); /*I think this is how Base64 will work in this case*/ - if(this.getProfilePicture() != null) { + if (this.getProfilePicture() != null) { Photo photo = new Photo(Base64.decode(this.getProfilePicture()), ImageType.JPEG); vCard.addPhoto(photo); } @@ -146,30 +150,20 @@ public class UserProfile implements DatabaseObject { UserProfile profile = (UserProfile) obj; - return (profile.getUsername().equals(this.username) && - profile.getFirstName().equals(this.firstName) && - profile.getLastName().equals(this.lastName)); + return (profile.getUsername().equals(this.username) + && profile.getFirstName().equals(this.firstName) + && profile.getLastName().equals(this.lastName)); } public void setDefaultValues() { - if (this.firstName == null) - this.firstName = ""; - if (this.lastName == null) - this.lastName = ""; - if (this.email == null) - this.email = ""; - if (this.profilePicture == null) - this.profilePicture = ""; - if (this.organization == null) - this.organization = ""; - if (this.phoneNumber == null) - this.phoneNumber = ""; - if (this.phoneNumberExtension == null) - this.phoneNumberExtension = ""; - if (this.faxNumber == null) - this.faxNumber = ""; - if (this.mobileNumber == null) - this.mobileNumber = ""; + if (this.firstName == null) this.firstName = ""; + if (this.lastName == null) this.lastName = ""; + if (this.email == null) this.email = ""; + if (this.profilePicture == null) this.profilePicture = ""; + if (this.organization == null) this.organization = ""; + if (this.phoneNumber == null) this.phoneNumber = ""; + if (this.phoneNumberExtension == null) this.phoneNumberExtension = ""; + if (this.faxNumber == null) this.faxNumber = ""; + if (this.mobileNumber == null) this.mobileNumber = ""; } - } diff --git a/jams-common/src/main/java/net/jami/jams/common/serialization/JsoniterRegistry.java b/jams-common/src/main/java/net/jami/jams/common/serialization/JsoniterRegistry.java index f3191945f184447ce051aa678db7356ac02e8a0e..1b56c8e35b0c0f5f5c4067d2f307d9c70d18c466 100644 --- a/jams-common/src/main/java/net/jami/jams/common/serialization/JsoniterRegistry.java +++ b/jams-common/src/main/java/net/jami/jams/common/serialization/JsoniterRegistry.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.serialization; import com.jsoniter.JsonIterator; @@ -27,6 +27,7 @@ import com.jsoniter.output.EncodingMode; import com.jsoniter.output.JsonStream; import com.jsoniter.spi.DecodingMode; import com.jsoniter.spi.JsoniterSpi; + import net.jami.jams.common.objects.contacts.Contact; import net.jami.jams.common.serialization.decoders.CSRDecoder; import net.jami.jams.common.serialization.decoders.PrivateKeyDecoder; @@ -34,6 +35,7 @@ import net.jami.jams.common.serialization.decoders.X509CertificateDecoder; import net.jami.jams.common.serialization.encoders.PrivateKeyEncoder; import net.jami.jams.common.serialization.encoders.X509CertificateEncoder; import net.jami.jams.common.serialization.serializers.ContactCodec; + import org.bouncycastle.pkcs.PKCS10CertificationRequest; import java.security.PrivateKey; @@ -41,17 +43,15 @@ import java.security.cert.X509Certificate; public class JsoniterRegistry { - public static void initCodecs(){ + public static void initCodecs() { JsonStream.setMode(EncodingMode.DYNAMIC_MODE); JsonIterator.setMode(DecodingMode.DYNAMIC_MODE_AND_MATCH_FIELD_WITH_HASH); - JsoniterSpi.registerTypeDecoder(X509Certificate.class,new X509CertificateDecoder()); - JsoniterSpi.registerTypeDecoder(PrivateKey.class,new PrivateKeyDecoder()); - JsoniterSpi.registerTypeEncoder(X509Certificate.class,new X509CertificateEncoder()); - JsoniterSpi.registerTypeEncoder(PrivateKey.class,new PrivateKeyEncoder()); - JsoniterSpi.registerTypeDecoder(PKCS10CertificationRequest.class,new CSRDecoder()); - JsoniterSpi.registerTypeEncoder(Contact.class,new ContactCodec()); - JsoniterSpi.registerTypeDecoder(Contact.class,new ContactCodec()); + JsoniterSpi.registerTypeDecoder(X509Certificate.class, new X509CertificateDecoder()); + JsoniterSpi.registerTypeDecoder(PrivateKey.class, new PrivateKeyDecoder()); + JsoniterSpi.registerTypeEncoder(X509Certificate.class, new X509CertificateEncoder()); + JsoniterSpi.registerTypeEncoder(PrivateKey.class, new PrivateKeyEncoder()); + JsoniterSpi.registerTypeDecoder(PKCS10CertificationRequest.class, new CSRDecoder()); + JsoniterSpi.registerTypeEncoder(Contact.class, new ContactCodec()); + JsoniterSpi.registerTypeDecoder(Contact.class, new ContactCodec()); } - - } diff --git a/jams-common/src/main/java/net/jami/jams/common/serialization/database/DatabaseObject.java b/jams-common/src/main/java/net/jami/jams/common/serialization/database/DatabaseObject.java index 0489430e839adb39190231da637a55253987d813..5e9f0aa7b3a2a1fce20cad980bdbce90a9f9ca11 100644 --- a/jams-common/src/main/java/net/jami/jams/common/serialization/database/DatabaseObject.java +++ b/jams-common/src/main/java/net/jami/jams/common/serialization/database/DatabaseObject.java @@ -1,31 +1,33 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.serialization.database; import java.sql.PreparedStatement; public interface DatabaseObject { PreparedStatement getInsert(PreparedStatement ps) throws Exception; + PreparedStatement getDelete(PreparedStatement ps) throws Exception; + PreparedStatement getUpdate(PreparedStatement ps) throws Exception; } diff --git a/jams-common/src/main/java/net/jami/jams/common/serialization/decoders/CSRDecoder.java b/jams-common/src/main/java/net/jami/jams/common/serialization/decoders/CSRDecoder.java index 8fd4f26e916e75d7ef89991b977ffe91b603f415..c7ae0ff77ca57b635ec362266595ed873d8c305e 100644 --- a/jams-common/src/main/java/net/jami/jams/common/serialization/decoders/CSRDecoder.java +++ b/jams-common/src/main/java/net/jami/jams/common/serialization/decoders/CSRDecoder.java @@ -25,6 +25,7 @@ package net.jami.jams.common.serialization.decoders; import com.jsoniter.JsonIterator; import com.jsoniter.spi.Decoder; + import net.jami.jams.common.utils.X509Utils; import java.io.IOException; @@ -36,14 +37,15 @@ public class CSRDecoder implements Decoder { @Override public Object decode(JsonIterator jsonIterator) throws IOException { - //This is legacy code, we need to sanitize the string + // This is legacy code, we need to sanitize the string String input = jsonIterator.readString(); if (input == null) return null; input = input.replace(CSR_HEAD, ""); input = input.replace(CSR_TAIL, ""); input = input.replace("\n", ""); input = CSR_HEAD + input + CSR_TAIL; - //Once all legacy clients stop existing, this can safely be removed leaving only the jsonIter.readString() + // Once all legacy clients stop existing, this can safely be removed leaving only the + // jsonIter.readString() return X509Utils.getCSRFromString(input); } } diff --git a/jams-common/src/main/java/net/jami/jams/common/serialization/decoders/PrivateKeyDecoder.java b/jams-common/src/main/java/net/jami/jams/common/serialization/decoders/PrivateKeyDecoder.java index d59d71b4653e1abfaa6be3a0f7c9b094d804217c..f5088ab2237cf1b61d55343dc76c9c7663f9666e 100644 --- a/jams-common/src/main/java/net/jami/jams/common/serialization/decoders/PrivateKeyDecoder.java +++ b/jams-common/src/main/java/net/jami/jams/common/serialization/decoders/PrivateKeyDecoder.java @@ -1,29 +1,30 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.serialization.decoders; import com.jsoniter.JsonIterator; import com.jsoniter.spi.Decoder; + import net.jami.jams.common.utils.X509Utils; import java.io.IOException; diff --git a/jams-common/src/main/java/net/jami/jams/common/serialization/decoders/X509CertificateDecoder.java b/jams-common/src/main/java/net/jami/jams/common/serialization/decoders/X509CertificateDecoder.java index 156a33d2706fdf15e185d2098240bc02fe1d7df1..e33e57732365cf28c2769dbb6d7a6ce287db4dc7 100644 --- a/jams-common/src/main/java/net/jami/jams/common/serialization/decoders/X509CertificateDecoder.java +++ b/jams-common/src/main/java/net/jami/jams/common/serialization/decoders/X509CertificateDecoder.java @@ -1,29 +1,30 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.serialization.decoders; import com.jsoniter.JsonIterator; import com.jsoniter.spi.Decoder; + import net.jami.jams.common.utils.X509Utils; import java.io.IOException; diff --git a/jams-common/src/main/java/net/jami/jams/common/serialization/encoders/PrivateKeyEncoder.java b/jams-common/src/main/java/net/jami/jams/common/serialization/encoders/PrivateKeyEncoder.java index 0043166169314fa2f6613708c804fa60e6d19e59..204cc3aad53abb2c0b02ade68f7c24e86c41b511 100644 --- a/jams-common/src/main/java/net/jami/jams/common/serialization/encoders/PrivateKeyEncoder.java +++ b/jams-common/src/main/java/net/jami/jams/common/serialization/encoders/PrivateKeyEncoder.java @@ -1,29 +1,30 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.serialization.encoders; import com.jsoniter.output.JsonStream; import com.jsoniter.spi.Encoder; + import net.jami.jams.common.utils.X509Utils; import java.io.IOException; @@ -33,6 +34,7 @@ public class PrivateKeyEncoder implements Encoder { @Override public void encode(Object o, JsonStream jsonStream) throws IOException { - jsonStream.write(("\"" + X509Utils.getPEMStringFromPrivateKey((PrivateKey) o) + "\"").getBytes()); + jsonStream.write( + ("\"" + X509Utils.getPEMStringFromPrivateKey((PrivateKey) o) + "\"").getBytes()); } } diff --git a/jams-common/src/main/java/net/jami/jams/common/serialization/encoders/X509CertificateEncoder.java b/jams-common/src/main/java/net/jami/jams/common/serialization/encoders/X509CertificateEncoder.java index 43d57e12458e521bfff0552459d579f843017d6a..8186c4f4f3b59a2cab7f439f688a8817f269eb05 100644 --- a/jams-common/src/main/java/net/jami/jams/common/serialization/encoders/X509CertificateEncoder.java +++ b/jams-common/src/main/java/net/jami/jams/common/serialization/encoders/X509CertificateEncoder.java @@ -1,29 +1,30 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.serialization.encoders; import com.jsoniter.output.JsonStream; import com.jsoniter.spi.Encoder; + import net.jami.jams.common.utils.X509Utils; import java.io.IOException; @@ -33,6 +34,8 @@ public class X509CertificateEncoder implements Encoder { @Override public void encode(Object o, JsonStream jsonStream) throws IOException { - jsonStream.write(("\"" + X509Utils.getPEMStringFromCertificate((X509Certificate) o) + "\"").getBytes()); + jsonStream.write( + ("\"" + X509Utils.getPEMStringFromCertificate((X509Certificate) o) + "\"") + .getBytes()); } } diff --git a/jams-common/src/main/java/net/jami/jams/common/serialization/fs/FileStorage.java b/jams-common/src/main/java/net/jami/jams/common/serialization/fs/FileStorage.java index 43322d32d568e86edad07a8691c339d11e4cfc05..905188280fc9b669e13f283fce04324621d81fc0 100644 --- a/jams-common/src/main/java/net/jami/jams/common/serialization/fs/FileStorage.java +++ b/jams-common/src/main/java/net/jami/jams/common/serialization/fs/FileStorage.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.serialization.fs; import lombok.Getter; @@ -44,21 +44,19 @@ public abstract class FileStorage<T> { } public abstract T getObject(byte[] bytes) throws Exception; + public abstract byte[] getBytesFromObject(T object) throws Exception; - public T getData() throws Exception{ + public T getData() throws Exception { fileInputStream = new FileInputStream(file); return getObject(fileInputStream.readAllBytes()); } - public void storeData(T data) throws Exception{ + public void storeData(T data) throws Exception { fileOutputStream = new FileOutputStream(file); fileDescriptor = fileOutputStream.getFD(); fileOutputStream.write(getBytesFromObject(data)); fileOutputStream.flush(); fileDescriptor.sync(); } - - - } diff --git a/jams-common/src/main/java/net/jami/jams/common/serialization/serializers/ContactCodec.java b/jams-common/src/main/java/net/jami/jams/common/serialization/serializers/ContactCodec.java index 7a54ab04653cfb6faf8fa586eb4b88287d4560a3..9f9fdfe3356d32ba3a4e35b14db8bbead377c3ce 100644 --- a/jams-common/src/main/java/net/jami/jams/common/serialization/serializers/ContactCodec.java +++ b/jams-common/src/main/java/net/jami/jams/common/serialization/serializers/ContactCodec.java @@ -5,6 +5,7 @@ import com.jsoniter.any.Any; import com.jsoniter.output.JsonStream; import com.jsoniter.spi.Decoder; import com.jsoniter.spi.Encoder; + import net.jami.jams.common.objects.contacts.Contact; import java.io.IOException; @@ -28,21 +29,21 @@ public class ContactCodec implements Encoder, Decoder { contact.setConversationId(input.get("conversationId").toString()); long timeAdded = 0L; long timeRemoved = 0L; - if(!input.get("added").toString().isBlank()) - timeAdded = input.get("added").toLong(); - if(!input.get("removed").toString().isBlank()){ + if (!input.get("added").toString().isBlank()) timeAdded = input.get("added").toLong(); + if (!input.get("removed").toString().isBlank()) { timeRemoved = input.get("removed").toLong(); } - if(timeAdded >= timeRemoved){ + if (timeAdded >= timeRemoved) { contact.setStatus('A'); contact.setTimestamp(input.get("added").toLong()); - } - else{ + } else { contact.setStatus('D'); contact.setTimestamp(input.get("removed").toLong()); } - if(!input.get("banned").toString().isBlank()) contact.setBanned(input.get("banned").as(Boolean.class)); - if(!input.get("confirmed").toString().isBlank()) contact.setConfirmed(input.get("confirmed").as(Boolean.class)); + if (!input.get("banned").toString().isBlank()) + contact.setBanned(input.get("banned").as(Boolean.class)); + if (!input.get("confirmed").toString().isBlank()) + contact.setConfirmed(input.get("confirmed").as(Boolean.class)); return contact; } @@ -52,14 +53,15 @@ public class ContactCodec implements Encoder, Decoder { StringBuilder sb = new StringBuilder(); sb.append("{\"uri\":\"").append(ct.getUri()).append("\","); sb.append("\"conversationId\":\"").append(ct.getConversationId()).append("\","); - switch (ct.getStatus()){ + switch (ct.getStatus()) { case 'A': sb.append("\"added\":").append(ct.getTimestamp()); sb.append(","); sb.append("\"confirmed\":").append(ct.getConfirmed()); break; - case 'D': sb.append("\"removed\":").append(ct.getTimestamp()); - if(ct.getBanned()) sb.append(",").append("\"banned\":").append(ct.getBanned()); + case 'D': + sb.append("\"removed\":").append(ct.getTimestamp()); + if (ct.getBanned()) sb.append(",").append("\"banned\":").append(ct.getBanned()); break; } sb.append("}"); diff --git a/jams-common/src/main/java/net/jami/jams/common/serialization/tomcat/TomcatCustomErrorHandler.java b/jams-common/src/main/java/net/jami/jams/common/serialization/tomcat/TomcatCustomErrorHandler.java index 2defb5b0d1501d779a758c48efeb68780f709668..b753bd7c08eed4fa536cd642cd30bcaf8cca4b47 100644 --- a/jams-common/src/main/java/net/jami/jams/common/serialization/tomcat/TomcatCustomErrorHandler.java +++ b/jams-common/src/main/java/net/jami/jams/common/serialization/tomcat/TomcatCustomErrorHandler.java @@ -1,39 +1,39 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.serialization.tomcat; import jakarta.servlet.http.HttpServletResponse; + import lombok.extern.slf4j.Slf4j; @Slf4j public class TomcatCustomErrorHandler { - public static void sendCustomError(HttpServletResponse resp,int errorCode, String text){ + public static void sendCustomError(HttpServletResponse resp, int errorCode, String text) { try { resp.setStatus(errorCode); resp.getOutputStream().write(("{\"error\":\"" + text + "\"}").getBytes()); - } - catch (Exception e){ + } catch (Exception e) { log.error("Could not generate an error!"); } } diff --git a/jams-common/src/main/java/net/jami/jams/common/server/ServerSettings.java b/jams-common/src/main/java/net/jami/jams/common/server/ServerSettings.java index d044b1e10199a854b311786570821c928d457691..528e13bfcb3a7e0e2a4d56cb8225af0311919a8c 100644 --- a/jams-common/src/main/java/net/jami/jams/common/server/ServerSettings.java +++ b/jams-common/src/main/java/net/jami/jams/common/server/ServerSettings.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.server; import lombok.Getter; @@ -34,5 +34,4 @@ public class ServerSettings { private String activeDirectoryConfiguration; private String localDirectoryConfiguration; private String serverPublicURI; - } diff --git a/jams-common/src/main/java/net/jami/jams/common/updater/AppUpdater.java b/jams-common/src/main/java/net/jami/jams/common/updater/AppUpdater.java index 5f58b0b2c6a70e903f6e60c39c2cbf7224abe438..2e796c6688a764718d37ab8a60a5bdfd72e63fd2 100644 --- a/jams-common/src/main/java/net/jami/jams/common/updater/AppUpdater.java +++ b/jams-common/src/main/java/net/jami/jams/common/updater/AppUpdater.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.updater; import java.security.PrivateKey; @@ -28,10 +28,13 @@ import java.util.HashMap; public interface AppUpdater { - HashMap<String,FileDescription> getLocalVersions(); - HashMap<String,FileDescription> getRemoteVersions(); + HashMap<String, FileDescription> getLocalVersions(); + + HashMap<String, FileDescription> getRemoteVersions(); + boolean getUpdateAvailable(); + void setLicense(X509Certificate certificate, PrivateKey privateKey); - void doUpdate(); + void doUpdate(); } diff --git a/jams-common/src/main/java/net/jami/jams/common/updater/FileDescription.java b/jams-common/src/main/java/net/jami/jams/common/updater/FileDescription.java index 28a269085f9600468df10b674b0c23dee1afbe1c..1d7791aaf26cc74bfd330e5c389bdb0f9db1235c 100644 --- a/jams-common/src/main/java/net/jami/jams/common/updater/FileDescription.java +++ b/jams-common/src/main/java/net/jami/jams/common/updater/FileDescription.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.updater; import lombok.AllArgsConstructor; @@ -44,7 +44,7 @@ public class FileDescription implements Comparable<FileDescription> { @Override public int compareTo(FileDescription o) { - if(o == null) throw new NullPointerException(); + if (o == null) throw new NullPointerException(); return new BigDecimal(this.version).compareTo(new BigDecimal(o.getVersion())); } } diff --git a/jams-common/src/main/java/net/jami/jams/common/updater/FileRepository.java b/jams-common/src/main/java/net/jami/jams/common/updater/FileRepository.java index 4cd45cd4e9c9b7bb4393f3c943256d1eef36b76b..81390791d98b34b269bd1c34534111d2f6f00084 100644 --- a/jams-common/src/main/java/net/jami/jams/common/updater/FileRepository.java +++ b/jams-common/src/main/java/net/jami/jams/common/updater/FileRepository.java @@ -1,29 +1,29 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.updater; import java.util.HashMap; public interface FileRepository { - HashMap<String,FileDescription> getFileVersions(); + HashMap<String, FileDescription> getFileVersions(); } diff --git a/jams-common/src/main/java/net/jami/jams/common/updater/FullSystemStatusResponse.java b/jams-common/src/main/java/net/jami/jams/common/updater/FullSystemStatusResponse.java index 51c1ba146bebae54023ec1f902d5ee7e7ee8f2ec..a415089feae785336b9b83baafd25cf39daf4684 100644 --- a/jams-common/src/main/java/net/jami/jams/common/updater/FullSystemStatusResponse.java +++ b/jams-common/src/main/java/net/jami/jams/common/updater/FullSystemStatusResponse.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.updater; import lombok.Getter; @@ -31,8 +31,7 @@ import java.util.HashMap; @Setter public class FullSystemStatusResponse { - private HashMap<String,FileDescription> localVersions; + private HashMap<String, FileDescription> localVersions; private HashMap<String, FileDescription> remoteVersions; private Boolean updateAvailable; - } diff --git a/jams-common/src/main/java/net/jami/jams/common/updater/subscription/LicenseInformation.java b/jams-common/src/main/java/net/jami/jams/common/updater/subscription/LicenseInformation.java index 8416b17a7d09af0862d2796ec2e97285b81ffd91..595a695944687e7599556bfcc95db61ba4e79000 100644 --- a/jams-common/src/main/java/net/jami/jams/common/updater/subscription/LicenseInformation.java +++ b/jams-common/src/main/java/net/jami/jams/common/updater/subscription/LicenseInformation.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.updater.subscription; import lombok.Getter; @@ -34,10 +34,7 @@ import java.util.List; @NoArgsConstructor public class LicenseInformation { - //TODO: Possibly add the expiry date here based on the certificate. + // TODO: Possibly add the expiry date here based on the certificate. private SubscriptionType type = SubscriptionType.COMMUNITY; private List<String> products = new ArrayList<>(); - - - } diff --git a/jams-common/src/main/java/net/jami/jams/common/updater/subscription/SubscriptionType.java b/jams-common/src/main/java/net/jami/jams/common/updater/subscription/SubscriptionType.java index f76550582c430dd8c290b9eecb38f2ccdb1964ea..610ba326211abff1b9c8a4717b912b16056e9215 100644 --- a/jams-common/src/main/java/net/jami/jams/common/updater/subscription/SubscriptionType.java +++ b/jams-common/src/main/java/net/jami/jams/common/updater/subscription/SubscriptionType.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.updater.subscription; public enum SubscriptionType { diff --git a/jams-common/src/main/java/net/jami/jams/common/utils/ContactMerger.java b/jams-common/src/main/java/net/jami/jams/common/utils/ContactMerger.java index f73f276cf6e4dd1db441dc4674c3820de4556082..623e3dc4f6c75bad967865ed7f108c7737154b6e 100644 --- a/jams-common/src/main/java/net/jami/jams/common/utils/ContactMerger.java +++ b/jams-common/src/main/java/net/jami/jams/common/utils/ContactMerger.java @@ -9,30 +9,31 @@ import java.util.List; public class ContactMerger { - public static List<Contact> mergeContacts(List<Contact> remote, List<Contact> local){ - //uri - [remote,local] + public static List<Contact> mergeContacts(List<Contact> remote, List<Contact> local) { + // uri - [remote,local] List<Contact> output = new ArrayList<>(); - final HashMap<String,Contact[]> contactMap = new HashMap<>(); + final HashMap<String, Contact[]> contactMap = new HashMap<>(); remote.sort(Comparator.comparingLong(Contact::getTimestamp)); - remote.forEach(contact -> { - contactMap.putIfAbsent(contact.getUri(),new Contact[]{null,null}); - contactMap.get(contact.getUri())[0] = contact; - }); - local.forEach(contact -> { - contactMap.putIfAbsent(contact.getUri(),new Contact[]{null,null}); - contactMap.get(contact.getUri())[1] = contact; - }); - contactMap.forEach((k,v) -> { - if(v[0] == null) output.add(v[1]); - else if(v[1] == null) output.add(v[0]); - else { - //Compare by date an choose the proper one - if(v[0].getTimestamp() > v[1].getTimestamp()) output.add(v[0]); - else output.add(v[1]); - } - }); + remote.forEach( + contact -> { + contactMap.putIfAbsent(contact.getUri(), new Contact[] {null, null}); + contactMap.get(contact.getUri())[0] = contact; + }); + local.forEach( + contact -> { + contactMap.putIfAbsent(contact.getUri(), new Contact[] {null, null}); + contactMap.get(contact.getUri())[1] = contact; + }); + contactMap.forEach( + (k, v) -> { + if (v[0] == null) output.add(v[1]); + else if (v[1] == null) output.add(v[0]); + else { + // Compare by date an choose the proper one + if (v[0].getTimestamp() > v[1].getTimestamp()) output.add(v[0]); + else output.add(v[1]); + } + }); return output; } - - } diff --git a/jams-common/src/main/java/net/jami/jams/common/utils/LibraryLoader.java b/jams-common/src/main/java/net/jami/jams/common/utils/LibraryLoader.java index f3a1b2699f9b61959d94726a347d73d83f000006..adf6644637c55171ead292a844193190bf1ef689 100644 --- a/jams-common/src/main/java/net/jami/jams/common/utils/LibraryLoader.java +++ b/jams-common/src/main/java/net/jami/jams/common/utils/LibraryLoader.java @@ -1,28 +1,29 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.utils; import lombok.extern.slf4j.Slf4j; + import org.apache.xbean.classloader.JarFileClassLoader; import java.io.File; @@ -34,7 +35,7 @@ public class LibraryLoader { public static JarFileClassLoader classLoader; - public static void loadlibs(String libDir, Class parentClass){ + public static void loadlibs(String libDir, Class parentClass) { try { File dependencyDirectory = new File(libDir); File[] files = dependencyDirectory.listFiles(); @@ -46,9 +47,12 @@ public class LibraryLoader { log.info("Successfully loaded the library " + files[i]); } } - classLoader = new JarFileClassLoader("Scheduler CL" + System.currentTimeMillis(), urls.toArray(new URL[urls.size()]), parentClass.getClassLoader()); - } - catch (Exception e){ + classLoader = + new JarFileClassLoader( + "Scheduler CL" + System.currentTimeMillis(), + urls.toArray(new URL[urls.size()]), + parentClass.getClassLoader()); + } catch (Exception e) { log.error("Errors occured while trying to load libraries..."); } } diff --git a/jams-common/src/main/java/net/jami/jams/common/utils/PasswordGenerator.java b/jams-common/src/main/java/net/jami/jams/common/utils/PasswordGenerator.java index f97efb899e163484c8e7bdf081ddec62fa080f25..dcd43872a07dd42aced05f74f50106fa5ba19958 100644 --- a/jams-common/src/main/java/net/jami/jams/common/utils/PasswordGenerator.java +++ b/jams-common/src/main/java/net/jami/jams/common/utils/PasswordGenerator.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.utils; import java.security.SecureRandom; @@ -27,9 +27,12 @@ import java.util.stream.Collectors; public class PasswordGenerator { - //Assume all passwords are 12 chars long. - public static String generatePassword(){ + // Assume all passwords are 12 chars long. + public static String generatePassword() { - return new SecureRandom().ints(12, 48, 58).mapToObj(i -> String.valueOf((char)i)).collect(Collectors.joining()); + return new SecureRandom() + .ints(12, 48, 58) + .mapToObj(i -> String.valueOf((char) i)) + .collect(Collectors.joining()); } } diff --git a/jams-common/src/main/java/net/jami/jams/common/utils/Validator.java b/jams-common/src/main/java/net/jami/jams/common/utils/Validator.java index a506c8ec1f646e0107119534f34265185fc79114..8429122806564d224671ffe77d8a8eb332bed7d7 100644 --- a/jams-common/src/main/java/net/jami/jams/common/utils/Validator.java +++ b/jams-common/src/main/java/net/jami/jams/common/utils/Validator.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.utils; import net.jami.jams.common.objects.requests.CreateCARequest; @@ -45,8 +45,13 @@ public class Validator { return rsaPublicKey.getModulus().equals(rsaPrivateKey.getModulus()) // https://en.wikipedia.org/wiki/RSA_(cryptosystem) // 2 ** (e * d - 1) mod n == 1 - && BigInteger.valueOf(2).modPow(rsaPublicKey.getPublicExponent() - .multiply(rsaPrivateKey.getPrivateExponent()).subtract(BigInteger.ONE), - rsaPublicKey.getModulus()).equals(BigInteger.ONE); + && BigInteger.valueOf(2) + .modPow( + rsaPublicKey + .getPublicExponent() + .multiply(rsaPrivateKey.getPrivateExponent()) + .subtract(BigInteger.ONE), + rsaPublicKey.getModulus()) + .equals(BigInteger.ONE); } } diff --git a/jams-common/src/main/java/net/jami/jams/common/utils/VersioningUtils.java b/jams-common/src/main/java/net/jami/jams/common/utils/VersioningUtils.java index ee6ab8ad1bea7164452a0e77e41ec3a71a7b20ff..f3a6877d8a6255f92d2fb8228640d261b4c0904d 100644 --- a/jams-common/src/main/java/net/jami/jams/common/utils/VersioningUtils.java +++ b/jams-common/src/main/java/net/jami/jams/common/utils/VersioningUtils.java @@ -1,29 +1,31 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.utils; import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.updater.FileDescription; + import org.bouncycastle.util.encoders.Hex; import java.io.File; @@ -42,32 +44,47 @@ public class VersioningUtils { public static HashMap<String, FileDescription> checkVersion(String baseLocation) { try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); - HashMap<String,FileDescription> res = new HashMap<>(); + HashMap<String, FileDescription> res = new HashMap<>(); ArrayList<Path> files = new ArrayList<>(); - if(baseLocation == null) baseLocation = System.getProperty("user.dir"); + if (baseLocation == null) baseLocation = System.getProperty("user.dir"); Stream<Path> stream = Files.walk(Paths.get(baseLocation)); stream.filter(Files::isRegularFile).forEach(files::add); stream.close(); - files.forEach( e -> { - String fileName = e.toString(); - if (fileName.endsWith(".jar")) { - try { - JarFile file = new JarFile(e.toFile()); - String version = file.getManifest().getMainAttributes().getValue("Implementation-Version"); - String className = file.getManifest().getMainAttributes().getValue("Main-Class"); - String md5 = Hex.toHexString(messageDigest.digest(Files.readAllBytes(e.toAbsolutePath()))); - String[] arr = e.toString().split(File.separator); - res.put(arr[arr.length - 1], new FileDescription(arr[arr.length - 1], version, md5, className)); - log.info("Found version {} of {}", version, fileName); - } catch (Exception e1) { - log.error("Could detect version for file with error {}", e1.getMessage()); - } - } - }); + files.forEach( + e -> { + String fileName = e.toString(); + if (fileName.endsWith(".jar")) { + try { + JarFile file = new JarFile(e.toFile()); + String version = + file.getManifest() + .getMainAttributes() + .getValue("Implementation-Version"); + String className = + file.getManifest() + .getMainAttributes() + .getValue("Main-Class"); + String md5 = + Hex.toHexString( + messageDigest.digest( + Files.readAllBytes(e.toAbsolutePath()))); + String[] arr = e.toString().split(File.separator); + res.put( + arr[arr.length - 1], + new FileDescription( + arr[arr.length - 1], version, md5, className)); + log.info("Found version {} of {}", version, fileName); + } catch (Exception e1) { + log.error( + "Could detect version for file with error {}", + e1.getMessage()); + } + } + }); return res; - } - catch (Exception e){ - log.error("An error has occurred while trying to list file versions {}",e.getMessage()); + } catch (Exception e) { + log.error( + "An error has occurred while trying to list file versions {}", e.getMessage()); return null; } } diff --git a/jams-common/src/main/java/net/jami/jams/common/utils/X509Utils.java b/jams-common/src/main/java/net/jami/jams/common/utils/X509Utils.java index 0cf2653eb3fd1e559c59773688f9d3d8f4571793..226eac30cc2f442c99ca83fe1910f6cb130f9307 100644 --- a/jams-common/src/main/java/net/jami/jams/common/utils/X509Utils.java +++ b/jams-common/src/main/java/net/jami/jams/common/utils/X509Utils.java @@ -23,8 +23,11 @@ package net.jami.jams.common.utils; import com.jsoniter.JsonIterator; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.updater.subscription.LicenseInformation; + import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.openssl.PEMKeyPair; @@ -32,8 +35,6 @@ import org.bouncycastle.openssl.PEMParser; import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; import org.bouncycastle.pkcs.PKCS10CertificationRequest; -import javax.naming.ldap.LdapName; -import javax.naming.ldap.Rdn; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.InputStream; @@ -50,6 +51,9 @@ import java.util.Base64; import java.util.HashMap; import java.util.Vector; +import javax.naming.ldap.LdapName; +import javax.naming.ldap.Rdn; + @Slf4j public class X509Utils { @@ -66,14 +70,17 @@ public class X509Utils { Object parsedObject = parser.readObject(); if (parsedObject instanceof PEMKeyPair) { PEMKeyPair pk = (PEMKeyPair) parsedObject; - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pk.getPrivateKeyInfo().getEncoded()); + PKCS8EncodedKeySpec keySpec = + new PKCS8EncodedKeySpec(pk.getPrivateKeyInfo().getEncoded()); return KeyFactory.getInstance("RSA").generatePrivate(keySpec); } else { JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); return converter.getPrivateKey((PrivateKeyInfo) parsedObject); } } catch (Exception e) { - log.error("An error has occured trying to convert the PEM to PrivateKey, stack trace: " + e.toString()); + log.error( + "An error has occured trying to convert the PEM to PrivateKey, stack trace: " + + e); return null; } } @@ -84,7 +91,8 @@ public class X509Utils { Object parsedObject = parser.readObject(); if (parsedObject instanceof PEMKeyPair) { PEMKeyPair pk = (PEMKeyPair) parsedObject; - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pk.getPublicKeyInfo().getEncoded()); + PKCS8EncodedKeySpec keySpec = + new PKCS8EncodedKeySpec(pk.getPublicKeyInfo().getEncoded()); return KeyFactory.getInstance("RSA").generatePublic(keySpec); } else { JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); @@ -96,14 +104,13 @@ public class X509Utils { } } - public static X509Certificate getCertificateFromPEMString(String certificateString) { try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); InputStream inputStream = new ByteArrayInputStream(certificateString.getBytes()); return (X509Certificate) certificateFactory.generateCertificate(inputStream); } catch (Exception e) { - log.error("An error has occured trying to convert the PEM to X509, stack trace: " + e.toString()); + log.error("An error has occured trying to convert the PEM to X509, stack trace: " + e); return null; } } @@ -116,7 +123,9 @@ public class X509Utils { stringBuilder.append(PVK_TAIL); return stringBuilder.toString(); } catch (Exception e) { - log.error("An error has occured trying to convert the Private Key to PEM, stack trace: " + e.toString()); + log.error( + "An error has occured trying to convert the Private Key to PEM, stack trace: " + + e); return null; } } @@ -129,7 +138,9 @@ public class X509Utils { stringBuilder.append(CERT_TAIL); return stringBuilder.toString(); } catch (Exception e) { - log.error("An error has occured trying to convert the Certificate Key to PEM, stack trace: " + e.toString()); + log.error( + "An error has occured trying to convert the Certificate Key to PEM, stack trace: " + + e); return null; } } @@ -142,26 +153,32 @@ public class X509Utils { stringBuilder.append(PPK_TAIL); return stringBuilder.toString(); } catch (Exception e) { - log.error("An error has occured trying to convert the Public Key to PEM, stack trace: " + e.toString()); + log.error( + "An error has occured trying to convert the Public Key to PEM, stack trace: " + + e); return null; } } public static PKCS10CertificationRequest getCSRFromString(String pkcs10StringRequest) { try { - ByteArrayInputStream pemStream = new ByteArrayInputStream(pkcs10StringRequest.getBytes(StandardCharsets.UTF_8)); - PEMParser pemParser = new PEMParser(new BufferedReader(new InputStreamReader(pemStream))); + ByteArrayInputStream pemStream = + new ByteArrayInputStream(pkcs10StringRequest.getBytes(StandardCharsets.UTF_8)); + PEMParser pemParser = + new PEMParser(new BufferedReader(new InputStreamReader(pemStream))); Object parsedObj = pemParser.readObject(); - if (parsedObj instanceof PKCS10CertificationRequest) return (PKCS10CertificationRequest) parsedObj; + if (parsedObj instanceof PKCS10CertificationRequest) + return (PKCS10CertificationRequest) parsedObj; log.error("The request does not seem to be a CSR request!"); return null; } catch (Exception e) { - log.error("An error has occured trying to convert a string to a PKCS10 Certification Request, stack trace: " + e.toString()); + log.error( + "An error has occured trying to convert a string to a PKCS10 Certification Request, stack trace: " + + e); return null; } } - public static Vector<Object> loadLicenseFromDatFile(String fileContents) { Vector<Object> res = new Vector<>(); String keypair = new String(Base64.getDecoder().decode(fileContents)); @@ -173,12 +190,14 @@ public class X509Utils { return res; } - public static LicenseInformation extractSubscriptionTypeFromCertificate(X509Certificate certificate) { + public static LicenseInformation extractSubscriptionTypeFromCertificate( + X509Certificate certificate) { try { LdapName ln = new LdapName(certificate.getSubjectDN().toString()); for (Rdn rdn : ln.getRdns()) { try { - return JsonIterator.deserialize(Base64.getDecoder().decode(rdn.getValue().toString().getBytes()), + return JsonIterator.deserialize( + Base64.getDecoder().decode(rdn.getValue().toString().getBytes()), LicenseInformation.class); } catch (Exception e) { } @@ -189,13 +208,13 @@ public class X509Utils { } } - public static HashMap<String,String> extractDNFromCertificate(X509Certificate certificate) throws Exception{ - HashMap<String,String> subjectMap = new HashMap<>(); + public static HashMap<String, String> extractDNFromCertificate(X509Certificate certificate) + throws Exception { + HashMap<String, String> subjectMap = new HashMap<>(); LdapName ln = new LdapName(certificate.getSubjectDN().toString()); for (Rdn rdn : ln.getRdns()) { - subjectMap.put(rdn.getType(),rdn.getValue().toString()); + subjectMap.put(rdn.getType(), rdn.getValue().toString()); } return subjectMap; } - } diff --git a/jams-common/src/test/java/net/jami/jams/common/objects/contacts/ContactTest.java b/jams-common/src/test/java/net/jami/jams/common/objects/contacts/ContactTest.java index 3eca7619976dd507fa1a58b7d6ee443cb0e4e893..2a953419e1229e2f1ab4d3f3bc7586a286e228e6 100644 --- a/jams-common/src/test/java/net/jami/jams/common/objects/contacts/ContactTest.java +++ b/jams-common/src/test/java/net/jami/jams/common/objects/contacts/ContactTest.java @@ -3,8 +3,10 @@ package net.jami.jams.common.objects.contacts; import com.jsoniter.JsonIterator; import com.jsoniter.output.JsonStream; import com.jsoniter.spi.JsoniterSpi; + import net.jami.jams.common.serialization.serializers.ContactCodec; import net.jami.jams.common.utils.ContactMerger; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -15,21 +17,22 @@ import java.util.List; class ContactTest { @BeforeAll - public static void init(){ - JsoniterSpi.registerTypeDecoder(Contact.class,new ContactCodec()); - JsoniterSpi.registerTypeEncoder(Contact.class,new ContactCodec()); + public static void init() { + JsoniterSpi.registerTypeDecoder(Contact.class, new ContactCodec()); + JsoniterSpi.registerTypeEncoder(Contact.class, new ContactCodec()); } @Test - public void deserialize(){ - String str = "[{\"uri\":\"tcp://def@local\",\"added\":1594742298377,\"banned\":false,\"confirmed\":true,\"confirmed\":6a61013979964f70c8fb9183a8b238d58a1846ed}," + - "{\"uri\":\"tcp://abc@19293.com\",\"removed\":1594742298377,\"banned\":true,\"confirmed\":true,\"confirmed\":2b61024119964f70c8fb9183a8b238d58a1846ed}]"; - Contact[] contacts = JsonIterator.deserialize(str,Contact[].class); - Assertions.assertEquals(2,contacts.length); + public void deserialize() { + String str = + "[{\"uri\":\"tcp://def@local\",\"added\":1594742298377,\"banned\":false,\"confirmed\":true,\"confirmed\":6a61013979964f70c8fb9183a8b238d58a1846ed}," + + "{\"uri\":\"tcp://abc@19293.com\",\"removed\":1594742298377,\"banned\":true,\"confirmed\":true,\"confirmed\":2b61024119964f70c8fb9183a8b238d58a1846ed}]"; + Contact[] contacts = JsonIterator.deserialize(str, Contact[].class); + Assertions.assertEquals(2, contacts.length); } @Test - public void serialize(){ + public void serialize() { Contact contact1 = new Contact(); contact1.setOwner("fsidokhine"); contact1.setStatus('A'); @@ -54,7 +57,7 @@ class ContactTest { } @Test - public void mergeTest(){ + public void mergeTest() { Contact contact1 = new Contact(); contact1.setOwner("fsidokhine"); contact1.setStatus('A'); @@ -77,7 +80,7 @@ class ContactTest { contact3.setConversationId("2b61024119964f70c8fb9183a8b238d58a1846ed"); ArrayList<Contact> lst2 = new ArrayList<>(); lst2.add(contact3); - List<Contact> out = ContactMerger.mergeContacts(lst,lst2); - Assertions.assertEquals(2,out.size()); + List<Contact> out = ContactMerger.mergeContacts(lst, lst2); + Assertions.assertEquals(2, out.size()); } -} \ No newline at end of file +} diff --git a/jams-common/src/test/java/net/jami/jams/common/serialization/JsoniterRegistryTest.java b/jams-common/src/test/java/net/jami/jams/common/serialization/JsoniterRegistryTest.java index c6466d0b599ef7ad19387c66fa17784f8a5f7099..69675e522f81ec93f32c5ebe11c13ac5df54c0ea 100644 --- a/jams-common/src/test/java/net/jami/jams/common/serialization/JsoniterRegistryTest.java +++ b/jams-common/src/test/java/net/jami/jams/common/serialization/JsoniterRegistryTest.java @@ -1,40 +1,42 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.serialization; +import static org.junit.jupiter.api.Assertions.fail; + import com.jsoniter.JsonIterator; import com.jsoniter.output.JsonStream; + import net.jami.jams.common.objects.requests.DeviceRegistrationRequest; import net.jami.jams.common.objects.roots.X509Entity; import net.jami.jams.common.utils.X509Utils; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.io.InputStream; -import static org.junit.jupiter.api.Assertions.fail; - class JsoniterRegistryTest { static String strPrivateKey; @@ -42,7 +44,7 @@ class JsoniterRegistryTest { static String strPkcs10Request; @BeforeAll - public static void loadProps(){ + public static void loadProps() { try { JsoniterRegistry.initCodecs(); InputStream path; @@ -53,30 +55,29 @@ class JsoniterRegistryTest { strCertificate = new String(path.readAllBytes()); path = classLoader.getResourceAsStream("pkcs10request.txt"); strPkcs10Request = new String(path.readAllBytes()); - } - catch (Exception e){ + } catch (Exception e) { fail("Could not set-up resources for test!"); } } @Test - void X509SerializationAndDeserialization(){ + void X509SerializationAndDeserialization() { X509Entity entity = new X509Entity(); entity.setCertificate(X509Utils.getCertificateFromPEMString(strCertificate)); entity.setPrivateKey(X509Utils.getKeyFromPEMString(strPrivateKey)); String x = JsonStream.serialize(entity); - Assertions.assertNotNull(x,"Serialization failed!"); + Assertions.assertNotNull(x, "Serialization failed!"); entity = null; - entity = JsonIterator.deserialize(x,X509Entity.class); - Assertions.assertNotNull(entity.getCertificate(),"Certificate was not parsed!"); - Assertions.assertNotNull(entity.getPrivateKey(),"Private key was not parsed!"); + entity = JsonIterator.deserialize(x, X509Entity.class); + Assertions.assertNotNull(entity.getCertificate(), "Certificate was not parsed!"); + Assertions.assertNotNull(entity.getPrivateKey(), "Private key was not parsed!"); } @Test - void CSRDeserializeTest(){ + void CSRDeserializeTest() { String input = "{\"csr\":\"" + strPkcs10Request + "\"}"; - DeviceRegistrationRequest request = JsonIterator.deserialize(input, DeviceRegistrationRequest.class); - Assertions.assertNotNull(request.getCsr(),"CSR Should not have been null!"); + DeviceRegistrationRequest request = + JsonIterator.deserialize(input, DeviceRegistrationRequest.class); + Assertions.assertNotNull(request.getCsr(), "CSR Should not have been null!"); } - -} \ No newline at end of file +} diff --git a/jams-common/src/test/java/net/jami/jams/common/utils/PasswordGeneratorTest.java b/jams-common/src/test/java/net/jami/jams/common/utils/PasswordGeneratorTest.java index 9b431d55067b830ffb4ab37b1631eab02705bf60..866efbfdacd2658add34ce452d079f77e03a8503 100644 --- a/jams-common/src/test/java/net/jami/jams/common/utils/PasswordGeneratorTest.java +++ b/jams-common/src/test/java/net/jami/jams/common/utils/PasswordGeneratorTest.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.utils; import org.junit.jupiter.api.Test; @@ -31,4 +31,4 @@ class PasswordGeneratorTest { String res = PasswordGenerator.generatePassword(); System.out.println(res); } -} \ No newline at end of file +} diff --git a/jams-common/src/test/java/net/jami/jams/common/utils/VersioningUtilsTest.java b/jams-common/src/test/java/net/jami/jams/common/utils/VersioningUtilsTest.java index 6b36420a8862be064adc716d5190104ec958752f..558b110c8df3bf368f3566cc239a1b8c4d2d61f1 100644 --- a/jams-common/src/test/java/net/jami/jams/common/utils/VersioningUtilsTest.java +++ b/jams-common/src/test/java/net/jami/jams/common/utils/VersioningUtilsTest.java @@ -1,28 +1,29 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.utils; import net.jami.jams.common.updater.FileDescription; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -33,10 +34,8 @@ class VersioningUtilsTest { @Test @Disabled - public void testFileScan(){ + public void testFileScan() { HashMap<String, FileDescription> res = VersioningUtils.checkVersion(null); - Assertions.assertEquals(7,res.size(),"Incorrect number of versions detected!"); + Assertions.assertEquals(7, res.size(), "Incorrect number of versions detected!"); } - - -} \ No newline at end of file +} diff --git a/jams-common/src/test/java/net/jami/jams/common/utils/X509UtilsTest.java b/jams-common/src/test/java/net/jami/jams/common/utils/X509UtilsTest.java index 5f90b18c72618c91f30f383d38747afb6c65aacc..3e29e92dfd681999046e25caa5f2467ac589936c 100644 --- a/jams-common/src/test/java/net/jami/jams/common/utils/X509UtilsTest.java +++ b/jams-common/src/test/java/net/jami/jams/common/utils/X509UtilsTest.java @@ -1,27 +1,29 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.common.utils; +import static org.junit.jupiter.api.Assertions.fail; + import org.bouncycastle.pkcs.PKCS10CertificationRequest; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -31,8 +33,6 @@ import java.io.InputStream; import java.security.PrivateKey; import java.security.cert.X509Certificate; -import static org.junit.jupiter.api.Assertions.fail; - class X509UtilsTest { static String strPrivateKey; @@ -40,7 +40,7 @@ class X509UtilsTest { static String strPkcs10Request; @BeforeAll - public static void loadProps(){ + public static void loadProps() { try { InputStream path; ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); @@ -50,8 +50,7 @@ class X509UtilsTest { strCertificate = new String(path.readAllBytes()); path = classLoader.getResourceAsStream("pkcs10request.txt"); strPkcs10Request = new String(path.readAllBytes()); - } - catch (Exception e){ + } catch (Exception e) { fail("Could not set-up resources for test!"); } } @@ -60,46 +59,54 @@ class X509UtilsTest { void getKeyFromPEMString() { PrivateKey privateKey; privateKey = X509Utils.getKeyFromPEMString(strPrivateKey); - Assertions.assertNotNull(privateKey,"Could not decode a correctly formatted private key!"); + Assertions.assertNotNull(privateKey, "Could not decode a correctly formatted private key!"); privateKey = X509Utils.getKeyFromPEMString(strPrivateKey.substring(10)); - Assertions.assertNull(privateKey,"Decoded a private key from an incorrect string!"); + Assertions.assertNull(privateKey, "Decoded a private key from an incorrect string!"); } @Test void getCertificateFromPEMString() { X509Certificate x509Certificate; x509Certificate = X509Utils.getCertificateFromPEMString(strCertificate); - Assertions.assertNotNull(x509Certificate,"Could not decoded a correctly formatted certificate!"); + Assertions.assertNotNull( + x509Certificate, "Could not decoded a correctly formatted certificate!"); x509Certificate = X509Utils.getCertificateFromPEMString(strCertificate.substring(25)); - Assertions.assertNull(x509Certificate,"Decoded certificate from an incorrect string!"); + Assertions.assertNull(x509Certificate, "Decoded certificate from an incorrect string!"); } @Test void getPEMStringFromPrivateKey() { PrivateKey privateKey; privateKey = X509Utils.getKeyFromPEMString(strPrivateKey); - Assertions.assertNotNull(privateKey,"Could not decode a correctly formatted private key!"); + Assertions.assertNotNull(privateKey, "Could not decode a correctly formatted private key!"); String str = X509Utils.getPEMStringFromPrivateKey(privateKey); PrivateKey privateKey1 = X509Utils.getKeyFromPEMString(str); - Assertions.assertEquals(privateKey,privateKey1,"Keys do not match - although they should!"); + Assertions.assertEquals( + privateKey, privateKey1, "Keys do not match - although they should!"); } @Test void getPEMStringFromCertificate() { X509Certificate x509Certificate; x509Certificate = X509Utils.getCertificateFromPEMString(strCertificate); - Assertions.assertNotNull(x509Certificate,"Could not decoded a correctly formatted certificate!"); + Assertions.assertNotNull( + x509Certificate, "Could not decoded a correctly formatted certificate!"); String str = X509Utils.getPEMStringFromCertificate(x509Certificate); X509Certificate x509Certificate1 = X509Utils.getCertificateFromPEMString(str); - Assertions.assertEquals(x509Certificate,x509Certificate1,"Certificates do not match - although they should!"); + Assertions.assertEquals( + x509Certificate, + x509Certificate1, + "Certificates do not match - although they should!"); } @Test void getCSRFromString() { PKCS10CertificationRequest certificationRequest; certificationRequest = X509Utils.getCSRFromString(strPkcs10Request); - Assertions.assertNotNull(certificationRequest,"Certification request should have been parsed correctly!"); + Assertions.assertNotNull( + certificationRequest, "Certification request should have been parsed correctly!"); certificationRequest = X509Utils.getCSRFromString(strPkcs10Request.substring(23)); - Assertions.assertNull(certificationRequest,"Certification request should not have been parsed!"); + Assertions.assertNull( + certificationRequest, "Certification request should not have been parsed!"); } -} \ No newline at end of file +} diff --git a/jams-launcher/src/main/java/launcher/AppStarter.java b/jams-launcher/src/main/java/launcher/AppStarter.java index c1baf0b3e3ea9677b139036026009e4702d589e0..7a69a7f389cde8c1c250422cf27a0cdc7bd49d84 100644 --- a/jams-launcher/src/main/java/launcher/AppStarter.java +++ b/jams-launcher/src/main/java/launcher/AppStarter.java @@ -24,9 +24,11 @@ package launcher; import launcher.zmq.MessageReceiver; + import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; + import org.zeromq.SocketType; import org.zeromq.ZMQ; @@ -53,18 +55,20 @@ public class AppStarter extends Thread { * The problematic here is whenever we will fire up a JAR (but then we need to be able to * kill and restart his PID, or whenever we fork via a main). */ - private void setupZmqBridge(){ + private void setupZmqBridge() { publisher = context.socket(SocketType.PUB); publisher.bind("tcp://*:4572"); - //Use this to updater. + // Use this to updater. receiver = context.socket(SocketType.REP); receiver.bind("tcp://*:4573"); messageReceiver = new MessageReceiver(receiver, doUpdate); messageReceiver.start(); } - private void unpackUpdate(){ - for (File f : Objects.requireNonNull(new File(System.getProperty("user.dir") + "/tmp/").listFiles())) { + private void unpackUpdate() { + for (File f : + Objects.requireNonNull( + new File(System.getProperty("user.dir") + "/tmp/").listFiles())) { if (f.getName().contains("jams-server")) { if (!f.renameTo(new File(System.getProperty("user.dir") + "/" + f.getName()))) { log.info("An error occurred while attempting to move the file!"); @@ -72,7 +76,8 @@ public class AppStarter extends Thread { f.delete(); } } else { - if (!f.renameTo(new File(System.getProperty("user.dir") + "/libs/" + f.getName()))) { + if (!f.renameTo( + new File(System.getProperty("user.dir") + "/libs/" + f.getName()))) { log.info("An error occurred while attempting to move the file!"); } else { f.delete(); @@ -83,18 +88,21 @@ public class AppStarter extends Thread { new File(System.getProperty("user.dir") + "/tmp/").delete(); } - public AppStarter(String[] args) { parentArgs = args; try { jamsProcessId = startAccountManagementServer(args); setupZmqBridge(); - Runtime.getRuntime().addShutdownHook(new Thread(() -> { - log.info("Shutting down..."); - ProcessHandle.of(jamsProcessId).get().destroyForcibly(); - })); + Runtime.getRuntime() + .addShutdownHook( + new Thread( + () -> { + log.info("Shutting down..."); + ProcessHandle.of(jamsProcessId).get().destroyForcibly(); + })); } catch (Exception e) { - log.warn("Could not create and bind publisher and/or receiver! Please contact software developer"); + log.warn( + "Could not create and bind publisher and/or receiver! Please contact software developer"); System.exit(-1); } } @@ -104,11 +112,11 @@ public class AppStarter extends Thread { appStarter.start(); } - //How this works - once the JAMSUpdater has notified back upstream to do an update, we lockdown - //and run the good old routine + // How this works - once the JAMSUpdater has notified back upstream to do an update, we lockdown + // and run the good old routine @Override public void run() { - //TODO: Hack this a bit to get it to work better - passing arguments damnit. + // TODO: Hack this a bit to get it to work better - passing arguments damnit. while (true) { try { if (doUpdate.get()) { @@ -116,7 +124,7 @@ public class AppStarter extends Thread { ProcessHandle.of(jamsProcessId).get().destroyForcibly(); // transfer newly downloaded files to the right folder. doUpdate.set(false); - //Upack the update. + // Upack the update. unpackUpdate(); // Restart the main JAR and set the processId to it. jamsProcessId = startAccountManagementServer(parentArgs); @@ -126,8 +134,10 @@ public class AppStarter extends Thread { doUpdate.wait(); } } catch (Exception e) { - log.error("An error occurred. Either while attempting to verify if an update was available, or" + - "when attempting to reload a library: {}", e.getMessage()); + log.error( + "An error occurred. Either while attempting to verify if an update was available, or" + + "when attempting to reload a library: {}", + e.getMessage()); } } } @@ -140,8 +150,15 @@ public class AppStarter extends Thread { pb = new ProcessBuilder("java", "-jar", "jams-server.jar", parentArgs[0]); break; case 3: - pb = new ProcessBuilder("java", "-Dorg.ldaptive.sortSearchResults=true", "-jar", "jams-server.jar", - parentArgs[0], parentArgs[1], parentArgs[2]); + pb = + new ProcessBuilder( + "java", + "-Dorg.ldaptive.sortSearchResults=true", + "-jar", + "jams-server.jar", + parentArgs[0], + parentArgs[1], + parentArgs[2]); break; default: pb = new ProcessBuilder("java", "-jar", "jams-server.jar", "8080"); @@ -153,4 +170,4 @@ public class AppStarter extends Thread { p = pb.start(); return p.pid(); } -} \ No newline at end of file +} diff --git a/jams-launcher/src/main/java/launcher/zmq/MessageReceiver.java b/jams-launcher/src/main/java/launcher/zmq/MessageReceiver.java index 705b3c4505b4763f26f67785d4862b4eaf8f9d71..f480bf8a0ed6e6b16beec275e98237befc04c506 100644 --- a/jams-launcher/src/main/java/launcher/zmq/MessageReceiver.java +++ b/jams-launcher/src/main/java/launcher/zmq/MessageReceiver.java @@ -1,6 +1,7 @@ package launcher.zmq; import lombok.Getter; + import org.zeromq.ZMQ; import java.util.concurrent.atomic.AtomicBoolean; @@ -18,21 +19,19 @@ public class MessageReceiver extends Thread { @Override public void run() { - while(true){ - try{ + while (true) { + try { String message = socket.recvStr(); - if(message.equals("DO-UPDATE")) { - //Use wait-notify mechanism to avoid burning CPU cycles. + if (message.equals("DO-UPDATE")) { + // Use wait-notify mechanism to avoid burning CPU cycles. synchronized (atomicBoolean) { atomicBoolean.set(true); atomicBoolean.notify(); } } - } - catch (Exception e){ + } catch (Exception e) { System.out.println("Some exception occurred!"); } } } } - diff --git a/jams-server/src/main/java/net/jami/jams/server/Server.java b/jams-server/src/main/java/net/jami/jams/server/Server.java index 7b9341d6e5c8a34a6130cd5c1bbbb3884dd32408..40488b8ca56d009ab80012f362c2344c83c5a081 100644 --- a/jams-server/src/main/java/net/jami/jams/server/Server.java +++ b/jams-server/src/main/java/net/jami/jams/server/Server.java @@ -23,8 +23,11 @@ package net.jami.jams.server; import com.jsoniter.JsonIterator; + import javassist.ClassPool; + import lombok.extern.slf4j.Slf4j; + import net.jami.datastore.main.DataStore; import net.jami.jams.common.annotations.ScopedServletAnnotationScanner; import net.jami.jams.common.authentication.AuthenticationSourceType; @@ -55,8 +58,8 @@ import java.util.concurrent.atomic.AtomicBoolean; // a thread. public class Server { - public final static AtomicBoolean isInstalled = new AtomicBoolean(false); - public final static AtomicBoolean activated = new AtomicBoolean(false); + public static final AtomicBoolean isInstalled = new AtomicBoolean(false); + public static final AtomicBoolean activated = new AtomicBoolean(false); public static DataStore dataStore; // This one gets loaded via JAR, to make it more flexible. @@ -73,7 +76,13 @@ public class Server { ClassPool.getDefault().clearImportedPackages(); ScopedServletAnnotationScanner scanner = new ScopedServletAnnotationScanner(); scanner.processClasses( - new java.io.File(Server.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getName()); + new java.io.File( + Server.class + .getProtectionDomain() + .getCodeSource() + .getLocation() + .getPath()) + .getName()); switch (args.length) { case 1: tomcatLauncher = new TomcatLauncher(Integer.parseInt(args[0])); @@ -104,44 +113,63 @@ public class Server { } } - isInstalled.set(new File(System.getProperty("user.dir") + File.separator + "config.json").exists()); + isInstalled.set( + new File(System.getProperty("user.dir") + File.separator + "config.json").exists()); log.info("Server is already installed: " + isInstalled.get()); ServerSettings serverSettings = null; if (isInstalled.get()) { try { - InputStream path = new FileInputStream( - new File(System.getProperty("user.dir") + File.separator + "config.json")); - serverSettings = JsonIterator.deserialize(path.readAllBytes(), ServerSettings.class); - certificateAuthority = CryptoEngineLoader.loadCertificateAuthority(serverSettings.getCaConfiguration(), - dataStore); - userAuthenticationModule = AuthModuleLoader.loadAuthenticationModule(dataStore, certificateAuthority); + InputStream path = + new FileInputStream( + new File( + System.getProperty("user.dir") + + File.separator + + "config.json")); + serverSettings = + JsonIterator.deserialize(path.readAllBytes(), ServerSettings.class); + certificateAuthority = + CryptoEngineLoader.loadCertificateAuthority( + serverSettings.getCaConfiguration(), dataStore); + userAuthenticationModule = + AuthModuleLoader.loadAuthenticationModule(dataStore, certificateAuthority); if (serverSettings.getLdapConfiguration() != null) - userAuthenticationModule.attachAuthSource(AuthenticationSourceType.LDAP, - serverSettings.getLdapConfiguration()); + userAuthenticationModule.attachAuthSource( + AuthenticationSourceType.LDAP, serverSettings.getLdapConfiguration()); if (serverSettings.getActiveDirectoryConfiguration() != null) { - userAuthenticationModule.attachAuthSource(AuthenticationSourceType.AD, + userAuthenticationModule.attachAuthSource( + AuthenticationSourceType.AD, serverSettings.getActiveDirectoryConfiguration()); } if (serverSettings.getLocalDirectoryConfiguration() != null) { - LocalAuthSettings settings = JsonIterator - .deserialize(serverSettings.getLocalDirectoryConfiguration(), LocalAuthSettings.class); + LocalAuthSettings settings = + JsonIterator.deserialize( + serverSettings.getLocalDirectoryConfiguration(), + LocalAuthSettings.class); if (settings.getPublicNames()) nameServer = new PublicNameServer(settings.getPublicNameServer()); else - nameServer = new LocalNameServer(dataStore, userAuthenticationModule, - serverSettings.getServerPublicURI()); + nameServer = + new LocalNameServer( + dataStore, + userAuthenticationModule, + serverSettings.getServerPublicURI()); } else - nameServer = new LocalNameServer(dataStore, userAuthenticationModule, - serverSettings.getServerPublicURI()); + nameServer = + new LocalNameServer( + dataStore, + userAuthenticationModule, + serverSettings.getServerPublicURI()); licenseService.loadLicense(); log.info("All services are UP and ready for use..."); } catch (Exception e) { - log.error("Could not load configuration file or initialize some components - this is critical"); + log.error( + "Could not load configuration file or initialize some components - this is critical"); } } else { certificateAuthority = CryptoEngineLoader.loadCertificateAuthority(null, dataStore); - userAuthenticationModule = AuthModuleLoader.loadAuthenticationModule(dataStore, certificateAuthority); + userAuthenticationModule = + AuthModuleLoader.loadAuthenticationModule(dataStore, certificateAuthority); log.info("Started server with empty modules waiting for setup..."); } // Now pop-up the GUI @@ -152,7 +180,6 @@ public class Server { } catch (Exception e) { log.error("Could not start GUI with error {}", e.getMessage()); } - } public static void startGUI() throws Exception { @@ -164,12 +191,20 @@ public class Server { } } log.info("Authentication module is ready!"); - if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { - Desktop.getDesktop().browse(new URI(tomcatLauncher.getTomcat().getConnector().getScheme() + "://localhost:" - + tomcatLauncher.getTomcat().getService().findConnectors()[0].getPort())); + if (Desktop.isDesktopSupported() + && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { + Desktop.getDesktop() + .browse( + new URI( + tomcatLauncher.getTomcat().getConnector().getScheme() + + "://localhost:" + + tomcatLauncher + .getTomcat() + .getService() + .findConnectors()[0] + .getPort())); } else { log.info("There is no graphical interface on this system - please connect remotely!"); } } - } diff --git a/jams-server/src/main/java/net/jami/jams/server/core/TomcatConnectorFactory.java b/jams-server/src/main/java/net/jami/jams/server/core/TomcatConnectorFactory.java index a219f4aeb15a1c65b3dae709b88ca7c89389f906..0a3a666a836095951182e3ea30ea825fa32406aa 100644 --- a/jams-server/src/main/java/net/jami/jams/server/core/TomcatConnectorFactory.java +++ b/jams-server/src/main/java/net/jami/jams/server/core/TomcatConnectorFactory.java @@ -1,28 +1,29 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.core; import lombok.extern.slf4j.Slf4j; + import org.apache.catalina.connector.Connector; import org.apache.tomcat.util.net.SSLHostConfig; import org.apache.tomcat.util.net.SSLHostConfigCertificate; @@ -32,23 +33,30 @@ import java.io.File; @Slf4j public class TomcatConnectorFactory { - public static Connector getSSLConnectorWithTrustStore(String certificateFile, String keyFile, int port) { + public static Connector getSSLConnectorWithTrustStore( + String certificateFile, String keyFile, int port) { log.info(System.getProperty("user.dir") + File.separator + "keystore.jks"); Connector connector = getSSLConnectorWithoutTrustStore(certificateFile, keyFile, port); - connector.findSslHostConfigs()[0].setTruststoreFile(System.getProperty("user.dir") + File.separator + "keystore.jks"); + connector.findSslHostConfigs()[0].setTruststoreFile( + System.getProperty("user.dir") + File.separator + "keystore.jks"); connector.findSslHostConfigs()[0].setTruststorePassword("changeit"); connector.findSslHostConfigs()[0].setCertificateVerification("optional"); return connector; } - public static Connector getSSLConnectorWithoutTrustStore(String certificateFile, String keyFile, int port) { - //Check if trust store exists or create it if necessary. + public static Connector getSSLConnectorWithoutTrustStore( + String certificateFile, String keyFile, int port) { + // Check if trust store exists or create it if necessary. Connector connector = new Connector(); SSLHostConfig sslConfig = new SSLHostConfig(); - SSLHostConfigCertificate sslHostConfigCertificate = new SSLHostConfigCertificate(sslConfig, SSLHostConfigCertificate.Type.RSA); - sslHostConfigCertificate.setCertificateChainFile(System.getProperty("user.dir") + File.separator + certificateFile); - sslHostConfigCertificate.setCertificateFile(System.getProperty("user.dir") + File.separator + certificateFile); - sslHostConfigCertificate.setCertificateKeyFile(System.getProperty("user.dir") + File.separator + keyFile); + SSLHostConfigCertificate sslHostConfigCertificate = + new SSLHostConfigCertificate(sslConfig, SSLHostConfigCertificate.Type.RSA); + sslHostConfigCertificate.setCertificateChainFile( + System.getProperty("user.dir") + File.separator + certificateFile); + sslHostConfigCertificate.setCertificateFile( + System.getProperty("user.dir") + File.separator + certificateFile); + sslHostConfigCertificate.setCertificateKeyFile( + System.getProperty("user.dir") + File.separator + keyFile); sslConfig.addCertificate(sslHostConfigCertificate); sslConfig.setProtocols("TLSv1,TLSv1.2,TLSv1.3"); connector.addSslHostConfig(sslConfig); @@ -59,13 +67,10 @@ public class TomcatConnectorFactory { return connector; } - public static Connector getNoSSLConnector(int port) { Connector connector = new Connector(); connector.setPort(port); connector.setScheme("http"); return connector; } - - } diff --git a/jams-server/src/main/java/net/jami/jams/server/core/TomcatLauncher.java b/jams-server/src/main/java/net/jami/jams/server/core/TomcatLauncher.java index fb0ab3d95c18024d335b1dfa7d781706a11ccbfb..59bd23119710461d5190d18450abdc9faafb5d9d 100644 --- a/jams-server/src/main/java/net/jami/jams/server/core/TomcatLauncher.java +++ b/jams-server/src/main/java/net/jami/jams/server/core/TomcatLauncher.java @@ -23,8 +23,11 @@ package net.jami.jams.server.core; +import static net.jami.jams.server.Server.certificateAuthority; + import lombok.Getter; import lombok.extern.slf4j.Slf4j; + import org.apache.catalina.WebResourceRoot; import org.apache.catalina.connector.Connector; import org.apache.catalina.core.StandardContext; @@ -37,13 +40,11 @@ import org.apache.tomcat.util.descriptor.web.ErrorPage; import java.io.File; import java.nio.file.Files; -import java.nio.file.Paths; import java.nio.file.Path; +import java.nio.file.Paths; -import static net.jami.jams.server.Server.certificateAuthority; - -//This class boots the tomcat server which provides the subsystem -//for the API calls. +// This class boots the tomcat server which provides the subsystem +// for the API calls. @Slf4j @Getter public class TomcatLauncher { @@ -60,29 +61,44 @@ public class TomcatLauncher { public void swapConnectors() { if (getTomcat().getConnector().findSslHostConfigs() != null && getTomcat().getConnector().findSslHostConfigs().length > 0) { - getTomcat().getConnector().findSslHostConfigs()[0] - .setTruststoreFile(System.getProperty("user.dir") + File.separator + "keystore.jks"); + getTomcat() + .getConnector() + .findSslHostConfigs()[0] + .setTruststoreFile( + System.getProperty("user.dir") + File.separator + "keystore.jks"); getTomcat().getConnector().findSslHostConfigs()[0].setTruststorePassword("changeit"); - getTomcat().getConnector().findSslHostConfigs()[0].setCertificateVerification("optional"); - ((Http11NioProtocol) getTomcat().getConnector().getProtocolHandler()).reloadSslHostConfigs(); + getTomcat() + .getConnector() + .findSslHostConfigs()[0] + .setCertificateVerification("optional"); + ((Http11NioProtocol) getTomcat().getConnector().getProtocolHandler()) + .reloadSslHostConfigs(); } else { - log.error("Could not reload SSL configuration because the server is not running over SSL!"); + log.error( + "Could not reload SSL configuration because the server is not running over SSL!"); } } public TomcatLauncher(int port, String certificateFile, String keyFile) { - if (!Files.exists(Paths.get(System.getProperty("user.dir") + File.separator + certificateFile)) - || !Files.exists(Paths.get(System.getProperty("user.dir") + File.separator + keyFile))) { + if (!Files.exists( + Paths.get( + System.getProperty("user.dir") + File.separator + certificateFile)) + || !Files.exists( + Paths.get(System.getProperty("user.dir") + File.separator + keyFile))) { log.info("Could not find certificate or keyfile, exiting"); System.exit(1); } - if (Files.exists(Paths.get(System.getProperty("user.dir") + File.separator + "keystore.jks"))) { + if (Files.exists( + Paths.get(System.getProperty("user.dir") + File.separator + "keystore.jks"))) { log.info("Found a valid trust store, injecting into tomcat!"); tomcat.getService() - .addConnector(TomcatConnectorFactory.getSSLConnectorWithTrustStore(certificateFile, keyFile, port)); + .addConnector( + TomcatConnectorFactory.getSSLConnectorWithTrustStore( + certificateFile, keyFile, port)); } else { - Connector connector = TomcatConnectorFactory.getSSLConnectorWithoutTrustStore(certificateFile, keyFile, - port); + Connector connector = + TomcatConnectorFactory.getSSLConnectorWithoutTrustStore( + certificateFile, keyFile, port); tomcat.getService().addConnector(connector); } this.startServer(); @@ -91,7 +107,8 @@ public class TomcatLauncher { public void startServer() { String jarName = System.getProperty("user.dir") + File.separator + "jams-server.jar"; log.info("JAR Resource File = " + jarName); - String contextPath = new File(System.getProperty("user.dir")).getAbsolutePath() + File.separator + "app"; + String contextPath = + new File(System.getProperty("user.dir")).getAbsolutePath() + File.separator + "app"; try { Path path = Paths.get(contextPath); Files.createDirectories(path); @@ -104,20 +121,29 @@ public class TomcatLauncher { WebResourceRoot resources = new StandardRoot(context); if (jarName.contains(".jar")) { resources.addPreResources( - new JarResourceSet(resources, "/WEB-INF/classes", jarName, "/net/jami/jams/server/servlets")); + new JarResourceSet( + resources, + "/WEB-INF/classes", + jarName, + "/net/jami/jams/server/servlets")); resources.addPreResources(new JarResourceSet(resources, "/", jarName, "/webapp")); } else { - log.info("WARNING: You are running from your local filesystem, this makes sense only for developers!"); + log.info( + "WARNING: You are running from your local filesystem, this makes sense only for developers!"); StringBuilder basePath = new StringBuilder(); String[] paths = System.getProperty("user.dir").split("/"); for (int i = 0; i < paths.length - 1; i++) { basePath.append("/").append(paths[i]); } basePath.append("/jams-server"); - resources.addPreResources(new DirResourceSet(resources, "/WEB-INF/classes", - basePath.toString() + "/target/classes/net/jami/jams/server/servlets", "/")); resources.addPreResources( - new DirResourceSet(resources, "/", basePath.toString() + "/target/classes", "/webapp")); + new DirResourceSet( + resources, + "/WEB-INF/classes", + basePath + "/target/classes/net/jami/jams/server/servlets", + "/")); + resources.addPreResources( + new DirResourceSet(resources, "/", basePath + "/target/classes", "/webapp")); } context.setResources(resources); // We always go to login by default. diff --git a/jams-server/src/main/java/net/jami/jams/server/core/workflows/ActivateSubscriptionWorkflow.java b/jams-server/src/main/java/net/jami/jams/server/core/workflows/ActivateSubscriptionWorkflow.java index d677be0e6ed84338cda4a42a256387f30c44ce80..c10cb2b2e900974e6d775d2a6d1be4d3d17d8dc3 100644 --- a/jams-server/src/main/java/net/jami/jams/server/core/workflows/ActivateSubscriptionWorkflow.java +++ b/jams-server/src/main/java/net/jami/jams/server/core/workflows/ActivateSubscriptionWorkflow.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.core.workflows; import lombok.extern.slf4j.Slf4j; @@ -30,28 +30,26 @@ import java.security.KeyStore; @Slf4j public class ActivateSubscriptionWorkflow { - public static boolean activateSubscription(String data){ + public static boolean activateSubscription(String data) { try { - //TODO: Decode the the data into a certificate and private key. + // TODO: Decode the the data into a certificate and private key. - //TODO: Verify that the certificate has really been signed by SavoirFaireLinux and is valid. + // TODO: Verify that the certificate has really been signed by SavoirFaireLinux and is + // valid. - //Build a keystore from the data. + // Build a keystore from the data. KeyStore ks = KeyStore.getInstance("JKS"); char[] password = "changeit".toCharArray(); ks.load(null, password); - ks.setKeyEntry("license",null,null); + ks.setKeyEntry("license", null, null); FileOutputStream fos = new FileOutputStream("license.jks"); ks.store(fos, password); fos.close(); log.info("Succesfully activated your license!"); return true; - } - catch (Exception e){ - log.error("The activation process failed with error: {}",e.getMessage()); + } catch (Exception e) { + log.error("The activation process failed with error: {}", e.getMessage()); return false; } } - - } diff --git a/jams-server/src/main/java/net/jami/jams/server/core/workflows/InstallationFinalizer.java b/jams-server/src/main/java/net/jami/jams/server/core/workflows/InstallationFinalizer.java index 05fd342990b4ade6fcc61461a12a87a49534f767..62f66789e53904ce0ef311af82bfae8681ff55d5 100644 --- a/jams-server/src/main/java/net/jami/jams/server/core/workflows/InstallationFinalizer.java +++ b/jams-server/src/main/java/net/jami/jams/server/core/workflows/InstallationFinalizer.java @@ -1,29 +1,37 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.core.workflows; +import static net.jami.jams.server.Server.certificateAuthority; +import static net.jami.jams.server.Server.dataStore; +import static net.jami.jams.server.Server.nameServer; +import static net.jami.jams.server.Server.tomcatLauncher; +import static net.jami.jams.server.Server.userAuthenticationModule; + import com.jsoniter.output.JsonStream; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.authentication.AuthenticationSourceType; import net.jami.jams.common.objects.roots.X509Fields; import net.jami.jams.common.objects.system.SystemAccount; @@ -40,43 +48,47 @@ import java.io.FileOutputStream; import java.io.OutputStream; import java.security.KeyStore; -import static net.jami.jams.server.Server.certificateAuthority; -import static net.jami.jams.server.Server.dataStore; -import static net.jami.jams.server.Server.nameServer; -import static net.jami.jams.server.Server.tomcatLauncher; -import static net.jami.jams.server.Server.userAuthenticationModule; - @Slf4j public class InstallationFinalizer { private boolean useLocalNS = true; public boolean finalizeInstallation() { - //Basically here we build the config and flush it. + // Basically here we build the config and flush it. try { log.info("Building configuration from submitted variables..."); ServerSettings serverSettings = new ServerSettings(); - serverSettings.setCaConfiguration(JsonStream.serialize(CachedObjects.certificateAuthorityConfig)); - //TODO: This is a bit of hack, we should fix this someday. - serverSettings.setServerPublicURI(CachedObjects.certificateAuthorityConfig.getServerDomain()); + serverSettings.setCaConfiguration( + JsonStream.serialize(CachedObjects.certificateAuthorityConfig)); + // TODO: This is a bit of hack, we should fix this someday. + serverSettings.setServerPublicURI( + CachedObjects.certificateAuthorityConfig.getServerDomain()); if (CachedObjects.activeDirectorySettings != null) { - serverSettings.setActiveDirectoryConfiguration(JsonStream.serialize(CachedObjects.activeDirectorySettings)); - log.info("Server configured to use Active Directory as the authentication backend!"); + serverSettings.setActiveDirectoryConfiguration( + JsonStream.serialize(CachedObjects.activeDirectorySettings)); + log.info( + "Server configured to use Active Directory as the authentication backend!"); } if (CachedObjects.ldapSettings != null) { - serverSettings.setLdapConfiguration(JsonStream.serialize(CachedObjects.ldapSettings)); + serverSettings.setLdapConfiguration( + JsonStream.serialize(CachedObjects.ldapSettings)); log.info("Server configured to use LDAP as the authentication backend!"); } if (CachedObjects.localAuthSettings != null) { - serverSettings.setLocalDirectoryConfiguration(JsonStream.serialize(CachedObjects.localAuthSettings)); + serverSettings.setLocalDirectoryConfiguration( + JsonStream.serialize(CachedObjects.localAuthSettings)); if (CachedObjects.localAuthSettings.getPublicNames()) { useLocalNS = false; - nameServer = new PublicNameServer(CachedObjects.localAuthSettings.getPublicNameServer()); - log.warn("Server configured to use {} as the nameserver for Jami clients !", CachedObjects.localAuthSettings.getPublicNameServer()); + nameServer = + new PublicNameServer( + CachedObjects.localAuthSettings.getPublicNameServer()); + log.warn( + "Server configured to use {} as the nameserver for Jami clients !", + CachedObjects.localAuthSettings.getPublicNameServer()); } log.info("Server is configured to use local authentication engine"); } - //Now flush the server settings. + // Now flush the server settings. OutputStream os = new FileOutputStream(new File("config.json")); os.write(JsonStream.serialize(serverSettings).getBytes()); os.flush(); @@ -99,35 +111,44 @@ public class InstallationFinalizer { certificateAuthority.getSignedCertificate(ocspAccount); dataStore.getSystemDao().storeObject(ocspAccount); log.info("Successfully created and stored the OCSP certificate"); - certificateAuthority.init(serverSettings.getCaConfiguration(), caAccount, ocspAccount); - log.info("Succesfully inited the certificate authority with the appropriate settings..."); + certificateAuthority.init( + serverSettings.getCaConfiguration(), caAccount, ocspAccount); + log.info( + "Succesfully inited the certificate authority with the appropriate settings..."); } log.info("Initializing the selected authentication providers"); - userAuthenticationModule = AuthModuleLoader.loadAuthenticationModule(dataStore, certificateAuthority); - if(serverSettings.getActiveDirectoryConfiguration() != null) - userAuthenticationModule.attachAuthSource(AuthenticationSourceType.AD,serverSettings.getActiveDirectoryConfiguration()); - if(serverSettings.getLdapConfiguration() != null) - userAuthenticationModule.attachAuthSource(AuthenticationSourceType.LDAP,serverSettings.getLdapConfiguration()); - if(useLocalNS) nameServer = new LocalNameServer(dataStore,userAuthenticationModule,serverSettings.getServerPublicURI()); + userAuthenticationModule = + AuthModuleLoader.loadAuthenticationModule(dataStore, certificateAuthority); + if (serverSettings.getActiveDirectoryConfiguration() != null) + userAuthenticationModule.attachAuthSource( + AuthenticationSourceType.AD, + serverSettings.getActiveDirectoryConfiguration()); + if (serverSettings.getLdapConfiguration() != null) + userAuthenticationModule.attachAuthSource( + AuthenticationSourceType.LDAP, serverSettings.getLdapConfiguration()); + if (useLocalNS) + nameServer = + new LocalNameServer( + dataStore, + userAuthenticationModule, + serverSettings.getServerPublicURI()); log.info("Building keystore for client auth for tomcat..."); KeyStore ks = KeyStore.getInstance("JKS"); char[] password = "changeit".toCharArray(); ks.load(null, password); - ks.setCertificateEntry("jams-ca",certificateAuthority.getCA()); - FileOutputStream fos = new FileOutputStream( "keystore.jks"); + ks.setCertificateEntry("jams-ca", certificateAuthority.getCA()); + FileOutputStream fos = new FileOutputStream("keystore.jks"); ks.store(fos, password); fos.close(); log.info("Successfully built keystore for for tomcat!"); Server.isInstalled.set(true); - //fix to swap connectors - this assumes you are running with an SSL certificate + // fix to swap connectors - this assumes you are running with an SSL certificate tomcatLauncher.swapConnectors(); log.info("The installation has completed successfully, you can now use JAMS!"); } catch (Exception e) { - log.error("Could not save settings to disk with error: " + e.toString()); + log.error("Could not save settings to disk with error: " + e); return false; } return true; } - - } diff --git a/jams-server/src/main/java/net/jami/jams/server/core/workflows/RegisterDeviceFlow.java b/jams-server/src/main/java/net/jami/jams/server/core/workflows/RegisterDeviceFlow.java index ac186055912445ffa8d12bdabfdd9d0eda39a5ac..ccc9a9123045fcf460b4c5c9474b13f40bbe54a4 100644 --- a/jams-server/src/main/java/net/jami/jams/server/core/workflows/RegisterDeviceFlow.java +++ b/jams-server/src/main/java/net/jami/jams/server/core/workflows/RegisterDeviceFlow.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.core.workflows; import static net.jami.jams.authmodule.UserAuthenticationModule.datastore; @@ -28,12 +28,8 @@ import static net.jami.jams.server.Server.dataStore; import static net.jami.jams.server.Server.nameServer; import static net.jami.jams.server.Server.userAuthenticationModule; -import java.security.cert.X509Certificate; -import java.util.Date; -import java.util.List; -import java.util.Optional; - import lombok.extern.slf4j.Slf4j; + import net.jami.jams.authmodule.UserAuthenticationModule; import net.jami.jams.common.authmodule.AuthModuleKey; import net.jami.jams.common.dao.StatementElement; @@ -48,22 +44,31 @@ import net.jami.jams.common.objects.user.UserGroupMapping; import net.jami.jams.common.objects.user.UserProfile; import net.jami.jams.dht.DeviceReceiptGenerator; +import java.security.cert.X509Certificate; +import java.util.Date; +import java.util.List; +import java.util.Optional; + @Slf4j public class RegisterDeviceFlow { - public static DeviceRegistrationResponse registerDevice(String username, - DeviceRegistrationRequest registrationRequest) { + public static DeviceRegistrationResponse registerDevice( + String username, DeviceRegistrationRequest registrationRequest) { try { StatementList statementList = new StatementList(); statementList.addStatement(new StatementElement("username", "=", username, "")); User user = dataStore.getUserDao().getObjects(statementList).get(0); - UserProfile userProfile = userAuthenticationModule.getAuthSources() - .get(new AuthModuleKey(user.getRealm(), user.getUserType())) - .searchUserProfiles(username, "LOGON_NAME", Optional.empty()).get(0); + UserProfile userProfile = + userAuthenticationModule + .getAuthSources() + .get(new AuthModuleKey(user.getRealm(), user.getUserType())) + .searchUserProfiles(username, "LOGON_NAME", Optional.empty()) + .get(0); if (user == null) { - log.error("Tried to enroll a device, but could not find a user, this is impossible!"); + log.error( + "Tried to enroll a device, but could not find a user, this is impossible!"); } // Renew user certificate if expired with same private key @@ -92,8 +97,12 @@ public class RegisterDeviceFlow { } // Device receipt - String[] devReceipt = DeviceReceiptGenerator.generateReceipt(user.getPrivateKey(), - user.getCertificate().getPublicKey(), device.getCertificate().getPublicKey(), user.getEthAddress()); + String[] devReceipt = + DeviceReceiptGenerator.generateReceipt( + user.getPrivateKey(), + user.getCertificate().getPublicKey(), + device.getCertificate().getPublicKey(), + user.getEthAddress()); response.setDeviceReceipt(devReceipt[0]); response.setReceiptSignature(devReceipt[1]); response.setDisplayName(userProfile.getFirstName() + " " + userProfile.getLastName()); @@ -102,11 +111,15 @@ public class RegisterDeviceFlow { if (userProfile.getProfilePicture() != null) response.setUserPhoto(userProfile.getProfilePicture()); // Chain certificate - response.setCertificateChain(new X509Certificate[] { certificateAuthority.getCA(), user.getCertificate(), - device.getCertificate() }); + response.setCertificateChain( + new X509Certificate[] { + certificateAuthority.getCA(), user.getCertificate(), device.getCertificate() + }); return response; } catch (Exception e) { - log.error("An exception has occurred while trying to enroll a device with error {}", e.getMessage()); + log.error( + "An exception has occurred while trying to enroll a device with error {}", + e.getMessage()); return null; } } @@ -116,7 +129,8 @@ public class RegisterDeviceFlow { StatementList statementList = new StatementList(); statementList.addStatement(new StatementElement("username", "=", username, "")); - List<UserGroupMapping> userGroupMappings = dataStore.getUserGroupMappingsDao().getObjects(statementList); + List<UserGroupMapping> userGroupMappings = + dataStore.getUserGroupMappingsDao().getObjects(statementList); if (userGroupMappings != null && !userGroupMappings.isEmpty()) { UserGroupMapping mapping = userGroupMappings.get(0); @@ -130,14 +144,16 @@ public class RegisterDeviceFlow { public static String getPolicyData(Group group) { if (!group.isEmpty() && group.hasBlueprint()) { - StatementElement statementElement = new StatementElement("name", "=", group.getBlueprint(), ""); + StatementElement statementElement = + new StatementElement("name", "=", group.getBlueprint(), ""); StatementList statementList = new StatementList(); statementList.addStatement(statementElement); try { Policy policy = dataStore.getPolicyDao().getObjects(statementList).get(0); return policy.getPolicyData(); } catch (Exception e) { - log.warn("No policy available for user - not adding a policy component to response"); + log.warn( + "No policy available for user - not adding a policy component to response"); } } diff --git a/jams-server/src/main/java/net/jami/jams/server/core/workflows/RevokeDeviceFlow.java b/jams-server/src/main/java/net/jami/jams/server/core/workflows/RevokeDeviceFlow.java index 986629fc432e9137b82648b6f88aa4ccc77ddf0c..410d2a73238cc2ad38263f41235caf1ed57f8bba 100644 --- a/jams-server/src/main/java/net/jami/jams/server/core/workflows/RevokeDeviceFlow.java +++ b/jams-server/src/main/java/net/jami/jams/server/core/workflows/RevokeDeviceFlow.java @@ -1,28 +1,32 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.core.workflows; +import static net.jami.jams.server.Server.certificateAuthority; +import static net.jami.jams.server.Server.dataStore; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.dao.StatementElement; import net.jami.jams.common.dao.StatementList; import net.jami.jams.common.objects.devices.Device; @@ -30,20 +34,17 @@ import net.jami.jams.common.objects.requests.RevocationRequest; import net.jami.jams.common.objects.requests.RevocationType; import net.jami.jams.common.objects.responses.DeviceRevocationResponse; -import static net.jami.jams.server.Server.certificateAuthority; -import static net.jami.jams.server.Server.dataStore; - import java.math.BigInteger; @Slf4j public class RevokeDeviceFlow { - public static DeviceRevocationResponse revokeDevice(String username, String deviceId){ + public static DeviceRevocationResponse revokeDevice(String username, String deviceId) { DeviceRevocationResponse response = new DeviceRevocationResponse(); try { StatementList statementList = new StatementList(); - StatementElement st1 = new StatementElement("owner","=",username,"AND"); - StatementElement st2 = new StatementElement("deviceId","=",deviceId,""); + StatementElement st1 = new StatementElement("owner", "=", username, "AND"); + StatementElement st2 = new StatementElement("deviceId", "=", deviceId, ""); statementList.addStatement(st1); statementList.addStatement(st2); Device device = dataStore.getDeviceDao().getObjects(statementList).get(0); @@ -58,21 +59,23 @@ public class RevokeDeviceFlow { certificateAuthority.revokeCertificate(request); long statTime = System.currentTimeMillis(); - while(certificateAuthority.getLatestCRL().get() - .getRevokedCertificate(serialNumber) == null){ + while (certificateAuthority.getLatestCRL().get().getRevokedCertificate(serialNumber) + == null) { log.warn("Certificate has not yet appeared in CRL!"); - if(System.currentTimeMillis() - statTime > 1000){ - log.error("The certificate has not appeared within 1 second, we are considering the operation has failed"); + if (System.currentTimeMillis() - statTime > 1000) { + log.error( + "The certificate has not appeared within 1 second, we are considering the operation has failed"); response.setSuccess(false); return response; } } - //Finally we return the successful response + // Finally we return the successful response response.setSuccess(true); return response; - } - catch (Exception e){ - log.error("An exception has occurred while trying to revoke a device with error {}", e.getMessage()); + } catch (Exception e) { + log.error( + "An exception has occurred while trying to revoke a device with error {}", + e.getMessage()); response.setSuccess(false); response.setErrorDetails(e.getMessage()); return response; diff --git a/jams-server/src/main/java/net/jami/jams/server/core/workflows/RevokeUserFlow.java b/jams-server/src/main/java/net/jami/jams/server/core/workflows/RevokeUserFlow.java index d12e325adb8a1dcb0289083df24191419922ba01..a71932981cca339e49e9f2b44c825130f7fea04b 100644 --- a/jams-server/src/main/java/net/jami/jams/server/core/workflows/RevokeUserFlow.java +++ b/jams-server/src/main/java/net/jami/jams/server/core/workflows/RevokeUserFlow.java @@ -1,28 +1,32 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.core.workflows; +import static net.jami.jams.server.Server.certificateAuthority; +import static net.jami.jams.server.Server.dataStore; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.dao.StatementElement; import net.jami.jams.common.dao.StatementList; import net.jami.jams.common.objects.requests.RevocationRequest; @@ -30,17 +34,14 @@ import net.jami.jams.common.objects.requests.RevocationType; import net.jami.jams.common.objects.responses.DeviceRevocationResponse; import net.jami.jams.common.objects.user.User; -import static net.jami.jams.server.Server.certificateAuthority; -import static net.jami.jams.server.Server.dataStore; - @Slf4j public class RevokeUserFlow { - public static DeviceRevocationResponse revokeUser(String username){ + public static DeviceRevocationResponse revokeUser(String username) { DeviceRevocationResponse response = new DeviceRevocationResponse(); try { StatementList statementList = new StatementList(); - StatementElement st1 = new StatementElement("username","=",username,""); + StatementElement st1 = new StatementElement("username", "=", username, ""); statementList.addStatement(st1); User user = dataStore.getUserDao().getObjects(statementList).get(0); if (user == null) { @@ -52,21 +53,26 @@ public class RevokeUserFlow { request.setIdentifier(user.getCertificate().getSerialNumber()); certificateAuthority.revokeCertificate(request); long statTime = System.currentTimeMillis(); - while(certificateAuthority.getLatestCRL().get() - .getRevokedCertificate(user.getCertificate().getSerialNumber()) == null){ + while (certificateAuthority + .getLatestCRL() + .get() + .getRevokedCertificate(user.getCertificate().getSerialNumber()) + == null) { log.warn("Certificate has not yet appeared in CRL!"); - if(System.currentTimeMillis() - statTime > 1000){ - log.error("The certificate has not appeared within 1 second, we are considering the operation has failed"); + if (System.currentTimeMillis() - statTime > 1000) { + log.error( + "The certificate has not appeared within 1 second, we are considering the operation has failed"); response.setSuccess(false); return response; } } - //Finally we return the successful response + // Finally we return the successful response response.setSuccess(true); return response; - } - catch (Exception e){ - log.error("An exception has occurred while trying to revoke a device with error {}", e.getMessage()); + } catch (Exception e) { + log.error( + "An exception has occurred while trying to revoke a device with error {}", + e.getMessage()); response.setSuccess(false); response.setErrorDetails(e.getMessage()); return response; diff --git a/jams-server/src/main/java/net/jami/jams/server/licensing/LicenseService.java b/jams-server/src/main/java/net/jami/jams/server/licensing/LicenseService.java index 772a2fd438bf350a37ada3809a1da708f543a472..c5835d5ed87fd4c4b8f0ad0bb3dd8d94880701ac 100644 --- a/jams-server/src/main/java/net/jami/jams/server/licensing/LicenseService.java +++ b/jams-server/src/main/java/net/jami/jams/server/licensing/LicenseService.java @@ -25,6 +25,7 @@ package net.jami.jams.server.licensing; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.updater.subscription.LicenseInformation; import net.jami.jams.common.utils.X509Utils; import net.jami.jams.server.Server; @@ -48,40 +49,47 @@ public class LicenseService { private X509Certificate caCertificate; private LicenseInformation licenseInformation = new LicenseInformation(); - //Load the license. + // Load the license. public void loadLicense() { try { - Vector<Object> v = X509Utils.loadLicenseFromDatFile( - new String(Files.readAllBytes(Path.of(System.getProperty("user.dir") + File.separator + "license.dat"))) - ); + Vector<Object> v = + X509Utils.loadLicenseFromDatFile( + new String( + Files.readAllBytes( + Path.of( + System.getProperty("user.dir") + + File.separator + + "license.dat")))); certificate = (X509Certificate) v.get(0); privateKey = (PrivateKey) v.get(1); - caCertificate = X509Utils.getCertificateFromPEMString( - new String(LicenseService.class.getClassLoader().getResourceAsStream("oem/ca.crt").readAllBytes()) - ); - //Check the license for validity. + caCertificate = + X509Utils.getCertificateFromPEMString( + new String( + LicenseService.class + .getClassLoader() + .getResourceAsStream("oem/ca.crt") + .readAllBytes())); + // Check the license for validity. try { certificate.checkValidity(); - } - catch (CertificateExpiredException | CertificateNotYetValidException c2){ + } catch (CertificateExpiredException | CertificateNotYetValidException c2) { log.error("Your license is not yet valid or has expired!"); Server.activated.set(false); } try { certificate.verify(caCertificate.getPublicKey()); - //If all these checks have passed then: + // If all these checks have passed then: Server.activated.set(true); log.info("Server is activated with valid license: {}", Server.activated.get()); - Server.appUpdater.setLicense(certificate,privateKey); + Server.appUpdater.setLicense(certificate, privateKey); log.info("Successfully set license inside updater module!"); - } - catch (Exception e) { + } catch (Exception e) { log.error("The license file you have provided could not be verified!"); Server.activated.set(false); } - } - catch (Exception e){ - log.error("A generic occurred while trying to load your license or your license could not be found"); + } catch (Exception e) { + log.error( + "A generic occurred while trying to load your license or your license could not be found"); Server.activated.set(false); } } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/LoginServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/LoginServlet.java index 4daadce5f3a8bc01b8e026b0bc0e80db498fa32a..349402305608f62781a3f310dbbbaf7967482a74 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/LoginServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/LoginServlet.java @@ -22,32 +22,30 @@ */ package net.jami.jams.server.servlets; +import static net.jami.jams.server.Server.certificateAuthority; +import static net.jami.jams.server.Server.dataStore; +import static net.jami.jams.server.servlets.api.auth.login.AuthRequestProcessor.processUsernamePasswordAuth; +import static net.jami.jams.server.servlets.api.auth.login.AuthRequestProcessor.processX509Auth; + import com.jsoniter.JsonIterator; import com.jsoniter.output.JsonStream; + import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import net.jami.jams.common.annotations.JsonContent; import net.jami.jams.common.authmodule.AuthTokenResponse; import net.jami.jams.common.dao.StatementElement; import net.jami.jams.common.dao.StatementList; +import net.jami.jams.common.objects.user.User; import net.jami.jams.common.serialization.tomcat.TomcatCustomErrorHandler; import net.jami.jams.server.servlets.api.auth.login.LoginRequest; -import static net.jami.jams.server.Server.certificateAuthority; -import static net.jami.jams.server.Server.dataStore; -import net.jami.jams.common.objects.user.User; - - import java.io.IOException; import java.security.cert.X509Certificate; -import java.util.ArrayList; import java.util.List; -import java.util.Objects; - -import static net.jami.jams.server.servlets.api.auth.login.AuthRequestProcessor.processUsernamePasswordAuth; -import static net.jami.jams.server.servlets.api.auth.login.AuthRequestProcessor.processX509Auth; @WebServlet("/api/login") // This method returns the token which is used for all the next calls to the @@ -77,28 +75,39 @@ public class LoginServlet extends HttpServlet { } // Case 2 SSL Certificate else if (req.getAttribute("jakarta.servlet.request.X509Certificate") != null) { - res = processX509Auth((X509Certificate[]) req.getAttribute("jakarta.servlet.request.X509Certificate")); + res = + processX509Auth( + (X509Certificate[]) + req.getAttribute("jakarta.servlet.request.X509Certificate")); } else { // Case 3: form submitted username/password - LoginRequest object = JsonIterator.deserialize(req.getInputStream().readAllBytes(), LoginRequest.class); + LoginRequest object = + JsonIterator.deserialize( + req.getInputStream().readAllBytes(), LoginRequest.class); if (object.getUsername() != null && object.getPassword() != null) { res = processUsernamePasswordAuth(object.getUsername(), object.getPassword()); StatementList statementList = new StatementList(); - StatementElement statementElement = new StatementElement("username", "=", object.getUsername(), ""); + StatementElement statementElement = + new StatementElement("username", "=", object.getUsername(), ""); statementList.addStatement(statementElement); List<User> users = dataStore.getUserDao().getObjects(statementList); - if( users.size() !=0 && - certificateAuthority.getLatestCRL().get() != null && - !users.get(0).getAccessLevelName().equals("ADMIN") && - certificateAuthority.getLatestCRL().get().getRevokedCertificate(users.get(0).getCertificate().getSerialNumber()) != null) { - TomcatCustomErrorHandler.sendCustomError(resp, 401, "Invalid credentials provided!"); + if (users.size() != 0 + && certificateAuthority.getLatestCRL().get() != null + && !users.get(0).getAccessLevelName().equals("ADMIN") + && certificateAuthority + .getLatestCRL() + .get() + .getRevokedCertificate( + users.get(0).getCertificate().getSerialNumber()) + != null) { + TomcatCustomErrorHandler.sendCustomError( + resp, 401, "Invalid credentials provided!"); } } } resp.setContentType("application/json;charset=UTF-8"); if (res == null) TomcatCustomErrorHandler.sendCustomError(resp, 401, "Invalid credentials provided!"); - else - resp.getOutputStream().write(JsonStream.serialize(res).getBytes()); + else resp.getOutputStream().write(JsonStream.serialize(res).getBytes()); } } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/contacts/ContactServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/contacts/ContactServlet.java index 52a2ffa3a0bbdabddd134808e675afb160029425..fd1df0c1b1b4965680c26f621ba8fe1e3041be5c 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/contacts/ContactServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/contacts/ContactServlet.java @@ -1,34 +1,38 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.api.admin.contacts; +import static net.jami.jams.server.Server.dataStore; + import com.jsoniter.JsonIterator; import com.jsoniter.output.JsonStream; + import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import net.jami.jams.common.annotations.JsonContent; import net.jami.jams.common.annotations.ScopedServletMethod; import net.jami.jams.common.dao.StatementElement; @@ -37,6 +41,7 @@ import net.jami.jams.common.objects.contacts.Contact; import net.jami.jams.common.objects.user.AccessLevel; import net.jami.jams.common.serialization.tomcat.TomcatCustomErrorHandler; import net.jami.jams.common.utils.ContactMerger; + import org.json.JSONObject; import java.io.IOException; @@ -45,8 +50,6 @@ import java.util.Arrays; import java.util.List; import java.util.Scanner; -import static net.jami.jams.server.Server.dataStore; - @WebServlet("/api/admin/contacts") public class ContactServlet extends HttpServlet { @@ -62,11 +65,13 @@ public class ContactServlet extends HttpServlet { * "removed": 12387873 }, ] */ @Override - @ScopedServletMethod(securityGroups = { AccessLevel.ADMIN }) + @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) @JsonContent - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { StatementList statementList = new StatementList(); - statementList.addStatement(new StatementElement("owner", "=", req.getParameter("username").toString(), "")); + statementList.addStatement( + new StatementElement("owner", "=", req.getParameter("username"), "")); List<Contact> contactList = dataStore.getContactDao().getObjects(statementList); resp.getOutputStream().write(JsonStream.serialize(contactList).getBytes()); } @@ -85,8 +90,9 @@ public class ContactServlet extends HttpServlet { * @apiError (500) {null} null contact could not be successfully added */ @Override - @ScopedServletMethod(securityGroups = { AccessLevel.ADMIN }) - protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) + protected void doPut(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { Scanner s = new Scanner(req.getInputStream()).useDelimiter("\\A"); String res = s.hasNext() ? s.next() : ""; final JSONObject obj = new JSONObject(res); @@ -98,15 +104,16 @@ public class ContactServlet extends HttpServlet { contact.setOwner(req.getParameter("username")); contact.setUri(obj.get("uri").toString()); StatementList statementList = new StatementList(); - statementList.addStatement(new StatementElement("owner", "=", req.getParameter("username").toString(), "")); + statementList.addStatement( + new StatementElement("owner", "=", req.getParameter("username"), "")); List<Contact> localList = dataStore.getContactDao().getObjects(statementList); List<Contact> remoteList = new ArrayList<>(); remoteList.add(contact); List<Contact> result = ContactMerger.mergeContacts(localList, remoteList); - if (dataStore.getContactDao().storeContactList(result)) - resp.setStatus(200); + if (dataStore.getContactDao().storeContactList(result)) resp.setStatus(200); else - TomcatCustomErrorHandler.sendCustomError(resp, 500, "could not store a contact due to server-side error"); + TomcatCustomErrorHandler.sendCustomError( + resp, 500, "could not store a contact due to server-side error"); } /** @@ -121,10 +128,12 @@ public class ContactServlet extends HttpServlet { * @apiError (500) {null} null contact could not be successfully deleted */ @Override - @ScopedServletMethod(securityGroups = { AccessLevel.ADMIN }) - protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) + protected void doDelete(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { StatementList statementList = new StatementList(); - statementList.addStatement(new StatementElement("owner", "=", req.getParameter("username").toString(), "AND")); + statementList.addStatement( + new StatementElement("owner", "=", req.getParameter("username"), "AND")); statementList.addStatement(new StatementElement("uri", "=", req.getParameter("uri"), "")); /* * List<Contact> remoteList = @@ -137,10 +146,10 @@ public class ContactServlet extends HttpServlet { * dataStore.getContactDao().getObjects(statementList); List<Contact> result = * ContactMerger.mergeContacts(localList,remoteList); */ - if (dataStore.getContactDao().deleteObject(statementList)) - resp.setStatus(200); + if (dataStore.getContactDao().deleteObject(statementList)) resp.setStatus(200); else - TomcatCustomErrorHandler.sendCustomError(resp, 500, "could not delete a contact due to server-side error"); + TomcatCustomErrorHandler.sendCustomError( + resp, 500, "could not delete a contact due to server-side error"); } /** @@ -158,18 +167,21 @@ public class ContactServlet extends HttpServlet { * @apiError (500) {null} null contact could not be successfully added */ @Override - @ScopedServletMethod(securityGroups = { AccessLevel.ADMIN }) - protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) + protected void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { StatementList statementList = new StatementList(); - statementList.addStatement(new StatementElement("owner", "=", req.getParameter("username").toString(), "")); + statementList.addStatement( + new StatementElement("owner", "=", req.getParameter("username"), "")); List<Contact> localList = dataStore.getContactDao().getObjects(statementList); - List<Contact> remoteList = Arrays - .asList(JsonIterator.deserialize(req.getInputStream().readAllBytes(), Contact[].class)); - remoteList.forEach(contact -> contact.setOwner(req.getParameter("username").toString())); + List<Contact> remoteList = + Arrays.asList( + JsonIterator.deserialize( + req.getInputStream().readAllBytes(), Contact[].class)); + remoteList.forEach(contact -> contact.setOwner(req.getParameter("username"))); List<Contact> result = ContactMerger.mergeContacts(localList, remoteList); if (!dataStore.getContactDao().storeContactList(result)) TomcatCustomErrorHandler.sendCustomError(resp, 500, "Could not store contacts!"); - else - resp.getOutputStream().write(JsonStream.serialize(result).getBytes()); + else resp.getOutputStream().write(JsonStream.serialize(result).getBytes()); } } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/devices/DeviceServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/devices/DeviceServlet.java index d12c92f5911084621f4e3b84541d37e670ddcaf5..100bf578d6759d04fa0b782b5f42c34d6594e4f3 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/devices/DeviceServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/devices/DeviceServlet.java @@ -1,33 +1,37 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.api.admin.devices; +import static net.jami.jams.server.Server.dataStore; + import com.jsoniter.output.JsonStream; + import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import net.jami.jams.common.annotations.ScopedServletMethod; import net.jami.jams.common.dao.StatementElement; import net.jami.jams.common.dao.StatementList; @@ -37,50 +41,58 @@ import net.jami.jams.server.core.workflows.RevokeDeviceFlow; import java.io.IOException; -import static net.jami.jams.server.Server.dataStore; - @WebServlet("/api/admin/device") public class DeviceServlet extends HttpServlet { - //Get a detailed device info. + // Get a detailed device info. @Override @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { String username = req.getParameter("username"); String deviceId = req.getParameter("deviceId"); StatementList statementList = new StatementList(); - StatementElement st1 = new StatementElement("owner","=",username,"AND"); - StatementElement st2 = new StatementElement("deviceId","=",deviceId,""); + StatementElement st1 = new StatementElement("owner", "=", username, "AND"); + StatementElement st2 = new StatementElement("deviceId", "=", deviceId, ""); statementList.addStatement(st1); statementList.addStatement(st2); - resp.getOutputStream().write(JsonStream.serialize(dataStore.getDeviceDao().getObjects(statementList).get(0)).getBytes()); + resp.getOutputStream() + .write( + JsonStream.serialize( + dataStore.getDeviceDao().getObjects(statementList).get(0)) + .getBytes()); } - //Update device data. + // Update device data. @Override @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) - protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doPut(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { String username = req.getParameter("username"); String deviceId = req.getParameter("deviceId"); String deviceName = req.getParameter("deviceName"); StatementList update = new StatementList(); - StatementElement st0 = new StatementElement("deviceName","=",deviceName,""); + StatementElement st0 = new StatementElement("deviceName", "=", deviceName, ""); update.addStatement(st0); StatementList constraint = new StatementList(); - StatementElement st1 = new StatementElement("owner","=",username,"AND"); - StatementElement st2 = new StatementElement("deviceId","=",deviceId,""); + StatementElement st1 = new StatementElement("owner", "=", username, "AND"); + StatementElement st2 = new StatementElement("deviceId", "=", deviceId, ""); update.addStatement(st1); update.addStatement(st2); - if(dataStore.getDeviceDao().updateObject(update,constraint)) resp.setStatus(200); - else resp.sendError(500,"could not update the device's information!"); + if (dataStore.getDeviceDao().updateObject(update, constraint)) resp.setStatus(200); + else resp.sendError(500, "could not update the device's information!"); } - //Revoke/delete a device. + // Revoke/delete a device. @Override @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) - protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - DeviceRevocationResponse devResponse = RevokeDeviceFlow.revokeDevice(req.getParameter("username").toString(),req.getParameter("deviceId")); - if(devResponse != null) resp.getOutputStream().write(JsonStream.serialize(devResponse).getBytes()); - else resp.sendError(500,"An exception has occurred while trying to revoke a device!"); + protected void doDelete(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + DeviceRevocationResponse devResponse = + RevokeDeviceFlow.revokeDevice( + req.getParameter("username"), req.getParameter("deviceId")); + if (devResponse != null) + resp.getOutputStream().write(JsonStream.serialize(devResponse).getBytes()); + else resp.sendError(500, "An exception has occurred while trying to revoke a device!"); } } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/devices/DevicesServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/devices/DevicesServlet.java index 63dd816bbaa1a1d91e951f48fca24e27cbc4620b..4697c5a13b411283e179dbfe3b84bdcca5c5e072 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/devices/DevicesServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/devices/DevicesServlet.java @@ -1,33 +1,38 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.api.admin.devices; +import static net.jami.jams.server.Server.certificateAuthority; +import static net.jami.jams.server.Server.dataStore; + import com.jsoniter.output.JsonStream; + import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import net.jami.jams.common.annotations.JsonContent; import net.jami.jams.common.annotations.ScopedServletMethod; import net.jami.jams.common.dao.StatementElement; @@ -38,28 +43,31 @@ import net.jami.jams.common.objects.user.AccessLevel; import java.io.IOException; import java.util.List; -import static net.jami.jams.server.Server.certificateAuthority; -import static net.jami.jams.server.Server.dataStore; - @WebServlet("/api/admin/devices") public class DevicesServlet extends HttpServlet { - //Get a list of devices for a user. + // Get a list of devices for a user. @Override @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) @JsonContent - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { String username = req.getParameter("username"); StatementList statementList = new StatementList(); - statementList.addStatement(new StatementElement("owner","=",username,"")); + statementList.addStatement(new StatementElement("owner", "=", username, "")); List<Device> devices = dataStore.getDeviceDao().getObjects(statementList); - if(certificateAuthority.getLatestCRL() != null) { - devices.forEach(device -> { - device.setRevoked(certificateAuthority.getLatestCRL().get().getRevokedCertificate(device.getCertificate().getSerialNumber()) != null); - }); - } - else - devices.forEach(device -> device.setRevoked(false)); + if (certificateAuthority.getLatestCRL() != null) { + devices.forEach( + device -> { + device.setRevoked( + certificateAuthority + .getLatestCRL() + .get() + .getRevokedCertificate( + device.getCertificate().getSerialNumber()) + != null); + }); + } else devices.forEach(device -> device.setRevoked(false)); resp.getOutputStream().write(JsonStream.serialize(devices).getBytes()); } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/directory/DirectoryEntryServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/directory/DirectoryEntryServlet.java index 33c6804f7dbbe599c3b637decb395fbccdd713f6..9726601219fc277455dec6f89ef40e8d96afe6c7 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/directory/DirectoryEntryServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/directory/DirectoryEntryServlet.java @@ -23,14 +23,20 @@ package net.jami.jams.server.servlets.api.admin.directory; +import static net.jami.jams.server.Server.dataStore; +import static net.jami.jams.server.Server.userAuthenticationModule; + import com.jsoniter.JsonIterator; import com.jsoniter.output.JsonStream; + import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.annotations.JsonContent; import net.jami.jams.common.annotations.ScopedServletMethod; import net.jami.jams.common.authentication.AuthenticationSourceType; @@ -39,19 +45,14 @@ import net.jami.jams.common.dao.StatementElement; import net.jami.jams.common.dao.StatementList; import net.jami.jams.common.objects.user.AccessLevel; import net.jami.jams.common.objects.user.User; -import net.jami.jams.common.objects.user.UserGroupMapping; import net.jami.jams.common.objects.user.UserProfile; + import org.json.JSONObject; import java.io.IOException; -import java.util.ArrayList; import java.util.HashMap; -import java.util.List; import java.util.Scanner; -import static net.jami.jams.server.Server.dataStore; -import static net.jami.jams.server.Server.userAuthenticationModule; - @Slf4j @WebServlet("/api/admin/directory/entry") public class DirectoryEntryServlet extends HttpServlet { @@ -60,7 +61,7 @@ public class DirectoryEntryServlet extends HttpServlet { @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) @JsonContent protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { - //Create a user profile. + // Create a user profile. String realm = "LOCAL"; Scanner s = new Scanner(req.getInputStream()).useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; @@ -79,8 +80,10 @@ public class DirectoryEntryServlet extends HttpServlet { userProfile.setMobileNumber(obj.get("mobileNumber").toString()); userProfile.setId(obj.get("jamiId").toString()); - userAuthenticationModule.getAuthSources().get(new AuthModuleKey(realm, AuthenticationSourceType.LOCAL)) - .setUserProfile(userProfile); + userAuthenticationModule + .getAuthSources() + .get(new AuthModuleKey(realm, AuthenticationSourceType.LOCAL)) + .setUserProfile(userProfile); resp.setStatus(200); HashMap<String, String> profileName = new HashMap<>(); profileName.put("username", userProfile.getUsername()); @@ -88,10 +91,12 @@ public class DirectoryEntryServlet extends HttpServlet { } @Override - protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException, SecurityException { - //Update a user's profile. - //Check if he is AD/LDAP - then return a 500, because we can't update those profile datas. - UserProfile userProfile = JsonIterator.deserialize(req.getInputStream().readAllBytes(), UserProfile.class); + protected void doPut(HttpServletRequest req, HttpServletResponse resp) + throws IOException, SecurityException { + // Update a user's profile. + // Check if he is AD/LDAP - then return a 500, because we can't update those profile datas. + UserProfile userProfile = + JsonIterator.deserialize(req.getInputStream().readAllBytes(), UserProfile.class); StatementList select = new StatementList(); StatementElement st = new StatementElement("username", "=", userProfile.getUsername(), ""); select.addStatement(st); @@ -104,26 +109,30 @@ public class DirectoryEntryServlet extends HttpServlet { User callingUser = dataStore.getUserDao().getObjects(select).get(0); if (targetUser.getUserType() != AuthenticationSourceType.LOCAL) { - resp.sendError(403, "The user is not a local user, therefore we cannot change his data!"); + resp.sendError( + 403, "The user is not a local user, therefore we cannot change his data!"); return; } - if (callingUser.getAccessLevel() == AccessLevel.ADMIN || (callingUser.getAccessLevel() == AccessLevel.USER && callingUser.getUsername().equals(targetUser.getUsername()))) { + if (callingUser.getAccessLevel() == AccessLevel.ADMIN + || (callingUser.getAccessLevel() == AccessLevel.USER + && callingUser.getUsername().equals(targetUser.getUsername()))) { select = new StatementList(); - select.addStatement(new StatementElement("username", "=", userProfile.getUsername(), "")); - if (dataStore.updateUserProfile(userProfile)) - resp.setStatus(200); - else - resp.sendError(500, "Could not update the users's profile information"); + select.addStatement( + new StatementElement("username", "=", userProfile.getUsername(), "")); + if (dataStore.updateUserProfile(userProfile)) resp.setStatus(200); + else resp.sendError(500, "Could not update the users's profile information"); } else { - resp.sendError(403, "The user is either not an admin account or is attempting to edit a profile that is not his own!"); - return; + resp.sendError( + 403, + "The user is either not an admin account or is attempting to edit a profile that is not his own!"); } } @Override @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) - protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - //This method will probably never be implemented. + protected void doDelete(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + // This method will probably never be implemented. } } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/group/AddGroupServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/group/AddGroupServlet.java index f6fb5be8118c1328662060c28e4d804bcbb6b840..40ffc71e12e62fa9fad39a102a7d9f6e2052490f 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/group/AddGroupServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/group/AddGroupServlet.java @@ -1,5 +1,7 @@ package net.jami.jams.server.servlets.api.admin.group; +import static net.jami.jams.server.Server.dataStore; + import com.google.gson.JsonObject; import com.google.gson.JsonParser; @@ -7,18 +9,17 @@ import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.annotations.JsonContent; import net.jami.jams.common.annotations.ScopedServletMethod; import net.jami.jams.common.objects.user.AccessLevel; import net.jami.jams.common.objects.user.Group; import java.io.IOException; -import java.util.ArrayList; import java.util.UUID; -import static net.jami.jams.server.Server.dataStore; - @WebServlet("/api/admin/group") @Slf4j public class AddGroupServlet extends HttpServlet { @@ -40,8 +41,6 @@ public class AddGroupServlet extends HttpServlet { data.addProperty("id", uuid.toString()); resp.getOutputStream().write(data.toString().getBytes()); resp.setStatus(200); - } - else - resp.sendError(500, "Could not create a group successfully!"); + } else resp.sendError(500, "Could not create a group successfully!"); } -} \ No newline at end of file +} diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/group/GroupServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/group/GroupServlet.java index 88cf7bc1c6279fd73655c81d0ae953741c9b97f0..489de813ba62cba5657f29c594dc7e4dc7ccef95 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/group/GroupServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/group/GroupServlet.java @@ -1,38 +1,40 @@ package net.jami.jams.server.servlets.api.admin.group; +import static net.jami.jams.server.Server.dataStore; + import com.jsoniter.output.JsonStream; + import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.annotations.JsonContent; import net.jami.jams.common.annotations.ScopedServletMethod; import net.jami.jams.common.dao.StatementElement; import net.jami.jams.common.dao.StatementList; import net.jami.jams.common.objects.user.AccessLevel; import net.jami.jams.common.objects.user.Group; -import net.jami.jams.common.objects.user.UserProfile; + import org.json.JSONObject; import java.io.IOException; -import java.util.List; import java.util.stream.Collectors; -import static net.jami.jams.server.Server.dataStore; - @WebServlet("/api/admin/group/*") @Slf4j public class GroupServlet extends HttpServlet { - @Override @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) @JsonContent - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { Group singleGroup = null; - String id = req.getPathInfo().replace("/",""); + String id = req.getPathInfo().replace("/", ""); StatementList statementList = new StatementList(); StatementElement st = new StatementElement("id", "=", id, ""); @@ -44,9 +46,8 @@ public class GroupServlet extends HttpServlet { if (singleGroup != null) { resp.getOutputStream().write(JsonStream.serialize(singleGroup).getBytes()); resp.setStatus(200); - } - else { - log.info("No group with this id was found!" ); + } else { + log.info("No group with this id was found!"); resp.setStatus(404); } } @@ -56,9 +57,13 @@ public class GroupServlet extends HttpServlet { @JsonContent protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException { - String id = req.getPathInfo().replace("/",""); + String id = req.getPathInfo().replace("/", ""); - final JSONObject obj = new JSONObject(req.getReader().lines().collect(Collectors.joining(System.lineSeparator()))); + final JSONObject obj = + new JSONObject( + req.getReader() + .lines() + .collect(Collectors.joining(System.lineSeparator()))); String name = obj.getString("name"); String blueprint = obj.getString("blueprint"); @@ -84,7 +89,7 @@ public class GroupServlet extends HttpServlet { @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) @JsonContent protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException { - String id = req.getPathInfo().replace("/",""); + String id = req.getPathInfo().replace("/", ""); StatementElement statementElement = new StatementElement("id", "=", id, ""); @@ -98,10 +103,8 @@ public class GroupServlet extends HttpServlet { constraintMapping.addStatement(statementElement2); if (dataStore.getUserGroupMappingsDao().deleteObject(constraintMapping)) resp.setStatus(200); - else - resp.sendError(500, "Could not delete the group mappings successfully!"); - } - else { + else resp.sendError(500, "Could not delete the group mappings successfully!"); + } else { resp.sendError(500, "Could not delete the group successfully!"); } } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/group/GroupsServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/group/GroupsServlet.java index 6fe101f2a94bc6acfd09b3407308ef5f22e247c4..9b5d34e6ea155cac6a6590eb7d08b851973f0de7 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/group/GroupsServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/group/GroupsServlet.java @@ -1,28 +1,24 @@ package net.jami.jams.server.servlets.api.admin.group; -import com.google.gson.JsonObject; +import static net.jami.jams.server.Server.dataStore; + import com.jsoniter.output.JsonStream; + import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.annotations.JsonContent; import net.jami.jams.common.annotations.ScopedServletMethod; -import net.jami.jams.common.dao.StatementElement; -import net.jami.jams.common.dao.StatementList; import net.jami.jams.common.objects.user.AccessLevel; import net.jami.jams.common.objects.user.Group; -import net.jami.jams.common.objects.user.UserProfile; import java.io.IOException; -import java.util.ArrayList; import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; - -import static net.jami.jams.server.Server.dataStore; @WebServlet("/api/admin/groups") @Slf4j @@ -31,16 +27,16 @@ public class GroupsServlet extends HttpServlet { @Override @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) @JsonContent - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { List<Group> groups = dataStore.getGroupDao().getObjects(null); if (!groups.isEmpty()) { resp.getOutputStream().write(JsonStream.serialize(groups).getBytes()); resp.setStatus(200); - } - else { + } else { resp.setStatus(404); } } -} \ No newline at end of file +} diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/group/PolicyProfileServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/group/PolicyProfileServlet.java index 79964a57638de0f04d9d73c8b309c53080a9ce57..174ededdcc3af4d4d12bd2e108e65723abaa4641 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/group/PolicyProfileServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/group/PolicyProfileServlet.java @@ -1,12 +1,17 @@ package net.jami.jams.server.servlets.api.admin.group; +import static net.jami.jams.server.Server.dataStore; + import com.jsoniter.output.JsonStream; + import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.annotations.JsonContent; import net.jami.jams.common.annotations.ScopedServletMethod; import net.jami.jams.common.dao.StatementElement; @@ -17,27 +22,32 @@ import net.jami.jams.common.objects.user.Policy; import java.io.IOException; import java.util.List; -import static net.jami.jams.server.Server.dataStore; - @WebServlet("/api/admin/policy/*") @Slf4j public class PolicyProfileServlet extends HttpServlet { - @Override @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) @JsonContent - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { List<Policy> policies; - String name = req.getPathInfo().replace("/",""); + String name = req.getPathInfo().replace("/", ""); if (!name.equals("*")) { StatementList statementList = new StatementList(); StatementElement st = new StatementElement("name", "=", name, ""); statementList.addStatement(st); if (!dataStore.getPolicyDao().getObjects(statementList).isEmpty()) { - resp.getOutputStream().write(JsonStream.serialize(dataStore.getPolicyDao().getObjects(statementList).get(0)).getBytes()); + resp.getOutputStream() + .write( + JsonStream.serialize( + dataStore + .getPolicyDao() + .getObjects(statementList) + .get(0)) + .getBytes()); resp.setStatus(200); } } else { diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/group/PolicyServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/group/PolicyServlet.java index 9893eae422a74d38f15faca0d4f9e195d5d747e9..09ca1d93a6ab62080f168ff62c2107c3d431c38b 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/group/PolicyServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/group/PolicyServlet.java @@ -1,36 +1,39 @@ package net.jami.jams.server.servlets.api.admin.group; +import static net.jami.jams.server.Server.dataStore; + import com.jsoniter.output.JsonStream; + import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.annotations.JsonContent; import net.jami.jams.common.annotations.ScopedServletMethod; import net.jami.jams.common.dao.StatementElement; import net.jami.jams.common.dao.StatementList; import net.jami.jams.common.objects.user.AccessLevel; import net.jami.jams.common.objects.user.Policy; + import org.json.JSONObject; import java.io.IOException; import java.util.List; import java.util.Scanner; -import static net.jami.jams.server.Server.dataStore; - @Slf4j @WebServlet("/api/admin/policy") public class PolicyServlet extends HttpServlet { - @Override @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) @JsonContent - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { List<Policy> policies; String name = req.getParameter("name"); @@ -102,11 +105,8 @@ public class PolicyServlet extends HttpServlet { StatementElement statementElement = new StatementElement("name", "=", name, ""); StatementList constraint = new StatementList(); constraint.addStatement(statementElement); - if (dataStore.getPolicyDao().deleteObject(constraint)) - resp.setStatus(200); - + if (dataStore.getPolicyDao().deleteObject(constraint)) resp.setStatus(200); resp.sendError(500, "Could not delete the blueprint successfully!"); } - } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/group/UserGroupServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/group/UserGroupServlet.java index 82666f4d172513792af28e2524741934eac8c677..6a9462a31b1881d6270ea901f1555ae780195b77 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/group/UserGroupServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/group/UserGroupServlet.java @@ -1,29 +1,29 @@ package net.jami.jams.server.servlets.api.admin.group; -import com.google.gson.JsonObject; +import static net.jami.jams.server.Server.dataStore; + import com.jsoniter.output.JsonStream; + import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.annotations.JsonContent; import net.jami.jams.common.annotations.ScopedServletMethod; import net.jami.jams.common.dao.StatementElement; import net.jami.jams.common.dao.StatementList; import net.jami.jams.common.objects.user.AccessLevel; import net.jami.jams.common.objects.user.UserGroupMapping; + import org.json.JSONObject; import java.io.IOException; -import java.lang.reflect.Array; -import java.util.ArrayList; import java.util.List; -import java.util.UUID; import java.util.stream.Collectors; -import static net.jami.jams.server.Server.dataStore; - @WebServlet("/api/admin/group/members/*") @Slf4j public class UserGroupServlet extends HttpServlet { @@ -45,17 +45,17 @@ public class UserGroupServlet extends HttpServlet { @JsonContent protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { - String groupId = req.getPathInfo().replace("/",""); + String groupId = req.getPathInfo().replace("/", ""); StatementList statementList = new StatementList(); StatementElement st = new StatementElement("groupId", "=", groupId, ""); statementList.addStatement(st); - List<UserGroupMapping> result = dataStore.getUserGroupMappingsDao().getObjects(statementList); + List<UserGroupMapping> result = + dataStore.getUserGroupMappingsDao().getObjects(statementList); - if (result.isEmpty()) - resp.sendError(404, "No users found for this group!"); + if (result.isEmpty()) resp.sendError(404, "No users found for this group!"); else { resp.getOutputStream().write(JsonStream.serialize(result).getBytes()); resp.setStatus(200); @@ -67,9 +67,13 @@ public class UserGroupServlet extends HttpServlet { @JsonContent protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { - String groupId = req.getPathInfo().replace("/",""); + String groupId = req.getPathInfo().replace("/", ""); - final JSONObject obj = new JSONObject(req.getReader().lines().collect(Collectors.joining(System.lineSeparator()))); + final JSONObject obj = + new JSONObject( + req.getReader() + .lines() + .collect(Collectors.joining(System.lineSeparator()))); String username = obj.getString("username"); @@ -78,7 +82,7 @@ public class UserGroupServlet extends HttpServlet { statementList.addStatement(new StatementElement("username", "=", username, "")); if (!dataStore.getUserGroupMappingsDao().getObjects(statementList).isEmpty()) { - resp.sendError( 409, "The user already part of the group!"); + resp.sendError(409, "The user already part of the group!"); return; } @@ -89,10 +93,7 @@ public class UserGroupServlet extends HttpServlet { if (dataStore.getUserGroupMappingsDao().storeObject(mapping)) { resp.setStatus(200); - } - else - resp.sendError(500, "Could not add user to group!"); - + } else resp.sendError(500, "Could not add user to group!"); } @Override @@ -100,13 +101,16 @@ public class UserGroupServlet extends HttpServlet { @JsonContent protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException { - String groupId = req.getPathInfo().replace("/",""); + String groupId = req.getPathInfo().replace("/", ""); - final JSONObject obj = new JSONObject(req.getReader().lines().collect(Collectors.joining(System.lineSeparator()))); + final JSONObject obj = + new JSONObject( + req.getReader() + .lines() + .collect(Collectors.joining(System.lineSeparator()))); String username = obj.getString("username"); - StatementElement statementElement1 = new StatementElement("username", "=", username, "AND"); StatementElement statementElement2 = new StatementElement("groupId", "=", groupId, ""); @@ -115,9 +119,8 @@ public class UserGroupServlet extends HttpServlet { constraint.addStatement(statementElement2); if (dataStore.getUserGroupMappingsDao().deleteObject(constraint)) { resp.setStatus(200); - } - else { + } else { resp.sendError(500, "Could not delete mapping between user and group!"); } } -} \ No newline at end of file +} diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/update/SubscriptionServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/update/SubscriptionServlet.java index bed20b4a1c90452de9ea1f6d19c0579aae0db913..098a95a0929a46da8f991c6ee2679d464d25981d 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/update/SubscriptionServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/update/SubscriptionServlet.java @@ -1,39 +1,42 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.api.admin.update; import com.jsoniter.output.JsonStream; + import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import net.jami.jams.common.annotations.JsonContent; import net.jami.jams.common.annotations.ScopedServletMethod; import net.jami.jams.common.objects.responses.SubscriptionStatusResponse; import net.jami.jams.common.objects.user.AccessLevel; import net.jami.jams.server.Server; import net.jami.jams.server.licensing.LicenseService; + import org.json.JSONObject; import java.io.FileWriter; @@ -42,19 +45,22 @@ import java.io.IOException; @WebServlet("/api/admin/subscription") public class SubscriptionServlet extends HttpServlet { - //Get the subscription status (see: SubscriptionStatusResponse.class) + // Get the subscription status (see: SubscriptionStatusResponse.class) @Override @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) @JsonContent - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { SubscriptionStatusResponse subscriptionStatusResponse = new SubscriptionStatusResponse(); - subscriptionStatusResponse.setLicenseInformation(Server.licenseService.getLicenseInformation()); + subscriptionStatusResponse.setLicenseInformation( + Server.licenseService.getLicenseInformation()); subscriptionStatusResponse.setActivated(Server.activated.get()); resp.getOutputStream().write(JsonStream.serialize(subscriptionStatusResponse).getBytes()); resp.getOutputStream().close(); } - //Upload the license here, which is really just uploading a base64 representation of the keypair - and store it + // Upload the license here, which is really just uploading a base64 representation of the + // keypair - and store it // on disk.. @Override @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) @@ -64,7 +70,7 @@ public class SubscriptionServlet extends HttpServlet { final JSONObject obj = new JSONObject(license); license = obj.getString("base64License"); - if(license != null || !license.isBlank()) { + if (license != null || !license.isBlank()) { // create .dat file to be used later FileWriter fw = new FileWriter("license.dat"); fw.write(license); @@ -77,6 +83,5 @@ public class SubscriptionServlet extends HttpServlet { } } resp.setStatus(500); - } } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/update/UpdateServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/update/UpdateServlet.java index 12419d105d4f9a9cda39258dac48df249f797816..915298bf550601453741616a21f473afce91925f 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/update/UpdateServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/update/UpdateServlet.java @@ -1,33 +1,37 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.api.admin.update; +import static net.jami.jams.server.Server.appUpdater; + import com.jsoniter.output.JsonStream; + import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import net.jami.jams.common.annotations.JsonContent; import net.jami.jams.common.annotations.ScopedServletMethod; import net.jami.jams.common.objects.user.AccessLevel; @@ -35,16 +39,15 @@ import net.jami.jams.common.updater.FullSystemStatusResponse; import java.io.IOException; -import static net.jami.jams.server.Server.appUpdater; - @WebServlet("/api/admin/update") public class UpdateServlet extends HttpServlet { - //Return the current version number and the available version number. + // Return the current version number and the available version number. @Override @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) @JsonContent - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { FullSystemStatusResponse response = new FullSystemStatusResponse(); response.setLocalVersions(appUpdater.getLocalVersions()); response.setRemoteVersions(appUpdater.getRemoteVersions()); @@ -52,12 +55,10 @@ public class UpdateServlet extends HttpServlet { resp.getOutputStream().write(JsonStream.serialize(response).getBytes()); } - //This is the do-update button. + // This is the do-update button. @Override @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) protected void doPost(HttpServletRequest req, HttpServletResponse resp) { - if(appUpdater.getUpdateAvailable()) - appUpdater.doUpdate(); - + if (appUpdater.getUpdateAvailable()) appUpdater.doUpdate(); } } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/users/UserGroupsServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/users/UserGroupsServlet.java index 696eb145b4e5ac577bd8a03db9c7f6aa81e0fb10..8dfbdba37f6283c98c0f3a8c0a12fae149da71f8 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/users/UserGroupsServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/users/UserGroupsServlet.java @@ -1,11 +1,16 @@ package net.jami.jams.server.servlets.api.admin.users; +import static net.jami.jams.server.Server.dataStore; + import com.jsoniter.output.JsonStream; + import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.annotations.JsonContent; import net.jami.jams.common.annotations.ScopedServletMethod; import net.jami.jams.common.dao.StatementElement; @@ -16,8 +21,6 @@ import net.jami.jams.common.objects.user.UserGroupMapping; import java.io.IOException; import java.util.List; -import static net.jami.jams.server.Server.dataStore; - @WebServlet("/api/admin/user/groups/*") @Slf4j public class UserGroupsServlet extends HttpServlet { @@ -40,20 +43,20 @@ public class UserGroupsServlet extends HttpServlet { @JsonContent protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { - String username = req.getPathInfo().replace("/",""); + String username = req.getPathInfo().replace("/", ""); StatementList statementList = new StatementList(); StatementElement st = new StatementElement("username", "=", username, ""); statementList.addStatement(st); - List<UserGroupMapping> result = dataStore.getUserGroupMappingsDao().getObjects(statementList); + List<UserGroupMapping> result = + dataStore.getUserGroupMappingsDao().getObjects(statementList); - if (result.isEmpty()) - resp.sendError(404, "No groups found for this user!"); + if (result.isEmpty()) resp.sendError(404, "No groups found for this user!"); else { resp.getOutputStream().write(JsonStream.serialize(result).getBytes()); resp.setStatus(200); } } -} \ No newline at end of file +} diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/users/UserServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/users/UserServlet.java index 1a4e1c174bf67b823c8ac57fa776740aee99f62f..ee33defd64935b43326ebff7442ace41e10c0e53 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/users/UserServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/users/UserServlet.java @@ -1,79 +1,94 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.api.admin.users; + +import static net.jami.jams.server.Server.certificateAuthority; +import static net.jami.jams.server.Server.dataStore; +import static net.jami.jams.server.Server.nameServer; +import static net.jami.jams.server.Server.userAuthenticationModule; + import com.jsoniter.output.JsonStream; + import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import net.jami.jams.authmodule.PasswordUtil; import net.jami.jams.common.annotations.JsonContent; import net.jami.jams.common.annotations.ScopedServletMethod; import net.jami.jams.common.authentication.AuthenticationSourceType; import net.jami.jams.common.dao.StatementElement; import net.jami.jams.common.dao.StatementList; +import net.jami.jams.common.objects.devices.Device; import net.jami.jams.common.objects.responses.DeviceRevocationResponse; import net.jami.jams.common.objects.user.AccessLevel; import net.jami.jams.common.objects.user.User; +import net.jami.jams.server.core.workflows.RevokeDeviceFlow; import net.jami.jams.server.core.workflows.RevokeUserFlow; + import org.apache.commons.codec.binary.Base64; import org.json.JSONObject; -import java.util.List; -import net.jami.jams.common.objects.devices.Device; -import net.jami.jams.server.core.workflows.RevokeDeviceFlow; - + import java.io.IOException; import java.util.HashMap; +import java.util.List; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; - -import static net.jami.jams.server.Server.certificateAuthority; -import static net.jami.jams.server.Server.dataStore; -import static net.jami.jams.server.Server.nameServer; -import static net.jami.jams.server.Server.userAuthenticationModule; + @WebServlet("/api/admin/user") public class UserServlet extends HttpServlet { - //Get the user + // Get the user @Override @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) @JsonContent protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { StatementList statementList = new StatementList(); - StatementElement st1 = new StatementElement("username","=",req.getParameter("username"),""); + StatementElement st1 = + new StatementElement("username", "=", req.getParameter("username"), ""); statementList.addStatement(st1); if (!dataStore.getUserDao().getObjects(statementList).isEmpty()) { User user = dataStore.getUserDao().getObjects(statementList).get(0); if (certificateAuthority.getLatestCRL().get() != null) - user.setRevoked(certificateAuthority.getLatestCRL().get().getRevokedCertificate(user.getCertificate().getSerialNumber()) != null); + user.setRevoked( + certificateAuthority + .getLatestCRL() + .get() + .getRevokedCertificate( + user.getCertificate().getSerialNumber()) + != null); else user.setRevoked(false); if (!user.getNeedsPasswordReset() && req.getParameter("needPW") != null) { - String pw = PasswordUtil.hashPassword(req.getParameter("password"), Base64.decodeBase64(user.getSalt())); + String pw = + PasswordUtil.hashPassword( + req.getParameter("password"), Base64.decodeBase64(user.getSalt())); StatementList update = new StatementList(); StatementElement st0 = new StatementElement("password", "=", pw, ""); update.addStatement(st0); StatementList constraint = new StatementList(); - StatementElement st = new StatementElement("username", "=", req.getParameter("username"), ""); + StatementElement st = + new StatementElement("username", "=", req.getParameter("username"), ""); constraint.addStatement(st); StatementElement st2 = new StatementElement("needsPasswordReset", "=", "true", ""); update.addStatement(st2); @@ -89,12 +104,18 @@ public class UserServlet extends HttpServlet { resp.sendError(404, "Could not obtain user!"); } } - //Create an internal user - this is always technically available, because internal users have the right to exist. + // Create an internal user - this is always technically available, because internal users have + // the right to exist. @Override @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) @JsonContent - protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - final JSONObject obj = new JSONObject(req.getReader().lines().collect(Collectors.joining(System.lineSeparator()))); + protected void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + final JSONObject obj = + new JSONObject( + req.getReader() + .lines() + .collect(Collectors.joining(System.lineSeparator()))); String pw = obj.getString("password"); if (!pw.isEmpty()) { User user = new User(); @@ -106,71 +127,87 @@ public class UserServlet extends HttpServlet { user.setSalt(Base64.encodeBase64String(salt)); user.setRealm("LOCAL"); user.setUserType(AuthenticationSourceType.LOCAL); - if(userAuthenticationModule.createUser(user.getUserType(),user.getRealm(),nameServer,user)) { - HashMap<String,String> statusInfo = new HashMap<>(); + if (userAuthenticationModule.createUser( + user.getUserType(), user.getRealm(), nameServer, user)) { + HashMap<String, String> statusInfo = new HashMap<>(); statusInfo.put("password", pw); resp.getOutputStream().write(JsonStream.serialize(statusInfo).getBytes()); resp.setStatus(200); return; } } - - resp.sendError(500,"Could not create a user successfully!"); + + resp.sendError(500, "Could not create a user successfully!"); } - //Update user data. + // Update user data. @Override @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException { - final JSONObject obj = new JSONObject(req.getReader().lines().collect(Collectors.joining(System.lineSeparator()))); + final JSONObject obj = + new JSONObject( + req.getReader() + .lines() + .collect(Collectors.joining(System.lineSeparator()))); String pw = obj.getString("password"); String username = obj.getString("username"); StatementList statementList = new StatementList(); - StatementElement st0 = new StatementElement("username","=",username,""); + StatementElement st0 = new StatementElement("username", "=", username, ""); statementList.addStatement(st0); if (dataStore.getUserDao().getObjects(statementList).isEmpty()) { - resp.sendError(404,"User was not found!"); + resp.sendError(404, "User was not found!"); return; } User user = dataStore.getUserDao().getObjects(statementList).get(0); - //Check if he is AD/LDAP - then return a 403, because we can't set such password. - if(user.getUserType() != AuthenticationSourceType.LOCAL){ - resp.sendError(500,"The user is not a local user, therefore we cannot change his data!"); + // Check if he is AD/LDAP - then return a 403, because we can't set such password. + if (user.getUserType() != AuthenticationSourceType.LOCAL) { + resp.sendError( + 500, "The user is not a local user, therefore we cannot change his data!"); return; } byte[] salt = PasswordUtil.generateSalt(); StatementList update = new StatementList(); - StatementElement st1 = new StatementElement("password","=",PasswordUtil.hashPassword(pw, salt),""); + StatementElement st1 = + new StatementElement("password", "=", PasswordUtil.hashPassword(pw, salt), ""); update.addStatement(st1); - StatementElement st2 = new StatementElement("salt","=",Base64.encodeBase64String(salt),""); + StatementElement st2 = + new StatementElement("salt", "=", Base64.encodeBase64String(salt), ""); update.addStatement(st2); StatementList constraint = new StatementList(); - StatementElement st3 = new StatementElement("username","=",username,""); + StatementElement st3 = new StatementElement("username", "=", username, ""); constraint.addStatement(st3); - if(dataStore.getUserDao().updateObject(update,constraint)) resp.setStatus(200); - else resp.sendError(500,"could not update the users's data field!"); + if (dataStore.getUserDao().updateObject(update, constraint)) resp.setStatus(200); + else resp.sendError(500, "could not update the users's data field!"); } - //Revoke a user. + // Revoke a user. @Override @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException { - AtomicReference<DeviceRevocationResponse> devResponse = new AtomicReference<>(RevokeUserFlow.revokeUser(req.getParameter("username"))); + AtomicReference<DeviceRevocationResponse> devResponse = + new AtomicReference<>(RevokeUserFlow.revokeUser(req.getParameter("username"))); StatementList statementList = new StatementList(); - StatementElement st1 = new StatementElement("owner","=",req.getParameter("username"),""); + StatementElement st1 = new StatementElement("owner", "=", req.getParameter("username"), ""); statementList.addStatement(st1); List<Device> devices = dataStore.getDeviceDao().getObjects(statementList); - if(certificateAuthority.getLatestCRL() != null) { - devices.forEach(device -> { - if(certificateAuthority.getLatestCRL().get().getRevokedCertificate(device.getCertificate().getSerialNumber()) == null) - devResponse.set(RevokeDeviceFlow.revokeDevice(req.getParameter("username").toString(), device.getDeviceId())); - }); + if (certificateAuthority.getLatestCRL() != null) { + devices.forEach( + device -> { + if (certificateAuthority + .getLatestCRL() + .get() + .getRevokedCertificate( + device.getCertificate().getSerialNumber()) + == null) + devResponse.set( + RevokeDeviceFlow.revokeDevice( + req.getParameter("username"), device.getDeviceId())); + }); } - if(devResponse.get() != null && devResponse.get().isSuccess()){ + if (devResponse.get() != null && devResponse.get().isSuccess()) { resp.getOutputStream().write(JsonStream.serialize(devResponse).getBytes()); - } - else resp.sendError(500,"An exception has occurred while trying to revoke a user!"); + } else resp.sendError(500, "An exception has occurred while trying to revoke a user!"); } -} \ No newline at end of file +} diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/users/UsersServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/users/UsersServlet.java index d3dd0e4beb7f86c53a49127ef85a121f941a70a0..6ec96c579e07c3100636c8d2bec21ecb76410872 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/users/UsersServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/admin/users/UsersServlet.java @@ -1,47 +1,53 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.api.admin.users; +import static net.jami.jams.server.Server.dataStore; + import com.jsoniter.output.JsonStream; + import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import net.jami.jams.common.annotations.ScopedServletMethod; import net.jami.jams.common.objects.user.AccessLevel; import java.io.IOException; -import static net.jami.jams.server.Server.dataStore; - @WebServlet("/api/admin/users") public class UsersServlet extends HttpServlet { - //Returns a list of users. + // Returns a list of users. @Override @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - resp.getOutputStream().write(JsonStream.serialize(dataStore.getUserDao().getObjects(null).get(0)).getBytes()); + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + resp.getOutputStream() + .write( + JsonStream.serialize(dataStore.getUserDao().getObjects(null).get(0)) + .getBytes()); } } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/contacts/ContactServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/contacts/ContactServlet.java index 739b1d9d65fa96ddea6d5dc03a56a2d18418ff22..246332af817f7ad947f6e61e3a02a3aefd32bb3b 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/contacts/ContactServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/contacts/ContactServlet.java @@ -1,39 +1,44 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.api.auth.contacts; +import static net.jami.jams.server.Server.dataStore; + import com.jsoniter.JsonIterator; import com.jsoniter.output.JsonStream; + import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import net.jami.jams.common.dao.StatementElement; import net.jami.jams.common.dao.StatementList; import net.jami.jams.common.objects.contacts.Contact; import net.jami.jams.common.serialization.tomcat.TomcatCustomErrorHandler; import net.jami.jams.common.utils.ContactMerger; + import org.json.JSONObject; import java.io.IOException; @@ -42,8 +47,6 @@ import java.util.Arrays; import java.util.List; import java.util.Scanner; -import static net.jami.jams.server.Server.dataStore; - @WebServlet("/api/auth/contacts") public class ContactServlet extends HttpServlet { @@ -59,9 +62,11 @@ public class ContactServlet extends HttpServlet { * "removed": 12387873 }, ] */ @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { StatementList statementList = new StatementList(); - statementList.addStatement(new StatementElement("owner", "=", req.getAttribute("username").toString(), "")); + statementList.addStatement( + new StatementElement("owner", "=", req.getAttribute("username").toString(), "")); List<Contact> contactList = dataStore.getContactDao().getObjects(statementList); resp.getOutputStream().write(JsonStream.serialize(contactList).getBytes()); } @@ -80,7 +85,8 @@ public class ContactServlet extends HttpServlet { * @apiError (500) {null} null contact could not be successfully added */ @Override - protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doPut(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { Scanner s = new Scanner(req.getInputStream()).useDelimiter("\\A"); String res = s.hasNext() ? s.next() : ""; final JSONObject obj = new JSONObject(res); @@ -92,15 +98,16 @@ public class ContactServlet extends HttpServlet { contact.setOwner(req.getAttribute("username").toString()); contact.setUri(obj.get("uri").toString()); StatementList statementList = new StatementList(); - statementList.addStatement(new StatementElement("owner", "=", req.getAttribute("username").toString(), "")); + statementList.addStatement( + new StatementElement("owner", "=", req.getAttribute("username").toString(), "")); List<Contact> localList = dataStore.getContactDao().getObjects(statementList); List<Contact> remoteList = new ArrayList<>(); remoteList.add(contact); List<Contact> result = ContactMerger.mergeContacts(localList, remoteList); - if (dataStore.getContactDao().storeContactList(result)) - resp.setStatus(200); + if (dataStore.getContactDao().storeContactList(result)) resp.setStatus(200); else - TomcatCustomErrorHandler.sendCustomError(resp, 500, "could not store a contact due to server-side error"); + TomcatCustomErrorHandler.sendCustomError( + resp, 500, "could not store a contact due to server-side error"); } /** @@ -115,9 +122,11 @@ public class ContactServlet extends HttpServlet { * @apiError (500) {null} null contact could not be successfully deleted */ @Override - protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doDelete(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { StatementList statementList = new StatementList(); - statementList.addStatement(new StatementElement("owner", "=", req.getAttribute("username").toString(), "AND")); + statementList.addStatement( + new StatementElement("owner", "=", req.getAttribute("username").toString(), "AND")); statementList.addStatement(new StatementElement("uri", "=", req.getParameter("uri"), "")); /* * List<Contact> remoteList = @@ -130,10 +139,10 @@ public class ContactServlet extends HttpServlet { * dataStore.getContactDao().getObjects(statementList); List<Contact> result = * ContactMerger.mergeContacts(localList,remoteList); */ - if (dataStore.getContactDao().deleteObject(statementList)) - resp.setStatus(200); + if (dataStore.getContactDao().deleteObject(statementList)) resp.setStatus(200); else - TomcatCustomErrorHandler.sendCustomError(resp, 500, "could not delete a contact due to server-side error"); + TomcatCustomErrorHandler.sendCustomError( + resp, 500, "could not delete a contact due to server-side error"); } /** @@ -151,17 +160,20 @@ public class ContactServlet extends HttpServlet { * @apiError (500) {null} null contact could not be successfully added */ @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { StatementList statementList = new StatementList(); - statementList.addStatement(new StatementElement("owner", "=", req.getAttribute("username").toString(), "")); + statementList.addStatement( + new StatementElement("owner", "=", req.getAttribute("username").toString(), "")); List<Contact> localList = dataStore.getContactDao().getObjects(statementList); - List<Contact> remoteList = Arrays - .asList(JsonIterator.deserialize(req.getInputStream().readAllBytes(), Contact[].class)); + List<Contact> remoteList = + Arrays.asList( + JsonIterator.deserialize( + req.getInputStream().readAllBytes(), Contact[].class)); remoteList.forEach(contact -> contact.setOwner(req.getAttribute("username").toString())); List<Contact> result = ContactMerger.mergeContacts(localList, remoteList); if (!dataStore.getContactDao().storeContactList(result)) TomcatCustomErrorHandler.sendCustomError(resp, 500, "Could not store contacts!"); - else - resp.getOutputStream().write(JsonStream.serialize(result).getBytes()); + else resp.getOutputStream().write(JsonStream.serialize(result).getBytes()); } } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/device/DeviceServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/device/DeviceServlet.java index 5d22274754e9a1ed8881c7f99550f2ffceced44d..79d903b97dc87a88e78f53068eab490ed1732cb5 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/device/DeviceServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/device/DeviceServlet.java @@ -25,8 +25,6 @@ package net.jami.jams.server.servlets.api.auth.device; import static net.jami.jams.server.Server.certificateAuthority; import static net.jami.jams.server.Server.dataStore; -import java.io.IOException; - import com.google.gson.Gson; import com.google.gson.JsonObject; import com.jsoniter.JsonIterator; @@ -37,6 +35,7 @@ import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import net.jami.jams.common.annotations.ScopedServletMethod; import net.jami.jams.common.dao.StatementElement; import net.jami.jams.common.dao.StatementList; @@ -49,6 +48,8 @@ import net.jami.jams.common.serialization.tomcat.TomcatCustomErrorHandler; import net.jami.jams.server.core.workflows.RegisterDeviceFlow; import net.jami.jams.server.core.workflows.RevokeDeviceFlow; +import java.io.IOException; + @WebServlet("/api/auth/device/*") public class DeviceServlet extends HttpServlet { @@ -71,7 +72,8 @@ public class DeviceServlet extends HttpServlet { * @apiError (500) {null} null Device could not be retrieved */ @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { String username = req.getAttribute("username").toString(); String deviceId = req.getPathInfo().replace("/", ""); StatementList statementList = new StatementList(); @@ -81,10 +83,14 @@ public class DeviceServlet extends HttpServlet { statementList.addStatement(st2); Device device = dataStore.getDeviceDao().getObjects(statementList).get(0); if (certificateAuthority.getLatestCRL().get() != null) - device.setRevoked(certificateAuthority.getLatestCRL().get() - .getRevokedCertificate(device.getCertificate().getSerialNumber()) != null); - else - device.setRevoked(false); + device.setRevoked( + certificateAuthority + .getLatestCRL() + .get() + .getRevokedCertificate( + device.getCertificate().getSerialNumber()) + != null); + else device.setRevoked(false); resp.getOutputStream().write(JsonStream.serialize(device).getBytes()); } @@ -115,15 +121,17 @@ public class DeviceServlet extends HttpServlet { * } */ @Override - @ScopedServletMethod(securityGroups = { AccessLevel.USER }) + @ScopedServletMethod(securityGroups = {AccessLevel.USER}) protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { - DeviceRegistrationRequest request = JsonIterator.deserialize(req.getInputStream().readAllBytes(), - DeviceRegistrationRequest.class); - DeviceRegistrationResponse devResponse = RegisterDeviceFlow - .registerDevice(req.getAttribute("username").toString(), request); + DeviceRegistrationRequest request = + JsonIterator.deserialize( + req.getInputStream().readAllBytes(), DeviceRegistrationRequest.class); + DeviceRegistrationResponse devResponse = + RegisterDeviceFlow.registerDevice(req.getAttribute("username").toString(), request); if (devResponse == null) { - TomcatCustomErrorHandler.sendCustomError(resp, 500, "could not enroll a device due to server-side error"); + TomcatCustomErrorHandler.sendCustomError( + resp, 500, "could not enroll a device due to server-side error"); return; } @@ -191,7 +199,8 @@ public class DeviceServlet extends HttpServlet { * @apiError (500) {null} null device name could not be changed */ @Override - protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doPut(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { String username = req.getAttribute("username").toString(); String deviceId = req.getPathInfo().replace("/", ""); String deviceName = req.getParameter("deviceName"); @@ -203,11 +212,10 @@ public class DeviceServlet extends HttpServlet { StatementElement st2 = new StatementElement("deviceId", "=", deviceId, ""); update.addStatement(st1); update.addStatement(st2); - if (dataStore.getDeviceDao().updateObject(update, constraint)) - resp.setStatus(200); + if (dataStore.getDeviceDao().updateObject(update, constraint)) resp.setStatus(200); else - TomcatCustomErrorHandler.sendCustomError(resp, 500, - "could not update device information due to server-side error"); + TomcatCustomErrorHandler.sendCustomError( + resp, 500, "could not update device information due to server-side error"); } /** @@ -222,25 +230,29 @@ public class DeviceServlet extends HttpServlet { * @apiError (500) {null} null device could not be deactivated */ @Override - @ScopedServletMethod(securityGroups = { AccessLevel.USER }) - protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + @ScopedServletMethod(securityGroups = {AccessLevel.USER}) + protected void doDelete(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { String deviceId = req.getPathInfo().replace("/", ""); // If the device does not belong to the user throw a 403 StatementList statementList = new StatementList(); - StatementElement statementElement = new StatementElement("owner", "=", req.getAttribute("username").toString(), - ""); + StatementElement statementElement = + new StatementElement("owner", "=", req.getAttribute("username").toString(), ""); statementList.addStatement(statementElement); if (dataStore.getDeviceDao().getObjects(statementList).stream() - .filter(device -> device.getDeviceId().equals(deviceId)).count() == 0) { - TomcatCustomErrorHandler.sendCustomError(resp, 403, - "You do not have sufficient rights to revoke this device!"); + .filter(device -> device.getDeviceId().equals(deviceId)) + .count() + == 0) { + TomcatCustomErrorHandler.sendCustomError( + resp, 403, "You do not have sufficient rights to revoke this device!"); return; } - DeviceRevocationResponse devResponse = RevokeDeviceFlow.revokeDevice(req.getAttribute("username").toString(), - deviceId); + DeviceRevocationResponse devResponse = + RevokeDeviceFlow.revokeDevice(req.getAttribute("username").toString(), deviceId); if (devResponse != null) resp.getOutputStream().write(JsonStream.serialize(devResponse).getBytes()); else - TomcatCustomErrorHandler.sendCustomError(resp, 500, "could not revoke device due to server-side error"); + TomcatCustomErrorHandler.sendCustomError( + resp, 500, "could not revoke device due to server-side error"); } } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/device/DevicesServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/device/DevicesServlet.java index 56e535032591eeb752024cfc7a8c7519be879360..e99fa20378cce9f2bbf15c92f8ca60b87d963056 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/device/DevicesServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/device/DevicesServlet.java @@ -1,33 +1,38 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.api.auth.device; +import static net.jami.jams.server.Server.certificateAuthority; +import static net.jami.jams.server.Server.dataStore; + import com.jsoniter.output.JsonStream; + import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import net.jami.jams.common.dao.StatementElement; import net.jami.jams.common.dao.StatementList; import net.jami.jams.common.objects.devices.Device; @@ -35,9 +40,6 @@ import net.jami.jams.common.objects.devices.Device; import java.io.IOException; import java.util.List; -import static net.jami.jams.server.Server.certificateAuthority; -import static net.jami.jams.server.Server.dataStore; - @WebServlet("/api/auth/devices") public class DevicesServlet extends HttpServlet { @@ -59,22 +61,27 @@ public class DevicesServlet extends HttpServlet { * @apiError (500) {null} null Device could not be retrieved */ @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { String username = req.getAttribute("username").toString(); StatementList statementList = new StatementList(); - statementList.addStatement(new StatementElement("owner","=",username,"")); + statementList.addStatement(new StatementElement("owner", "=", username, "")); List<Device> devices = dataStore.getDeviceDao().getObjects(statementList); - if(certificateAuthority.getLatestCRL() != null) { - devices.forEach(device -> { - device.setRevoked(certificateAuthority.getLatestCRL().get().getRevokedCertificate(device.getCertificate().getSerialNumber()) != null); - }); - } - else{ + if (certificateAuthority.getLatestCRL() != null) { + devices.forEach( + device -> { + device.setRevoked( + certificateAuthority + .getLatestCRL() + .get() + .getRevokedCertificate( + device.getCertificate().getSerialNumber()) + != null); + }); + } else { devices.forEach(device -> device.setRevoked(false)); } resp.getOutputStream().write(JsonStream.serialize(devices).getBytes()); resp.setStatus(200); } - - } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/directory/DirectoriesServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/directory/DirectoriesServlet.java index 6d30302f596edb765addde4602b6ee62d0a15027..c4e8aadc6b3221848205752774f6b59b2c75a9b8 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/directory/DirectoriesServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/directory/DirectoriesServlet.java @@ -1,39 +1,41 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.api.auth.directory; +import static net.jami.jams.server.Server.userAuthenticationModule; + import com.jsoniter.output.JsonStream; + import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import net.jami.jams.common.annotations.JsonContent; import java.io.IOException; -import static net.jami.jams.server.Server.userAuthenticationModule; - @WebServlet("/api/auth/directories") public class DirectoriesServlet extends HttpServlet { @@ -63,7 +65,11 @@ public class DirectoriesServlet extends HttpServlet { */ @Override @JsonContent - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - resp.getOutputStream().write(JsonStream.serialize(userAuthenticationModule.getAuthSources().keySet()).getBytes()); + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + resp.getOutputStream() + .write( + JsonStream.serialize(userAuthenticationModule.getAuthSources().keySet()) + .getBytes()); } } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/directory/DirectoryEntryServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/directory/DirectoryEntryServlet.java index 33b5d5bdd92c3f304316e3e6efb4fe320b957c92..414efe02d377ea123fc6d1debd8aad89b3b2edc6 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/directory/DirectoryEntryServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/directory/DirectoryEntryServlet.java @@ -1,33 +1,38 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.api.auth.directory; +import static net.jami.jams.server.Server.dataStore; +import static net.jami.jams.server.Server.userAuthenticationModule; + import com.jsoniter.output.JsonStream; + import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import net.jami.jams.common.authentication.AuthenticationSourceType; import net.jami.jams.common.authmodule.AuthModuleKey; import net.jami.jams.common.dao.StatementElement; @@ -40,10 +45,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; -import static net.jami.jams.server.Server.dataStore; -import static net.jami.jams.server.Server.userAuthenticationModule; - -//This is an endpoint to manipulate directory entry-data, this make sense only for local setups. +// This is an endpoint to manipulate directory entry-data, this make sense only for local setups. @WebServlet("/api/auth/directory/entry") public class DirectoryEntryServlet extends HttpServlet { @@ -195,44 +197,66 @@ public class DirectoryEntryServlet extends HttpServlet { * @apiError (500) {null} null could not return any authentication sources */ @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - if(req.getParameter("jamiId") != null){ + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + if (req.getParameter("jamiId") != null) { StatementList statementList = new StatementList(); - StatementElement statementElement = new StatementElement("jamiId","=",req.getParameter("jamiId"),null); + StatementElement statementElement = + new StatementElement("jamiId", "=", req.getParameter("jamiId"), null); statementList.addStatement(statementElement); User user = dataStore.getUserDao().getObjects(statementList).get(0); List<UserProfile> userProfiles = new ArrayList<>(); - userAuthenticationModule.getAuthSources().forEach((k, v) -> { - userProfiles.addAll(v.searchUserProfiles(user.getUsername(), "LOGON_NAME", Optional.empty())); - }); - if(req.getParameter("format") != null && req.getParameter("format").equals("vcard")){ + userAuthenticationModule + .getAuthSources() + .forEach( + (k, v) -> { + userProfiles.addAll( + v.searchUserProfiles( + user.getUsername(), + "LOGON_NAME", + Optional.empty())); + }); + if (req.getParameter("format") != null && req.getParameter("format").equals("vcard")) { resp.getOutputStream().write(userProfiles.get(0).getAsVCard().getBytes()); - } - else resp.getOutputStream().write(JsonStream.serialize(userProfiles.get(0)).getBytes()); + } else + resp.getOutputStream().write(JsonStream.serialize(userProfiles.get(0)).getBytes()); return; } if (req.getParameter("directory") != null && req.getParameter("directoryType") != null) { - List<UserProfile> profiles = userAuthenticationModule.getAuthSources() - .get(new AuthModuleKey(req.getParameter("directory"), AuthenticationSourceType.fromString(req.getParameter("directoryType")))) - .searchUserProfiles(req.getParameter("username"), "LOGON_NAME", Optional.empty()); - if(req.getParameter("format") != null && req.getParameter("format").equals("vcard")){ + List<UserProfile> profiles = + userAuthenticationModule + .getAuthSources() + .get( + new AuthModuleKey( + req.getParameter("directory"), + AuthenticationSourceType.fromString( + req.getParameter("directoryType")))) + .searchUserProfiles( + req.getParameter("username"), "LOGON_NAME", Optional.empty()); + if (req.getParameter("format") != null && req.getParameter("format").equals("vcard")) { resp.getOutputStream().write(profiles.get(0).getAsVCard().getBytes()); - } - else resp.getOutputStream().write(JsonStream.serialize(profiles.get(0)).getBytes()); + } else resp.getOutputStream().write(JsonStream.serialize(profiles.get(0)).getBytes()); return; } List<UserProfile> userProfiles = new ArrayList<>(); - userAuthenticationModule.getAuthSources().forEach((k, v) -> { - userProfiles.addAll(v.searchUserProfiles(req.getParameter("username"), "LOGON_NAME", Optional.empty())); - }); - if(req.getParameter("format") != null && req.getParameter("format").equals("vcard")){ + userAuthenticationModule + .getAuthSources() + .forEach( + (k, v) -> { + userProfiles.addAll( + v.searchUserProfiles( + req.getParameter("username"), + "LOGON_NAME", + Optional.empty())); + }); + if (req.getParameter("format") != null && req.getParameter("format").equals("vcard")) { resp.getOutputStream().write(userProfiles.get(0).getAsVCard().getBytes()); - } - else resp.getOutputStream().write(JsonStream.serialize(userProfiles.get(0)).getBytes()); + } else resp.getOutputStream().write(JsonStream.serialize(userProfiles.get(0)).getBytes()); } @Override - protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - //This should work to modify a profile only in the case of a LOCAL directory. + protected void doPut(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + // This should work to modify a profile only in the case of a LOCAL directory. } } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/directory/SearchDirectoryServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/directory/SearchDirectoryServlet.java index 057bed081c89a0bb35c6f8313c146b2e4bee8e2d..4319ce71f1ff86163c307523caec210d534619f8 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/directory/SearchDirectoryServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/directory/SearchDirectoryServlet.java @@ -26,24 +26,16 @@ import static net.jami.jams.server.Server.dataStore; import static net.jami.jams.server.Server.nameServer; import static net.jami.jams.server.Server.userAuthenticationModule; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.TreeSet; -import java.util.concurrent.ConcurrentHashMap; - -import org.json.JSONObject; - import com.jsoniter.JsonIterator; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import lombok.extern.slf4j.Slf4j; + +import net.jami.datastore.main.DataStore; import net.jami.jams.common.annotations.JsonContent; import net.jami.jams.common.authentication.AuthenticationSource; import net.jami.jams.common.authentication.AuthenticationSourceType; @@ -58,6 +50,17 @@ import net.jami.jams.common.objects.user.User; import net.jami.jams.common.objects.user.UserGroupMapping; import net.jami.jams.common.objects.user.UserProfile; +import org.json.JSONObject; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.TreeSet; +import java.util.concurrent.ConcurrentHashMap; + @Slf4j @WebServlet("/api/auth/directory/search") public class SearchDirectoryServlet extends HttpServlet { @@ -75,24 +78,25 @@ public class SearchDirectoryServlet extends HttpServlet { @JsonContent protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { Optional<Integer> page; - if (req.getParameter("page") == null) - page = Optional.empty(); - else - page = Optional.ofNullable(Integer.parseInt(req.getParameter("page"))); + if (req.getParameter("page") == null) page = Optional.empty(); + else page = Optional.ofNullable(Integer.parseInt(req.getParameter("page"))); - ConcurrentHashMap<AuthModuleKey, AuthenticationSource> authSources = new ConcurrentHashMap<>( - userAuthenticationModule.getAuthSources()); + ConcurrentHashMap<AuthModuleKey, AuthenticationSource> authSources = + new ConcurrentHashMap<>(userAuthenticationModule.getAuthSources()); // Check if the actual user is allowed to lookup in the directory Group group = new Group(); StatementList statementList1 = new StatementList(); - statementList1.addStatement(new StatementElement("username", "=", req.getAttribute("username").toString(), "")); - List<UserGroupMapping> mappings = dataStore.getUserGroupMappingsDao().getObjects(statementList1); + statementList1.addStatement( + new StatementElement("username", "=", req.getAttribute("username").toString(), "")); + List<UserGroupMapping> mappings = + dataStore.getUserGroupMappingsDao().getObjects(statementList1); if (mappings != null && !mappings.isEmpty()) { statementList1 = new StatementList(); - statementList1.addStatement(new StatementElement("id", "=", mappings.get(0).getGroupId(), "")); - group = dataStore.getGroupDao().getObjects(statementList1).get(0); + statementList1.addStatement( + new StatementElement("id", "=", mappings.get(0).getGroupId(), "")); + group = dataStore.getGroupDao().getObjects(statementList1).get(0); } if (!group.isEmpty() && group.hasBlueprint()) { @@ -101,68 +105,91 @@ public class SearchDirectoryServlet extends HttpServlet { statementList2.addStatement((st2)); try { Policy policy = dataStore.getPolicyDao().getObjects(statementList2).get(0); - PolicyData policyData = JsonIterator.deserialize(policy.getPolicyData(),PolicyData.class); - if(!policyData.getAllowLookup()) { + PolicyData policyData = + JsonIterator.deserialize(policy.getPolicyData(), PolicyData.class); + if (!policyData.getAllowLookup()) { resp.sendError(403, "Operation not allowed!"); return; } } catch (Exception e1) { - log.warn("No policy available for user - not adding a policy component to response"); + log.warn( + "No policy available for user - not adding a policy component to response"); } } if (authSources.size() > 1) { - authSources.forEach((k, v) -> { - if (k.getType() == AuthenticationSourceType.LOCAL) - authSources.remove(k); - }); + authSources.forEach( + (k, v) -> { + if (k.getType() == AuthenticationSourceType.LOCAL) authSources.remove(k); + }); } - authSources.forEach((k, v) -> { - if (req.getParameter("queryString").equals("*")) - userProfiles = v.searchUserProfiles(req.getParameter("queryString"), "FULL_TEXT_NAME", page); - else { - userProfiles = v.searchUserProfiles(req.getParameter("queryString"), "FULL_TEXT_NAME", page); - if (userProfiles.isEmpty() && userProfiles - .addAll(v.searchUserProfiles(req.getParameter("queryString"), "LOGON_NAME", page))) { - Set<UserProfile> s = new TreeSet<UserProfile>(new Comparator<UserProfile>() { - @Override - public int compare(UserProfile o1, UserProfile o2) { - if (o1.getUsername().equals(o2.getUsername())) - return 0; - return 1; + authSources.forEach( + (k, v) -> { + if (req.getParameter("queryString").equals("*")) + userProfiles = + v.searchUserProfiles( + req.getParameter("queryString"), "FULL_TEXT_NAME", page); + else { + userProfiles = + v.searchUserProfiles( + req.getParameter("queryString"), "FULL_TEXT_NAME", page); + if (userProfiles.isEmpty() + && userProfiles.addAll( + v.searchUserProfiles( + req.getParameter("queryString"), + "LOGON_NAME", + page))) { + Set<UserProfile> s = + new TreeSet<UserProfile>( + new Comparator<UserProfile>() { + @Override + public int compare(UserProfile o1, UserProfile o2) { + if (o1.getUsername().equals(o2.getUsername())) + return 0; + return 1; + } + }); + s.addAll(userProfiles); + userProfiles = new ArrayList<>(s); } - }); - s.addAll(userProfiles); - userProfiles = new ArrayList<>(s); - } - - } - userProfiles.parallelStream().forEach(profile -> { - StatementList statementList = new StatementList(); - StatementElement statementElement = new StatementElement("username", "=", profile.getUsername(), ""); - statementList.addStatement(statementElement); - List<User> results = new ArrayList<>(); - while (results.size() == 0) { - results = dataStore.getUserDao().getObjects(statementList); - if (results.size() == 0) { - User user = new User(); - user.setUsername(profile.getUsername()); - user.setRealm(k.getRealm()); - user.setUserType(k.getType()); - user.setAccessLevel(AccessLevel.USER); - userAuthenticationModule.createUser(user.getUserType(), user.getRealm(), nameServer, user); - } else { - profile.setId(results.get(0).getJamiId()); } - } - }); - }); + userProfiles.parallelStream() + .forEach( + profile -> { + StatementList statementList = new StatementList(); + StatementElement statementElement = + new StatementElement( + "username", "=", profile.getUsername(), ""); + statementList.addStatement(statementElement); + List<User> results = new ArrayList<>(); + while (results.size() == 0) { + results = + dataStore + .getUserDao() + .getObjects(statementList); + if (results.size() == 0) { + User user = new User(); + user.setUsername(profile.getUsername()); + user.setRealm(k.getRealm()); + user.setUserType(k.getType()); + user.setAccessLevel(AccessLevel.USER); + userAuthenticationModule.createUser( + user.getUserType(), + user.getRealm(), + nameServer, + user); + } else { + profile.setId(results.get(0).getJamiId()); + } + } + }); + }); JSONObject obj = new JSONObject(); obj.put("profiles", userProfiles); - obj.put("numPages", dataStore.NUM_PAGES); + obj.put("numPages", DataStore.NUM_PAGES); resp.getOutputStream().write((obj.toString()).getBytes()); resp.setStatus(200); } -} \ No newline at end of file +} diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/login/AuthRequestProcessor.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/login/AuthRequestProcessor.java index 181bc0963ac41aab5bb96d115294b8defe01ee24..cb5c9ce6c1b528673466e2ce3579d4d3b781eee2 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/login/AuthRequestProcessor.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/login/AuthRequestProcessor.java @@ -1,49 +1,51 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.api.auth.login; +import static net.jami.jams.server.Server.certificateAuthority; +import static net.jami.jams.server.Server.userAuthenticationModule; + import net.jami.jams.common.authmodule.AuthTokenResponse; import java.security.cert.X509Certificate; -import static net.jami.jams.server.Server.certificateAuthority; -import static net.jami.jams.server.Server.userAuthenticationModule; - public class AuthRequestProcessor { - //This case does not talk to the authentication module, only to the ca - public static AuthTokenResponse processX509Auth(X509Certificate[] certificates){ - return userAuthenticationModule.authenticateUser(certificates,certificateAuthority.getLatestCRL().get(), - certificateAuthority.getCA()); + // This case does not talk to the authentication module, only to the ca + public static AuthTokenResponse processX509Auth(X509Certificate[] certificates) { + return userAuthenticationModule.authenticateUser( + certificates, + certificateAuthority.getLatestCRL().get(), + certificateAuthority.getCA()); } - public static AuthTokenResponse processUsernamePasswordAuth(String username, String password){ - return userAuthenticationModule.authenticateUser(username,password); + public static AuthTokenResponse processUsernamePasswordAuth(String username, String password) { + return userAuthenticationModule.authenticateUser(username, password); } - public static AuthTokenResponse processUsernamePasswordAuth(String authorization){ + public static AuthTokenResponse processUsernamePasswordAuth(String authorization) { String[] credentials = Decoders.decodeAuthHeader(authorization); - if(credentials != null && credentials.length == 2) { + if (credentials != null && credentials.length == 2) { return userAuthenticationModule.authenticateUser(credentials[0], credentials[1]); } return null; diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/login/Decoders.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/login/Decoders.java index 123eb69aaa309d26693c56a12e37ce46e8890045..23f719bd7d332f71157dd5661f9115589b9f9979 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/login/Decoders.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/login/Decoders.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.api.auth.login; import java.nio.charset.StandardCharsets; @@ -27,13 +27,13 @@ import java.util.Base64; public class Decoders { - public static String[] decodeAuthHeader(String authorization){ + public static String[] decodeAuthHeader(String authorization) { if (authorization != null && authorization.toLowerCase().startsWith("basic")) { // Authorization: Basic base64credentials String base64Credentials = authorization.substring("Basic".length()).trim(); byte[] credDecoded = Base64.getDecoder().decode(base64Credentials); - //TODO: change this to char array + // TODO: change this to char array String credentials = new String(credDecoded, StandardCharsets.UTF_8); // credentials = username:password return credentials.split(":", 2); diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/login/LoginRequest.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/login/LoginRequest.java index a4af81a98649a68116e9a3701cb6a1a9809df33e..a383b3965c77920b7acf97ce409f6fd9e34e6b17 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/login/LoginRequest.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/login/LoginRequest.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.api.auth.login; import lombok.Getter; diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/policyData/PolicyDataServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/policyData/PolicyDataServlet.java index c2e2d85d3f220df15cca202df31a4e25f250a75a..0087a0aff6755df41625267aea13c2473701649f 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/policyData/PolicyDataServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/policyData/PolicyDataServlet.java @@ -1,23 +1,21 @@ /* -* Copyright (C) 2023 by Savoir-faire Linux -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2023 by Savoir-faire Linux + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.api.auth.policyData; -import java.io.IOException; - import com.google.gson.JsonObject; import com.google.gson.JsonParser; @@ -26,10 +24,13 @@ import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import net.jami.jams.common.objects.user.Group; import net.jami.jams.server.core.workflows.RegisterDeviceFlow; import net.jami.jams.server.servlets.api.auth.device.DeviceServlet; +import java.io.IOException; + @WebServlet("/api/auth/policyData") public class PolicyDataServlet extends HttpServlet { @@ -62,7 +63,8 @@ public class PolicyDataServlet extends HttpServlet { * @apiError (500) {null} null Policy Data could not be retrieved */ @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { String username = req.getAttribute("username").toString(); Group group = RegisterDeviceFlow.getGroupByUsername(username); diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/user/UserProfileServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/user/UserProfileServlet.java index fc28c2bf7e74ca3a1dd4c6f6745cb16343cdafd2..55e3b2a44955020b24fa9a6a63e15e4ea1483fce 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/user/UserProfileServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/user/UserProfileServlet.java @@ -22,42 +22,46 @@ */ package net.jami.jams.server.servlets.api.auth.user; +import static net.jami.jams.server.Server.userAuthenticationModule; + import com.jsoniter.output.JsonStream; + import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import net.jami.jams.common.annotations.JsonContent; import net.jami.jams.common.objects.user.UserProfile; import java.io.IOException; -import static net.jami.jams.server.Server.dataStore; -import static net.jami.jams.server.Server.userAuthenticationModule; - @WebServlet("/api/auth/userprofile/*") @JsonContent public class UserProfileServlet extends HttpServlet { - //Get the user profile + // Get the user profile @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { final UserProfile[] profile = new UserProfile[1]; - String username = req.getPathInfo().replace("/",""); + String username = req.getPathInfo().replace("/", ""); - userAuthenticationModule.getAuthSources().forEach((k, v) -> { - if (v.getUserProfile(username) != null) - profile[0] = v.getUserProfile(username); - }); + userAuthenticationModule + .getAuthSources() + .forEach( + (k, v) -> { + if (v.getUserProfile(username) != null) + profile[0] = v.getUserProfile(username); + }); if (profile[0] != null) { resp.getOutputStream().write(JsonStream.serialize(profile[0]).getBytes()); resp.setStatus(200); } else { - resp.sendError(500,"User profile was not found!"); - return; + resp.sendError(500, "User profile was not found!"); } } -} \ No newline at end of file +} diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/user/UserServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/user/UserServlet.java index 1fe53042ac53ff1733766445e0732d0faba12b45..4fb2a126ffd955304798c0bf795272ae655b14fe 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/user/UserServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/auth/user/UserServlet.java @@ -1,33 +1,38 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.api.auth.user; +import static net.jami.jams.server.Server.certificateAuthority; +import static net.jami.jams.server.Server.dataStore; + import com.jsoniter.output.JsonStream; + import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import net.jami.jams.common.annotations.ScopedServletMethod; import net.jami.jams.common.authentication.AuthenticationSourceType; import net.jami.jams.common.dao.StatementElement; @@ -37,13 +42,10 @@ import net.jami.jams.common.objects.user.User; import java.io.IOException; -import static net.jami.jams.server.Server.certificateAuthority; -import static net.jami.jams.server.Server.dataStore; - @WebServlet("/api/auth/user") public class UserServlet extends HttpServlet { - //User can "read" himself. + // User can "read" himself. /** * @apiVersion 1.0.0 * @api {get} /api/auth/user Get JAMS user info @@ -70,24 +72,30 @@ public class UserServlet extends HttpServlet { */ @Override @ScopedServletMethod(securityGroups = {AccessLevel.USER}) - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { StatementList statementList = new StatementList(); - StatementElement st = new StatementElement("username","=",req.getAttribute("username").toString(),""); + StatementElement st = + new StatementElement("username", "=", req.getAttribute("username").toString(), ""); statementList.addStatement(st); if (!dataStore.getUserDao().getObjects(statementList).isEmpty()) { User user = dataStore.getUserDao().getObjects(statementList).get(0); - if(certificateAuthority.getLatestCRL().get() != null) { - user.setRevoked(certificateAuthority.getLatestCRL().get().getRevokedCertificate(user.getCertificate().getSerialNumber()) != null); - } - else user.setRevoked(false); + if (certificateAuthority.getLatestCRL().get() != null) { + user.setRevoked( + certificateAuthority + .getLatestCRL() + .get() + .getRevokedCertificate( + user.getCertificate().getSerialNumber()) + != null); + } else user.setRevoked(false); resp.setStatus(200); resp.getOutputStream().write(JsonStream.serialize(user).getBytes()); - } - else resp.sendError(404, "User was not found!"); + } else resp.sendError(404, "User was not found!"); } - //The user can update 3 fields: password,privatekey,publickey - //For now we do not consider the possibility for privatekey, publickey for other reasons. + // The user can update 3 fields: password,privatekey,publickey + // For now we do not consider the possibility for privatekey, publickey for other reasons. /** * @apiVersion 1.0.0 * @api {put} /api/auth/user Modify the user's info (for now just the password) @@ -102,21 +110,24 @@ public class UserServlet extends HttpServlet { @ScopedServletMethod(securityGroups = AccessLevel.USER) protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { String username = req.getAttribute("username").toString(); - //Check if he is AD/LDAP - then return a 403, because we can't set such password. + // Check if he is AD/LDAP - then return a 403, because we can't set such password. StatementList select = new StatementList(); - StatementElement st = new StatementElement("username","=",username,""); + StatementElement st = new StatementElement("username", "=", username, ""); select.addStatement(st); - if(dataStore.getUserDao().getObjects(select).get(0).getUserType() != AuthenticationSourceType.LOCAL){ - resp.sendError(403,"The user is not a local user, therefore we cannot change his data!"); + if (dataStore.getUserDao().getObjects(select).get(0).getUserType() + != AuthenticationSourceType.LOCAL) { + resp.sendError( + 403, "The user is not a local user, therefore we cannot change his data!"); return; } StatementList update = new StatementList(); - StatementElement st0 = new StatementElement("password","=",req.getParameter("password"),""); + StatementElement st0 = + new StatementElement("password", "=", req.getParameter("password"), ""); update.addStatement(st0); StatementList constraint = new StatementList(); - StatementElement st1 = new StatementElement("username","=",username,""); + StatementElement st1 = new StatementElement("username", "=", username, ""); constraint.addStatement(st1); - if(dataStore.getUserDao().updateObject(update,constraint)) resp.setStatus(200); - else resp.sendError(500,"could not update the users's data field!"); + if (dataStore.getUserDao().updateObject(update, constraint)) resp.setStatus(200); + else resp.sendError(500, "could not update the users's data field!"); } } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/image/FileHandlerServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/image/FileHandlerServlet.java index 6f9b108c24eb5273bd428cad7f2826230ff75c85..9ac1bb43ec76f9a50d719d6283bc0140929cd2fe 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/image/FileHandlerServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/image/FileHandlerServlet.java @@ -1,14 +1,5 @@ package net.jami.jams.server.servlets.api.image; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; - import jakarta.servlet.ServletException; import jakarta.servlet.annotation.MultipartConfig; import jakarta.servlet.annotation.WebServlet; @@ -16,16 +7,35 @@ import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.Part; + import lombok.extern.slf4j.Slf4j; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + @MultipartConfig @Slf4j @WebServlet("/api/image/filehandler/*") public class FileHandlerServlet extends HttpServlet { private static final String IMAGES_DIR = "images"; - private static final String SAVE_DIR = ".." + File.separator + ".." + File.separator + ".." + File.separator + ".." - + File.separator + ".." + File.separator + IMAGES_DIR; + private static final String SAVE_DIR = + ".." + + File.separator + + ".." + + File.separator + + ".." + + File.separator + + ".." + + File.separator + + ".." + + File.separator + + IMAGES_DIR; /** * @apiVersion 1.0.0 @@ -70,9 +80,20 @@ public class FileHandlerServlet extends HttpServlet { imagesFolder.mkdirs(); - File imagesFolderLogo = new File(IMAGES_DIR + File.separator + blueprintName + File.separator + "logo"); - File imagesFolderBackground = new File( - IMAGES_DIR + File.separator + blueprintName + File.separator + "background"); + File imagesFolderLogo = + new File( + IMAGES_DIR + + File.separator + + blueprintName + + File.separator + + "logo"); + File imagesFolderBackground = + new File( + IMAGES_DIR + + File.separator + + blueprintName + + File.separator + + "background"); imagesFolderLogo.mkdirs(); imagesFolderBackground.mkdirs(); @@ -82,8 +103,14 @@ public class FileHandlerServlet extends HttpServlet { String fileName = filePart.getSubmittedFileName(); for (Part part : request.getParts()) { - part.write(SAVE_DIR + File.separator + blueprintName + File.separator + imageType + File.separator - + fileName); + part.write( + SAVE_DIR + + File.separator + + blueprintName + + File.separator + + imageType + + File.separator + + fileName); } response.setStatus(HttpServletResponse.SC_OK); diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/install/CachedObjects.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/install/CachedObjects.java index b6fcf1e010bef3594e7358d0d55e3100a1849504..c8cf0c6dd6f62585033c90ca1241998b07f603d8 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/install/CachedObjects.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/install/CachedObjects.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.api.install; import net.jami.jams.common.authentication.activedirectory.ActiveDirectorySettings; diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/install/CreateAuthSourceServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/install/CreateAuthSourceServlet.java index 51a757fb0f4fb9d8a9462f63e5251a2aeac9f7fd..cf189835c45b00fdd7562ece0b31059c614e5067 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/install/CreateAuthSourceServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/install/CreateAuthSourceServlet.java @@ -1,35 +1,40 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.api.install; +import static net.jami.jams.server.Server.userAuthenticationModule; + import com.jsoniter.JsonIterator; import com.jsoniter.output.JsonStream; + import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.annotations.ScopedServletMethod; import net.jami.jams.common.authentication.AuthenticationSourceType; import net.jami.jams.common.objects.requests.CreateAuthSourceRequest; @@ -37,47 +42,52 @@ import net.jami.jams.common.objects.user.AccessLevel; import java.io.IOException; -import static net.jami.jams.server.Server.userAuthenticationModule; - @WebServlet("/api/install/auth") @Slf4j public class CreateAuthSourceServlet extends HttpServlet { @Override @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { super.doGet(req, resp); } @Override @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) - protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - CreateAuthSourceRequest authSourceRequest = JsonIterator.deserialize( - req.getInputStream().readAllBytes(),CreateAuthSourceRequest.class); + protected void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + CreateAuthSourceRequest authSourceRequest = + JsonIterator.deserialize( + req.getInputStream().readAllBytes(), CreateAuthSourceRequest.class); CachedObjects.localAuthSettings = null; CachedObjects.activeDirectorySettings = null; CachedObjects.ldapSettings = null; boolean error = false; - switch (authSourceRequest.getType()){ + switch (authSourceRequest.getType()) { case LOCAL: CachedObjects.localAuthSettings = authSourceRequest.getLocalAuthSettings(); break; case LDAP: - if(userAuthenticationModule.testModuleConfiguration(AuthenticationSourceType.LDAP, - JsonStream.serialize(authSourceRequest.getLdapSettings()))){ + if (userAuthenticationModule.testModuleConfiguration( + AuthenticationSourceType.LDAP, + JsonStream.serialize(authSourceRequest.getLdapSettings()))) { CachedObjects.ldapSettings = authSourceRequest.getLdapSettings(); - } - else error = true; + } else error = true; break; case AD: - if(userAuthenticationModule.testModuleConfiguration(AuthenticationSourceType.AD, + if (userAuthenticationModule.testModuleConfiguration( + AuthenticationSourceType.AD, JsonStream.serialize(authSourceRequest.getActiveDirectorySettings()))) { - CachedObjects.activeDirectorySettings = authSourceRequest.getActiveDirectorySettings(); - } - else error = true; + CachedObjects.activeDirectorySettings = + authSourceRequest.getActiveDirectorySettings(); + } else error = true; break; } - if(error) resp.sendError(500,"The supplied configuration is invalid or the connectivity tests has failed"); + if (error) + resp.sendError( + 500, + "The supplied configuration is invalid or the connectivity tests has failed"); else CachedObjects.endpoint = "/api/install/settings"; } } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/install/CreateCAServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/install/CreateCAServlet.java index 7a813d1d9d368299094ca4f6b98000d8a67a7cc4..aab5313254594af58855a6b29dc692a004651910 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/install/CreateCAServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/install/CreateCAServlet.java @@ -1,33 +1,35 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.api.install; import com.jsoniter.JsonIterator; + import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import net.jami.jams.common.annotations.ScopedServletMethod; import net.jami.jams.common.objects.requests.CreateCARequest; import net.jami.jams.common.objects.user.AccessLevel; @@ -40,18 +42,23 @@ public class CreateCAServlet extends HttpServlet { @Override @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { super.doGet(req, resp); } @Override @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) - protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - CreateCARequest caRequest = JsonIterator.deserialize(req.getInputStream().readAllBytes(),CreateCARequest.class); - if(!Validator.validateCARequests(caRequest)){ - resp.sendError(500,"Certificate was either not a CA or the private key did not match the certificate"); - } - else{ + protected void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + CreateCARequest caRequest = + JsonIterator.deserialize( + req.getInputStream().readAllBytes(), CreateCARequest.class); + if (!Validator.validateCARequests(caRequest)) { + resp.sendError( + 500, + "Certificate was either not a CA or the private key did not match the certificate"); + } else { CachedObjects.createCARequest = caRequest; CachedObjects.endpoint = "/api/install/auth"; } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/install/CreateServerSettingsServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/install/CreateServerSettingsServlet.java index 71ee86d12a7096973dbcf5013b11c767e52e4acc..c11d2b917de293be73710dbb4bde658e2aa47f09 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/install/CreateServerSettingsServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/install/CreateServerSettingsServlet.java @@ -1,33 +1,35 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.api.install; import com.jsoniter.JsonIterator; + import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import net.jami.jams.common.annotations.ScopedServletMethod; import net.jami.jams.common.cryptoengineapi.CertificateAuthorityConfig; import net.jami.jams.common.objects.user.AccessLevel; @@ -42,18 +44,22 @@ public class CreateServerSettingsServlet extends HttpServlet { @Override @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { super.doGet(req, resp); } @Override @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { - CertificateAuthorityConfig config = JsonIterator.deserialize( - req.getInputStream().readAllBytes(),CertificateAuthorityConfig.class); + CertificateAuthorityConfig config = + JsonIterator.deserialize( + req.getInputStream().readAllBytes(), CertificateAuthorityConfig.class); CachedObjects.certificateAuthorityConfig = config; - if(!finalizer.finalizeInstallation()) { - resp.sendError(500, "Could not store settings, a problem occured with finishing the installation"); + if (!finalizer.finalizeInstallation()) { + resp.sendError( + 500, + "Could not store settings, a problem occured with finishing the installation"); return; } resp.setStatus(200); diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/install/InstallLastStepServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/install/InstallLastStepServlet.java index 7a3ae21828967dff0fad92de298d7a2163dfd72f..74fa00f7246bb8a22c973bb6449cb9d2240ebaf4 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/install/InstallLastStepServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/install/InstallLastStepServlet.java @@ -1,32 +1,34 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.api.install; import com.jsoniter.output.JsonStream; + import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import net.jami.jams.common.annotations.JsonContent; import net.jami.jams.common.annotations.ScopedServletMethod; import net.jami.jams.common.objects.user.AccessLevel; @@ -41,8 +43,8 @@ public class InstallLastStepServlet extends HttpServlet { @ScopedServletMethod(securityGroups = {AccessLevel.ADMIN}) @JsonContent protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { - HashMap<String,String> payload = new HashMap<>(); - payload.put("uri",CachedObjects.endpoint); + HashMap<String, String> payload = new HashMap<>(); + payload.put("uri", CachedObjects.endpoint); resp.setStatus(200); resp.getOutputStream().write(JsonStream.serialize(payload).getBytes()); } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/install/StartInstallServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/install/StartInstallServlet.java index febef091a6f5b6afa427cec5c447585929fb0b50..72b2cc1135cabdb26328e546ea401349ea60b4c7 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/install/StartInstallServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/install/StartInstallServlet.java @@ -1,35 +1,41 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.api.install; +import static net.jami.jams.server.Server.dataStore; +import static net.jami.jams.server.servlets.api.auth.login.AuthRequestProcessor.processUsernamePasswordAuth; + import com.jsoniter.JsonIterator; import com.jsoniter.output.JsonStream; + import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.authmodule.PasswordUtil; import net.jami.jams.common.annotations.JsonContent; import net.jami.jams.common.authentication.AuthenticationSourceType; @@ -37,13 +43,11 @@ import net.jami.jams.common.authmodule.AuthTokenResponse; import net.jami.jams.common.objects.requests.CredentialsRequest; import net.jami.jams.common.objects.user.AccessLevel; import net.jami.jams.common.objects.user.User; + import org.apache.commons.codec.binary.Base64; import java.io.IOException; -import static net.jami.jams.server.Server.dataStore; -import static net.jami.jams.server.servlets.api.auth.login.AuthRequestProcessor.processUsernamePasswordAuth; - /* This is not scoped because it is called once. */ @@ -53,37 +57,48 @@ public class StartInstallServlet extends HttpServlet { @Override @JsonContent - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - //Here we must decide which page to show - login or sign-up - if(dataStore != null && dataStore.getUserDao() != null && !dataStore.getUserDao().getObjects(null).isEmpty()) - resp.setHeader("showLogin","true"); - else - resp.setHeader("showLogin","false"); + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + // Here we must decide which page to show - login or sign-up + if (dataStore != null + && dataStore.getUserDao() != null + && !dataStore.getUserDao().getObjects(null).isEmpty()) + resp.setHeader("showLogin", "true"); + else resp.setHeader("showLogin", "false"); } @Override @JsonContent protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { - CredentialsRequest credentialsRequest = JsonIterator.deserialize(req.getInputStream().readAllBytes(),CredentialsRequest.class); + CredentialsRequest credentialsRequest = + JsonIterator.deserialize( + req.getInputStream().readAllBytes(), CredentialsRequest.class); AuthTokenResponse res = null; - if(credentialsRequest.getUsername() != null && credentialsRequest.getPassword() != null){ - res = processUsernamePasswordAuth(credentialsRequest.getUsername(),credentialsRequest.getPassword()); + if (credentialsRequest.getUsername() != null && credentialsRequest.getPassword() != null) { + res = + processUsernamePasswordAuth( + credentialsRequest.getUsername(), credentialsRequest.getPassword()); } - resp.setHeader("endpoint",CachedObjects.endpoint); - if(res == null) resp.sendError(403,"Could not authenticate!"); + resp.setHeader("endpoint", CachedObjects.endpoint); + if (res == null) resp.sendError(403, "Could not authenticate!"); else resp.getOutputStream().write(JsonStream.serialize(res).getBytes()); } - //This is the ONLY case where we write directly to the DB + // This is the ONLY case where we write directly to the DB @Override @JsonContent - protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - if(dataStore.getUserDao().getObjects(null).size() != 0){ - resp.sendError(500,"We have tried to create an administrative account where one already exists!"); + protected void doPut(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + if (dataStore.getUserDao().getObjects(null).size() != 0) { + resp.sendError( + 500, + "We have tried to create an administrative account where one already exists!"); return; } - CredentialsRequest credentialsRequest = JsonIterator.deserialize(req.getInputStream().readAllBytes(),CredentialsRequest.class); - //The admin user has no X509 properties. + CredentialsRequest credentialsRequest = + JsonIterator.deserialize( + req.getInputStream().readAllBytes(), CredentialsRequest.class); + // The admin user has no X509 properties. byte[] salt = PasswordUtil.generateSalt(); String pw = PasswordUtil.hashPassword(credentialsRequest.getPassword(), salt); @@ -95,7 +110,8 @@ public class StartInstallServlet extends HttpServlet { user.setRealm("LOCAL"); user.setAccessLevel(AccessLevel.ADMIN); dataStore.getUserDao().storeObject(user); - AuthTokenResponse res = processUsernamePasswordAuth(user.getUsername(), credentialsRequest.getPassword()); + AuthTokenResponse res = + processUsernamePasswordAuth(user.getUsername(), credentialsRequest.getPassword()); CachedObjects.endpoint = "/api/install/ca"; resp.getOutputStream().write(JsonStream.serialize(res).getBytes()); } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/jaminameserver/AddressServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/jaminameserver/AddressServlet.java index 2cab1704875cc43af8a5008fc7a759bbe78a39db..e2e06a045721d0253471dfa014f145a917c04c44 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/jaminameserver/AddressServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/jaminameserver/AddressServlet.java @@ -1,41 +1,42 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.api.jaminameserver; -import com.jsoniter.output.JsonStream; +import static net.jami.jams.server.Server.nameServer; + import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import net.jami.jams.common.annotations.JsonContent; import net.jami.jams.common.serialization.tomcat.TomcatCustomErrorHandler; + import org.json.JSONObject; import java.io.IOException; -import static net.jami.jams.server.Server.nameServer; - @WebServlet("/api/nameserver/addr/*") public class AddressServlet extends HttpServlet { @@ -56,7 +57,8 @@ public class AddressServlet extends HttpServlet { */ @Override @JsonContent - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { String[] path = req.getPathInfo().split("/"); String username = nameServer.getNameFromAddress(path[path.length - 1]); @@ -64,7 +66,8 @@ public class AddressServlet extends HttpServlet { obj.put("name", username); resp.setContentType("application/json;charset=UTF-8"); - if (username == null) TomcatCustomErrorHandler.sendCustomError(resp,404,"Address not found!"); + if (username == null) + TomcatCustomErrorHandler.sendCustomError(resp, 404, "Address not found!"); else resp.getWriter().write(obj.toString()); } } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/api/jaminameserver/NameServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/api/jaminameserver/NameServlet.java index b2dec3b8d8cbb2b5a7e14652b7b617bd97a4b50c..679e4e53663a0a32b668eaf8cbcbd7854d131c1d 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/api/jaminameserver/NameServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/api/jaminameserver/NameServlet.java @@ -1,40 +1,42 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.api.jaminameserver; +import static net.jami.jams.server.Server.nameServer; + import com.jsoniter.output.JsonStream; + import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import net.jami.jams.common.jami.NameLookupResponse; import net.jami.jams.common.serialization.tomcat.TomcatCustomErrorHandler; import java.io.IOException; -import static net.jami.jams.server.Server.nameServer; - @WebServlet("/api/nameserver/name/*") public class NameServlet extends HttpServlet { @@ -56,10 +58,13 @@ public class NameServlet extends HttpServlet { * @apiError (500) {null} null could not fetch user information */ @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - NameLookupResponse nameLookupResponse = nameServer.getAddressFromName(req.getPathInfo().replace("/","")); + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + NameLookupResponse nameLookupResponse = + nameServer.getAddressFromName(req.getPathInfo().replace("/", "")); resp.setContentType("application/json;charset=UTF-8"); - if(nameLookupResponse == null) TomcatCustomErrorHandler.sendCustomError(resp,404,"name not found"); + if (nameLookupResponse == null) + TomcatCustomErrorHandler.sendCustomError(resp, 404, "name not found"); else resp.getOutputStream().write(JsonStream.serialize(nameLookupResponse).getBytes()); } } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/filters/ARequestLoggingFilter.java b/jams-server/src/main/java/net/jami/jams/server/servlets/filters/ARequestLoggingFilter.java index d3864de8a9f68d35e73bb613db31cfaf9cc174c7..412bedc66dc1155e8c2834363999cda037d5983e 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/filters/ARequestLoggingFilter.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/filters/ARequestLoggingFilter.java @@ -1,7 +1,5 @@ package net.jami.jams.server.servlets.filters; -import java.io.IOException; - import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; @@ -9,9 +7,12 @@ import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.annotation.WebFilter; import jakarta.servlet.http.HttpServletRequest; + import lombok.extern.slf4j.Slf4j; -@WebFilter(urlPatterns = { "*" }) +import java.io.IOException; + +@WebFilter(urlPatterns = {"*"}) @Slf4j public class ARequestLoggingFilter implements Filter { @Override diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/filters/AuthRequestType.java b/jams-server/src/main/java/net/jami/jams/server/servlets/filters/AuthRequestType.java index 22457b4df9464a9edbcebac6b1ac5e8c054dcbda..379a1ccfb3186eb2bb49251d0ffc11edc8ea8346 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/filters/AuthRequestType.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/filters/AuthRequestType.java @@ -1,8 +1,8 @@ package net.jami.jams.server.servlets.filters; public enum AuthRequestType { - FORM, //not supported on filters. + FORM, // not supported on filters. BASIC, BEARER_TOKEN, - CLIENT_CERT //not supported on filters. + CLIENT_CERT // not supported on filters. } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/filters/BCorsFilter.java b/jams-server/src/main/java/net/jami/jams/server/servlets/filters/BCorsFilter.java index e8199f0ffb121ab265c026c913e9e02c90384dbf..ee2e9c6e24a109cff3c4922aa933d410f4e7a5bd 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/filters/BCorsFilter.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/filters/BCorsFilter.java @@ -3,11 +3,12 @@ package net.jami.jams.server.servlets.filters; import jakarta.servlet.annotation.WebFilter; import jakarta.servlet.annotation.WebInitParam; -@WebFilter(urlPatterns = { "*" }, initParams = { - @WebInitParam(name = "cors.allowed.origins", value = "*"), - @WebInitParam(name = "cors.allowed.methods", value = "PUT, POST, GET, OPTIONS, DELETE"), - @WebInitParam(name = "cors.allowed.headers", value = "Content-Type, Authorization"), - @WebInitParam(name = "cors.preflight.maxage", value = "3600") -}) -public class BCorsFilter extends org.apache.catalina.filters.CorsFilter { -} +@WebFilter( + urlPatterns = {"*"}, + initParams = { + @WebInitParam(name = "cors.allowed.origins", value = "*"), + @WebInitParam(name = "cors.allowed.methods", value = "PUT, POST, GET, OPTIONS, DELETE"), + @WebInitParam(name = "cors.allowed.headers", value = "Content-Type, Authorization"), + @WebInitParam(name = "cors.preflight.maxage", value = "3600") + }) +public class BCorsFilter extends org.apache.catalina.filters.CorsFilter {} diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/filters/CInstallFilter.java b/jams-server/src/main/java/net/jami/jams/server/servlets/filters/CInstallFilter.java index 72b567c615f5c5cfb55533cd123303a6bc9414eb..9aafe891096c2f15eae3acd4f28bb19961b24090 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/filters/CInstallFilter.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/filters/CInstallFilter.java @@ -1,27 +1,29 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.filters; +import static net.jami.jams.server.servlets.filters.FilterUtils.doAuthCheck; + import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; @@ -30,34 +32,39 @@ import jakarta.servlet.ServletResponse; import jakarta.servlet.annotation.WebFilter; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.serialization.tomcat.TomcatCustomErrorHandler; import net.jami.jams.server.Server; import java.io.IOException; -import static net.jami.jams.server.servlets.filters.FilterUtils.doAuthCheck; - -@WebFilter(filterName = "installFilter", urlPatterns = { "/api/install/*" }) +@WebFilter( + filterName = "installFilter", + urlPatterns = {"/api/install/*"}) @Slf4j public class CInstallFilter implements Filter { @Override - public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + public void doFilter( + ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) + throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; response.setContentType("application/json;charset=UTF-8"); - if(Server.isInstalled.get()){ - TomcatCustomErrorHandler.sendCustomError(response,404,"The server is already installed"); - } - else{ + if (Server.isInstalled.get()) { + TomcatCustomErrorHandler.sendCustomError( + response, 404, "The server is already installed"); + } else { boolean authsuccess = false; boolean isLogin = false; - if(request.getServletPath().contains("start")) isLogin = true; + if (request.getServletPath().contains("start")) isLogin = true; else authsuccess = doAuthCheck(request); - if(authsuccess || isLogin) filterChain.doFilter(servletRequest,servletResponse); - else TomcatCustomErrorHandler.sendCustomError(response,401,"You are not authenticated!"); + if (authsuccess || isLogin) filterChain.doFilter(servletRequest, servletResponse); + else + TomcatCustomErrorHandler.sendCustomError( + response, 401, "You are not authenticated!"); } } - } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/filters/DApiFilter.java b/jams-server/src/main/java/net/jami/jams/server/servlets/filters/DApiFilter.java index d9c31fc67c80ba3e3bfc1b52d9421a0fb68a5c31..6fc069c75e9c58c29a19df7159e05b48a73c3a0e 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/filters/DApiFilter.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/filters/DApiFilter.java @@ -23,6 +23,8 @@ package net.jami.jams.server.servlets.filters; +import static net.jami.jams.server.servlets.filters.FilterUtils.doAuthCheck; + import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; @@ -31,29 +33,32 @@ import jakarta.servlet.ServletResponse; import jakarta.servlet.annotation.WebFilter; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.serialization.tomcat.TomcatCustomErrorHandler; import net.jami.jams.server.Server; import java.io.IOException; -import static net.jami.jams.server.servlets.filters.FilterUtils.doAuthCheck; - /** * Since we have the @ScopedServletMethod annotation, the admin filter became absolutely useless * as we can simply scope things. */ -@WebFilter(urlPatterns = {"/api/auth/*","/api/admin/*"}) +@WebFilter(urlPatterns = {"/api/auth/*", "/api/admin/*"}) @Slf4j public class DApiFilter implements Filter { @Override - public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + public void doFilter( + ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) + throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; response.setContentType("application/json;charset=UTF-8"); if (!Server.isInstalled.get()) { - TomcatCustomErrorHandler.sendCustomError(response,404,"Setup has not yet been completed!"); + TomcatCustomErrorHandler.sendCustomError( + response, 404, "Setup has not yet been completed!"); } else { boolean authsuccess = false; boolean isLogin = false; @@ -65,7 +70,8 @@ public class DApiFilter implements Filter { if (authsuccess || isLogin || isOCSPCheck) { filterChain.doFilter(servletRequest, servletResponse); } else { - TomcatCustomErrorHandler.sendCustomError(response,401,"You are not authenticated!"); + TomcatCustomErrorHandler.sendCustomError( + response, 401, "You are not authenticated!"); } } } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/filters/FilterUtils.java b/jams-server/src/main/java/net/jami/jams/server/servlets/filters/FilterUtils.java index 0209bd959ad66dfe2d87ff7d7cf8e322b51a96f0..7bdab5d79f7b8580c4be73d711aadbcb7183c201 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/filters/FilterUtils.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/filters/FilterUtils.java @@ -23,23 +23,25 @@ package net.jami.jams.server.servlets.filters; +import static net.jami.jams.server.Server.*; +import static net.jami.jams.server.Server.certificateAuthority; +import static net.jami.jams.server.servlets.api.auth.login.AuthRequestProcessor.processUsernamePasswordAuth; + import com.nimbusds.jose.JWSVerifier; import com.nimbusds.jose.crypto.RSASSAVerifier; import com.nimbusds.jwt.SignedJWT; + import jakarta.servlet.http.HttpServletRequest; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.dao.StatementElement; import net.jami.jams.common.dao.StatementList; import net.jami.jams.common.objects.user.AccessLevel; import net.jami.jams.common.objects.user.User; -import net.jami.jams.common.serialization.tomcat.TomcatCustomErrorHandler; import java.util.Date; -import static net.jami.jams.server.Server.*; -import static net.jami.jams.server.Server.certificateAuthority; -import static net.jami.jams.server.servlets.api.auth.login.AuthRequestProcessor.processUsernamePasswordAuth; - @Slf4j public class FilterUtils { @@ -56,10 +58,12 @@ public class FilterUtils { public static AuthRequestType classifyRequest(HttpServletRequest request) { if (request.getHeader("authorization") != null) { - if (request.getHeader("authorization").contains("basic") || request.getHeader("authorization").contains("Basic")) { + if (request.getHeader("authorization").contains("basic") + || request.getHeader("authorization").contains("Basic")) { return AuthRequestType.BASIC; } - if (request.getHeader("authorization").contains("bearer") || request.getHeader("authorization").contains("Bearer")) { + if (request.getHeader("authorization").contains("bearer") + || request.getHeader("authorization").contains("Bearer")) { return AuthRequestType.BEARER_TOKEN; } return null; @@ -67,7 +71,7 @@ public class FilterUtils { return null; } - public static boolean doAuthCheck(HttpServletRequest request){ + public static boolean doAuthCheck(HttpServletRequest request) { AuthRequestType requestType = FilterUtils.classifyRequest(request); if (requestType == null) { return false; @@ -76,35 +80,49 @@ public class FilterUtils { SignedJWT token = null; switch (requestType) { case BASIC: - token = SignedJWT.parse(processUsernamePasswordAuth(request.getHeader("authorization")).getAccess_token()); + token = + SignedJWT.parse( + processUsernamePasswordAuth(request.getHeader("authorization")) + .getAccess_token()); break; case BEARER_TOKEN: - token = SignedJWT.parse(request.getHeader("authorization"). - replace("bearer", "") - .replace("Bearer", "")); + token = + SignedJWT.parse( + request.getHeader("authorization") + .replace("bearer", "") + .replace("Bearer", "")); break; default: return false; } StatementList statementList = new StatementList(); - StatementElement statementElement = new StatementElement("username", "=", token.getJWTClaimsSet().getSubject(), ""); + StatementElement statementElement = + new StatementElement("username", "=", token.getJWTClaimsSet().getSubject(), ""); statementList.addStatement(statementElement); log.info("Getting user from database"); - User user = dataStore.getUserDao().getObjects(statementList).get(0); + User user = dataStore.getUserDao().getObjects(statementList).get(0); log.info("User retrieved from database: {}", user); - if(!user.getAccessLevelName().equals("ADMIN") && certificateAuthority.getLatestCRL().get() != null) { - if(certificateAuthority.getLatestCRL().get().getRevokedCertificate(user.getCertificate().getSerialNumber()) != null) - return false; + if (!user.getAccessLevelName().equals("ADMIN") + && certificateAuthority.getLatestCRL().get() != null) { + if (certificateAuthority + .getLatestCRL() + .get() + .getRevokedCertificate(user.getCertificate().getSerialNumber()) + != null) return false; } - JWSVerifier jwsVerifier = new RSASSAVerifier(userAuthenticationModule.getAuthModulePubKey()); + JWSVerifier jwsVerifier = + new RSASSAVerifier(userAuthenticationModule.getAuthModulePubKey()); if (token.verify(jwsVerifier) && verifyValidity(token)) { request.setAttribute(USERNAME_ATTR, token.getJWTClaimsSet().getSubject()); - request.setAttribute(ACCESS_LEVEL_ATTR, AccessLevel.valueOf(token.getJWTClaimsSet().getClaim("scope").toString())); + request.setAttribute( + ACCESS_LEVEL_ATTR, + AccessLevel.valueOf(token.getJWTClaimsSet().getClaim("scope").toString())); return true; } - } - catch (Exception e){ - log.info("Failed to process authentication request and denying access: {}",e.getMessage()); + } catch (Exception e) { + log.info( + "Failed to process authentication request and denying access: {}", + e.getMessage()); } return false; diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/general/ServerStatusServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/general/ServerStatusServlet.java index e84c41e3e289e11c2351411f1180b27f4f9c20ab..ff78ca78cf446b84d7f5f14923a26bf2ef8b6cda 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/general/ServerStatusServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/general/ServerStatusServlet.java @@ -1,32 +1,34 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.general; import com.jsoniter.output.JsonStream; + import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import net.jami.jams.common.annotations.JsonContent; import net.jami.jams.server.Server; @@ -39,8 +41,8 @@ public class ServerStatusServlet extends HttpServlet { @Override @JsonContent protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { - HashMap<String,String> statusInfo = new HashMap<>(); - statusInfo.put("installed",String.valueOf(Server.isInstalled.get())); + HashMap<String, String> statusInfo = new HashMap<>(); + statusInfo.put("installed", String.valueOf(Server.isInstalled.get())); resp.setContentType("application/json;charset=UTF-8"); resp.getOutputStream().write(JsonStream.serialize(statusInfo).getBytes()); } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/generic/InternalErrorServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/generic/InternalErrorServlet.java index d4feddd0145dae634beb8dc651a432397f83d1e3..e06c9d8744947fab3cfe9f3dca24a42d8ccd24ca 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/generic/InternalErrorServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/generic/InternalErrorServlet.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.generic; import jakarta.servlet.ServletException; @@ -27,6 +27,7 @@ import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import lombok.extern.slf4j.Slf4j; import java.io.IOException; @@ -36,12 +37,13 @@ import java.io.IOException; public class InternalErrorServlet extends HttpServlet { @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { try { resp.setStatus(500); - resp.getOutputStream().write(("{\"error\":\"" + "internal server error" + "\"}").getBytes()); - } - catch (Exception e){ + resp.getOutputStream() + .write(("{\"error\":\"" + "internal server error" + "\"}").getBytes()); + } catch (Exception e) { log.error("Could not generate an error!"); } } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/generic/NotFoundServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/generic/NotFoundServlet.java index 5862b7b1ba0c7b141b6aae400f20755be190c6a7..b1b8461846d9f2d7b92ec2e85c55e3e3f068fb2a 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/generic/NotFoundServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/generic/NotFoundServlet.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.generic; import jakarta.servlet.ServletException; @@ -27,6 +27,7 @@ import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import lombok.extern.slf4j.Slf4j; import java.io.IOException; @@ -36,12 +37,13 @@ import java.io.IOException; public class NotFoundServlet extends HttpServlet { @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { try { resp.setStatus(404); - resp.getOutputStream().write(("{\"error\":\"" + "requested page does not exist" + "\"}").getBytes()); - } - catch (Exception e){ + resp.getOutputStream() + .write(("{\"error\":\"" + "requested page does not exist" + "\"}").getBytes()); + } catch (Exception e) { log.error("Could not generate an error!"); } } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/x509/CRLServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/x509/CRLServlet.java index 77c8d2f0a29404bc7dca0ce93904c9d54e990e1b..ce526e917463daae37998386c746854d6eca3839 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/x509/CRLServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/x509/CRLServlet.java @@ -1,27 +1,29 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.servlets.x509; +import static net.jami.jams.server.Server.certificateAuthority; + import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; @@ -30,9 +32,6 @@ import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; -import static net.jami.jams.server.Server.certificateAuthority; - - @WebServlet("/api/auth/crl") public class CRLServlet extends HttpServlet { @@ -40,11 +39,9 @@ public class CRLServlet extends HttpServlet { private static final String CRL_TAIL = "\n-----END X509 CRL-----"; @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append(CRL_HEAD); - stringBuilder.append(certificateAuthority.getLatestCRLPEMEncoded()); - stringBuilder.append(CRL_TAIL); - resp.getOutputStream().write(stringBuilder.toString().getBytes()); + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + String stringBuilder = CRL_HEAD + certificateAuthority.getLatestCRLPEMEncoded() + CRL_TAIL; + resp.getOutputStream().write(stringBuilder.getBytes()); } } diff --git a/jams-server/src/main/java/net/jami/jams/server/servlets/x509/OCSPServlet.java b/jams-server/src/main/java/net/jami/jams/server/servlets/x509/OCSPServlet.java index 3a94f3905202cb0fc719079ac0ea38c8e53c32be..165864a3810c6062c2453cb58d404126a4220d65 100644 --- a/jams-server/src/main/java/net/jami/jams/server/servlets/x509/OCSPServlet.java +++ b/jams-server/src/main/java/net/jami/jams/server/servlets/x509/OCSPServlet.java @@ -22,15 +22,19 @@ */ package net.jami.jams.server.servlets.x509; +import static net.jami.jams.server.Server.dataStore; + import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import net.jami.jams.ca.JamsCA; import net.jami.jams.common.dao.StatementElement; import net.jami.jams.common.dao.StatementList; import net.jami.jams.common.objects.devices.Device; import net.jami.jams.common.objects.user.User; + import org.bouncycastle.cert.ocsp.OCSPReq; import org.bouncycastle.cert.ocsp.OCSPResp; import org.bouncycastle.cert.ocsp.Req; @@ -40,8 +44,6 @@ import java.math.BigInteger; import java.util.ArrayList; import java.util.List; -import static net.jami.jams.server.Server.dataStore; - @WebServlet("/api/ocsp/*") public class OCSPServlet extends HttpServlet { @@ -50,8 +52,7 @@ public class OCSPServlet extends HttpServlet { resp.setContentType("application/ocsp-response"); byte[] content = new byte[Integer.parseInt(req.getHeader("Content-Length"))]; try { - for(int i=0;i<content.length;i++) - req.getInputStream().read(content); + for (int i = 0; i < content.length; i++) req.getInputStream().read(content); OCSPReq ocspReq = new OCSPReq(content); List<BigInteger> ids = new ArrayList<>(); @@ -59,64 +60,78 @@ public class OCSPServlet extends HttpServlet { for (Req request : ocspReq.getRequestList()) ids.add(request.getCertID().getSerialNumber()); - String issuerId = req.getPathInfo().replace("/",""); + String issuerId = req.getPathInfo().replace("/", ""); /* * If there is no issue id we are dealing with a certificate signed byt the CA root * Else the certificate is a device certificate signed by a user with and the issuerId is his Jami Id */ - if(issuerId == ""){ - OCSPResp response = JamsCA.getOCSPResponse(ocspReq, JamsCA.CA.getCertificate(), JamsCA.CA.getPrivateKey(), false); + if (issuerId == "") { + OCSPResp response = + JamsCA.getOCSPResponse( + ocspReq, + JamsCA.CA.getCertificate(), + JamsCA.CA.getPrivateKey(), + false); if (response != null) { byte[] respBytes = response.getEncoded(); resp.getOutputStream().write(respBytes); } else resp.setStatus(404); - } - else { + } else { User targetUser = null; StatementList userStatementsList = new StatementList(); - StatementElement usernameStatement = new StatementElement("jamiId", "=", issuerId, ""); + StatementElement usernameStatement = + new StatementElement("jamiId", "=", issuerId, ""); userStatementsList.addStatement(usernameStatement); try { targetUser = dataStore.getUserDao().getObjects(userStatementsList).get(0); StatementList deviceStatementsList = new StatementList(); - StatementElement deviceOwnerStatement = new StatementElement("owner", "=", targetUser.getUsername(), ""); + StatementElement deviceOwnerStatement = + new StatementElement("owner", "=", targetUser.getUsername(), ""); deviceStatementsList.addStatement(deviceOwnerStatement); - List<Device> devices = dataStore.getDeviceDao().getObjects(deviceStatementsList); + List<Device> devices = + dataStore.getDeviceDao().getObjects(deviceStatementsList); boolean deviceDoesNotExist = true; - for (Device d: devices) { - for (BigInteger id: ids) { + for (Device d : devices) { + for (BigInteger id : ids) { if (d.getCertificate().getSerialNumber().equals(id)) { - deviceDoesNotExist= false; + deviceDoesNotExist = false; } } } OCSPResp response = null; - if(deviceDoesNotExist){ - response = JamsCA.getOCSPResponse(ocspReq, targetUser.getCertificate(), targetUser.getPrivateKey(), true); - } - else{ - response = JamsCA.getOCSPResponse(ocspReq, targetUser.getCertificate(), targetUser.getPrivateKey(), false); + if (deviceDoesNotExist) { + response = + JamsCA.getOCSPResponse( + ocspReq, + targetUser.getCertificate(), + targetUser.getPrivateKey(), + true); + } else { + response = + JamsCA.getOCSPResponse( + ocspReq, + targetUser.getCertificate(), + targetUser.getPrivateKey(), + false); } if (response != null) { byte[] respBytes = response.getEncoded(); resp.getOutputStream().write(respBytes); } else resp.setStatus(404); - } - catch (Exception e) { + } catch (Exception e) { resp.sendError(404, "Could not find the requested certificate!"); } } - } - catch (Exception e) { + } catch (Exception e) { resp.sendError(404, "Could not find the requested certificate!"); } } -} \ No newline at end of file +} diff --git a/jams-server/src/main/java/net/jami/jams/server/startup/AuthModuleLoader.java b/jams-server/src/main/java/net/jami/jams/server/startup/AuthModuleLoader.java index 857bc20cc15074eca16fed2924e2c9ba21eca916..f91719ed370e924a99fd40f1c1e09593b31c3126 100644 --- a/jams-server/src/main/java/net/jami/jams/server/startup/AuthModuleLoader.java +++ b/jams-server/src/main/java/net/jami/jams/server/startup/AuthModuleLoader.java @@ -1,28 +1,29 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.startup; import lombok.extern.slf4j.Slf4j; + import net.jami.datastore.main.DataStore; import net.jami.jams.common.authmodule.AuthenticationModule; import net.jami.jams.common.cryptoengineapi.CertificateAuthority; @@ -31,12 +32,16 @@ import net.jami.jams.common.utils.LibraryLoader; @Slf4j public class AuthModuleLoader { - public static AuthenticationModule loadAuthenticationModule(DataStore dataStore, CertificateAuthority certificateAuthority) { + public static AuthenticationModule loadAuthenticationModule( + DataStore dataStore, CertificateAuthority certificateAuthority) { try { - Class<?> cls = LibraryLoader.classLoader.loadClass("net.jami.jams.authmodule.UserAuthenticationModule"); + Class<?> cls = + LibraryLoader.classLoader.loadClass( + "net.jami.jams.authmodule.UserAuthenticationModule"); AuthenticationModule authenticationModule = - (AuthenticationModule) cls.getConstructor(DataStore.class, CertificateAuthority.class) - .newInstance(dataStore, certificateAuthority); + (AuthenticationModule) + cls.getConstructor(DataStore.class, CertificateAuthority.class) + .newInstance(dataStore, certificateAuthority); log.info("Loaded Authentication Module succesfully!"); return authenticationModule; } catch (Exception e) { @@ -44,5 +49,4 @@ public class AuthModuleLoader { return null; } } - } diff --git a/jams-server/src/main/java/net/jami/jams/server/startup/CryptoEngineLoader.java b/jams-server/src/main/java/net/jami/jams/server/startup/CryptoEngineLoader.java index c0c8cfa03266daef5d7b11278f77cfa9fe047766..465d71617c61ee95251dd8690cef41003c9ad60a 100644 --- a/jams-server/src/main/java/net/jami/jams/server/startup/CryptoEngineLoader.java +++ b/jams-server/src/main/java/net/jami/jams/server/startup/CryptoEngineLoader.java @@ -1,28 +1,29 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.startup; import lombok.extern.slf4j.Slf4j; + import net.jami.datastore.main.DataStore; import net.jami.jams.common.cryptoengineapi.CertificateAuthority; import net.jami.jams.common.dao.StatementElement; @@ -35,34 +36,36 @@ import java.util.List; @Slf4j public class CryptoEngineLoader { - public static CertificateAuthority loadCertificateAuthority(String config, DataStore dataStore){ + public static CertificateAuthority loadCertificateAuthority( + String config, DataStore dataStore) { try { Class<?> cls = LibraryLoader.classLoader.loadClass("net.jami.jams.ca.JamsCA"); - CertificateAuthority certificateAuthority = (CertificateAuthority) cls.getConstructor().newInstance(); + CertificateAuthority certificateAuthority = + (CertificateAuthority) cls.getConstructor().newInstance(); StatementList statementList = new StatementList(); - statementList.addStatement(new StatementElement("entity","=","CA","")); + statementList.addStatement(new StatementElement("entity", "=", "CA", "")); List<SystemAccount> accounts = dataStore.getSystemDao().getObjects(statementList); - if(accounts.size() == 0){ - log.info("This is an fresh install, and it has no CA or any system accounts - if there is a config.json" + - " file in your directory, this means the install is broken and you should delete and restart!"); - } - else{ + if (accounts.size() == 0) { + log.info( + "This is an fresh install, and it has no CA or any system accounts - if there is a config.json" + + " file in your directory, this means the install is broken and you should delete and restart!"); + } else { statementList = new StatementList(); - statementList.addStatement(new StatementElement("entity","=","CA","")); + statementList.addStatement(new StatementElement("entity", "=", "CA", "")); SystemAccount caAccount = dataStore.getSystemDao().getObjects(statementList).get(0); statementList = new StatementList(); - statementList.addStatement(new StatementElement("entity","=","OCSP","")); - SystemAccount ocspAccount = dataStore.getSystemDao().getObjects(statementList).get(0); + statementList.addStatement(new StatementElement("entity", "=", "OCSP", "")); + SystemAccount ocspAccount = + dataStore.getSystemDao().getObjects(statementList).get(0); log.info("Injecting OCSP and CA acocunts..."); - certificateAuthority.init(config,caAccount,ocspAccount); + certificateAuthority.init(config, caAccount, ocspAccount); } - log.info("Loaded X509 Engine - please make sure it is initialized before using it to sign requests!"); + log.info( + "Loaded X509 Engine - please make sure it is initialized before using it to sign requests!"); return certificateAuthority; - } - catch (Exception e){ + } catch (Exception e) { log.error("Unable to load X509 Engine!"); return null; } } - } diff --git a/jams-server/src/main/java/net/jami/jams/server/update/JAMSUpdater.java b/jams-server/src/main/java/net/jami/jams/server/update/JAMSUpdater.java index cae39d5ae38158b229493b0b21a0307910fa955c..83d00ed45ad61d0675a30bddc5a0f851220348cb 100644 --- a/jams-server/src/main/java/net/jami/jams/server/update/JAMSUpdater.java +++ b/jams-server/src/main/java/net/jami/jams/server/update/JAMSUpdater.java @@ -24,9 +24,11 @@ package net.jami.jams.server.update; import com.jsoniter.JsonIterator; import com.jsoniter.any.Any; + import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.updater.AppUpdater; import net.jami.jams.common.updater.FileDescription; import net.jami.jams.server.Server; @@ -52,16 +54,16 @@ public class JAMSUpdater implements AppUpdater { private final UpdateCheckTask updateCheckTask = new UpdateCheckTask(); private final UpdateDownloader updateDownloader = new UpdateDownloader(); private final Timer timer = new Timer(); - //These get written to from the server, so we set them to volatile for visibility purposes. - public volatile static X509Certificate certificate; - public volatile static PrivateKey privateKey; - + // These get written to from the server, so we set them to volatile for visibility purposes. + public static volatile X509Certificate certificate; + public static volatile PrivateKey privateKey; public JAMSUpdater(AtomicBoolean doUpdate) { // read config json try { - InputStream input = this.getClass().getClassLoader().getResourceAsStream("oem/config.json"); + InputStream input = + this.getClass().getClassLoader().getResourceAsStream("oem/config.json"); Any any = JsonIterator.deserialize(input.readAllBytes()); UPDATE_SERVER_URI = any.get("UPDATE_URL").toString(); UPDATE_INTERVAL = any.get("UPDATE_INTERVAL").toLong(); @@ -70,7 +72,7 @@ public class JAMSUpdater implements AppUpdater { } this.doUpdate = doUpdate; - timer.schedule(updateCheckTask,0,UPDATE_INTERVAL); + timer.schedule(updateCheckTask, 0, UPDATE_INTERVAL); } @Override @@ -79,7 +81,7 @@ public class JAMSUpdater implements AppUpdater { } @Override - public HashMap<String,FileDescription> getRemoteVersions() { + public HashMap<String, FileDescription> getRemoteVersions() { return updateCheckTask.getRemoteData(); } @@ -96,12 +98,10 @@ public class JAMSUpdater implements AppUpdater { @Override public void doUpdate() { - //Some logic here about replacing the existing files. + // Some logic here about replacing the existing files. boolean res = updateDownloader.downloadFiles(getRemoteVersions()); - //Notify back up-stream to the launcher that we want the update to happen. - if(res) - Server.updateInterface.approveUpdate(); - else - log.error("Could not perform update - the downloaded files may have been invalid!"); + // Notify back up-stream to the launcher that we want the update to happen. + if (res) Server.updateInterface.approveUpdate(); + else log.error("Could not perform update - the downloaded files may have been invalid!"); } } diff --git a/jams-server/src/main/java/net/jami/jams/server/update/UpdateCheckTask.java b/jams-server/src/main/java/net/jami/jams/server/update/UpdateCheckTask.java index 89ac515b1c1ee9d912e6f8c4ba57263bf9f17eee..72577dfcf98664a2b129e5700770c47ced621363 100644 --- a/jams-server/src/main/java/net/jami/jams/server/update/UpdateCheckTask.java +++ b/jams-server/src/main/java/net/jami/jams/server/update/UpdateCheckTask.java @@ -1,49 +1,51 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.update; import com.jsoniter.JsonIterator; import com.jsoniter.any.Any; + import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.updater.FileDescription; import net.jami.jams.common.utils.VersioningUtils; import net.jami.jams.common.utils.X509Utils; + import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContexts; -import javax.net.ssl.SSLContext; import java.io.InputStream; import java.security.KeyStore; import java.security.cert.X509Certificate; import java.util.HashMap; import java.util.TimerTask; - +import javax.net.ssl.SSLContext; @Slf4j @Getter @@ -58,45 +60,47 @@ public class UpdateCheckTask extends TimerTask { protected UpdateCheckTask() { try { - InputStream is = UpdateCheckTask.class.getClassLoader().getResourceAsStream("oem/ca.crt"); - X509Certificate certificate = X509Utils.getCertificateFromPEMString(new String(is.readAllBytes())); + InputStream is = + UpdateCheckTask.class.getClassLoader().getResourceAsStream("oem/ca.crt"); + X509Certificate certificate = + X509Utils.getCertificateFromPEMString(new String(is.readAllBytes())); trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); - trustStore.setCertificateEntry("ca",certificate); + trustStore.setCertificateEntry("ca", certificate); is = UpdateCheckTask.class.getClassLoader().getResourceAsStream("oem/update.crt"); certificate = X509Utils.getCertificateFromPEMString(new String(is.readAllBytes())); - trustStore.setCertificateEntry("update",certificate); + trustStore.setCertificateEntry("update", certificate); - //Inject the SSL Connection here for a first time. + // Inject the SSL Connection here for a first time. sslContext = SSLContexts.custom().loadTrustMaterial(trustStore, null).build(); // read config json - InputStream input = this.getClass().getClassLoader().getResourceAsStream("oem/config.json"); + InputStream input = + this.getClass().getClassLoader().getResourceAsStream("oem/config.json"); Any any = JsonIterator.deserialize(input.readAllBytes()); UPDATE_SERVER_URI = any.get("UPDATE_URL").toString(); - } - catch (Exception e){ - log.error("Could not initialize the trust store with error {}",e.getMessage()); + } catch (Exception e) { + log.error("Could not initialize the trust store with error {}", e.getMessage()); } } @Override public void run() { try { - //Get the local data + // Get the local data localData = VersioningUtils.checkVersion(null); - //Download the info from the remote server. + // Download the info from the remote server. getLatestVersion(); - localData.forEach((k,v) -> { - if(remoteData.containsKey(k) && remoteData.get(k).compareTo(v) > 0){ - log.info("Detected a new version on SFL servers!"); - JAMSUpdater.updateAvailable.set(true); - } - }); - } - catch (Exception e){ - log.error("Could not check for updates with error: {}",e.getMessage()); + localData.forEach( + (k, v) -> { + if (remoteData.containsKey(k) && remoteData.get(k).compareTo(v) > 0) { + log.info("Detected a new version on SFL servers!"); + JAMSUpdater.updateAvailable.set(true); + } + }); + } catch (Exception e) { + log.error("Could not check for updates with error: {}", e.getMessage()); } } @@ -104,22 +108,24 @@ public class UpdateCheckTask extends TimerTask { // about what new versions of WHAT are available. private void getLatestVersion() { try { - //Step 1: Download a file called versions.json + // Step 1: Download a file called versions.json HttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build(); - HttpResponse response = httpClient.execute(new HttpGet(UPDATE_SERVER_URI + "/versions.json")); - //Step 2: Load the file into the hashmaps + HttpResponse response = + httpClient.execute(new HttpGet(UPDATE_SERVER_URI + "/versions.json")); + // Step 2: Load the file into the hashmaps Any any = JsonIterator.deserialize(response.getEntity().getContent().readAllBytes()); - any.asMap().forEach((k, v) -> - remoteData.put(v.get("filename").toString(),new FileDescription( - v.get("filename").toString(), - v.get("version").toString(), - v.get("md5").toString(), - k)) - - ); + any.asMap() + .forEach( + (k, v) -> + remoteData.put( + v.get("filename").toString(), + new FileDescription( + v.get("filename").toString(), + v.get("version").toString(), + v.get("md5").toString(), + k))); } catch (Exception e) { - log.warn("Could not establish connection to JAMS Update Center with error: " + e.toString()); + log.warn("Could not establish connection to JAMS Update Center with error: " + e); } } - } diff --git a/jams-server/src/main/java/net/jami/jams/server/update/UpdateDownloader.java b/jams-server/src/main/java/net/jami/jams/server/update/UpdateDownloader.java index 5021bff8a50701978e1bc259e3c868bc2b03e8bf..d3a212280648073244478a3571781761a2126390 100644 --- a/jams-server/src/main/java/net/jami/jams/server/update/UpdateDownloader.java +++ b/jams-server/src/main/java/net/jami/jams/server/update/UpdateDownloader.java @@ -1,40 +1,42 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.update; import com.jsoniter.JsonIterator; import com.jsoniter.any.Any; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.updater.FileDescription; import net.jami.jams.common.utils.X509Utils; import net.jami.jams.server.licensing.LicenseService; + import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContexts; -import javax.net.ssl.SSLContext; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -44,6 +46,7 @@ import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.HashMap; +import javax.net.ssl.SSLContext; @Slf4j public class UpdateDownloader { @@ -53,28 +56,31 @@ public class UpdateDownloader { private KeyStore trustStore; private static volatile String UPDATE_SERVER_URL; - private HashMap<String, FileDescription> remoteChecksums = new HashMap<>(); + private final HashMap<String, FileDescription> remoteChecksums = new HashMap<>(); public UpdateDownloader() { try { - InputStream is = UpdateCheckTask.class.getClassLoader().getResourceAsStream("oem/ca.crt"); - X509Certificate certificate = X509Utils.getCertificateFromPEMString(new String(is.readAllBytes())); + InputStream is = + UpdateCheckTask.class.getClassLoader().getResourceAsStream("oem/ca.crt"); + X509Certificate certificate = + X509Utils.getCertificateFromPEMString(new String(is.readAllBytes())); trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); trustStore.setCertificateEntry("ca", certificate); is = UpdateDownloader.class.getClassLoader().getResourceAsStream("oem/update.crt"); certificate = X509Utils.getCertificateFromPEMString(new String(is.readAllBytes())); - trustStore.setCertificateEntry("update",certificate); - } - catch (Exception e){ - log.info("Could not load SFL's CA - this should not happen! detailed error: {}",e.getMessage()); + trustStore.setCertificateEntry("update", certificate); + } catch (Exception e) { + log.info( + "Could not load SFL's CA - this should not happen! detailed error: {}", + e.getMessage()); } - try { - InputStream input = this.getClass().getClassLoader().getResourceAsStream("oem/config.json"); + InputStream input = + this.getClass().getClassLoader().getResourceAsStream("oem/config.json"); Any any = JsonIterator.deserialize(input.readAllBytes()); UPDATE_SERVER_URL = any.get("UPDATE_URL").toString(); @@ -85,26 +91,35 @@ public class UpdateDownloader { } public boolean downloadFiles(HashMap<String, FileDescription> files) { - //I know this contradicts my dogma, but this really would have been an overkill for this project, - //I just claim that everything which is not core gets dumped to the lib directory. - //We can perpetually reload this,it doesn't really harm anything. - //Build the SSL context here, (this is fairly simple) + // I know this contradicts my dogma, but this really would have been an overkill for this + // project, + // I just claim that everything which is not core gets dumped to the lib directory. + // We can perpetually reload this,it doesn't really harm anything. + // Build the SSL context here, (this is fairly simple) KeyStore ks = null; try { ks = KeyStore.getInstance(KEYSTORE_TYPE); ks.load(null); LicenseService licenseService = new LicenseService(); licenseService.loadLicense(); - ks.setKeyEntry("licenses", JAMSUpdater.privateKey,"".toCharArray(),new Certificate[]{JAMSUpdater.certificate}); - sslContext = SSLContexts.custom().loadKeyMaterial(ks, "".toCharArray()).loadTrustMaterial(trustStore, null).build(); + ks.setKeyEntry( + "licenses", + JAMSUpdater.privateKey, + "".toCharArray(), + new Certificate[] {JAMSUpdater.certificate}); + sslContext = + SSLContexts.custom() + .loadKeyMaterial(ks, "".toCharArray()) + .loadTrustMaterial(trustStore, null) + .build(); } catch (Exception e) { - log.warn("Could not download an update with error " + e.toString()); + log.warn("Could not download an update with error " + e); } // temp folder for safe download and integrity check File tmpFolder = new File(System.getProperty("user.dir") + "/tmp/"); - if(!tmpFolder.exists()){ + if (!tmpFolder.exists()) { try { tmpFolder.mkdirs(); } catch (Exception e) { @@ -113,27 +128,39 @@ public class UpdateDownloader { } } - files.forEach((k, v) -> { - try { - File tmpFile = new File( System.getProperty("user.dir") + "/tmp/" + v.getFileName()); - if(tmpFile.exists()){ - - try{ - tmpFile.delete(); - } catch (Exception e) { - log.warn("Error deleting file: " + v.getFileName() + " with error " + e); + files.forEach( + (k, v) -> { + try { + File tmpFile = + new File( + System.getProperty("user.dir") + "/tmp/" + v.getFileName()); + if (tmpFile.exists()) { + + try { + tmpFile.delete(); + } catch (Exception e) { + log.warn( + "Error deleting file: " + + v.getFileName() + + " with error " + + e); + } + } + HttpClient httpClient = + HttpClients.custom().setSSLContext(sslContext).build(); + HttpResponse httpResponse = + httpClient.execute( + new HttpGet( + UPDATE_SERVER_URL + "/updates/" + v.getFileName())); + if (httpResponse.getStatusLine().getStatusCode() != 200) return; + FileOutputStream fos = + new FileOutputStream(tmpFolder.getPath() + "/" + v.getFileName()); + httpResponse.getEntity().writeTo(fos); + fos.close(); + } catch (Exception e1) { + log.warn("Could not download an update with error " + e1); } - } - HttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build(); - HttpResponse httpResponse = httpClient.execute(new HttpGet(UPDATE_SERVER_URL + "/updates/" + v.getFileName())); - if (httpResponse.getStatusLine().getStatusCode() != 200) return; - FileOutputStream fos = new FileOutputStream(tmpFolder.getPath() + "/" + v.getFileName()); - httpResponse.getEntity().writeTo(fos); - fos.close(); - } catch (Exception e1) { - log.warn("Could not download an update with error " + e1.toString()); - } - }); + }); return true; } diff --git a/jams-server/src/main/java/net/jami/jams/server/update/UpdateInterface.java b/jams-server/src/main/java/net/jami/jams/server/update/UpdateInterface.java index e54e92ed37afbce04f6c59aa883926a3b8aa044c..3c0bd77bfb22f5713f528e3c5c1bad66d0b7131b 100644 --- a/jams-server/src/main/java/net/jami/jams/server/update/UpdateInterface.java +++ b/jams-server/src/main/java/net/jami/jams/server/update/UpdateInterface.java @@ -2,6 +2,7 @@ package net.jami.jams.server.update; import lombok.Getter; import lombok.Setter; + import org.zeromq.SocketType; import org.zeromq.ZMQ; @@ -24,20 +25,19 @@ public class UpdateInterface extends Thread { this.start(); } - public void approveUpdate(){ + public void approveUpdate() { sender.send("DO-UPDATE"); } @Override public void run() { - while(true){ - try{ + while (true) { + try { receiver.recv(); updateAvailable.set(true); versions = receiver.recvStr(); - } - catch (Exception e){ - System.out.println(e.toString()); + } catch (Exception e) { + System.out.println(e); } } } diff --git a/jams-server/src/test/java/net/jami/jams/server/core/jaminamserver/PublicNameServerTest.java b/jams-server/src/test/java/net/jami/jams/server/core/jaminamserver/PublicNameServerTest.java index a920a9707006586d4e1ee4ee535f488f4b25e135..35db9fcd20a6d0a94b7260652734edcf45665506 100644 --- a/jams-server/src/test/java/net/jami/jams/server/core/jaminamserver/PublicNameServerTest.java +++ b/jams-server/src/test/java/net/jami/jams/server/core/jaminamserver/PublicNameServerTest.java @@ -1,31 +1,32 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.core.jaminamserver; import net.jami.jams.common.jami.NameLookupResponse; import net.jami.jams.common.jami.NameRegistrationRequest; import net.jami.jams.common.jami.NameServer; import net.jami.jams.nameserver.PublicNameServer; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -37,33 +38,31 @@ class PublicNameServerTest { private static NameServer nameServer; @BeforeAll - public static void init(){ + public static void init() { nameServer = new PublicNameServer("http://ns.jami.net"); } @Test - public void testNameRegistration(){ + public void testNameRegistration() { NameRegistrationRequest nameRegistrationRequest = new NameRegistrationRequest(); nameRegistrationRequest.setAddr("0e76529938772ac7626552ab71"); nameRegistrationRequest.setOwner("0x74ef2cD532a0f3cE31089b4fd296DDdFB5d6566A"); nameRegistrationRequest.setSignature(null); nameRegistrationRequest.setPublickey(null); - String name = UUID.randomUUID().toString().replace("-",""); - Integer res = nameServer.registerName(name,nameRegistrationRequest); - Assertions.assertEquals(200,res,"The response should have been 200!"); + String name = UUID.randomUUID().toString().replace("-", ""); + Integer res = nameServer.registerName(name, nameRegistrationRequest); + Assertions.assertEquals(200, res, "The response should have been 200!"); } @Test - public void testNameLookUp(){ + public void testNameLookUp() { NameLookupResponse resp = nameServer.getAddressFromName("sidokhine6"); - Assertions.assertNotNull(resp,"The response should exist!"); + Assertions.assertNotNull(resp, "The response should exist!"); } @Test - public void testAddrLookUp(){ + public void testAddrLookUp() { String addr = nameServer.getNameFromAddress("0d1f0002ce728d6aa8b98b5227c75fc773735f9e"); - Assertions.assertNotNull(addr,"The address should exist!"); + Assertions.assertNotNull(addr, "The address should exist!"); } - - -} \ No newline at end of file +} diff --git a/jams-server/src/test/java/net/jami/jams/server/licensing/LicenseServiceTest.java b/jams-server/src/test/java/net/jami/jams/server/licensing/LicenseServiceTest.java index f5eef373ff7e2e78578e8f7ada5a01c6277ccf70..3686910f5f12113375acd3651ad5bb596d371bd4 100644 --- a/jams-server/src/test/java/net/jami/jams/server/licensing/LicenseServiceTest.java +++ b/jams-server/src/test/java/net/jami/jams/server/licensing/LicenseServiceTest.java @@ -1,25 +1,25 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.server.licensing; import org.junit.jupiter.api.Test; @@ -27,9 +27,8 @@ import org.junit.jupiter.api.Test; class LicenseServiceTest { @Test - public void loadLicenseTest(){ + public void loadLicenseTest() { LicenseService licenseService = new LicenseService(); licenseService.loadLicense(); } - -} \ No newline at end of file +} diff --git a/ldap-connector/src/main/java/net/jami/jams/ldap/connector/LDAPConnector.java b/ldap-connector/src/main/java/net/jami/jams/ldap/connector/LDAPConnector.java index 4e3902b903dde972d8e18bab944d1d2ed2d76090..ca4a2104a9a52ec00de2e7988d7660344c753071 100644 --- a/ldap-connector/src/main/java/net/jami/jams/ldap/connector/LDAPConnector.java +++ b/ldap-connector/src/main/java/net/jami/jams/ldap/connector/LDAPConnector.java @@ -1,29 +1,31 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.ldap.connector; import com.jsoniter.JsonIterator; + import lombok.extern.slf4j.Slf4j; + import net.jami.jams.common.authentication.AuthenticationSource; import net.jami.jams.common.authentication.AuthenticationSourceInfo; import net.jami.jams.common.authentication.AuthenticationSourceType; @@ -33,6 +35,7 @@ import net.jami.jams.common.objects.user.UserProfile; import net.jami.jams.common.serialization.JsoniterRegistry; import net.jami.jams.ldap.connector.service.AuthenticationService; import net.jami.jams.ldap.connector.service.UserProfileService; + import org.ldaptive.BindConnectionInitializer; import org.ldaptive.ConnectionConfig; import org.ldaptive.Credential; @@ -50,15 +53,16 @@ public class LDAPConnector implements AuthenticationSource { public LDAPConnector(String strSettings) { JsoniterRegistry.initCodecs(); - LDAPConnector.settings = JsonIterator.deserialize(strSettings,LDAPSettings.class); + LDAPConnector.settings = JsonIterator.deserialize(strSettings, LDAPSettings.class); BindConnectionInitializer bindConnectionInitializer = new BindConnectionInitializer(); bindConnectionInitializer.setBindDn(settings.getUsername()); bindConnectionInitializer.setBindCredential(new Credential(settings.getPassword())); - ConnectionConfig connConfig = ConnectionConfig.builder() - .url(settings.getHost()) - .useStartTLS(settings.getUseStartTLS()) - .connectionInitializers(bindConnectionInitializer) - .build(); + ConnectionConfig connConfig = + ConnectionConfig.builder() + .url(settings.getHost()) + .useStartTLS(settings.getUseStartTLS()) + .connectionInitializers(bindConnectionInitializer) + .build(); authenticationService = new AuthenticationService(new DefaultConnectionFactory(connConfig)); userProfileService = new UserProfileService(new DefaultConnectionFactory(connConfig)); log.info("Started LDAP Connector!"); @@ -70,26 +74,28 @@ public class LDAPConnector implements AuthenticationSource { } @Override - public List<UserProfile> searchUserProfiles(String queryString, String field, Optional<Integer> page) { - return userProfileService.getUserProfile(queryString,field,false, page); + public List<UserProfile> searchUserProfiles( + String queryString, String field, Optional<Integer> page) { + return userProfileService.getUserProfile(queryString, field, false, page); } @Override public UserProfile getUserProfile(String username) { - List<UserProfile> results = userProfileService.getUserProfile(username,"LOGON_NAME",true, Optional.empty()); - if(results == null || results.size() != 1) return null; + List<UserProfile> results = + userProfileService.getUserProfile(username, "LOGON_NAME", true, Optional.empty()); + if (results == null || results.size() != 1) return null; return results.get(0); } @Override public boolean setUserProfile(UserProfile userProfile) { - //does nothing since we cannot edit LDAP profiles. + // does nothing since we cannot edit LDAP profiles. return false; } @Override public boolean authenticate(String username, String password) { - return authenticationService.authenticateUser(username,password); + return authenticationService.authenticateUser(username, password); } @Override @@ -99,10 +105,9 @@ public class LDAPConnector implements AuthenticationSource { @Override public boolean test() { - return (searchUserProfiles("*","LOGON_NAME", Optional.empty()).size() != 0); + return (searchUserProfiles("*", "LOGON_NAME", Optional.empty()).size() != 0); } - @Override public boolean updatePassword(User user, String password) { return false; diff --git a/ldap-connector/src/main/java/net/jami/jams/ldap/connector/service/AuthenticationService.java b/ldap-connector/src/main/java/net/jami/jams/ldap/connector/service/AuthenticationService.java index 493cd047473a33d8b3174dea329ea4d91bcbd399..7280fdccf002c09a78dbaf5aa3c6700253cbe109 100644 --- a/ldap-connector/src/main/java/net/jami/jams/ldap/connector/service/AuthenticationService.java +++ b/ldap-connector/src/main/java/net/jami/jams/ldap/connector/service/AuthenticationService.java @@ -1,28 +1,31 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.ldap.connector.service; +import static net.jami.jams.ldap.connector.LDAPConnector.settings; + import lombok.extern.slf4j.Slf4j; + import org.ldaptive.ConnectionFactory; import org.ldaptive.Credential; import org.ldaptive.auth.AuthenticationRequest; @@ -31,8 +34,6 @@ import org.ldaptive.auth.Authenticator; import org.ldaptive.auth.FormatDnResolver; import org.ldaptive.auth.SimpleBindAuthenticationHandler; -import static net.jami.jams.ldap.connector.LDAPConnector.settings; - @Slf4j public class AuthenticationService { @@ -46,19 +47,23 @@ public class AuthenticationService { try { FormatDnResolver dnResolver = new FormatDnResolver(); dnResolver.setFormat(settings.getUsernameField() + "=%s," + settings.getBaseDN()); - SimpleBindAuthenticationHandler bindAuthenticationHandler = new SimpleBindAuthenticationHandler(connectionFactory); + SimpleBindAuthenticationHandler bindAuthenticationHandler = + new SimpleBindAuthenticationHandler(connectionFactory); Authenticator auth = new Authenticator(); auth.setDnResolver(dnResolver); auth.setAuthenticationHandler(bindAuthenticationHandler); - AuthenticationResponse resp = auth.authenticate(new AuthenticationRequest(username, new Credential(password))); - log.info("User " + username + " has tried to authenticate with result: " + resp.getAuthenticationResultCode()); + AuthenticationResponse resp = + auth.authenticate( + new AuthenticationRequest(username, new Credential(password))); + log.info( + "User " + + username + + " has tried to authenticate with result: " + + resp.getAuthenticationResultCode()); return resp.isSuccess(); - } - catch (Exception e){ - log.info("An exception has occured trying to process and authentication request: " + e.toString()); + } catch (Exception e) { + log.info("An exception has occured trying to process and authentication request: " + e); return false; } } - - } diff --git a/ldap-connector/src/main/java/net/jami/jams/ldap/connector/service/UserProfileService.java b/ldap-connector/src/main/java/net/jami/jams/ldap/connector/service/UserProfileService.java index c7b346bb12e1cf468e8364e015f5ea0e8efebd88..84e023f30a3cb7f5693d3391772c37fe2db7a41e 100644 --- a/ldap-connector/src/main/java/net/jami/jams/ldap/connector/service/UserProfileService.java +++ b/ldap-connector/src/main/java/net/jami/jams/ldap/connector/service/UserProfileService.java @@ -1,32 +1,37 @@ /* -* Copyright (C) 2020 by Savoir-faire Linux -* Authors: William Enright <william.enright@savoirfairelinux.com> -* Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> -* Johnny Flores <johnny.flores@savoirfairelinux.com> -* Mohammed Raza <mohammed.raza@savoirfairelinux.com> -* Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> -* -* -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see <https://www.gnu.org/licenses/>. -*/ + * Copyright (C) 2020 by Savoir-faire Linux + * Authors: William Enright <william.enright@savoirfairelinux.com> + * Ndeye Anna Ndiaye <anna.ndiaye@savoirfairelinux.com> + * Johnny Flores <johnny.flores@savoirfairelinux.com> + * Mohammed Raza <mohammed.raza@savoirfairelinux.com> + * Felix Sidokhine <felix.sidokhine@savoirfairelinux.com> + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ package net.jami.jams.ldap.connector.service; +import static net.jami.jams.server.Server.dataStore; + import lombok.extern.slf4j.Slf4j; + +import net.jami.datastore.main.DataStore; import net.jami.jams.common.dao.StatementElement; import net.jami.jams.common.dao.StatementList; import net.jami.jams.common.objects.user.UserProfile; import net.jami.jams.ldap.connector.LDAPConnector; + import org.ldaptive.Connection; import org.ldaptive.ConnectionFactory; import org.ldaptive.LdapEntry; @@ -34,11 +39,10 @@ import org.ldaptive.SearchOperation; import org.ldaptive.SearchRequest; import org.ldaptive.SearchResponse; +import java.nio.charset.StandardCharsets; import java.util.*; import java.util.stream.Collectors; -import static net.jami.jams.server.Server.dataStore; - @Slf4j public class UserProfileService { private final ConnectionFactory connectionFactory; @@ -47,35 +51,49 @@ public class UserProfileService { this.connectionFactory = connectionFactory; } - public List<UserProfile> getUserProfile(String queryString, String field, boolean exactMatch, Optional<Integer> page){ + public List<UserProfile> getUserProfile( + String queryString, String field, boolean exactMatch, Optional<Integer> page) { Connection connection = null; try { - queryString = new String(queryString.getBytes("UTF-8"), "ISO-8859-1"); + queryString = + new String( + queryString.getBytes(StandardCharsets.UTF_8), + StandardCharsets.ISO_8859_1); connection = connectionFactory.getConnection(); try { connection.open(); SearchOperation search = new SearchOperation(connectionFactory); - SearchResponse res = search.execute(buildRequest(queryString,field, exactMatch)); + SearchResponse res = search.execute(buildRequest(queryString, field, exactMatch)); - dataStore.NUM_PAGES = (Integer) res.getEntries().size() / dataStore.RESULTS_PER_PAGE; - if (res.getEntries().size() % dataStore.RESULTS_PER_PAGE != 0) - dataStore.NUM_PAGES++; + DataStore.NUM_PAGES = + (Integer) res.getEntries().size() / DataStore.RESULTS_PER_PAGE; + if (res.getEntries().size() % DataStore.RESULTS_PER_PAGE != 0) + DataStore.NUM_PAGES++; if (page.isPresent() && !res.getEntries().isEmpty()) { - if (res.getEntries().size() < dataStore.RESULTS_PER_PAGE) - res= res.subResult(0, res.getEntries().size()); - else if (page.get() * dataStore.RESULTS_PER_PAGE > res.getEntries().size()) - res = res.subResult((page.get()-1) * dataStore.RESULTS_PER_PAGE, res.getEntries().size()); + if (res.getEntries().size() < DataStore.RESULTS_PER_PAGE) + res = res.subResult(0, res.getEntries().size()); + else if (page.get() * DataStore.RESULTS_PER_PAGE > res.getEntries().size()) + res = + res.subResult( + (page.get() - 1) * DataStore.RESULTS_PER_PAGE, + res.getEntries().size()); else - res = res.subResult((page.get()-1) * dataStore.RESULTS_PER_PAGE, (page.get() * dataStore.RESULTS_PER_PAGE)); - + res = + res.subResult( + (page.get() - 1) * DataStore.RESULTS_PER_PAGE, + (page.get() * DataStore.RESULTS_PER_PAGE)); } if (res.getEntries().size() == 0) return new ArrayList<>(); - List<UserProfile> profilesFromResponse = res.getEntries().stream().map(UserProfileService::profileFromResponse).collect(Collectors.toList()); - for (UserProfile p: profilesFromResponse) { + List<UserProfile> profilesFromResponse = + res.getEntries().stream() + .map(UserProfileService::profileFromResponse) + .collect(Collectors.toList()); + for (UserProfile p : profilesFromResponse) { StatementList statementList = new StatementList(); - StatementElement st = new StatementElement("username", "=", p.getUsername(), ""); + StatementElement st = + new StatementElement("username", "=", p.getUsername(), ""); statementList.addStatement(st); if (dataStore.getUserProfileDao().getObjects(statementList).isEmpty()) @@ -84,60 +102,56 @@ public class UserProfileService { return profilesFromResponse; } catch (Exception e) { - log.error("Could not search LDAP directory with error " + e.toString()); + log.error("Could not search LDAP directory with error " + e); return null; } - } - catch (Exception e){ - log.info("Failed to search LDAP directory with error " + e.toString()); + } catch (Exception e) { + log.info("Failed to search LDAP directory with error " + e); return null; - } - finally { + } finally { connection.close(); } } - public static SearchRequest buildRequest(String queryString, String field, boolean exactMatch) { - if(!exactMatch) { - if (!queryString.startsWith("*")) - queryString = "*".concat(queryString); - if(!queryString.endsWith("*")) - queryString = queryString.concat("*"); + if (!exactMatch) { + if (!queryString.startsWith("*")) queryString = "*".concat(queryString); + if (!queryString.endsWith("*")) queryString = queryString.concat("*"); } - if(field.equals("LOGON_NAME")) { + if (field.equals("LOGON_NAME")) { return SearchRequest.builder() .dn(LDAPConnector.settings.getBaseDN()) .filter("(&(uid=" + queryString + "))") .build(); } - if(field.equals("FULL_TEXT_NAME")){ + if (field.equals("FULL_TEXT_NAME")) { return SearchRequest.builder() .dn(LDAPConnector.settings.getBaseDN()) - .filter("(|(givenName=" + queryString + ")(sn="+queryString+")") + .filter("(|(givenName=" + queryString + ")(sn=" + queryString + ")") .build(); } return null; } - public static UserProfile profileFromResponse(LdapEntry entry){ - //Use reflection to remap. - HashMap<String,String> fieldMap = LDAPConnector.settings.getFieldMappings(); + public static UserProfile profileFromResponse(LdapEntry entry) { + // Use reflection to remap. + HashMap<String, String> fieldMap = LDAPConnector.settings.getFieldMappings(); try { UserProfile userProfile = new UserProfile(); for (String attribute : entry.getAttributeNames()) { - if(fieldMap.containsKey(attribute)) { - UserProfile.exposedMethods.get("set" + fieldMap.get(attribute)).invoke(userProfile, entry.getAttribute(attribute).getStringValue()); + if (fieldMap.containsKey(attribute)) { + UserProfile.exposedMethods + .get("set" + fieldMap.get(attribute)) + .invoke(userProfile, entry.getAttribute(attribute).getStringValue()); } } userProfile.setDefaultValues(); return userProfile; - } - catch (Exception e){ - log.error("An error occurred while trying to invoke methods: " + e.toString()); + } catch (Exception e) { + log.error("An error occurred while trying to invoke methods: " + e); return null; } } diff --git a/ldap-connector/src/test/java/tests/GenericLDAPTest.java b/ldap-connector/src/test/java/tests/GenericLDAPTest.java index cb5698460b136c38d586cc82fc4664eafc7b700a..af9e55a3e18ec1f165e4ad4476a6ee4e34e92980 100644 --- a/ldap-connector/src/test/java/tests/GenericLDAPTest.java +++ b/ldap-connector/src/test/java/tests/GenericLDAPTest.java @@ -2,6 +2,7 @@ package tests; import net.jami.jams.common.objects.user.UserProfile; import net.jami.jams.ldap.connector.LDAPConnector; + import org.junit.Assert; import org.junit.Rule; import org.junit.Test; @@ -17,48 +18,50 @@ public class GenericLDAPTest { private static LDAPConnector ldapConnector = null; - private void initLdapConnector() throws Exception{ - if(ldapConnector == null) { - InputStream inputStream = GenericLDAPTest.class.getClassLoader().getResourceAsStream("ldapconfig.json"); + private void initLdapConnector() throws Exception { + if (ldapConnector == null) { + InputStream inputStream = + GenericLDAPTest.class.getClassLoader().getResourceAsStream("ldapconfig.json"); ldapConnector = new LDAPConnector(new String(inputStream.readAllBytes())); } } @Rule - public EmbeddedLdapRule server = EmbeddedLdapRuleBuilder - .newInstance() - .usingDomainDsn("dc=savoirfairelinux,dc=net") - .bindingToPort(1089) - .importingLdifs("bootstrap.ldif") - .build(); + public EmbeddedLdapRule server = + EmbeddedLdapRuleBuilder.newInstance() + .usingDomainDsn("dc=savoirfairelinux,dc=net") + .bindingToPort(1089) + .importingLdifs("bootstrap.ldif") + .build(); @Test - public void testLookUp() throws Exception{ + public void testLookUp() throws Exception { initLdapConnector(); - List<UserProfile> profiles = ldapConnector.searchUserProfiles("*","FULL_TEXT_NAME", Optional.empty()); - Assertions.assertEquals(2,profiles.size()); + List<UserProfile> profiles = + ldapConnector.searchUserProfiles("*", "FULL_TEXT_NAME", Optional.empty()); + Assertions.assertEquals(2, profiles.size()); Assertions.assertNotNull(profiles.get(0).getFirstName()); Assertions.assertNotNull(profiles.get(1).getFirstName()); } @Test - public void testAuth() throws Exception{ + public void testAuth() throws Exception { boolean res; initLdapConnector(); - res = ldapConnector.authenticate("fsidokhine","password"); + res = ldapConnector.authenticate("fsidokhine", "password"); Assertions.assertTrue(res); - res = ldapConnector.authenticate("fsidokhine","badpassword"); + res = ldapConnector.authenticate("fsidokhine", "badpassword"); Assertions.assertFalse(res); } @Test - public void getVcard() throws Exception{ + public void getVcard() throws Exception { initLdapConnector(); - List<UserProfile> profiles = ldapConnector.searchUserProfiles("Felix","FULL_TEXT_NAME", Optional.empty()); - Assert.assertEquals(1,profiles.size()); + List<UserProfile> profiles = + ldapConnector.searchUserProfiles("Felix", "FULL_TEXT_NAME", Optional.empty()); + Assert.assertEquals(1, profiles.size()); Assert.assertNotNull(profiles.get(0).getUsername()); String vcard = profiles.get(0).getAsVCard(); Assert.assertNotNull(vcard); } - }