]> WPIA git - gigi.git/commitdiff
Format code according do BenBE's formatter.
authorFelix Dörre <felix@dogcraft.de>
Sat, 26 Jul 2014 20:57:42 +0000 (22:57 +0200)
committerFelix Dörre <felix@dogcraft.de>
Sat, 26 Jul 2014 20:57:42 +0000 (22:57 +0200)
91 files changed:
src/org/cacert/gigi/Certificate.java
src/org/cacert/gigi/DevelLauncher.java
src/org/cacert/gigi/Digest.java
src/org/cacert/gigi/Domain.java
src/org/cacert/gigi/EmailAddress.java
src/org/cacert/gigi/Gigi.java
src/org/cacert/gigi/GigiApiException.java
src/org/cacert/gigi/GigiConfig.java
src/org/cacert/gigi/Language.java
src/org/cacert/gigi/Launcher.java
src/org/cacert/gigi/Name.java
src/org/cacert/gigi/PolicyRedirector.java
src/org/cacert/gigi/User.java
src/org/cacert/gigi/api/GigiAPI.java
src/org/cacert/gigi/database/DatabaseConnection.java
src/org/cacert/gigi/email/CommandlineEmailProvider.java
src/org/cacert/gigi/email/EmailProvider.java
src/org/cacert/gigi/email/Sendmail.java
src/org/cacert/gigi/email/TestEmailProvider.java
src/org/cacert/gigi/natives/SetUID.java
src/org/cacert/gigi/output/CertificateTable.java
src/org/cacert/gigi/output/ClientCSRGenerate.java
src/org/cacert/gigi/output/DateSelector.java
src/org/cacert/gigi/output/Form.java
src/org/cacert/gigi/output/Menu.java
src/org/cacert/gigi/output/MenuItem.java
src/org/cacert/gigi/output/Outputable.java
src/org/cacert/gigi/output/template/ForeachStatement.java
src/org/cacert/gigi/output/template/HashAlgorithms.java
src/org/cacert/gigi/output/template/IfStatement.java
src/org/cacert/gigi/output/template/IterableDataset.java
src/org/cacert/gigi/output/template/OutputVariableCommand.java
src/org/cacert/gigi/output/template/SprintfCommand.java
src/org/cacert/gigi/output/template/Template.java
src/org/cacert/gigi/output/template/TemplateBlock.java
src/org/cacert/gigi/output/template/TranslateCommand.java
src/org/cacert/gigi/pages/LoginPage.java
src/org/cacert/gigi/pages/MainPage.java
src/org/cacert/gigi/pages/Page.java
src/org/cacert/gigi/pages/TestSecure.java
src/org/cacert/gigi/pages/Verify.java
src/org/cacert/gigi/pages/account/ChangeForm.java
src/org/cacert/gigi/pages/account/ChangePasswordPage.java
src/org/cacert/gigi/pages/account/IssueCertificateForm.java
src/org/cacert/gigi/pages/account/MailAddForm.java
src/org/cacert/gigi/pages/account/MailCertificateAdd.java
src/org/cacert/gigi/pages/account/MailCertificates.java
src/org/cacert/gigi/pages/account/MailManagementForm.java
src/org/cacert/gigi/pages/account/MailOverview.java
src/org/cacert/gigi/pages/account/MyDetails.java
src/org/cacert/gigi/pages/error/PageNotFound.java
src/org/cacert/gigi/pages/main/RegisterPage.java
src/org/cacert/gigi/pages/main/Signup.java
src/org/cacert/gigi/pages/wot/AssuranceForm.java
src/org/cacert/gigi/pages/wot/AssurePage.java
src/org/cacert/gigi/ping/DNSPinger.java
src/org/cacert/gigi/ping/DomainPinger.java
src/org/cacert/gigi/ping/HTTPFetch.java
src/org/cacert/gigi/ping/SSLPinger.java
src/org/cacert/gigi/util/CipherInfo.java
src/org/cacert/gigi/util/HTMLEncoder.java
src/org/cacert/gigi/util/Job.java
src/org/cacert/gigi/util/KeyStorage.java
src/org/cacert/gigi/util/Notary.java
src/org/cacert/gigi/util/PasswordHash.java
src/org/cacert/gigi/util/PasswordStrengthChecker.java
src/org/cacert/gigi/util/RandomToken.java
src/org/cacert/gigi/util/ServerConstants.java
tests/org/cacert/gigi/LoginTest.java
tests/org/cacert/gigi/TestCertificate.java
tests/org/cacert/gigi/TestDomain.java
tests/org/cacert/gigi/TestSSL.java
tests/org/cacert/gigi/TestSecurityHeaders.java
tests/org/cacert/gigi/TestSeparateSessionScope.java
tests/org/cacert/gigi/TestUser.java
tests/org/cacert/gigi/pages/account/TestChangePassword.java
tests/org/cacert/gigi/pages/account/TestMailManagement.java
tests/org/cacert/gigi/pages/main/RegisterPageTest.java
tests/org/cacert/gigi/pages/wot/TestAssurance.java
tests/org/cacert/gigi/testUtils/IOUtils.java
tests/org/cacert/gigi/testUtils/InitTruststore.java
tests/org/cacert/gigi/testUtils/ManagedTest.java
tests/org/cacert/gigi/testUtils/PemKey.java
tests/org/cacert/gigi/testUtils/TestEmailReciever.java
tests/org/cacert/gigi/util/TestHTMLEncoder.java
tests/org/cacert/gigi/util/TestNotary.java
tests/org/cacert/gigi/util/TestPasswordHash.java
tests/org/cacert/gigi/util/TestPasswordStrengthChecker.java
util/org/cacert/gigi/util/DatabaseManager.java
util/org/cacert/gigi/util/FetchLocales.java
util/org/cacert/gigi/util/SimpleSigner.java

index 7a13b45f945d1b1935032102ac0732d18b7f9411..d7af542b674134f0045e57a162077716bac49b17 100644 (file)
@@ -19,194 +19,198 @@ import org.cacert.gigi.util.KeyStorage;
 import org.cacert.gigi.util.Notary;
 
 public class Certificate {
-       public enum CSRType {
-               CSR, SPKAC;
-       }
-
-       private int id;
-       private int ownerId;
-       private String serial;
-       private String dn;
-       private String md;
-       private String csrName;
-       private String crtName;
-       private String csr = null;
-       private CSRType csrType;
-
-       public Certificate(int ownerId, String dn, String md, String csr, CSRType csrType) {
-               this.ownerId = ownerId;
-               this.dn = dn;
-               this.md = md;
-               this.csr = csr;
-               this.csrType = csrType;
-       }
-
-       private Certificate(String serial) {
-               try {
-                       PreparedStatement ps = DatabaseConnection.getInstance().prepare(
-                               "SELECT id,subject, md, csr_name, crt_name,memid FROM `emailcerts` WHERE serial=?");
-                       ps.setString(1, serial);
-                       ResultSet rs = ps.executeQuery();
-                       if (!rs.next()) {
-                               throw new IllegalArgumentException("Invalid mid " + serial);
-                       }
-                       this.id = rs.getInt(1);
-                       dn = rs.getString(2);
-                       md = rs.getString(3);
-                       csrName = rs.getString(4);
-                       crtName = rs.getString(5);
-                       ownerId = rs.getInt(6);
-                       this.serial = serial;
-                       rs.close();
-               } catch (SQLException e) {
-                       e.printStackTrace();
-               }
-       }
-
-       public enum CertificateStatus {
-               /**
-                * This certificate is not in the database, has no id and only exists as
-                * this java object.
-                */
-               DRAFT(),
-               /**
-                * The certificate has been signed. It is stored in the database.
-                * {@link Certificate#cert()} is valid.
-                */
-               ISSUED(),
-
-               /**
-                * The certificate has been revoked.
-                */
-               REVOKED(),
-
-               /**
-                * If this certificate cannot be updated because an error happened in
-                * the signer.
-                */
-               ERROR();
-
-               private CertificateStatus() {
-               }
-
-       }
-
-       public CertificateStatus getStatus() throws SQLException {
-               if (id == 0) {
-                       return CertificateStatus.DRAFT;
-               }
-               PreparedStatement searcher = DatabaseConnection.getInstance().prepare(
-                       "SELECT crt_name, created, revoked, serial FROM emailcerts WHERE id=?");
-               searcher.setInt(1, id);
-               ResultSet rs = searcher.executeQuery();
-               if (!rs.next()) {
-                       throw new IllegalStateException("Certificate not in Database");
-               }
-
-               crtName = rs.getString(1);
-               serial = rs.getString(4);
-               if (rs.getTime(2) == null) {
-                       return CertificateStatus.DRAFT;
-               }
-               if (rs.getTime(2) != null && rs.getTime(3) == null) {
-                       return CertificateStatus.ISSUED;
-               }
-               return CertificateStatus.REVOKED;
-       }
-
-       public Job issue() throws IOException, SQLException {
-               if (getStatus() != CertificateStatus.DRAFT) {
-                       throw new IllegalStateException();
-               }
-               Notary.writeUserAgreement(ownerId, "CCA", "issue certificate", "", true, 0);
-
-               PreparedStatement inserter = DatabaseConnection.getInstance().prepare(
-                       "INSERT INTO emailcerts SET md=?, subject=?, csr_type=?, crt_name='', memid=?");
-               inserter.setString(1, md);
-               inserter.setString(2, dn);
-               inserter.setString(3, csrType.toString());
-               inserter.setInt(4, ownerId);
-               inserter.execute();
-               id = DatabaseConnection.lastInsertId(inserter);
-               File csrFile = KeyStorage.locateCsr(id);
-               csrName = csrFile.getPath();
-               FileOutputStream fos = new FileOutputStream(csrFile);
-               fos.write(csr.getBytes());
-               fos.close();
-
-               PreparedStatement updater = DatabaseConnection.getInstance().prepare(
-                       "UPDATE emailcerts SET csr_name=? WHERE id=?");
-               updater.setString(1, csrName);
-               updater.setInt(2, id);
-               updater.execute();
-               return Job.submit(this, JobType.SIGN);
-
-       }
-
-       public Job revoke() throws SQLException {
-               if (getStatus() != CertificateStatus.ISSUED) {
-                       throw new IllegalStateException();
-               }
-               return Job.submit(this, JobType.REVOKE);
-
-       }
-
-       public X509Certificate cert() throws IOException, GeneralSecurityException, SQLException {
-               CertificateStatus status = getStatus();
-               if (status != CertificateStatus.ISSUED) {
-                       throw new IllegalStateException(status + " is not wanted here.");
-               }
-               InputStream is = null;
-               X509Certificate crt = null;
-               try {
-                       is = new FileInputStream(crtName);
-                       CertificateFactory cf = CertificateFactory.getInstance("X.509");
-                       crt = (X509Certificate) cf.generateCertificate(is);
-               } finally {
-                       if (is != null) {
-                               is.close();
-                       }
-               }
-               return crt;
-       }
-
-       public Certificate renew() {
-               return null;
-       }
-
-       public int getId() {
-               return id;
-       }
-
-       public String getSerial() {
-               try {
-                       getStatus();
-               } catch (SQLException e) {
-                       e.printStackTrace();
-               } // poll changes
-               return serial;
-       }
-
-       public String getDistinguishedName() {
-               return dn;
-       }
-
-       public String getMessageDigest() {
-               return md;
-       }
-
-       public int getOwnerId() {
-               return ownerId;
-       }
-
-       public static Certificate getBySerial(String serial) {
-               // TODO caching?
-               try {
-                       return new Certificate(serial);
-               } catch (IllegalArgumentException e) {
-
-               }
-               return null;
-       }
+
+    public enum CSRType {
+        CSR, SPKAC;
+    }
+
+    private int id;
+
+    private int ownerId;
+
+    private String serial;
+
+    private String dn;
+
+    private String md;
+
+    private String csrName;
+
+    private String crtName;
+
+    private String csr = null;
+
+    private CSRType csrType;
+
+    public Certificate(int ownerId, String dn, String md, String csr, CSRType csrType) {
+        this.ownerId = ownerId;
+        this.dn = dn;
+        this.md = md;
+        this.csr = csr;
+        this.csrType = csrType;
+    }
+
+    private Certificate(String serial) {
+        try {
+            PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id,subject, md, csr_name, crt_name,memid FROM `emailcerts` WHERE serial=?");
+            ps.setString(1, serial);
+            ResultSet rs = ps.executeQuery();
+            if ( !rs.next()) {
+                throw new IllegalArgumentException("Invalid mid " + serial);
+            }
+            this.id = rs.getInt(1);
+            dn = rs.getString(2);
+            md = rs.getString(3);
+            csrName = rs.getString(4);
+            crtName = rs.getString(5);
+            ownerId = rs.getInt(6);
+            this.serial = serial;
+            rs.close();
+        } catch (SQLException e) {
+            e.printStackTrace();
+        }
+    }
+
+    public enum CertificateStatus {
+        /**
+         * This certificate is not in the database, has no id and only exists as
+         * this java object.
+         */
+        DRAFT(),
+        /**
+         * The certificate has been signed. It is stored in the database.
+         * {@link Certificate#cert()} is valid.
+         */
+        ISSUED(),
+
+        /**
+         * The certificate has been revoked.
+         */
+        REVOKED(),
+
+        /**
+         * If this certificate cannot be updated because an error happened in
+         * the signer.
+         */
+        ERROR();
+
+        private CertificateStatus() {}
+
+    }
+
+    public CertificateStatus getStatus() throws SQLException {
+        if (id == 0) {
+            return CertificateStatus.DRAFT;
+        }
+        PreparedStatement searcher = DatabaseConnection.getInstance().prepare("SELECT crt_name, created, revoked, serial FROM emailcerts WHERE id=?");
+        searcher.setInt(1, id);
+        ResultSet rs = searcher.executeQuery();
+        if ( !rs.next()) {
+            throw new IllegalStateException("Certificate not in Database");
+        }
+
+        crtName = rs.getString(1);
+        serial = rs.getString(4);
+        if (rs.getTime(2) == null) {
+            return CertificateStatus.DRAFT;
+        }
+        if (rs.getTime(2) != null && rs.getTime(3) == null) {
+            return CertificateStatus.ISSUED;
+        }
+        return CertificateStatus.REVOKED;
+    }
+
+    public Job issue() throws IOException, SQLException {
+        if (getStatus() != CertificateStatus.DRAFT) {
+            throw new IllegalStateException();
+        }
+        Notary.writeUserAgreement(ownerId, "CCA", "issue certificate", "", true, 0);
+
+        PreparedStatement inserter = DatabaseConnection.getInstance().prepare("INSERT INTO emailcerts SET md=?, subject=?, csr_type=?, crt_name='', memid=?");
+        inserter.setString(1, md);
+        inserter.setString(2, dn);
+        inserter.setString(3, csrType.toString());
+        inserter.setInt(4, ownerId);
+        inserter.execute();
+        id = DatabaseConnection.lastInsertId(inserter);
+        File csrFile = KeyStorage.locateCsr(id);
+        csrName = csrFile.getPath();
+        FileOutputStream fos = new FileOutputStream(csrFile);
+        fos.write(csr.getBytes());
+        fos.close();
+
+        PreparedStatement updater = DatabaseConnection.getInstance().prepare("UPDATE emailcerts SET csr_name=? WHERE id=?");
+        updater.setString(1, csrName);
+        updater.setInt(2, id);
+        updater.execute();
+        return Job.submit(this, JobType.SIGN);
+
+    }
+
+    public Job revoke() throws SQLException {
+        if (getStatus() != CertificateStatus.ISSUED) {
+            throw new IllegalStateException();
+        }
+        return Job.submit(this, JobType.REVOKE);
+
+    }
+
+    public X509Certificate cert() throws IOException, GeneralSecurityException, SQLException {
+        CertificateStatus status = getStatus();
+        if (status != CertificateStatus.ISSUED) {
+            throw new IllegalStateException(status + " is not wanted here.");
+        }
+        InputStream is = null;
+        X509Certificate crt = null;
+        try {
+            is = new FileInputStream(crtName);
+            CertificateFactory cf = CertificateFactory.getInstance("X.509");
+            crt = (X509Certificate) cf.generateCertificate(is);
+        } finally {
+            if (is != null) {
+                is.close();
+            }
+        }
+        return crt;
+    }
+
+    public Certificate renew() {
+        return null;
+    }
+
+    public int getId() {
+        return id;
+    }
+
+    public String getSerial() {
+        try {
+            getStatus();
+        } catch (SQLException e) {
+            e.printStackTrace();
+        } // poll changes
+        return serial;
+    }
+
+    public String getDistinguishedName() {
+        return dn;
+    }
+
+    public String getMessageDigest() {
+        return md;
+    }
+
+    public int getOwnerId() {
+        return ownerId;
+    }
+
+    public static Certificate getBySerial(String serial) {
+        // TODO caching?
+        try {
+            return new Certificate(serial);
+        } catch (IllegalArgumentException e) {
+
+        }
+        return null;
+    }
 
 }
index 3a78d6286f8902af29099f6fe0d4e0216c65e228..e83ae4145f3d47d955c5b087a9e23b27479eb882 100644 (file)
@@ -19,66 +19,66 @@ import org.kamranzafar.jtar.TarHeader;
 import org.kamranzafar.jtar.TarOutputStream;
 
 public class DevelLauncher {
-       public static final boolean DEVEL = true;
 
-       public static void main(String[] args) throws Exception {
-               Properties mainProps = new Properties();
-               mainProps.load(new FileInputStream("config/gigi.properties"));
-               for (int i = 0; i < args.length; i++) {
-                       if (args[i].equals("--port")) {
-                               mainProps.setProperty("port", args[i + 1]);
-                       }
-                       i++;
-               }
+    public static final boolean DEVEL = true;
 
-               ByteArrayOutputStream chunkConfig = new ByteArrayOutputStream();
-               DataOutputStream dos = new DataOutputStream(chunkConfig);
-               byte[] cacerts = Files.readAllBytes(Paths.get("config/cacerts.jks"));
-               byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12"));
+    public static void main(String[] args) throws Exception {
+        Properties mainProps = new Properties();
+        mainProps.load(new FileInputStream("config/gigi.properties"));
+        for (int i = 0; i < args.length; i++) {
+            if (args[i].equals("--port")) {
+                mainProps.setProperty("port", args[i + 1]);
+            }
+            i++;
+        }
 
-               DevelLauncher.writeGigiConfig(dos, "changeit".getBytes(), "changeit".getBytes(), mainProps, cacerts, keystore);
-               dos.flush();
-               InputStream oldin = System.in;
-               System.setIn(new ByteArrayInputStream(chunkConfig.toByteArray()));
-               Launcher.main(args);
-               System.setIn(oldin);
-               BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
-               System.out.println("Cacert-gigi system sucessfully started.");
-               System.out.println("Press enter to shutdown.");
-               br.readLine();
-               System.exit(0);
-       }
+        ByteArrayOutputStream chunkConfig = new ByteArrayOutputStream();
+        DataOutputStream dos = new DataOutputStream(chunkConfig);
+        byte[] cacerts = Files.readAllBytes(Paths.get("config/cacerts.jks"));
+        byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12"));
 
-       public static void writeGigiConfig(OutputStream target, byte[] keystorepw, byte[] truststorepw,
-               Properties mainprop, byte[] cacerts, byte[] keystore) throws IOException {
-               TarOutputStream tos = new TarOutputStream(target);
-               ByteArrayOutputStream baos = new ByteArrayOutputStream();
-               mainprop.store(baos, "");
+        DevelLauncher.writeGigiConfig(dos, "changeit".getBytes(), "changeit".getBytes(), mainProps, cacerts, keystore);
+        dos.flush();
+        InputStream oldin = System.in;
+        System.setIn(new ByteArrayInputStream(chunkConfig.toByteArray()));
+        Launcher.main(args);
+        System.setIn(oldin);
+        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
+        System.out.println("Cacert-gigi system sucessfully started.");
+        System.out.println("Press enter to shutdown.");
+        br.readLine();
+        System.exit(0);
+    }
 
-               putTarEntry(baos.toByteArray(), tos, "gigi.properties");
-               putTarEntry(keystorepw, tos, "keystorepw");
-               putTarEntry(truststorepw, tos, "truststorepw");
-               putTarEntry(keystore, tos, "keystore.pkcs12");
-               putTarEntry(cacerts, tos, "cacerts.jks");
-               tos.close();
+    public static void writeGigiConfig(OutputStream target, byte[] keystorepw, byte[] truststorepw, Properties mainprop, byte[] cacerts, byte[] keystore) throws IOException {
+        TarOutputStream tos = new TarOutputStream(target);
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        mainprop.store(baos, "");
 
-       }
+        putTarEntry(baos.toByteArray(), tos, "gigi.properties");
+        putTarEntry(keystorepw, tos, "keystorepw");
+        putTarEntry(truststorepw, tos, "truststorepw");
+        putTarEntry(keystore, tos, "keystore.pkcs12");
+        putTarEntry(cacerts, tos, "cacerts.jks");
+        tos.close();
 
-       private static void putTarEntry(byte[] data, TarOutputStream tos, String name) throws IOException {
-               TarHeader th = new TarHeader();
-               th.name = new StringBuffer(name);
-               th.size = data.length;
-               tos.putNextEntry(new TarEntry(th));
-               tos.write(data);
-       }
+    }
 
-       public static void writeChunk(DataOutputStream dos, byte[] chunk) throws IOException {
-               dos.writeInt(chunk.length);
-               dos.write(chunk);
-       }
+    private static void putTarEntry(byte[] data, TarOutputStream tos, String name) throws IOException {
+        TarHeader th = new TarHeader();
+        th.name = new StringBuffer(name);
+        th.size = data.length;
+        tos.putNextEntry(new TarEntry(th));
+        tos.write(data);
+    }
 
-       public static void launch(Properties props, File cacerts, File keystore) throws IOException {
-               ByteArrayOutputStream config = new ByteArrayOutputStream();
-               props.store(config, "");
-       }
+    public static void writeChunk(DataOutputStream dos, byte[] chunk) throws IOException {
+        dos.writeInt(chunk.length);
+        dos.write(chunk);
+    }
+
+    public static void launch(Properties props, File cacerts, File keystore) throws IOException {
+        ByteArrayOutputStream config = new ByteArrayOutputStream();
+        props.store(config, "");
+    }
 }
index e183be7275ac4b45c7c57792f6d5c97e23e1bd73..bf7cfee60f8a0b2aaa50e1ad5c9d45d7148ca335 100644 (file)
@@ -1,21 +1,19 @@
 package org.cacert.gigi;
 
 public enum Digest {
-       SHA256("Currently recommended, because the other algorithms"
-               + " might break on some older versions of the GnuTLS library"
-               + " (older than 3.x) still shipped in Debian for example."), SHA384(null), SHA512(
-               "Highest protection against hash collision attacks of the algorithms offered here.");
-       final String exp;
+    SHA256("Currently recommended, because the other algorithms" + " might break on some older versions of the GnuTLS library" + " (older than 3.x) still shipped in Debian for example."), SHA384(null), SHA512("Highest protection against hash collision attacks of the algorithms offered here.");
 
-       private Digest(String explanation) {
-               exp = explanation;
-       }
+    final String exp;
 
-       public String getExp() {
-               return exp;
-       }
+    private Digest(String explanation) {
+        exp = explanation;
+    }
 
-       public static Digest getDefault() {
-               return SHA256;
-       }
+    public String getExp() {
+        return exp;
+    }
+
+    public static Digest getDefault() {
+        return SHA256;
+    }
 }
index 2aca793e9b1d2988c9826133113b5c3fa31553ad..246dbc145ff8152b13e0021b30b8b1a09074ec59 100644 (file)
@@ -7,104 +7,101 @@ import java.sql.SQLException;
 import org.cacert.gigi.database.DatabaseConnection;
 
 public class Domain {
-       User owner;
-       String suffix;
-       int id;
-
-       public Domain(int id) throws SQLException {
-               PreparedStatement ps = DatabaseConnection.getInstance().prepare(
-                       "SELECT memid, domain FROM `domain` WHERE id=? AND deleted IS NULL");
-               ps.setInt(1, id);
-
-               ResultSet rs = ps.executeQuery();
-               if (!rs.next()) {
-                       throw new IllegalArgumentException("Invalid email id " + id);
-               }
-               this.id = id;
-               owner = User.getById(rs.getInt(1));
-               suffix = rs.getString(2);
-               rs.close();
-       }
-
-       public Domain(User owner, String suffix) throws GigiApiException {
-               this.owner = owner;
-               this.suffix = suffix;
-
-       }
-
-       private static void checkInsert(String suffix) throws GigiApiException {
-               try {
-                       PreparedStatement ps = DatabaseConnection
-                               .getInstance()
-                               .prepare(
-                                       "SELECT 1 FROM `domain` WHERE (domain=RIGHT(?,LENGTH(domain))  OR RIGHT(domain,LENGTH(?))=?) AND deleted IS NULL");
-                       ps.setString(1, suffix);
-                       ps.setString(2, suffix);
-                       ps.setString(3, suffix);
-                       ResultSet rs = ps.executeQuery();
-                       boolean existed = rs.next();
-                       rs.close();
-                       if (existed) {
-                               throw new GigiApiException("Domain could not be inserted. Domain is already valid.");
-                       }
-               } catch (SQLException e) {
-                       throw new GigiApiException(e);
-               }
-       }
-
-       public void insert() throws GigiApiException {
-               if (id != 0) {
-                       throw new GigiApiException("already inserted.");
-               }
-               synchronized (Domain.class) {
-                       checkInsert(suffix);
-                       try {
-                               PreparedStatement ps = DatabaseConnection.getInstance().prepare(
-                                       "INSERT INTO `domain` SET memid=?, domain=?");
-                               ps.setInt(1, owner.getId());
-                               ps.setString(2, suffix);
-                               ps.execute();
-                               id = DatabaseConnection.lastInsertId(ps);
-                       } catch (SQLException e) {
-                               throw new GigiApiException(e);
-                       }
-               }
-       }
-
-       public void delete() throws GigiApiException {
-               if (id == 0) {
-                       throw new GigiApiException("not inserted.");
-               }
-               try {
-                       PreparedStatement ps = DatabaseConnection.getInstance().prepare(
-                               "UPDATE `domain` SET deleted=CURRENT_TIMESTAMP WHERE id=?");
-                       ps.setInt(1, id);
-                       ps.execute();
-               } catch (SQLException e) {
-                       throw new GigiApiException(e);
-               }
-       }
-
-       public User getOwner() {
-               return owner;
-       }
-
-       public int getId() {
-               return id;
-       }
-
-       public String getSuffix() {
-               return suffix;
-       }
-
-       public static Domain getById(int id) throws IllegalArgumentException {
-               // TODO cache
-               try {
-                       Domain e = new Domain(id);
-                       return e;
-               } catch (SQLException e) {
-                       throw new IllegalArgumentException(e);
-               }
-       }
+
+    User owner;
+
+    String suffix;
+
+    int id;
+
+    public Domain(int id) throws SQLException {
+        PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT memid, domain FROM `domain` WHERE id=? AND deleted IS NULL");
+        ps.setInt(1, id);
+
+        ResultSet rs = ps.executeQuery();
+        if ( !rs.next()) {
+            throw new IllegalArgumentException("Invalid email id " + id);
+        }
+        this.id = id;
+        owner = User.getById(rs.getInt(1));
+        suffix = rs.getString(2);
+        rs.close();
+    }
+
+    public Domain(User owner, String suffix) throws GigiApiException {
+        this.owner = owner;
+        this.suffix = suffix;
+
+    }
+
+    private static void checkInsert(String suffix) throws GigiApiException {
+        try {
+            PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT 1 FROM `domain` WHERE (domain=RIGHT(?,LENGTH(domain))  OR RIGHT(domain,LENGTH(?))=?) AND deleted IS NULL");
+            ps.setString(1, suffix);
+            ps.setString(2, suffix);
+            ps.setString(3, suffix);
+            ResultSet rs = ps.executeQuery();
+            boolean existed = rs.next();
+            rs.close();
+            if (existed) {
+                throw new GigiApiException("Domain could not be inserted. Domain is already valid.");
+            }
+        } catch (SQLException e) {
+            throw new GigiApiException(e);
+        }
+    }
+
+    public void insert() throws GigiApiException {
+        if (id != 0) {
+            throw new GigiApiException("already inserted.");
+        }
+        synchronized (Domain.class) {
+            checkInsert(suffix);
+            try {
+                PreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `domain` SET memid=?, domain=?");
+                ps.setInt(1, owner.getId());
+                ps.setString(2, suffix);
+                ps.execute();
+                id = DatabaseConnection.lastInsertId(ps);
+            } catch (SQLException e) {
+                throw new GigiApiException(e);
+            }
+        }
+    }
+
+    public void delete() throws GigiApiException {
+        if (id == 0) {
+            throw new GigiApiException("not inserted.");
+        }
+        try {
+            PreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE `domain` SET deleted=CURRENT_TIMESTAMP WHERE id=?");
+            ps.setInt(1, id);
+            ps.execute();
+        } catch (SQLException e) {
+            throw new GigiApiException(e);
+        }
+    }
+
+    public User getOwner() {
+        return owner;
+    }
+
+    public int getId() {
+        return id;
+    }
+
+    public String getSuffix() {
+        return suffix;
+    }
+
+    public static Domain getById(int id) throws IllegalArgumentException {
+        // TODO cache
+        try {
+            Domain e = new Domain(id);
+            return e;
+        } catch (SQLException e) {
+            throw new IllegalArgumentException(e);
+        }
+    }
 
 }
index a2a7e5801d8566ef88b5c7fd59840650a77204d1..365e95388a707f385b275e613e63238551c4a7ac 100644 (file)
@@ -11,115 +11,113 @@ import org.cacert.gigi.util.RandomToken;
 import org.cacert.gigi.util.ServerConstants;
 
 public class EmailAddress {
-       private String address;
-       private int id;
-       private User owner;
-       private String hash = null;
-
-       private EmailAddress(int id) throws SQLException {
-               PreparedStatement ps = DatabaseConnection.getInstance().prepare(
-                       "SELECT memid, email, hash FROM `email` WHERE id=? AND deleted=0");
-               ps.setInt(1, id);
-
-               ResultSet rs = ps.executeQuery();
-               if (!rs.next()) {
-                       throw new IllegalArgumentException("Invalid email id " + id);
-               }
-               this.id = id;
-               owner = User.getById(rs.getInt(1));
-               address = rs.getString(2);
-               hash = rs.getString(3);
-               rs.close();
-       }
-
-       public EmailAddress(String address, User owner) {
-               if (!EmailProvider.MAIL.matcher(address).matches()) {
-                       throw new IllegalArgumentException("Invalid email.");
-               }
-               this.address = address;
-               this.owner = owner;
-               this.hash = RandomToken.generateToken(16);
-       }
-
-       public void insert(Language l) {
-               if (id != 0) {
-                       throw new IllegalStateException("already inserted.");
-               }
-               try {
-                       PreparedStatement ps = DatabaseConnection.getInstance().prepare(
-                               "INSERT INTO `email` SET memid=?, hash=?, email=?");
-                       ps.setInt(1, owner.getId());
-                       ps.setString(2, hash);
-                       ps.setString(3, address);
-                       ps.execute();
-                       id = DatabaseConnection.lastInsertId(ps);
-                       StringBuffer body = new StringBuffer();
-                       body.append(l
-                               .getTranslation("Thanks for signing up with CAcert.org, below is the link you need to open to verify your account. Once your account is verified you will be able to start issuing certificates till your hearts' content!"));
-                       body.append("\n\nhttps://");
-                       body.append(ServerConstants.getWwwHostNamePort());
-                       body.append("/verify?type=email&id=");
-                       body.append(id);
-                       body.append("&hash=");
-                       body.append(hash);
-                       body.append("\n\n");
-                       body.append(l.getTranslation("Best regards"));
-                       body.append("\n");
-                       body.append(l.getTranslation("CAcert.org Support!"));
-                       EmailProvider.getInstance().sendmail(address, "[CAcert.org] " + l.getTranslation("Mail Probe"),
-                               body.toString(), "support@cacert.org", null, null, null, null, false);
-               } catch (SQLException e) {
-                       e.printStackTrace();
-               } catch (IOException e) {
-                       e.printStackTrace();
-               }
-       }
-
-       public int getId() {
-               return id;
-       }
-
-       public String getAddress() {
-               return address;
-       }
-
-       public synchronized void verify(String hash) throws GigiApiException {
-               if (this.hash.equals(hash)) {
-
-                       try {
-                               PreparedStatement ps = DatabaseConnection.getInstance()
-                                       .prepare("UPDATE `email` SET hash='' WHERE id=?");
-                               ps.setInt(1, id);
-                               ps.execute();
-                               hash = "";
-
-                               // Verify user with that primary email
-                               PreparedStatement ps2 = DatabaseConnection.getInstance().prepare(
-                                       "update `users` set `verified`='1' where `id`=? and `email`=? and `verified`='0'");
-                               ps2.setInt(1, owner.getId());
-                               ps2.setString(2, address);
-                               ps2.execute();
-                               this.hash = "";
-                       } catch (SQLException e) {
-                               throw new GigiApiException(e);
-                       }
-
-               } else {
-                       throw new GigiApiException("Email verification hash is invalid.");
-               }
-       }
-
-       public static EmailAddress getById(int id) throws IllegalArgumentException {
-               // TODO cache
-               try {
-                       EmailAddress e = new EmailAddress(id);
-                       return e;
-               } catch (SQLException e) {
-                       throw new IllegalArgumentException(e);
-               }
-       }
-
-       public boolean isVerified() {
-               return hash.isEmpty();
-       }
+
+    private String address;
+
+    private int id;
+
+    private User owner;
+
+    private String hash = null;
+
+    private EmailAddress(int id) throws SQLException {
+        PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT memid, email, hash FROM `email` WHERE id=? AND deleted=0");
+        ps.setInt(1, id);
+
+        ResultSet rs = ps.executeQuery();
+        if ( !rs.next()) {
+            throw new IllegalArgumentException("Invalid email id " + id);
+        }
+        this.id = id;
+        owner = User.getById(rs.getInt(1));
+        address = rs.getString(2);
+        hash = rs.getString(3);
+        rs.close();
+    }
+
+    public EmailAddress(String address, User owner) {
+        if ( !EmailProvider.MAIL.matcher(address).matches()) {
+            throw new IllegalArgumentException("Invalid email.");
+        }
+        this.address = address;
+        this.owner = owner;
+        this.hash = RandomToken.generateToken(16);
+    }
+
+    public void insert(Language l) {
+        if (id != 0) {
+            throw new IllegalStateException("already inserted.");
+        }
+        try {
+            PreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `email` SET memid=?, hash=?, email=?");
+            ps.setInt(1, owner.getId());
+            ps.setString(2, hash);
+            ps.setString(3, address);
+            ps.execute();
+            id = DatabaseConnection.lastInsertId(ps);
+            StringBuffer body = new StringBuffer();
+            body.append(l.getTranslation("Thanks for signing up with CAcert.org, below is the link you need to open to verify your account. Once your account is verified you will be able to start issuing certificates till your hearts' content!"));
+            body.append("\n\nhttps://");
+            body.append(ServerConstants.getWwwHostNamePort());
+            body.append("/verify?type=email&id=");
+            body.append(id);
+            body.append("&hash=");
+            body.append(hash);
+            body.append("\n\n");
+            body.append(l.getTranslation("Best regards"));
+            body.append("\n");
+            body.append(l.getTranslation("CAcert.org Support!"));
+            EmailProvider.getInstance().sendmail(address, "[CAcert.org] " + l.getTranslation("Mail Probe"), body.toString(), "support@cacert.org", null, null, null, null, false);
+        } catch (SQLException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
+
+    public int getId() {
+        return id;
+    }
+
+    public String getAddress() {
+        return address;
+    }
+
+    public synchronized void verify(String hash) throws GigiApiException {
+        if (this.hash.equals(hash)) {
+
+            try {
+                PreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE `email` SET hash='' WHERE id=?");
+                ps.setInt(1, id);
+                ps.execute();
+                hash = "";
+
+                // Verify user with that primary email
+                PreparedStatement ps2 = DatabaseConnection.getInstance().prepare("update `users` set `verified`='1' where `id`=? and `email`=? and `verified`='0'");
+                ps2.setInt(1, owner.getId());
+                ps2.setString(2, address);
+                ps2.execute();
+                this.hash = "";
+            } catch (SQLException e) {
+                throw new GigiApiException(e);
+            }
+
+        } else {
+            throw new GigiApiException("Email verification hash is invalid.");
+        }
+    }
+
+    public static EmailAddress getById(int id) throws IllegalArgumentException {
+        // TODO cache
+        try {
+            EmailAddress e = new EmailAddress(id);
+            return e;
+        } catch (SQLException e) {
+            throw new IllegalArgumentException(e);
+        }
+    }
+
+    public boolean isVerified() {
+        return hash.isEmpty();
+    }
 }
index 9d1bb1b9afb4b84f56bae564ec02e7dc3fa47721..5590663ddc2a7fdffe8fe02fcfe01b2e3fdcbd9a 100644 (file)
@@ -36,159 +36,161 @@ import org.cacert.gigi.pages.wot.AssurePage;
 import org.cacert.gigi.util.ServerConstants;
 
 public class Gigi extends HttpServlet {
-       public static final String LOGGEDIN = "loggedin";
-       public static final String USER = "user";
-       private static final long serialVersionUID = -6386785421902852904L;
-       private Template baseTemplate;
-       private HashMap<String, Page> pages = new HashMap<String, Page>();
-       Menu m;
-
-       public Gigi(Properties conf) {
-               EmailProvider.init(conf);
-               DatabaseConnection.init(conf);
-       }
-
-       @Override
-       public void init() throws ServletException {
-               pages.put("/error", new PageNotFound());
-               pages.put("/login", new LoginPage("CACert - Login"));
-               pages.put("/", new MainPage("CACert - Home"));
-               pages.put("/secure", new TestSecure());
-               pages.put(Verify.PATH, new Verify());
-               pages.put(AssurePage.PATH + "/*", new AssurePage());
-               pages.put(MailCertificates.PATH + "/*", new MailCertificates());
-               pages.put(MyDetails.PATH, new MyDetails());
-               pages.put(ChangePasswordPage.PATH, new ChangePasswordPage());
-               pages.put(RegisterPage.PATH, new RegisterPage());
-               pages.put(MailCertificateAdd.PATH, new MailCertificateAdd());
-               pages.put(MailOverview.DEFAULT_PATH, new MailOverview("My email addresses"));
-               baseTemplate = new Template(Gigi.class.getResource("Gigi.templ"));
-               m = new Menu("Certificates", "cert", new MenuItem(MailOverview.DEFAULT_PATH, "Emails"), new MenuItem("",
-                       "Client Certificates"), new MenuItem("", "Domains"), new MenuItem("", "Server Certificates"));
-               super.init();
-
-       }
-
-       @Override
-       protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException,
-               IOException {
-               addXSSHeaders(resp);
-               // if (req.getHeader("Origin") != null) {
-               // resp.getWriter().println("No cross domain access allowed.");
-               // return;
-               // }
-               HttpSession hs = req.getSession();
-               if (req.getPathInfo() != null && req.getPathInfo().equals("/logout")) {
-                       if (hs != null) {
-                               hs.setAttribute(LOGGEDIN, null);
-                               hs.invalidate();
-                       }
-                       resp.sendRedirect("/");
-                       return;
-               }
-
-               final Page p = getPage(req.getPathInfo());
-               if (p != null) {
-
-                       if (p.needsLogin() && hs.getAttribute("loggedin") == null) {
-                               String request = req.getPathInfo();
-                               request = request.split("\\?")[0];
-                               hs.setAttribute(LoginPage.LOGIN_RETURNPATH, request);
-                               resp.sendRedirect("/login");
-                               return;
-                       }
-                       if (p.beforeTemplate(req, resp)) {
-                               return;
-                       }
-                       HashMap<String, Object> vars = new HashMap<String, Object>();
-
-                       resp.setContentType("text/html; charset=utf-8");
-                       Outputable content = new Outputable() {
-
-                               @Override
-                               public void output(PrintWriter out, Language l, Map<String, Object> vars) {
-                                       try {
-                                               if (req.getMethod().equals("POST")) {
-                                                       if (req.getQueryString() != null) {
-                                                               return;
-                                                       }
-                                                       p.doPost(req, resp);
-                                               } else {
-                                                       p.doGet(req, resp);
-                                               }
-                                       } catch (CSRFException err) {
-                                               try {
-                                                       resp.sendError(500, "CSRF invalid");
-                                               } catch (IOException e) {
-                                                       e.printStackTrace();
-                                               }
-                                       } catch (IOException e) {
-                                               e.printStackTrace();
-                                       }
-
-                               }
-                       };
-                       vars.put("menu", m);
-                       vars.put("title", p.getTitle());
-                       vars.put("static", ServerConstants.getStaticHostNamePort());
-                       vars.put("year", Calendar.getInstance().get(Calendar.YEAR));
-                       vars.put("content", content);
-                       baseTemplate.output(resp.getWriter(), Page.getLanguage(req), vars);
-               } else {
-                       resp.sendError(404, "Page not found.");
-               }
-
-       }
-
-       private Page getPage(String pathInfo) {
-               if (pathInfo.endsWith("/") && !pathInfo.equals("/")) {
-                       pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
-               }
-               Page page = pages.get(pathInfo);
-               if (page != null) {
-                       return page;
-               }
-               page = pages.get(pathInfo + "/*");
-               if (page != null) {
-                       return page;
-               }
-               int idx = pathInfo.lastIndexOf('/');
-               pathInfo = pathInfo.substring(0, idx);
-
-               page = pages.get(pathInfo + "/*");
-               if (page != null) {
-                       return page;
-               }
-               return null;
-
-       }
-
-       public static void addXSSHeaders(HttpServletResponse hsr) {
-               hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePort() + " https://"
-                       + ServerConstants.getSecureHostNamePort());
-               hsr.addHeader("Access-Control-Max-Age", "60");
-
-               hsr.addHeader("Content-Security-Policy", getDefaultCSP());
-               hsr.addHeader("Strict-Transport-Security", "max-age=31536000");
-
-       }
-
-       private static String defaultCSP = null;
-
-       private static String getDefaultCSP() {
-               if (defaultCSP == null) {
-                       StringBuffer csp = new StringBuffer();
-                       csp.append("default-src 'none';");
-                       csp.append("font-src https://" + ServerConstants.getStaticHostNamePort());
-                       csp.append(";img-src https://" + ServerConstants.getStaticHostNamePort());
-                       csp.append(";media-src 'none'; object-src 'none';");
-                       csp.append("script-src https://" + ServerConstants.getStaticHostNamePort());
-                       csp.append(";style-src https://" + ServerConstants.getStaticHostNamePort());
-                       csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://"
-                               + ServerConstants.getWwwHostNamePort());
-                       csp.append("report-url https://api.cacert.org/security/csp/report");
-                       defaultCSP = csp.toString();
-               }
-               return defaultCSP;
-       }
+
+    public static final String LOGGEDIN = "loggedin";
+
+    public static final String USER = "user";
+
+    private static final long serialVersionUID = -6386785421902852904L;
+
+    private Template baseTemplate;
+
+    private HashMap<String, Page> pages = new HashMap<String, Page>();
+
+    Menu m;
+
+    public Gigi(Properties conf) {
+        EmailProvider.init(conf);
+        DatabaseConnection.init(conf);
+    }
+
+    @Override
+    public void init() throws ServletException {
+        pages.put("/error", new PageNotFound());
+        pages.put("/login", new LoginPage("CACert - Login"));
+        pages.put("/", new MainPage("CACert - Home"));
+        pages.put("/secure", new TestSecure());
+        pages.put(Verify.PATH, new Verify());
+        pages.put(AssurePage.PATH + "/*", new AssurePage());
+        pages.put(MailCertificates.PATH + "/*", new MailCertificates());
+        pages.put(MyDetails.PATH, new MyDetails());
+        pages.put(ChangePasswordPage.PATH, new ChangePasswordPage());
+        pages.put(RegisterPage.PATH, new RegisterPage());
+        pages.put(MailCertificateAdd.PATH, new MailCertificateAdd());
+        pages.put(MailOverview.DEFAULT_PATH, new MailOverview("My email addresses"));
+        baseTemplate = new Template(Gigi.class.getResource("Gigi.templ"));
+        m = new Menu("Certificates", "cert", new MenuItem(MailOverview.DEFAULT_PATH, "Emails"), new MenuItem("", "Client Certificates"), new MenuItem("", "Domains"), new MenuItem("", "Server Certificates"));
+        super.init();
+
+    }
+
+    @Override
+    protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
+        addXSSHeaders(resp);
+        // if (req.getHeader("Origin") != null) {
+        // resp.getWriter().println("No cross domain access allowed.");
+        // return;
+        // }
+        HttpSession hs = req.getSession();
+        if (req.getPathInfo() != null && req.getPathInfo().equals("/logout")) {
+            if (hs != null) {
+                hs.setAttribute(LOGGEDIN, null);
+                hs.invalidate();
+            }
+            resp.sendRedirect("/");
+            return;
+        }
+
+        final Page p = getPage(req.getPathInfo());
+        if (p != null) {
+
+            if (p.needsLogin() && hs.getAttribute("loggedin") == null) {
+                String request = req.getPathInfo();
+                request = request.split("\\?")[0];
+                hs.setAttribute(LoginPage.LOGIN_RETURNPATH, request);
+                resp.sendRedirect("/login");
+                return;
+            }
+            if (p.beforeTemplate(req, resp)) {
+                return;
+            }
+            HashMap<String, Object> vars = new HashMap<String, Object>();
+
+            resp.setContentType("text/html; charset=utf-8");
+            Outputable content = new Outputable() {
+
+                @Override
+                public void output(PrintWriter out, Language l, Map<String, Object> vars) {
+                    try {
+                        if (req.getMethod().equals("POST")) {
+                            if (req.getQueryString() != null) {
+                                return;
+                            }
+                            p.doPost(req, resp);
+                        } else {
+                            p.doGet(req, resp);
+                        }
+                    } catch (CSRFException err) {
+                        try {
+                            resp.sendError(500, "CSRF invalid");
+                        } catch (IOException e) {
+                            e.printStackTrace();
+                        }
+                    } catch (IOException e) {
+                        e.printStackTrace();
+                    }
+
+                }
+            };
+            vars.put("menu", m);
+            vars.put("title", p.getTitle());
+            vars.put("static", ServerConstants.getStaticHostNamePort());
+            vars.put("year", Calendar.getInstance().get(Calendar.YEAR));
+            vars.put("content", content);
+            baseTemplate.output(resp.getWriter(), Page.getLanguage(req), vars);
+        } else {
+            resp.sendError(404, "Page not found.");
+        }
+
+    }
+
+    private Page getPage(String pathInfo) {
+        if (pathInfo.endsWith("/") && !pathInfo.equals("/")) {
+            pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
+        }
+        Page page = pages.get(pathInfo);
+        if (page != null) {
+            return page;
+        }
+        page = pages.get(pathInfo + "/*");
+        if (page != null) {
+            return page;
+        }
+        int idx = pathInfo.lastIndexOf('/');
+        pathInfo = pathInfo.substring(0, idx);
+
+        page = pages.get(pathInfo + "/*");
+        if (page != null) {
+            return page;
+        }
+        return null;
+
+    }
+
+    public static void addXSSHeaders(HttpServletResponse hsr) {
+        hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePort() + " https://" + ServerConstants.getSecureHostNamePort());
+        hsr.addHeader("Access-Control-Max-Age", "60");
+
+        hsr.addHeader("Content-Security-Policy", getDefaultCSP());
+        hsr.addHeader("Strict-Transport-Security", "max-age=31536000");
+
+    }
+
+    private static String defaultCSP = null;
+
+    private static String getDefaultCSP() {
+        if (defaultCSP == null) {
+            StringBuffer csp = new StringBuffer();
+            csp.append("default-src 'none';");
+            csp.append("font-src https://" + ServerConstants.getStaticHostNamePort());
+            csp.append(";img-src https://" + ServerConstants.getStaticHostNamePort());
+            csp.append(";media-src 'none'; object-src 'none';");
+            csp.append("script-src https://" + ServerConstants.getStaticHostNamePort());
+            csp.append(";style-src https://" + ServerConstants.getStaticHostNamePort());
+            csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePort());
+            csp.append("report-url https://api.cacert.org/security/csp/report");
+            defaultCSP = csp.toString();
+        }
+        return defaultCSP;
+    }
 }
index 7b91d125fb1d200a4e1a822ab7dac70bbf3a693a..430c199befb11bc916c3d84fb7e98247fd04923e 100644 (file)
@@ -5,53 +5,55 @@ import java.sql.SQLException;
 import java.util.LinkedList;
 
 public class GigiApiException extends Exception {
-       SQLException e;
-       LinkedList<String> messages = new LinkedList<>();
-
-       public GigiApiException(SQLException e) {
-               super(e);
-               this.e = e;
-       }
-
-       public GigiApiException(String message) {
-               super(message);
-               messages.add(message);
-       }
-
-       public GigiApiException() {
-
-       }
-
-       public void mergeInto(GigiApiException e2) {
-               messages.addAll(e2.messages);
-               if (e == null) {
-                       e = e2.e;
-               }
-       }
-
-       public boolean isInternalError() {
-               return e != null;
-       }
-
-       public void format(PrintWriter out, Language language) {
-               out.println("<div class='formError'>");
-               if (isInternalError()) {
-                       e.printStackTrace();
-                       out.print("<div>");
-                       out.println(language.getTranslation("An internal error ouccured."));
-                       out.println("</div>");
-               }
-               for (String message : messages) {
-                       out.print("<div>");
-                       out.print(language.getTranslation(message));
-                       out.println("</div>");
-               }
-               out.println("</div>");
-
-       }
-
-       public boolean isEmpty() {
-               return e == null && messages.size() == 0;
-       }
+
+    SQLException e;
+
+    LinkedList<String> messages = new LinkedList<>();
+
+    public GigiApiException(SQLException e) {
+        super(e);
+        this.e = e;
+    }
+
+    public GigiApiException(String message) {
+        super(message);
+        messages.add(message);
+    }
+
+    public GigiApiException() {
+
+    }
+
+    public void mergeInto(GigiApiException e2) {
+        messages.addAll(e2.messages);
+        if (e == null) {
+            e = e2.e;
+        }
+    }
+
+    public boolean isInternalError() {
+        return e != null;
+    }
+
+    public void format(PrintWriter out, Language language) {
+        out.println("<div class='formError'>");
+        if (isInternalError()) {
+            e.printStackTrace();
+            out.print("<div>");
+            out.println(language.getTranslation("An internal error ouccured."));
+            out.println("</div>");
+        }
+        for (String message : messages) {
+            out.print("<div>");
+            out.print(language.getTranslation(message));
+            out.println("</div>");
+        }
+        out.println("</div>");
+
+    }
+
+    public boolean isEmpty() {
+        return e == null && messages.size() == 0;
+    }
 
 }
index 86738007eb237b6ccd66ee490e603b8e1068c59a..4c36302abaca89c52ef66ba8ca32681686562bd5 100644 (file)
@@ -12,84 +12,89 @@ import org.kamranzafar.jtar.TarEntry;
 import org.kamranzafar.jtar.TarInputStream;
 
 public class GigiConfig {
-       public static final String GIGI_CONFIG_VERSION = "GigiConfigV1.0";
-       byte[] cacerts;
-       byte[] keystore;
-       Properties mainProps = new Properties();
-       private char[] keystorpw;
-       private char[] truststorepw;
-
-       private GigiConfig() {
-       }
-
-       public byte[] getCacerts() {
-               return cacerts;
-       }
-
-       public byte[] getKeystore() {
-               return keystore;
-       }
-
-       public Properties getMainProps() {
-               return mainProps;
-       }
-
-       public static GigiConfig parse(InputStream input) throws IOException {
-               TarInputStream tis = new TarInputStream(input);
-               TarEntry t;
-               GigiConfig gc = new GigiConfig();
-               while ((t = tis.getNextEntry()) != null) {
-                       if (t.getName().equals("gigi.properties")) {
-                               gc.mainProps.load(tis);
-                       } else if (t.getName().equals("cacerts.jks")) {
-                               gc.cacerts = readFully(tis);
-                       } else if (t.getName().equals("keystore.pkcs12")) {
-                               gc.keystore = readFully(tis);
-                       } else if (t.getName().equals("keystorepw")) {
-                               gc.keystorpw = transformSafe(readFully(tis));
-                       } else if (t.getName().equals("truststorepw")) {
-                               gc.truststorepw = transformSafe(readFully(tis));
-                       } else {
-                               System.out.println("Unknown config: " + t.getName());
-                       }
-               }
-               tis.close();
-               return gc;
-       }
-
-       public static byte[] readFully(InputStream is) throws IOException {
-               ByteArrayOutputStream baos = new ByteArrayOutputStream();
-               byte[] buffer = new byte[1024];
-               int len = 0;
-               while ((len = is.read(buffer)) > 0) {
-                       baos.write(buffer, 0, len);
-               }
-               baos.close();
-               return baos.toByteArray();
-       }
-
-       private static char[] transformSafe(byte[] readChunk) {
-               char[] res = new char[readChunk.length];
-               for (int i = 0; i < res.length; i++) {
-                       res[i] = (char) readChunk[i];
-                       readChunk[i] = 0;
-               }
-               return res;
-       }
-
-       public KeyStore getPrivateStore() throws GeneralSecurityException, IOException {
-               KeyStore ks1 = KeyStore.getInstance("pkcs12");
-               ks1.load(new ByteArrayInputStream(keystore), keystorpw);
-               return ks1;
-       }
-
-       public KeyStore getTrustStore() throws GeneralSecurityException, IOException {
-               KeyStore ks1 = KeyStore.getInstance("jks");
-               ks1.load(new ByteArrayInputStream(cacerts), truststorepw);
-               return ks1;
-       }
-
-       public String getPrivateStorePw() {
-               return new String(keystorpw);
-       }
+
+    public static final String GIGI_CONFIG_VERSION = "GigiConfigV1.0";
+
+    byte[] cacerts;
+
+    byte[] keystore;
+
+    Properties mainProps = new Properties();
+
+    private char[] keystorpw;
+
+    private char[] truststorepw;
+
+    private GigiConfig() {}
+
+    public byte[] getCacerts() {
+        return cacerts;
+    }
+
+    public byte[] getKeystore() {
+        return keystore;
+    }
+
+    public Properties getMainProps() {
+        return mainProps;
+    }
+
+    public static GigiConfig parse(InputStream input) throws IOException {
+        TarInputStream tis = new TarInputStream(input);
+        TarEntry t;
+        GigiConfig gc = new GigiConfig();
+        while ((t = tis.getNextEntry()) != null) {
+            if (t.getName().equals("gigi.properties")) {
+                gc.mainProps.load(tis);
+            } else if (t.getName().equals("cacerts.jks")) {
+                gc.cacerts = readFully(tis);
+            } else if (t.getName().equals("keystore.pkcs12")) {
+                gc.keystore = readFully(tis);
+            } else if (t.getName().equals("keystorepw")) {
+                gc.keystorpw = transformSafe(readFully(tis));
+            } else if (t.getName().equals("truststorepw")) {
+                gc.truststorepw = transformSafe(readFully(tis));
+            } else {
+                System.out.println("Unknown config: " + t.getName());
+            }
+        }
+        tis.close();
+        return gc;
+    }
+
+    public static byte[] readFully(InputStream is) throws IOException {
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        byte[] buffer = new byte[1024];
+        int len = 0;
+        while ((len = is.read(buffer)) > 0) {
+            baos.write(buffer, 0, len);
+        }
+        baos.close();
+        return baos.toByteArray();
+    }
+
+    private static char[] transformSafe(byte[] readChunk) {
+        char[] res = new char[readChunk.length];
+        for (int i = 0; i < res.length; i++) {
+            res[i] = (char) readChunk[i];
+            readChunk[i] = 0;
+        }
+        return res;
+    }
+
+    public KeyStore getPrivateStore() throws GeneralSecurityException, IOException {
+        KeyStore ks1 = KeyStore.getInstance("pkcs12");
+        ks1.load(new ByteArrayInputStream(keystore), keystorpw);
+        return ks1;
+    }
+
+    public KeyStore getTrustStore() throws GeneralSecurityException, IOException {
+        KeyStore ks1 = KeyStore.getInstance("jks");
+        ks1.load(new ByteArrayInputStream(cacerts), truststorepw);
+        return ks1;
+    }
+
+    public String getPrivateStorePw() {
+        return new String(keystorpw);
+    }
 }
index 75593ccf723618a47598b084611d971c987c809e..6c03b19ca59694020952ff79e3c6159eb96137e4 100644 (file)
@@ -17,61 +17,64 @@ import org.w3c.dom.NodeList;
 import org.xml.sax.SAXException;
 
 public class Language {
-       private static HashMap<String, Language> langs = new HashMap<String, Language>();
-       HashMap<String, String> translations = new HashMap<String, String>();
-       Locale l;
 
-       private Language(String language) throws ParserConfigurationException, IOException, SAXException {
-               if (language.contains("_")) {
-                       String[] parts = language.split("_");
-                       l = new Locale(parts[0], parts[1]);
-               } else {
-                       l = new Locale(language);
-               }
+    private static HashMap<String, Language> langs = new HashMap<String, Language>();
 
-               DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
-               DocumentBuilder db = dbf.newDocumentBuilder();
-               Document d = db.parse(new FileInputStream(new File("locale", language + ".xml")));
-               NodeList nl = d.getDocumentElement().getChildNodes();
-               for (int i = 0; i < nl.getLength(); i++) {
-                       if (!(nl.item(i) instanceof Element)) {
-                               continue;
-                       }
-                       Element e = (Element) nl.item(i);
-                       Element id = (Element) e.getElementsByTagName("id").item(0);
-                       Element msg = (Element) e.getElementsByTagName("msg").item(0);
-                       translations.put(id.getTextContent(), HTMLEncoder.encodeHTML(msg.getTextContent()));
-               }
-               System.out.println(translations.size() + " strings loaded.");
-       }
+    HashMap<String, String> translations = new HashMap<String, String>();
 
-       public String getTranslation(String text) {
-               String string = translations.get(text);
-               if (string == null || string.equals("")) {
-                       return text;
-               }
-               return string;
-       }
+    Locale l;
 
-       public static Language getInstance(String language) {
-               Language l = langs.get(language);
-               if (l == null) {
-                       try {
-                               l = new Language(language);
-                               langs.put(language, l);
-                       } catch (ParserConfigurationException e) {
-                               e.printStackTrace();
-                       } catch (IOException e) {
-                               e.printStackTrace();
-                       } catch (SAXException e) {
-                               e.printStackTrace();
-                       }
-               }
-               return l;
-       }
+    private Language(String language) throws ParserConfigurationException, IOException, SAXException {
+        if (language.contains("_")) {
+            String[] parts = language.split("_");
+            l = new Locale(parts[0], parts[1]);
+        } else {
+            l = new Locale(language);
+        }
 
-       public Locale getLocale() {
-               return l;
-       }
+        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+        DocumentBuilder db = dbf.newDocumentBuilder();
+        Document d = db.parse(new FileInputStream(new File("locale", language + ".xml")));
+        NodeList nl = d.getDocumentElement().getChildNodes();
+        for (int i = 0; i < nl.getLength(); i++) {
+            if ( !(nl.item(i) instanceof Element)) {
+                continue;
+            }
+            Element e = (Element) nl.item(i);
+            Element id = (Element) e.getElementsByTagName("id").item(0);
+            Element msg = (Element) e.getElementsByTagName("msg").item(0);
+            translations.put(id.getTextContent(), HTMLEncoder.encodeHTML(msg.getTextContent()));
+        }
+        System.out.println(translations.size() + " strings loaded.");
+    }
+
+    public String getTranslation(String text) {
+        String string = translations.get(text);
+        if (string == null || string.equals("")) {
+            return text;
+        }
+        return string;
+    }
+
+    public static Language getInstance(String language) {
+        Language l = langs.get(language);
+        if (l == null) {
+            try {
+                l = new Language(language);
+                langs.put(language, l);
+            } catch (ParserConfigurationException e) {
+                e.printStackTrace();
+            } catch (IOException e) {
+                e.printStackTrace();
+            } catch (SAXException e) {
+                e.printStackTrace();
+            }
+        }
+        return l;
+    }
+
+    public Locale getLocale() {
+        return l;
+    }
 
 }
index f34a05e504a25178e3f9571b2887f83e535548d1..c2e11286a07414d6894e0d91b505c1184a2d84af 100644 (file)
@@ -38,175 +38,189 @@ import org.eclipse.jetty.util.log.Log;
 import org.eclipse.jetty.util.ssl.SslContextFactory;
 
 public class Launcher {
-       public static void main(String[] args) throws Exception {
-               GigiConfig conf = GigiConfig.parse(System.in);
-               ServerConstants.init(conf.getMainProps());
-
-               Server s = new Server();
-               // === SSL HTTP Configuration ===
-               HttpConfiguration https_config = new HttpConfiguration();
-               https_config.setSendServerVersion(false);
-               https_config.setSendXPoweredBy(false);
-
-               // for client-cert auth
-               https_config.addCustomizer(new SecureRequestCustomizer());
-
-               ServerConnector connector = new ServerConnector(s, createConnectionFactory(conf), new HttpConnectionFactory(
-                       https_config));
-               connector.setHost(conf.getMainProps().getProperty("host"));
-               connector.setPort(Integer.parseInt(conf.getMainProps().getProperty("port")));
-               s.setConnectors(new Connector[] { connector });
-
-               HandlerList hl = new HandlerList();
-               hl.setHandlers(new Handler[] { generateStaticContext(), generateGigiContexts(conf.getMainProps()),
-                               generateAPIContext() });
-               s.setHandler(hl);
-               s.start();
-               if (connector.getPort() <= 1024 && !System.getProperty("os.name").toLowerCase().contains("win")) {
-                       SetUID uid = new SetUID();
-                       if (!uid.setUid(65536 - 2, 65536 - 2).getSuccess()) {
-                               Log.getLogger(Launcher.class).warn("Couldn't set uid!");
-                       }
-               }
-       }
-
-       private static SslConnectionFactory createConnectionFactory(GigiConfig conf) throws GeneralSecurityException,
-               IOException {
-               final SslContextFactory sslContextFactory = generateSSLContextFactory(conf, "www");
-               final SslContextFactory secureContextFactory = generateSSLContextFactory(conf, "secure");
-               secureContextFactory.setWantClientAuth(true);
-               secureContextFactory.setNeedClientAuth(false);
-               final SslContextFactory staticContextFactory = generateSSLContextFactory(conf, "static");
-               final SslContextFactory apiContextFactory = generateSSLContextFactory(conf, "api");
-               try {
-                       secureContextFactory.start();
-                       staticContextFactory.start();
-                       apiContextFactory.start();
-               } catch (Exception e) {
-                       e.printStackTrace();
-               }
-               return new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()) {
-                       @Override
-                       public boolean shouldRestartSSL() {
-                               return true;
-                       }
-
-                       @Override
-                       public SSLEngine restartSSL(SSLSession sslSession) {
-                               SSLEngine e2 = null;
-                               if (sslSession instanceof ExtendedSSLSession) {
-                                       ExtendedSSLSession es = (ExtendedSSLSession) sslSession;
-                                       List<SNIServerName> names = es.getRequestedServerNames();
-                                       for (SNIServerName sniServerName : names) {
-                                               if (sniServerName instanceof SNIHostName) {
-                                                       SNIHostName host = (SNIHostName) sniServerName;
-                                                       String hostname = host.getAsciiName();
-                                                       if (hostname.equals(ServerConstants.getWwwHostName())) {
-                                                               e2 = sslContextFactory.newSSLEngine();
-                                                       } else if (hostname.equals(ServerConstants.getStaticHostName())) {
-                                                               e2 = staticContextFactory.newSSLEngine();
-                                                       } else if (hostname.equals(ServerConstants.getSecureHostName())) {
-                                                               e2 = secureContextFactory.newSSLEngine();
-                                                       } else if (hostname.equals(ServerConstants.getApiHostName())) {
-                                                               e2 = apiContextFactory.newSSLEngine();
-                                                       }
-                                                       break;
-                                               }
-                                       }
-                               }
-                               if (e2 == null) {
-                                       e2 = sslContextFactory.newSSLEngine(sslSession.getPeerHost(), sslSession.getPeerPort());
-                               }
-                               e2.setUseClientMode(false);
-                               return e2;
-                       }
-               };
-       }
-
-       private static Handler generateGigiContexts(Properties conf) {
-               ServletHolder webAppServlet = new ServletHolder(new Gigi(conf));
-
-               ContextHandler ch = generateGigiServletContext(webAppServlet);
-               ch.setVirtualHosts(new String[] { ServerConstants.getWwwHostName() });
-               ContextHandler chSecure = generateGigiServletContext(webAppServlet);
-               chSecure.setVirtualHosts(new String[] { ServerConstants.getSecureHostName() });
-
-               HandlerList hl = new HandlerList();
-               hl.setHandlers(new Handler[] { ch, chSecure });
-               return hl;
-       }
-
-       private static ContextHandler generateGigiServletContext(ServletHolder webAppServlet) {
-               final ResourceHandler rh = new ResourceHandler();
-               rh.setResourceBase("static/www");
-
-               HandlerWrapper hw = new PolicyRedirector();
-               hw.setHandler(rh);
-
-               ServletContextHandler servlet = new ServletContextHandler(ServletContextHandler.SESSIONS);
-               servlet.setInitParameter(SessionManager.__SessionCookieProperty, "CACert-Session");
-               servlet.addServlet(webAppServlet, "/*");
-               ErrorPageErrorHandler epeh = new ErrorPageErrorHandler();
-               epeh.addErrorPage(404, "/error");
-               servlet.setErrorHandler(epeh);
-
-               HandlerList hl = new HandlerList();
-               hl.setHandlers(new Handler[] { hw, servlet });
-
-               ContextHandler ch = new ContextHandler();
-               ch.setHandler(hl);
-               return ch;
-       }
-
-       private static Handler generateStaticContext() {
-               final ResourceHandler rh = new ResourceHandler();
-               rh.setResourceBase("static/static");
-
-               ContextHandler ch = new ContextHandler();
-               ch.setHandler(rh);
-               ch.setVirtualHosts(new String[] { ServerConstants.getStaticHostName() });
-
-               return ch;
-       }
-
-       private static Handler generateAPIContext() {
-               ServletContextHandler sch = new ServletContextHandler();
-
-               sch.addVirtualHosts(new String[] { ServerConstants.getApiHostName() });
-               sch.addServlet(new ServletHolder(new GigiAPI()), "/*");
-               return sch;
-       }
-
-       private static SslContextFactory generateSSLContextFactory(GigiConfig conf, String alias)
-               throws GeneralSecurityException, IOException {
-               SslContextFactory scf = new SslContextFactory() {
-
-                       String[] ciphers = null;
-
-                       @Override
-                       public void customize(SSLEngine sslEngine) {
-                               super.customize(sslEngine);
-
-                               SSLParameters ssl = sslEngine.getSSLParameters();
-                               ssl.setUseCipherSuitesOrder(true);
-                               if (ciphers == null) {
-                                       ciphers = CipherInfo.filter(sslEngine.getSupportedCipherSuites());
-                               }
-
-                               ssl.setCipherSuites(ciphers);
-                               sslEngine.setSSLParameters(ssl);
-
-                       }
-
-               };
-               scf.setRenegotiationAllowed(false);
-
-               scf.setProtocol("TLS");
-               scf.setTrustStore(conf.getTrustStore());
-               KeyStore privateStore = conf.getPrivateStore();
-               scf.setKeyStorePassword(conf.getPrivateStorePw());
-               scf.setKeyStore(privateStore);
-               scf.setCertAlias(alias);
-               return scf;
-       }
+
+    public static void main(String[] args) throws Exception {
+        GigiConfig conf = GigiConfig.parse(System.in);
+        ServerConstants.init(conf.getMainProps());
+
+        Server s = new Server();
+        // === SSL HTTP Configuration ===
+        HttpConfiguration https_config = new HttpConfiguration();
+        https_config.setSendServerVersion(false);
+        https_config.setSendXPoweredBy(false);
+
+        // for client-cert auth
+        https_config.addCustomizer(new SecureRequestCustomizer());
+
+        ServerConnector connector = new ServerConnector(s, createConnectionFactory(conf), new HttpConnectionFactory(https_config));
+        connector.setHost(conf.getMainProps().getProperty("host"));
+        connector.setPort(Integer.parseInt(conf.getMainProps().getProperty("port")));
+        s.setConnectors(new Connector[] {
+            connector
+        });
+
+        HandlerList hl = new HandlerList();
+        hl.setHandlers(new Handler[] {
+                generateStaticContext(), generateGigiContexts(conf.getMainProps()), generateAPIContext()
+        });
+        s.setHandler(hl);
+        s.start();
+        if (connector.getPort() <= 1024 && !System.getProperty("os.name").toLowerCase().contains("win")) {
+            SetUID uid = new SetUID();
+            if ( !uid.setUid(65536 - 2, 65536 - 2).getSuccess()) {
+                Log.getLogger(Launcher.class).warn("Couldn't set uid!");
+            }
+        }
+    }
+
+    private static SslConnectionFactory createConnectionFactory(GigiConfig conf) throws GeneralSecurityException, IOException {
+        final SslContextFactory sslContextFactory = generateSSLContextFactory(conf, "www");
+        final SslContextFactory secureContextFactory = generateSSLContextFactory(conf, "secure");
+        secureContextFactory.setWantClientAuth(true);
+        secureContextFactory.setNeedClientAuth(false);
+        final SslContextFactory staticContextFactory = generateSSLContextFactory(conf, "static");
+        final SslContextFactory apiContextFactory = generateSSLContextFactory(conf, "api");
+        try {
+            secureContextFactory.start();
+            staticContextFactory.start();
+            apiContextFactory.start();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()) {
+
+            @Override
+            public boolean shouldRestartSSL() {
+                return true;
+            }
+
+            @Override
+            public SSLEngine restartSSL(SSLSession sslSession) {
+                SSLEngine e2 = null;
+                if (sslSession instanceof ExtendedSSLSession) {
+                    ExtendedSSLSession es = (ExtendedSSLSession) sslSession;
+                    List<SNIServerName> names = es.getRequestedServerNames();
+                    for (SNIServerName sniServerName : names) {
+                        if (sniServerName instanceof SNIHostName) {
+                            SNIHostName host = (SNIHostName) sniServerName;
+                            String hostname = host.getAsciiName();
+                            if (hostname.equals(ServerConstants.getWwwHostName())) {
+                                e2 = sslContextFactory.newSSLEngine();
+                            } else if (hostname.equals(ServerConstants.getStaticHostName())) {
+                                e2 = staticContextFactory.newSSLEngine();
+                            } else if (hostname.equals(ServerConstants.getSecureHostName())) {
+                                e2 = secureContextFactory.newSSLEngine();
+                            } else if (hostname.equals(ServerConstants.getApiHostName())) {
+                                e2 = apiContextFactory.newSSLEngine();
+                            }
+                            break;
+                        }
+                    }
+                }
+                if (e2 == null) {
+                    e2 = sslContextFactory.newSSLEngine(sslSession.getPeerHost(), sslSession.getPeerPort());
+                }
+                e2.setUseClientMode(false);
+                return e2;
+            }
+        };
+    }
+
+    private static Handler generateGigiContexts(Properties conf) {
+        ServletHolder webAppServlet = new ServletHolder(new Gigi(conf));
+
+        ContextHandler ch = generateGigiServletContext(webAppServlet);
+        ch.setVirtualHosts(new String[] {
+            ServerConstants.getWwwHostName()
+        });
+        ContextHandler chSecure = generateGigiServletContext(webAppServlet);
+        chSecure.setVirtualHosts(new String[] {
+            ServerConstants.getSecureHostName()
+        });
+
+        HandlerList hl = new HandlerList();
+        hl.setHandlers(new Handler[] {
+                ch, chSecure
+        });
+        return hl;
+    }
+
+    private static ContextHandler generateGigiServletContext(ServletHolder webAppServlet) {
+        final ResourceHandler rh = new ResourceHandler();
+        rh.setResourceBase("static/www");
+
+        HandlerWrapper hw = new PolicyRedirector();
+        hw.setHandler(rh);
+
+        ServletContextHandler servlet = new ServletContextHandler(ServletContextHandler.SESSIONS);
+        servlet.setInitParameter(SessionManager.__SessionCookieProperty, "CACert-Session");
+        servlet.addServlet(webAppServlet, "/*");
+        ErrorPageErrorHandler epeh = new ErrorPageErrorHandler();
+        epeh.addErrorPage(404, "/error");
+        servlet.setErrorHandler(epeh);
+
+        HandlerList hl = new HandlerList();
+        hl.setHandlers(new Handler[] {
+                hw, servlet
+        });
+
+        ContextHandler ch = new ContextHandler();
+        ch.setHandler(hl);
+        return ch;
+    }
+
+    private static Handler generateStaticContext() {
+        final ResourceHandler rh = new ResourceHandler();
+        rh.setResourceBase("static/static");
+
+        ContextHandler ch = new ContextHandler();
+        ch.setHandler(rh);
+        ch.setVirtualHosts(new String[] {
+            ServerConstants.getStaticHostName()
+        });
+
+        return ch;
+    }
+
+    private static Handler generateAPIContext() {
+        ServletContextHandler sch = new ServletContextHandler();
+
+        sch.addVirtualHosts(new String[] {
+            ServerConstants.getApiHostName()
+        });
+        sch.addServlet(new ServletHolder(new GigiAPI()), "/*");
+        return sch;
+    }
+
+    private static SslContextFactory generateSSLContextFactory(GigiConfig conf, String alias) throws GeneralSecurityException, IOException {
+        SslContextFactory scf = new SslContextFactory() {
+
+            String[] ciphers = null;
+
+            @Override
+            public void customize(SSLEngine sslEngine) {
+                super.customize(sslEngine);
+
+                SSLParameters ssl = sslEngine.getSSLParameters();
+                ssl.setUseCipherSuitesOrder(true);
+                if (ciphers == null) {
+                    ciphers = CipherInfo.filter(sslEngine.getSupportedCipherSuites());
+                }
+
+                ssl.setCipherSuites(ciphers);
+                sslEngine.setSSLParameters(ssl);
+
+            }
+
+        };
+        scf.setRenegotiationAllowed(false);
+
+        scf.setProtocol("TLS");
+        scf.setTrustStore(conf.getTrustStore());
+        KeyStore privateStore = conf.getPrivateStore();
+        scf.setKeyStorePassword(conf.getPrivateStorePw());
+        scf.setKeyStore(privateStore);
+        scf.setCertAlias(alias);
+        return scf;
+    }
 }
index 865090f0071670d50dcfc20847c1c61b99924370..0c919dab4da4057a66c2437a6ad3763ece1ce2b0 100644 (file)
@@ -6,54 +6,58 @@ import java.util.Map;
 import org.cacert.gigi.output.Outputable;
 
 public class Name implements Outputable {
-       String fname;
-       String mname;
-       String lname;
-       String suffix;
-
-       public Name(String fname, String lname, String mname, String suffix) {
-               this.fname = fname;
-               this.lname = lname;
-               this.mname = mname;
-               this.suffix = suffix;
-       }
-
-       @Override
-       public void output(PrintWriter out, Language l, Map<String, Object> vars) {
-               out.println("<span class=\"accountdetail\">");
-               out.print("<span class=\"fname\">");
-               out.print(fname);
-               out.print("</span> ");
-               out.print("<span class=\"lname\">");
-               out.print(lname);
-               out.print("</span>");
-               out.println("</span>");
-       }
-
-       @Override
-       public boolean equals(Object obj) {
-               if (!(obj instanceof Name)) {
-                       return false;
-               }
-               Name n = (Name) obj;
-               if (!(n.fname.equals(fname) && n.lname.equals(lname))) {
-                       return false;
-               }
-               if (mname == null) {
-                       if (n.mname != null) {
-                               return false;
-                       }
-               } else if (!mname.equals(n.mname)) {
-                       return false;
-               }
-               if (suffix == null) {
-                       if (n.suffix != null) {
-                               return false;
-                       }
-               } else if (!suffix.equals(n.suffix)) {
-                       return false;
-               }
-               return true;
-
-       }
+
+    String fname;
+
+    String mname;
+
+    String lname;
+
+    String suffix;
+
+    public Name(String fname, String lname, String mname, String suffix) {
+        this.fname = fname;
+        this.lname = lname;
+        this.mname = mname;
+        this.suffix = suffix;
+    }
+
+    @Override
+    public void output(PrintWriter out, Language l, Map<String, Object> vars) {
+        out.println("<span class=\"accountdetail\">");
+        out.print("<span class=\"fname\">");
+        out.print(fname);
+        out.print("</span> ");
+        out.print("<span class=\"lname\">");
+        out.print(lname);
+        out.print("</span>");
+        out.println("</span>");
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if ( !(obj instanceof Name)) {
+            return false;
+        }
+        Name n = (Name) obj;
+        if ( !(n.fname.equals(fname) && n.lname.equals(lname))) {
+            return false;
+        }
+        if (mname == null) {
+            if (n.mname != null) {
+                return false;
+            }
+        } else if ( !mname.equals(n.mname)) {
+            return false;
+        }
+        if (suffix == null) {
+            if (n.suffix != null) {
+                return false;
+            }
+        } else if ( !suffix.equals(n.suffix)) {
+            return false;
+        }
+        return true;
+
+    }
 }
index d96ed732f58c5e0eefef858448447722d7edb4a9..c4a260e53e772ec27852afa4fe87e98e7a85dd03 100644 (file)
@@ -10,18 +10,18 @@ import org.eclipse.jetty.server.Request;
 import org.eclipse.jetty.server.handler.HandlerWrapper;
 
 public class PolicyRedirector extends HandlerWrapper {
-       @Override
-       public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
-               throws IOException, ServletException {
-               if (target.equals("/")) {
-                       return;
-               }
-               if (target.startsWith("/policy/") && target.endsWith(".php")) {
-                       target = target.replace(".php", ".html");
-                       response.sendRedirect(target);
-                       baseRequest.setHandled(true);
-                       return;
-               }
-               super.handle(target, baseRequest, request, response);
-       }
+
+    @Override
+    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
+        if (target.equals("/")) {
+            return;
+        }
+        if (target.startsWith("/policy/") && target.endsWith(".php")) {
+            target = target.replace(".php", ".html");
+            response.sendRedirect(target);
+            baseRequest.setHandled(true);
+            return;
+        }
+        super.handle(target, baseRequest, request, response);
+    }
 }
index 010df4a9773cd48ee705d79d4a50c0f6491c16f8..949d77a4bb49dc2fbe609718ddf97d3741d14260 100644 (file)
@@ -12,331 +12,322 @@ import org.cacert.gigi.util.PasswordStrengthChecker;
 
 public class User {
 
-       private int id;
-       Name name = new Name(null, null, null, null);
-
-       Date dob;
-       String email;
-
-       public User(int id) {
-               this.id = id;
-               try {
-                       PreparedStatement ps = DatabaseConnection.getInstance().prepare(
-                               "SELECT `fname`, `lname`,`mname`, `suffix`, `dob`, `email` FROM `users` WHERE id=?");
-                       ps.setInt(1, id);
-                       ResultSet rs = ps.executeQuery();
-                       if (rs.next()) {
-                               name = new Name(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4));
-                               dob = rs.getDate(5);
-                               email = rs.getString(6);
-                       }
-                       rs.close();
-               } catch (SQLException e) {
-                       e.printStackTrace();
-               }
-       }
-
-       public User() {
-       }
-
-       public int getId() {
-               return id;
-       }
-
-       public String getFname() {
-               return name.fname;
-       }
-
-       public String getLname() {
-               return name.lname;
-       }
-
-       public String getMname() {
-               return name.mname;
-       }
-
-       public Name getName() {
-               return name;
-       }
-
-       public void setMname(String mname) {
-               this.name.mname = mname;
-       }
-
-       public String getSuffix() {
-               return name.suffix;
-       }
-
-       public void setSuffix(String suffix) {
-               this.name.suffix = suffix;
-       }
-
-       public Date getDob() {
-               return dob;
-       }
-
-       public void setDob(Date dob) {
-               this.dob = dob;
-       }
-
-       public String getEmail() {
-               return email;
-       }
-
-       public void setEmail(String email) {
-               this.email = email;
-       }
-
-       public void setId(int id) {
-               this.id = id;
-       }
-
-       public void setFname(String fname) {
-               this.name.fname = fname;
-       }
-
-       public void setLname(String lname) {
-               this.name.lname = lname;
-       }
-
-       public void insert(String password) throws SQLException {
-               if (id != 0) {
-                       throw new Error("refusing to insert");
-               }
-               PreparedStatement query = DatabaseConnection.getInstance().prepare(
-                       "insert into `users` set `email`=?, `password`=?, " + "`fname`=?, `mname`=?, `lname`=?, "
-                               + "`suffix`=?, `dob`=?, `created`=NOW(), locked=0");
-               query.setString(1, email);
-               query.setString(2, PasswordHash.hash(password));
-               query.setString(3, name.fname);
-               query.setString(4, name.mname);
-               query.setString(5, name.lname);
-               query.setString(6, name.suffix);
-               query.setDate(7, new java.sql.Date(dob.getTime()));
-               query.execute();
-               id = DatabaseConnection.lastInsertId(query);
-       }
-
-       public void changePassword(String oldPass, String newPass) throws GigiApiException {
-               try {
-                       PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `password` FROM users WHERE id=?");
-                       ps.setInt(1, id);
-                       ResultSet rs = ps.executeQuery();
-                       if (!rs.next()) {
-                               throw new GigiApiException("User not found... very bad.");
-                       }
-                       if (!PasswordHash.verifyHash(oldPass, rs.getString(1))) {
-                               throw new GigiApiException("Old password does not match.");
-                       }
-                       rs.close();
-                       PasswordStrengthChecker.assertStrongPassword(newPass, this);
-                       ps = DatabaseConnection.getInstance().prepare("UPDATE users SET `password`=? WHERE id=?");
-                       ps.setString(1, PasswordHash.hash(newPass));
-                       ps.setInt(2, id);
-                       if (ps.executeUpdate() != 1) {
-                               throw new GigiApiException("Password update failed.");
-                       }
-               } catch (SQLException e) {
-                       throw new GigiApiException(e);
-               }
-       }
-
-       public boolean canAssure() throws SQLException {
-               if (getAssurancePoints() < 100) {
-                       return false;
-               }
-
-               return hasPassedCATS();
-
-       }
-
-       public boolean hasPassedCATS() throws SQLException {
-               PreparedStatement query = DatabaseConnection.getInstance().prepare(
-                       "SELECT 1 FROM `cats_passed` where `user_id`=?");
-               query.setInt(1, id);
-               ResultSet rs = query.executeQuery();
-               if (rs.next()) {
-                       return true;
-               } else {
-                       return false;
-               }
-       }
-
-       public int getAssurancePoints() throws SQLException {
-               PreparedStatement query = DatabaseConnection.getInstance().prepare(
-                       "SELECT sum(points) FROM `notary` where `to`=? AND `deleted`=0");
-               query.setInt(1, id);
-               ResultSet rs = query.executeQuery();
-               int points = 0;
-               if (rs.next()) {
-                       points = rs.getInt(1);
-               }
-               rs.close();
-               return points;
-       }
-
-       public int getExperiencePoints() throws SQLException {
-               PreparedStatement query = DatabaseConnection.getInstance().prepare(
-                       "SELECT count(*) FROM `notary` where `from`=? AND `deleted`=0");
-               query.setInt(1, id);
-               ResultSet rs = query.executeQuery();
-               int points = 0;
-               if (rs.next()) {
-                       points = rs.getInt(1) * 2;
-               }
-               rs.close();
-               return points;
-       }
-
-       @Override
-       public boolean equals(Object obj) {
-               if (!(obj instanceof User)) {
-                       return false;
-               }
-               User s = (User) obj;
-               return name.equals(s.name) && email.equals(s.email) && dob.toString().equals(s.dob.toString()); // This
-                                                                                                                                                                                                               // is
-                                                                                                                                                                                                               // due
-                                                                                                                                                                                                               // to
-                                                                                                                                                                                                               // day
-                                                                                                                                                                                                               // cutoff
-       }
-
-       /**
-        * Gets the maximum allowed points NOW. Note that an assurance needs to
-        * re-check PoJam as it has taken place in the past.
-        * 
-        * @return the maximal points
-        * @throws SQLException
-        */
-       public int getMaxAssurePoints() throws SQLException {
-               int exp = getExperiencePoints();
-               int points = 10;
-               Calendar c = Calendar.getInstance();
-               c.setTime(dob);
-               int year = c.get(Calendar.YEAR);
-               int month = c.get(Calendar.MONTH);
-               int day = c.get(Calendar.DAY_OF_MONTH);
-               c.set(year + 18, month, day);
-               if (System.currentTimeMillis() < c.getTime().getTime()) {
-                       return points; // not 18 Years old.
-               }
-
-               if (exp >= 10) {
-                       points += 5;
-               }
-               if (exp >= 20) {
-                       points += 5;
-               }
-               if (exp >= 30) {
-                       points += 5;
-               }
-               if (exp >= 40) {
-                       points += 5;
-               }
-               if (exp >= 50) {
-                       points += 5;
-               }
-               return points;
-       }
-
-       public static User getById(int id) {
-               return new User(id);
-       }
-
-       public EmailAddress[] getEmails() {
-               try {
-                       PreparedStatement ps = DatabaseConnection.getInstance().prepare(
-                               "SELECT id FROM email WHERE memid=? AND deleted=0");
-                       ps.setInt(1, id);
-                       ResultSet rs = ps.executeQuery();
-                       rs.last();
-                       int count = rs.getRow();
-                       EmailAddress[] data = new EmailAddress[count];
-                       rs.beforeFirst();
-                       for (int i = 0; i < data.length; i++) {
-                               if (!rs.next()) {
-                                       throw new Error("Internal sql api violation.");
-                               }
-                               data[i] = EmailAddress.getById(rs.getInt(1));
-                       }
-                       rs.close();
-                       return data;
-               } catch (SQLException e) {
-                       e.printStackTrace();
-               }
-
-               return null;
-       }
-
-       public Domain[] getDomains() {
-               try {
-                       PreparedStatement ps = DatabaseConnection.getInstance().prepare(
-                               "SELECT id FROM domain WHERE memid=? AND deleted IS NULL");
-                       ps.setInt(1, id);
-                       ResultSet rs = ps.executeQuery();
-                       rs.last();
-                       int count = rs.getRow();
-                       Domain[] data = new Domain[count];
-                       rs.beforeFirst();
-                       for (int i = 0; i < data.length; i++) {
-                               if (!rs.next()) {
-                                       throw new Error("Internal sql api violation.");
-                               }
-                               data[i] = Domain.getById(rs.getInt(1));
-                       }
-                       rs.close();
-                       return data;
-               } catch (SQLException e) {
-                       e.printStackTrace();
-               }
-
-               return null;
-       }
-
-       public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
-               try {
-                       EmailAddress[] adrs = getEmails();
-                       for (int i = 0; i < adrs.length; i++) {
-                               if (adrs[i].getAddress().equals(newMail.getAddress())) {
-                                       if (!adrs[i].isVerified()) {
-                                               throw new GigiApiException("Email not verified.");
-                                       }
-                                       PreparedStatement ps = DatabaseConnection.getInstance().prepare(
-                                               "UPDATE users SET email=? WHERE id=?");
-                                       ps.setString(1, newMail.getAddress());
-                                       ps.setInt(2, getId());
-                                       ps.execute();
-                                       email = newMail.getAddress();
-                                       return;
-                               }
-                       }
-                       throw new GigiApiException("Given address not an address of the user.");
-               } catch (SQLException e) {
-                       throw new GigiApiException(e);
-               }
-       }
-
-       public void deleteEmail(EmailAddress mail) throws GigiApiException {
-               if (getEmail().equals(mail.getAddress())) {
-                       throw new GigiApiException("Can't delete user's default e-mail.");
-               }
-               EmailAddress[] emails = getEmails();
-               for (int i = 0; i < emails.length; i++) {
-                       if (emails[i].getId() == mail.getId()) {
-                               try {
-                                       PreparedStatement ps = DatabaseConnection.getInstance().prepare(
-                                               "UPDATE email SET deleted=? WHERE id=?");
-                                       ps.setDate(1, new Date(System.currentTimeMillis()));
-                                       ps.setInt(2, mail.getId());
-                                       ps.execute();
-                               } catch (SQLException e) {
-                                       e.printStackTrace();
-                                       throw new GigiApiException(e);
-                               }
-                               return;
-                       }
-               }
-               throw new GigiApiException("Email not one user's mail addresses.");
-       }
+    private int id;
+
+    Name name = new Name(null, null, null, null);
+
+    Date dob;
+
+    String email;
+
+    public User(int id) {
+        this.id = id;
+        try {
+            PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `fname`, `lname`,`mname`, `suffix`, `dob`, `email` FROM `users` WHERE id=?");
+            ps.setInt(1, id);
+            ResultSet rs = ps.executeQuery();
+            if (rs.next()) {
+                name = new Name(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4));
+                dob = rs.getDate(5);
+                email = rs.getString(6);
+            }
+            rs.close();
+        } catch (SQLException e) {
+            e.printStackTrace();
+        }
+    }
+
+    public User() {}
+
+    public int getId() {
+        return id;
+    }
+
+    public String getFname() {
+        return name.fname;
+    }
+
+    public String getLname() {
+        return name.lname;
+    }
+
+    public String getMname() {
+        return name.mname;
+    }
+
+    public Name getName() {
+        return name;
+    }
+
+    public void setMname(String mname) {
+        this.name.mname = mname;
+    }
+
+    public String getSuffix() {
+        return name.suffix;
+    }
+
+    public void setSuffix(String suffix) {
+        this.name.suffix = suffix;
+    }
+
+    public Date getDob() {
+        return dob;
+    }
+
+    public void setDob(Date dob) {
+        this.dob = dob;
+    }
+
+    public String getEmail() {
+        return email;
+    }
+
+    public void setEmail(String email) {
+        this.email = email;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public void setFname(String fname) {
+        this.name.fname = fname;
+    }
+
+    public void setLname(String lname) {
+        this.name.lname = lname;
+    }
+
+    public void insert(String password) throws SQLException {
+        if (id != 0) {
+            throw new Error("refusing to insert");
+        }
+        PreparedStatement query = DatabaseConnection.getInstance().prepare("insert into `users` set `email`=?, `password`=?, " + "`fname`=?, `mname`=?, `lname`=?, " + "`suffix`=?, `dob`=?, `created`=NOW(), locked=0");
+        query.setString(1, email);
+        query.setString(2, PasswordHash.hash(password));
+        query.setString(3, name.fname);
+        query.setString(4, name.mname);
+        query.setString(5, name.lname);
+        query.setString(6, name.suffix);
+        query.setDate(7, new java.sql.Date(dob.getTime()));
+        query.execute();
+        id = DatabaseConnection.lastInsertId(query);
+    }
+
+    public void changePassword(String oldPass, String newPass) throws GigiApiException {
+        try {
+            PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `password` FROM users WHERE id=?");
+            ps.setInt(1, id);
+            ResultSet rs = ps.executeQuery();
+            if ( !rs.next()) {
+                throw new GigiApiException("User not found... very bad.");
+            }
+            if ( !PasswordHash.verifyHash(oldPass, rs.getString(1))) {
+                throw new GigiApiException("Old password does not match.");
+            }
+            rs.close();
+            PasswordStrengthChecker.assertStrongPassword(newPass, this);
+            ps = DatabaseConnection.getInstance().prepare("UPDATE users SET `password`=? WHERE id=?");
+            ps.setString(1, PasswordHash.hash(newPass));
+            ps.setInt(2, id);
+            if (ps.executeUpdate() != 1) {
+                throw new GigiApiException("Password update failed.");
+            }
+        } catch (SQLException e) {
+            throw new GigiApiException(e);
+        }
+    }
+
+    public boolean canAssure() throws SQLException {
+        if (getAssurancePoints() < 100) {
+            return false;
+        }
+
+        return hasPassedCATS();
+
+    }
+
+    public boolean hasPassedCATS() throws SQLException {
+        PreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT 1 FROM `cats_passed` where `user_id`=?");
+        query.setInt(1, id);
+        ResultSet rs = query.executeQuery();
+        if (rs.next()) {
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    public int getAssurancePoints() throws SQLException {
+        PreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT sum(points) FROM `notary` where `to`=? AND `deleted`=0");
+        query.setInt(1, id);
+        ResultSet rs = query.executeQuery();
+        int points = 0;
+        if (rs.next()) {
+            points = rs.getInt(1);
+        }
+        rs.close();
+        return points;
+    }
+
+    public int getExperiencePoints() throws SQLException {
+        PreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT count(*) FROM `notary` where `from`=? AND `deleted`=0");
+        query.setInt(1, id);
+        ResultSet rs = query.executeQuery();
+        int points = 0;
+        if (rs.next()) {
+            points = rs.getInt(1) * 2;
+        }
+        rs.close();
+        return points;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if ( !(obj instanceof User)) {
+            return false;
+        }
+        User s = (User) obj;
+        return name.equals(s.name) && email.equals(s.email) && dob.toString().equals(s.dob.toString()); // This
+                                                                                                        // is
+                                                                                                        // due
+                                                                                                        // to
+                                                                                                        // day
+                                                                                                        // cutoff
+    }
+
+    /**
+     * Gets the maximum allowed points NOW. Note that an assurance needs to
+     * re-check PoJam as it has taken place in the past.
+     * 
+     * @return the maximal points
+     * @throws SQLException
+     */
+    public int getMaxAssurePoints() throws SQLException {
+        int exp = getExperiencePoints();
+        int points = 10;
+        Calendar c = Calendar.getInstance();
+        c.setTime(dob);
+        int year = c.get(Calendar.YEAR);
+        int month = c.get(Calendar.MONTH);
+        int day = c.get(Calendar.DAY_OF_MONTH);
+        c.set(year + 18, month, day);
+        if (System.currentTimeMillis() < c.getTime().getTime()) {
+            return points; // not 18 Years old.
+        }
+
+        if (exp >= 10) {
+            points += 5;
+        }
+        if (exp >= 20) {
+            points += 5;
+        }
+        if (exp >= 30) {
+            points += 5;
+        }
+        if (exp >= 40) {
+            points += 5;
+        }
+        if (exp >= 50) {
+            points += 5;
+        }
+        return points;
+    }
+
+    public static User getById(int id) {
+        return new User(id);
+    }
+
+    public EmailAddress[] getEmails() {
+        try {
+            PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM email WHERE memid=? AND deleted=0");
+            ps.setInt(1, id);
+            ResultSet rs = ps.executeQuery();
+            rs.last();
+            int count = rs.getRow();
+            EmailAddress[] data = new EmailAddress[count];
+            rs.beforeFirst();
+            for (int i = 0; i < data.length; i++) {
+                if ( !rs.next()) {
+                    throw new Error("Internal sql api violation.");
+                }
+                data[i] = EmailAddress.getById(rs.getInt(1));
+            }
+            rs.close();
+            return data;
+        } catch (SQLException e) {
+            e.printStackTrace();
+        }
+
+        return null;
+    }
+
+    public Domain[] getDomains() {
+        try {
+            PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM domain WHERE memid=? AND deleted IS NULL");
+            ps.setInt(1, id);
+            ResultSet rs = ps.executeQuery();
+            rs.last();
+            int count = rs.getRow();
+            Domain[] data = new Domain[count];
+            rs.beforeFirst();
+            for (int i = 0; i < data.length; i++) {
+                if ( !rs.next()) {
+                    throw new Error("Internal sql api violation.");
+                }
+                data[i] = Domain.getById(rs.getInt(1));
+            }
+            rs.close();
+            return data;
+        } catch (SQLException e) {
+            e.printStackTrace();
+        }
+
+        return null;
+    }
+
+    public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
+        try {
+            EmailAddress[] adrs = getEmails();
+            for (int i = 0; i < adrs.length; i++) {
+                if (adrs[i].getAddress().equals(newMail.getAddress())) {
+                    if ( !adrs[i].isVerified()) {
+                        throw new GigiApiException("Email not verified.");
+                    }
+                    PreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE users SET email=? WHERE id=?");
+                    ps.setString(1, newMail.getAddress());
+                    ps.setInt(2, getId());
+                    ps.execute();
+                    email = newMail.getAddress();
+                    return;
+                }
+            }
+            throw new GigiApiException("Given address not an address of the user.");
+        } catch (SQLException e) {
+            throw new GigiApiException(e);
+        }
+    }
+
+    public void deleteEmail(EmailAddress mail) throws GigiApiException {
+        if (getEmail().equals(mail.getAddress())) {
+            throw new GigiApiException("Can't delete user's default e-mail.");
+        }
+        EmailAddress[] emails = getEmails();
+        for (int i = 0; i < emails.length; i++) {
+            if (emails[i].getId() == mail.getId()) {
+                try {
+                    PreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE email SET deleted=? WHERE id=?");
+                    ps.setDate(1, new Date(System.currentTimeMillis()));
+                    ps.setInt(2, mail.getId());
+                    ps.execute();
+                } catch (SQLException e) {
+                    e.printStackTrace();
+                    throw new GigiApiException(e);
+                }
+                return;
+            }
+        }
+        throw new GigiApiException("Email not one user's mail addresses.");
+    }
 }
index 4104feb3f78a1940517763d72dbef8ca3c9ffee9..209ffe563932be8e87971ad2d0b7a33eeddd5971 100644 (file)
@@ -10,22 +10,23 @@ import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
 public class GigiAPI extends HttpServlet {
-       @Override
-       protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
-               String pi = req.getPathInfo();
-               if (pi == null) {
-                       return;
-               }
-               if (pi.equals("/security/csp/report")) {
-                       ServletInputStream sis = req.getInputStream();
-                       InputStreamReader isr = new InputStreamReader(sis, "UTF-8");
-                       StringBuffer strB = new StringBuffer();
-                       char[] buffer = new char[4 * 1024];
-                       int len;
-                       while ((len = isr.read(buffer)) > 0) {
-                               strB.append(buffer, 0, len);
-                       }
-                       System.out.println(strB);
-               }
-       }
+
+    @Override
+    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
+        String pi = req.getPathInfo();
+        if (pi == null) {
+            return;
+        }
+        if (pi.equals("/security/csp/report")) {
+            ServletInputStream sis = req.getInputStream();
+            InputStreamReader isr = new InputStreamReader(sis, "UTF-8");
+            StringBuffer strB = new StringBuffer();
+            char[] buffer = new char[4 * 1024];
+            int len;
+            while ((len = isr.read(buffer)) > 0) {
+                strB.append(buffer, 0, len);
+            }
+            System.out.println(strB);
+        }
+    }
 }
index b52b63debeef44748860b861fb63a4f558a01ad4..389a82cfe84bb43fbe1b0a1b8ac39448389778e0 100644 (file)
@@ -10,110 +10,115 @@ import java.util.Properties;
 import java.sql.Statement;
 
 public class DatabaseConnection {
-       public static final int CONNECTION_TIMEOUT = 24 * 60 * 60;
-       Connection c;
-       HashMap<String, PreparedStatement> statements = new HashMap<String, PreparedStatement>();
-       private static Properties credentials;
-       Statement adHoc;
-
-       public DatabaseConnection() {
-               try {
-                       Class.forName(credentials.getProperty("sql.driver"));
-               } catch (ClassNotFoundException e) {
-                       e.printStackTrace();
-               }
-               tryConnect();
-
-       }
-
-       private void tryConnect() {
-               try {
-                       c = DriverManager.getConnection(credentials.getProperty("sql.url") + "?zeroDateTimeBehavior=convertToNull",
-                               credentials.getProperty("sql.user"), credentials.getProperty("sql.password"));
-                       PreparedStatement ps = c.prepareStatement("SET SESSION wait_timeout=?;");
-                       ps.setInt(1, CONNECTION_TIMEOUT);
-                       ps.execute();
-                       ps.close();
-                       adHoc = c.createStatement();
-               } catch (SQLException e) {
-                       e.printStackTrace();
-               }
-       }
-
-       public PreparedStatement prepare(String query) throws SQLException {
-               ensureOpen();
-               PreparedStatement statement = statements.get(query);
-               if (statement == null) {
-                       statement = c.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
-                       statements.put(query, statement);
-               }
-               return statement;
-       }
-
-       long lastAction = System.currentTimeMillis();
-
-       private void ensureOpen() {
-               if (System.currentTimeMillis() - lastAction > CONNECTION_TIMEOUT * 1000L) {
-                       try {
-                               ResultSet rs = adHoc.executeQuery("SELECT 1");
-                               rs.close();
-                               lastAction = System.currentTimeMillis();
-                               return;
-                       } catch (SQLException e) {
-                       }
-                       statements.clear();
-                       tryConnect();
-               }
-               lastAction = System.currentTimeMillis();
-       }
-
-       public static int lastInsertId(PreparedStatement query) throws SQLException {
-               ResultSet rs = query.getGeneratedKeys();
-               rs.next();
-               int id = rs.getInt(1);
-               rs.close();
-               return id;
-       }
-
-       static ThreadLocal<DatabaseConnection> instances = new ThreadLocal<DatabaseConnection>() {
-               @Override
-               protected DatabaseConnection initialValue() {
-                       return new DatabaseConnection();
-               }
-       };
-
-       public static DatabaseConnection getInstance() {
-               return instances.get();
-       }
-
-       public static boolean isInited() {
-               return credentials != null;
-       }
-
-       public static void init(Properties conf) {
-               if (credentials != null) {
-                       throw new Error("Re-initiaizing is forbidden.");
-               }
-               credentials = conf;
-       }
-
-       public void beginTransaction() throws SQLException {
-               c.setAutoCommit(false);
-       }
-
-       public void commitTransaction() throws SQLException {
-               c.commit();
-               c.setAutoCommit(true);
-       }
-
-       public void quitTransaction() {
-               try {
-                       if (!c.getAutoCommit()) {
-                               c.rollback();
-                               c.setAutoCommit(true);
-                       }
-               } catch (SQLException e) {
-                       e.printStackTrace();
-               }
-       }
+
+    public static final int CONNECTION_TIMEOUT = 24 * 60 * 60;
+
+    Connection c;
+
+    HashMap<String, PreparedStatement> statements = new HashMap<String, PreparedStatement>();
+
+    private static Properties credentials;
+
+    Statement adHoc;
+
+    public DatabaseConnection() {
+        try {
+            Class.forName(credentials.getProperty("sql.driver"));
+        } catch (ClassNotFoundException e) {
+            e.printStackTrace();
+        }
+        tryConnect();
+
+    }
+
+    private void tryConnect() {
+        try {
+            c = DriverManager.getConnection(credentials.getProperty("sql.url") + "?zeroDateTimeBehavior=convertToNull", credentials.getProperty("sql.user"), credentials.getProperty("sql.password"));
+            PreparedStatement ps = c.prepareStatement("SET SESSION wait_timeout=?;");
+            ps.setInt(1, CONNECTION_TIMEOUT);
+            ps.execute();
+            ps.close();
+            adHoc = c.createStatement();
+        } catch (SQLException e) {
+            e.printStackTrace();
+        }
+    }
+
+    public PreparedStatement prepare(String query) throws SQLException {
+        ensureOpen();
+        PreparedStatement statement = statements.get(query);
+        if (statement == null) {
+            statement = c.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
+            statements.put(query, statement);
+        }
+        return statement;
+    }
+
+    long lastAction = System.currentTimeMillis();
+
+    private void ensureOpen() {
+        if (System.currentTimeMillis() - lastAction > CONNECTION_TIMEOUT * 1000L) {
+            try {
+                ResultSet rs = adHoc.executeQuery("SELECT 1");
+                rs.close();
+                lastAction = System.currentTimeMillis();
+                return;
+            } catch (SQLException e) {
+            }
+            statements.clear();
+            tryConnect();
+        }
+        lastAction = System.currentTimeMillis();
+    }
+
+    public static int lastInsertId(PreparedStatement query) throws SQLException {
+        ResultSet rs = query.getGeneratedKeys();
+        rs.next();
+        int id = rs.getInt(1);
+        rs.close();
+        return id;
+    }
+
+    static ThreadLocal<DatabaseConnection> instances = new ThreadLocal<DatabaseConnection>() {
+
+        @Override
+        protected DatabaseConnection initialValue() {
+            return new DatabaseConnection();
+        }
+    };
+
+    public static DatabaseConnection getInstance() {
+        return instances.get();
+    }
+
+    public static boolean isInited() {
+        return credentials != null;
+    }
+
+    public static void init(Properties conf) {
+        if (credentials != null) {
+            throw new Error("Re-initiaizing is forbidden.");
+        }
+        credentials = conf;
+    }
+
+    public void beginTransaction() throws SQLException {
+        c.setAutoCommit(false);
+    }
+
+    public void commitTransaction() throws SQLException {
+        c.commit();
+        c.setAutoCommit(true);
+    }
+
+    public void quitTransaction() {
+        try {
+            if ( !c.getAutoCommit()) {
+                c.rollback();
+                c.setAutoCommit(true);
+            }
+        } catch (SQLException e) {
+            e.printStackTrace();
+        }
+    }
 }
index a9149fab1ccadf8d17df7f8a6afca50cb4df3eaf..108dd646fc1ab376c50b1feda643a1416a25569c 100644 (file)
@@ -4,28 +4,27 @@ import java.io.IOException;
 import java.util.Properties;
 
 public class CommandlineEmailProvider extends EmailProvider {
-       public CommandlineEmailProvider(Properties p) {
-       }
 
-       @Override
-       public void sendmail(String to, String subject, String message, String from, String replyto, String toname,
-               String fromname, String errorsto, boolean extra) throws IOException {
-               synchronized (System.out) {
-                       System.out.println("== MAIL ==");
-                       System.out.println("To: " + to);
-                       System.out.println("Subject: " + subject);
-                       System.out.println("From: " + from);
-                       System.out.println("Errors-To: " + errorsto);
-                       System.out.println("Extra: " + extra);
-                       System.out.println(message);
-               }
+    public CommandlineEmailProvider(Properties p) {}
 
-       }
+    @Override
+    public void sendmail(String to, String subject, String message, String from, String replyto, String toname, String fromname, String errorsto, boolean extra) throws IOException {
+        synchronized (System.out) {
+            System.out.println("== MAIL ==");
+            System.out.println("To: " + to);
+            System.out.println("Subject: " + subject);
+            System.out.println("From: " + from);
+            System.out.println("Errors-To: " + errorsto);
+            System.out.println("Extra: " + extra);
+            System.out.println(message);
+        }
 
-       @Override
-       public String checkEmailServer(int forUid, String address) throws IOException {
-               System.out.println("checkMailBox: " + address);
-               return OK;
-       }
+    }
+
+    @Override
+    public String checkEmailServer(int forUid, String address) throws IOException {
+        System.out.println("checkMailBox: " + address);
+        return OK;
+    }
 
 }
index 6855f398d1332f73dccebb9bf70aeb2592751f7b..3ccac586e24a47ce7794e3d87169a261d781a964 100644 (file)
@@ -14,121 +14,120 @@ import java.util.regex.Pattern;
 import org.cacert.gigi.database.DatabaseConnection;
 
 public abstract class EmailProvider {
-       public abstract void sendmail(String to, String subject, String message, String from, String replyto,
-               String toname, String fromname, String errorsto, boolean extra) throws IOException;
-
-       private static EmailProvider instance;
-
-       public static EmailProvider getInstance() {
-               return instance;
-       }
-
-       protected static void setInstance(EmailProvider instance) {
-               EmailProvider.instance = instance;
-       }
-
-       public static void init(Properties conf) {
-               try {
-                       Class<?> c = Class.forName(conf.getProperty("emailProvider"));
-                       instance = (EmailProvider) c.getDeclaredConstructor(Properties.class).newInstance(conf);
-               } catch (ReflectiveOperationException e) {
-                       e.printStackTrace();
-               }
-       }
-
-       public static final String OK = "OK";
-       public static final String FAIL = "FAIL";
-       public static final Pattern MAIL = Pattern
-               .compile("^([a-zA-Z0-9])+([a-zA-Z0-9\\+\\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\\._-]+)+$");
-
-       public String checkEmailServer(int forUid, String address) throws IOException {
-               if (MAIL.matcher(address).matches()) {
-                       String[] parts = address.split("@", 2);
-                       String domain = parts[1];
-
-                       LinkedList<String> mxhosts = getMxHosts(domain);
-
-                       for (String host : mxhosts) {
-                               try (Socket s = new Socket(host, 25);
-                                       BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
-                                       PrintWriter pw = new PrintWriter(s.getOutputStream())) {
-                                       String line;
-                                       while ((line = br.readLine()) != null && line.startsWith("220-")) {
-                                       }
-                                       if (line == null || !line.startsWith("220")) {
-                                               continue;
-                                       }
-
-                                       pw.print("HELO www.cacert.org\r\n");
-                                       pw.flush();
-
-                                       while ((line = br.readLine()) != null && line.startsWith("220")) {
-                                       }
-
-                                       if (line == null || !line.startsWith("250")) {
-                                               continue;
-                                       }
-                                       pw.print("MAIL FROM: <returns@cacert.org>\r\n");
-                                       pw.flush();
-
-                                       line = br.readLine();
-
-                                       if (line == null || !line.startsWith("250")) {
-                                               continue;
-                                       }
-                                       pw.print("RCPT TO: <" + address + ">\r\n");
-                                       pw.flush();
-
-                                       line = br.readLine();
-                                       pw.print("QUIT\r\n");
-                                       pw.flush();
-
-                                       try {
-                                               PreparedStatement statmt = DatabaseConnection.getInstance().prepare(
-                                                       "insert into `pinglog` set `when`=NOW(), `email`=?, `result`=?, `uid`=?");
-                                               statmt.setString(1, address);
-                                               statmt.setString(2, line);
-                                               statmt.setInt(3, forUid);
-                                               statmt.execute();
-                                       } catch (SQLException e) {
-                                               e.printStackTrace();
-                                       }
-
-                                       if (line == null || !line.startsWith("250")) {
-                                               return line;
-                                       } else {
-                                               return OK;
-                                       }
-                               }
-
-                       }
-               }
-               try {
-                       PreparedStatement statmt = DatabaseConnection.getInstance().prepare(
-                               "insert into `pinglog` set `when`=NOW(), `email`=?, `result`=?, `uid`=?");
-                       statmt.setString(1, address);
-                       statmt.setString(2, "Failed to make a connection to the mail server");
-                       statmt.setInt(3, forUid);
-                       statmt.execute();
-               } catch (SQLException e) {
-                       e.printStackTrace();
-               }
-               return FAIL;
-       }
-
-       private static LinkedList<String> getMxHosts(String domain) throws IOException {
-               LinkedList<String> mxhosts = new LinkedList<String>();
-               Process dig = Runtime.getRuntime().exec(new String[] { "dig", "+short", "MX", domain });
-               try (BufferedReader br = new BufferedReader(new InputStreamReader(dig.getInputStream()))) {
-                       String line;
-                       while ((line = br.readLine()) != null) {
-                               String[] mxparts = line.split(" ", 2);
-                               if (mxparts.length != 2) {
-                                       continue;
-                               }
-                               mxhosts.add(mxparts[1].substring(0, mxparts[1].length() - 1));
-                       }
-               }
-               return mxhosts;
-       }
+
+    public abstract void sendmail(String to, String subject, String message, String from, String replyto, String toname, String fromname, String errorsto, boolean extra) throws IOException;
+
+    private static EmailProvider instance;
+
+    public static EmailProvider getInstance() {
+        return instance;
+    }
+
+    protected static void setInstance(EmailProvider instance) {
+        EmailProvider.instance = instance;
+    }
+
+    public static void init(Properties conf) {
+        try {
+            Class<?> c = Class.forName(conf.getProperty("emailProvider"));
+            instance = (EmailProvider) c.getDeclaredConstructor(Properties.class).newInstance(conf);
+        } catch (ReflectiveOperationException e) {
+            e.printStackTrace();
+        }
+    }
+
+    public static final String OK = "OK";
+
+    public static final String FAIL = "FAIL";
+
+    public static final Pattern MAIL = Pattern.compile("^([a-zA-Z0-9])+([a-zA-Z0-9\\+\\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\\._-]+)+$");
+
+    public String checkEmailServer(int forUid, String address) throws IOException {
+        if (MAIL.matcher(address).matches()) {
+            String[] parts = address.split("@", 2);
+            String domain = parts[1];
+
+            LinkedList<String> mxhosts = getMxHosts(domain);
+
+            for (String host : mxhosts) {
+                try (Socket s = new Socket(host, 25); BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); PrintWriter pw = new PrintWriter(s.getOutputStream())) {
+                    String line;
+                    while ((line = br.readLine()) != null && line.startsWith("220-")) {
+                    }
+                    if (line == null || !line.startsWith("220")) {
+                        continue;
+                    }
+
+                    pw.print("HELO www.cacert.org\r\n");
+                    pw.flush();
+
+                    while ((line = br.readLine()) != null && line.startsWith("220")) {
+                    }
+
+                    if (line == null || !line.startsWith("250")) {
+                        continue;
+                    }
+                    pw.print("MAIL FROM: <returns@cacert.org>\r\n");
+                    pw.flush();
+
+                    line = br.readLine();
+
+                    if (line == null || !line.startsWith("250")) {
+                        continue;
+                    }
+                    pw.print("RCPT TO: <" + address + ">\r\n");
+                    pw.flush();
+
+                    line = br.readLine();
+                    pw.print("QUIT\r\n");
+                    pw.flush();
+
+                    try {
+                        PreparedStatement statmt = DatabaseConnection.getInstance().prepare("insert into `pinglog` set `when`=NOW(), `email`=?, `result`=?, `uid`=?");
+                        statmt.setString(1, address);
+                        statmt.setString(2, line);
+                        statmt.setInt(3, forUid);
+                        statmt.execute();
+                    } catch (SQLException e) {
+                        e.printStackTrace();
+                    }
+
+                    if (line == null || !line.startsWith("250")) {
+                        return line;
+                    } else {
+                        return OK;
+                    }
+                }
+
+            }
+        }
+        try {
+            PreparedStatement statmt = DatabaseConnection.getInstance().prepare("insert into `pinglog` set `when`=NOW(), `email`=?, `result`=?, `uid`=?");
+            statmt.setString(1, address);
+            statmt.setString(2, "Failed to make a connection to the mail server");
+            statmt.setInt(3, forUid);
+            statmt.execute();
+        } catch (SQLException e) {
+            e.printStackTrace();
+        }
+        return FAIL;
+    }
+
+    private static LinkedList<String> getMxHosts(String domain) throws IOException {
+        LinkedList<String> mxhosts = new LinkedList<String>();
+        Process dig = Runtime.getRuntime().exec(new String[] {
+                "dig", "+short", "MX", domain
+        });
+        try (BufferedReader br = new BufferedReader(new InputStreamReader(dig.getInputStream()))) {
+            String line;
+            while ((line = br.readLine()) != null) {
+                String[] mxparts = line.split(" ", 2);
+                if (mxparts.length != 2) {
+                    continue;
+                }
+                mxhosts.add(mxparts[1].substring(0, mxparts[1].length() - 1));
+            }
+        }
+        return mxhosts;
+    }
 }
index f47d2bc3cbefdba25a40a95f20c5557f4b7e5c1e..67c0fb5b2eb00a6d802afe25989b2044ee2f0db2 100644 (file)
@@ -13,89 +13,87 @@ import java.util.Properties;
 import java.util.regex.Pattern;
 
 public class Sendmail extends EmailProvider {
-       protected Sendmail(Properties props) {
-       }
 
-       private static final Pattern NON_ASCII = Pattern.compile("[^a-zA-Z0-9 .-\\[\\]!_@]");
+    protected Sendmail(Properties props) {}
 
-       @Override
-       public void sendmail(String to, String subject, String message, String from, String replyto, String toname,
-               String fromname, String errorsto, boolean extra) throws IOException {
+    private static final Pattern NON_ASCII = Pattern.compile("[^a-zA-Z0-9 .-\\[\\]!_@]");
 
-               String[] bits = from.split(",");
+    @Override
+    public void sendmail(String to, String subject, String message, String from, String replyto, String toname, String fromname, String errorsto, boolean extra) throws IOException {
 
-               Socket smtp = new Socket("dogcraft.de", 25);
-               PrintWriter out = new PrintWriter(smtp.getOutputStream());
-               BufferedReader in = new BufferedReader(new InputStreamReader(smtp.getInputStream()));
-               readResponse(in);
-               out.print("HELO www.cacert.org\r\n");
-               out.flush();
-               readResponse(in);
-               out.print("MAIL FROM:<returns@cacert.org>\r\n");
-               out.flush();
-               readResponse(in);
-               bits = to.split(",");
-               for (String user : bits) {
-                       out.print("RCPT TO:<" + user.trim() + ">\r\n");
-                       out.flush();
-                       readResponse(in);
-               }
-               out.print("DATA\r\n");
-               out.flush();
-               readResponse(in);
-               out.print("X-Mailer: CAcert.org Website\r\n");
-               // if (array_key_exists("REMOTE_ADDR", $_SERVER)) {
-               // out.print("X-OriginatingIP: ".$_SERVER["REMOTE_ADDR"]."\r\n");
-               // }
-               // TODO
-               SimpleDateFormat emailDate = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss ZZZZ (z)", Locale.ENGLISH);
-               out.print("Date: " + emailDate.format(new Date(System.currentTimeMillis())) + "\r\n");
-               out.print("Sender: " + errorsto + "\r\n");
-               out.print("Errors-To: " + errorsto + "\r\n");
-               if (replyto != null) {
-                       out.print("Reply-To: " + replyto + "\r\n");
-               } else {
-                       out.print("Reply-To: " + from + "\r\n");
-               }
-               out.print("From: " + from + "\r\n");
-               out.print("To: " + to + "\r\n");
-               if (NON_ASCII.matcher(subject).matches()) {
+        String[] bits = from.split(",");
 
-                       out.print("Subject: =?utf-8?B?" + Base64.getEncoder().encodeToString(subject.getBytes()) + "?=\r\n");
-               } else {
-                       out.print("Subject: " + subject + "\r\n");
-               }
-               out.print("Mime-Version: 1.0\r\n");
-               if (!extra) {
-                       out.print("Content-Type: text/plain; charset=\"utf-8\"\r\n");
-                       out.print("Content-Transfer-Encoding: 8bit\r\n");
-               } else {
-                       out.print("Content-Type: text/plain; charset=\"iso-8859-1\"\r\n");
-                       out.print("Content-Transfer-Encoding: quoted-printable\r\n");
-                       out.print("Content-Disposition: inline\r\n");
-               }
-               // out.print("Content-Transfer-Encoding: BASE64\r\n");
-               out.print("\r\n");
-               // out.print(chunk_split(base64_encode(recode("html..utf-8",
-               // $message)))."\r\n.\r\n");
-               message = message + "\r\n";
+        Socket smtp = new Socket("dogcraft.de", 25);
+        PrintWriter out = new PrintWriter(smtp.getOutputStream());
+        BufferedReader in = new BufferedReader(new InputStreamReader(smtp.getInputStream()));
+        readResponse(in);
+        out.print("HELO www.cacert.org\r\n");
+        out.flush();
+        readResponse(in);
+        out.print("MAIL FROM:<returns@cacert.org>\r\n");
+        out.flush();
+        readResponse(in);
+        bits = to.split(",");
+        for (String user : bits) {
+            out.print("RCPT TO:<" + user.trim() + ">\r\n");
+            out.flush();
+            readResponse(in);
+        }
+        out.print("DATA\r\n");
+        out.flush();
+        readResponse(in);
+        out.print("X-Mailer: CAcert.org Website\r\n");
+        // if (array_key_exists("REMOTE_ADDR", $_SERVER)) {
+        // out.print("X-OriginatingIP: ".$_SERVER["REMOTE_ADDR"]."\r\n");
+        // }
+        // TODO
+        SimpleDateFormat emailDate = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss ZZZZ (z)", Locale.ENGLISH);
+        out.print("Date: " + emailDate.format(new Date(System.currentTimeMillis())) + "\r\n");
+        out.print("Sender: " + errorsto + "\r\n");
+        out.print("Errors-To: " + errorsto + "\r\n");
+        if (replyto != null) {
+            out.print("Reply-To: " + replyto + "\r\n");
+        } else {
+            out.print("Reply-To: " + from + "\r\n");
+        }
+        out.print("From: " + from + "\r\n");
+        out.print("To: " + to + "\r\n");
+        if (NON_ASCII.matcher(subject).matches()) {
 
-               String sendM = message.replace("\r", "").replace("\n.\n", "\n").replace("\n.\n", "\n").replace("\n", "\r\n")
-                       + ".\r\n";
-               out.print(sendM);
-               out.flush();
-               readResponse(in);
-               out.print("QUIT\n");
-               out.flush();
-               readResponse(in);
-               smtp.close();
-       }
+            out.print("Subject: =?utf-8?B?" + Base64.getEncoder().encodeToString(subject.getBytes()) + "?=\r\n");
+        } else {
+            out.print("Subject: " + subject + "\r\n");
+        }
+        out.print("Mime-Version: 1.0\r\n");
+        if ( !extra) {
+            out.print("Content-Type: text/plain; charset=\"utf-8\"\r\n");
+            out.print("Content-Transfer-Encoding: 8bit\r\n");
+        } else {
+            out.print("Content-Type: text/plain; charset=\"iso-8859-1\"\r\n");
+            out.print("Content-Transfer-Encoding: quoted-printable\r\n");
+            out.print("Content-Disposition: inline\r\n");
+        }
+        // out.print("Content-Transfer-Encoding: BASE64\r\n");
+        out.print("\r\n");
+        // out.print(chunk_split(base64_encode(recode("html..utf-8",
+        // $message)))."\r\n.\r\n");
+        message = message + "\r\n";
 
-       private static void readResponse(BufferedReader in) throws IOException {
-               String line;
-               while ((line = in.readLine()) != null && line.matches("\\d+-")) {
-               }
+        String sendM = message.replace("\r", "").replace("\n.\n", "\n").replace("\n.\n", "\n").replace("\n", "\r\n") + ".\r\n";
+        out.print(sendM);
+        out.flush();
+        readResponse(in);
+        out.print("QUIT\n");
+        out.flush();
+        readResponse(in);
+        smtp.close();
+    }
 
-       }
+    private static void readResponse(BufferedReader in) throws IOException {
+        String line;
+        while ((line = in.readLine()) != null && line.matches("\\d+-")) {
+        }
+
+    }
 
 }
index 35c4b3fe81351af1aaf6df7a44a983899a92ee30..caf29661e4df6565bd1e70d4c813bd95e77b3ee6 100644 (file)
@@ -9,75 +9,77 @@ import java.net.Socket;
 import java.util.Properties;
 
 class TestEmailProvider extends EmailProvider {
-       ServerSocket servs;
-       Socket client;
-       DataOutputStream out;
-       DataInputStream in;
 
-       protected TestEmailProvider(Properties props) {
-               try {
-                       servs = new ServerSocket(Integer.parseInt(props.getProperty("emailProvider.port")), 10,
-                               InetAddress.getByName("127.0.0.1"));
-               } catch (IOException e) {
-                       e.printStackTrace();
-               }
-       }
+    ServerSocket servs;
 
-       @Override
-       public synchronized void sendmail(String to, String subject, String message, String from, String replyto,
-               String toname, String fromname, String errorsto, boolean extra) throws IOException {
-               while (true) {
-                       assureLocalConnection();
-                       try {
-                               out.writeUTF("mail");
-                               write(to);
-                               write(subject);
-                               write(message);
-                               write(from);
-                               write(replyto);
-                               out.flush();
-                               return;
-                       } catch (IOException e) {
-                               client = null;
-                       }
-               }
-       }
+    Socket client;
 
-       private void assureLocalConnection() throws IOException {
-               if (out != null) {
-                       try {
-                               out.writeUTF("ping");
-                       } catch (IOException e) {
-                               client = null;
-                       }
-               }
-               if (client == null || client.isClosed()) {
-                       client = servs.accept();
-                       out = new DataOutputStream(client.getOutputStream());
-                       in = new DataInputStream(client.getInputStream());
-               }
-       }
+    DataOutputStream out;
 
-       @Override
-       public synchronized String checkEmailServer(int forUid, String address) throws IOException {
-               while (true) {
-                       assureLocalConnection();
-                       try {
-                               out.writeUTF("challengeAddrBox");
-                               out.writeUTF(address);
-                               return in.readUTF();
-                       } catch (IOException e) {
-                               client = null;
-                       }
-               }
-       }
+    DataInputStream in;
 
-       private void write(String to) throws IOException {
-               if (to == null) {
-                       out.writeUTF("<null>");
-               } else {
-                       out.writeUTF(to);
-               }
-       }
+    protected TestEmailProvider(Properties props) {
+        try {
+            servs = new ServerSocket(Integer.parseInt(props.getProperty("emailProvider.port")), 10, InetAddress.getByName("127.0.0.1"));
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
+
+    @Override
+    public synchronized void sendmail(String to, String subject, String message, String from, String replyto, String toname, String fromname, String errorsto, boolean extra) throws IOException {
+        while (true) {
+            assureLocalConnection();
+            try {
+                out.writeUTF("mail");
+                write(to);
+                write(subject);
+                write(message);
+                write(from);
+                write(replyto);
+                out.flush();
+                return;
+            } catch (IOException e) {
+                client = null;
+            }
+        }
+    }
+
+    private void assureLocalConnection() throws IOException {
+        if (out != null) {
+            try {
+                out.writeUTF("ping");
+            } catch (IOException e) {
+                client = null;
+            }
+        }
+        if (client == null || client.isClosed()) {
+            client = servs.accept();
+            out = new DataOutputStream(client.getOutputStream());
+            in = new DataInputStream(client.getInputStream());
+        }
+    }
+
+    @Override
+    public synchronized String checkEmailServer(int forUid, String address) throws IOException {
+        while (true) {
+            assureLocalConnection();
+            try {
+                out.writeUTF("challengeAddrBox");
+                out.writeUTF(address);
+                return in.readUTF();
+            } catch (IOException e) {
+                client = null;
+            }
+        }
+    }
+
+    private void write(String to) throws IOException {
+        if (to == null) {
+            out.writeUTF("<null>");
+        } else {
+            out.writeUTF(to);
+        }
+    }
 
 }
index e6b0f7cb95901d57dd3a88b18cfbf42b5d65285d..a4a5d8595eaf71f64ea6a31eed4ee5efb2fe929c 100644 (file)
@@ -6,31 +6,32 @@ import java.io.File;
  * Native to use privileged ports on unix-like hosts.
  * 
  * @author janis
- * 
  */
 public class SetUID {
-       static {
-               System.load(new File("natives/libsetuid.so").getAbsolutePath());
-       }
 
-       public native Status setUid(int uid, int gid);
+    static {
+        System.load(new File("natives/libsetuid.so").getAbsolutePath());
+    }
+
+    public native Status setUid(int uid, int gid);
+
+    public static class Status {
 
-       public static class Status {
+        private boolean success;
 
-               private boolean success;
-               private String message;
+        private String message;
 
-               public Status(boolean success, String message) {
-                       this.success = success;
-                       this.message = message;
-               }
+        public Status(boolean success, String message) {
+            this.success = success;
+            this.message = message;
+        }
 
-               public boolean getSuccess() {
-                       return success;
-               }
+        public boolean getSuccess() {
+            return success;
+        }
 
-               public String getMessage() {
-                       return message;
-               }
-       }
+        public String getMessage() {
+            return message;
+        }
+    }
 }
index 826fa1b56d35fd10f4034754c18439610a7a9079..1b478f0906115d1fd151cc6beb575d3cfb204702 100644 (file)
@@ -9,56 +9,58 @@ import org.cacert.gigi.Language;
 import org.cacert.gigi.pages.account.MailCertificates;
 
 public class CertificateTable implements Outputable {
-       String resultSet;
 
-       public CertificateTable(String resultSet) {
-               this.resultSet = resultSet;
-       }
+    String resultSet;
 
-       private static final String[] columnNames = new String[] { "Renew/Revoke/Delete", "Status", "Email Address",
-                       "SerialNumber", "Revoked", "Expires", "Login" };
+    public CertificateTable(String resultSet) {
+        this.resultSet = resultSet;
+    }
 
-       @Override
-       public void output(PrintWriter out, Language l, Map<String, Object> vars) {
-               ResultSet rs = (ResultSet) vars.get(resultSet);
-               try {
-                       out.println("<form method=\"post\">");
-                       out.println("<table class=\"wrapper dataTable\">");
-                       out.println("<thead><tr>");
-                       for (String column : columnNames) {
-                               out.print("<td>");
-                               out.print(l.getTranslation(column));
-                               out.println("</td>");
-                       }
-                       out.print("<td colspan=\"2\">");
-                       out.print(l.getTranslation("Comment *"));
-                       out.println("</td></tr></thead><tbody>");
+    private static final String[] columnNames = new String[] {
+            "Renew/Revoke/Delete", "Status", "Email Address", "SerialNumber", "Revoked", "Expires", "Login"
+    };
 
-                       rs.beforeFirst();
-                       while (rs.next()) {
-                               // out.println(rs.getString("id"));
-                               out.print("<tr><td>&nbsp;</td><td>State</td><td>");
-                               out.println(rs.getString("CN"));
-                               out.print("</td><td><a href='");
-                               out.print(MailCertificates.PATH);
-                               out.print("/");
-                               out.print(rs.getString("serial"));
-                               out.print("'>");
-                               out.println(rs.getString("serial"));
-                               out.print("</a></td><td>");
-                               if (rs.getString("revoked") == null) {
-                                       out.println("N/A");
-                               } else {
-                                       out.println(rs.getString("revoked"));
-                               }
-                               out.print("</td><td>");
-                               out.println(rs.getString("expire"));
-                               out.println("</td><td>a</td><td>a</td></tr>");
-                       }
-                       out.println("</tbody></table>");
-               } catch (SQLException e) {
-                       e.printStackTrace();
-               }
+    @Override
+    public void output(PrintWriter out, Language l, Map<String, Object> vars) {
+        ResultSet rs = (ResultSet) vars.get(resultSet);
+        try {
+            out.println("<form method=\"post\">");
+            out.println("<table class=\"wrapper dataTable\">");
+            out.println("<thead><tr>");
+            for (String column : columnNames) {
+                out.print("<td>");
+                out.print(l.getTranslation(column));
+                out.println("</td>");
+            }
+            out.print("<td colspan=\"2\">");
+            out.print(l.getTranslation("Comment *"));
+            out.println("</td></tr></thead><tbody>");
 
-       }
+            rs.beforeFirst();
+            while (rs.next()) {
+                // out.println(rs.getString("id"));
+                out.print("<tr><td>&nbsp;</td><td>State</td><td>");
+                out.println(rs.getString("CN"));
+                out.print("</td><td><a href='");
+                out.print(MailCertificates.PATH);
+                out.print("/");
+                out.print(rs.getString("serial"));
+                out.print("'>");
+                out.println(rs.getString("serial"));
+                out.print("</a></td><td>");
+                if (rs.getString("revoked") == null) {
+                    out.println("N/A");
+                } else {
+                    out.println(rs.getString("revoked"));
+                }
+                out.print("</td><td>");
+                out.println(rs.getString("expire"));
+                out.println("</td><td>a</td><td>a</td></tr>");
+            }
+            out.println("</tbody></table>");
+        } catch (SQLException e) {
+            e.printStackTrace();
+        }
+
+    }
 }
index 5b474a1eed98ff14ce4f3ba86178a09fb7a11946..4885440ccb5b29c3eb220f72e9712ba89015c2d0 100644 (file)
@@ -11,23 +11,25 @@ import org.cacert.gigi.pages.Page;
 import org.cacert.gigi.util.ServerConstants;
 
 public class ClientCSRGenerate {
-       static Template normal;
-       static Template IE;
-       static {
-               normal = new Template(ClientCSRGenerate.class.getResource("ClientCSRGenerate.templ"));
-               IE = new Template(ClientCSRGenerate.class.getResource("ClientCSRGenerateIE.templ"));
-       }
 
-       public static void output(HttpServletRequest req, HttpServletResponse resp) {
-               HashMap<String, Object> vars = new HashMap<String, Object>();
-               vars.put("minsize", "2048");
-               vars.put("normalhost", "https://" + ServerConstants.getWwwHostNamePort());
-               vars.put("securehost", "https://" + ServerConstants.getSecureHostNamePort());
-               vars.put("statichost", "https://" + ServerConstants.getStaticHostNamePort());
-               try {
-                       normal.output(resp.getWriter(), Page.getLanguage(req), vars);
-               } catch (IOException e) {
-                       e.printStackTrace();
-               }
-       }
+    static Template normal;
+
+    static Template IE;
+    static {
+        normal = new Template(ClientCSRGenerate.class.getResource("ClientCSRGenerate.templ"));
+        IE = new Template(ClientCSRGenerate.class.getResource("ClientCSRGenerateIE.templ"));
+    }
+
+    public static void output(HttpServletRequest req, HttpServletResponse resp) {
+        HashMap<String, Object> vars = new HashMap<String, Object>();
+        vars.put("minsize", "2048");
+        vars.put("normalhost", "https://" + ServerConstants.getWwwHostNamePort());
+        vars.put("securehost", "https://" + ServerConstants.getSecureHostNamePort());
+        vars.put("statichost", "https://" + ServerConstants.getStaticHostNamePort());
+        try {
+            normal.output(resp.getWriter(), Page.getLanguage(req), vars);
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
 }
index 4c162cfc7408f95c69d681be403bfcc86e51366e..45697fe0cd2be63ad081d2074cc4e83a652a2fff 100644 (file)
@@ -12,95 +12,99 @@ import javax.servlet.http.HttpServletRequest;
 import org.cacert.gigi.Language;
 
 public class DateSelector implements Outputable {
-       String[] names;
-
-       public DateSelector(String day, String month, String year) {
-               this.names = new String[] { day, month, year };
-       }
-
-       int day;
-       int month;
-       int year;
-
-       @Override
-       public void output(PrintWriter out, Language l, Map<String, Object> vars) {
-               out.print("<nobr><select name=\"");
-               out.print(names[0]);
-               out.println("\">");
-               for (int i = 1; i <= 31; i++) {
-                       out.print("<option");
-                       if (i == day) {
-                               out.print(" selected=\"selected\"");
-                       }
-                       out.println(">" + i + "</option>");
-               }
-               out.println("</select>");
-               SimpleDateFormat sdf = new SimpleDateFormat("MMMM", l.getLocale());
-               out.print("<select name=\"");
-               out.print(names[1]);
-               out.println("\">");
-               Calendar c = sdf.getCalendar();
-               for (int i = 1; i <= 12; i++) {
-                       c.set(Calendar.MONTH, i - 1);
-                       out.print("<option value='" + i + "'");
-                       if (i == month) {
-                               out.print(" selected=\"selected\"");
-                       }
-                       out.println(">" + sdf.format(c.getTime()) + " (" + i + ")</option>");
-               }
-               out.println("</select>");
-               out.print("<input type=\"text\" name=\"");
-               out.print(names[2]);
-               out.print("\" value=\"");
-               if (year != 0) {
-                       out.print(year);
-               }
-               out.print("\" size=\"4\" autocomplete=\"off\"></nobr>");
-       }
-
-       public void update(HttpServletRequest r) {
-               String dayS = r.getParameter(names[0]);
-               if (dayS != null) {
-                       day = parseIntSafe(dayS);
-               }
-
-               String monthS = r.getParameter(names[1]);
-               if (monthS != null) {
-                       month = parseIntSafe(monthS);
-               }
-
-               String yearS = r.getParameter(names[2]);
-               if (yearS != null) {
-                       year = parseIntSafe(yearS);
-               }
-       }
-
-       private int parseIntSafe(String dayS) {
-               try {
-                       return Integer.parseInt(dayS);
-               } catch (NumberFormatException e) {
-
-               }
-               return 0;
-       }
-
-       public boolean isValid() {
-               if (!(1900 < year && 1 <= month && month <= 12 && 1 <= day && day <= 32)) {
-                       return false;
-               }
-               return true; // TODO checkdate
-       }
-
-       @Override
-       public String toString() {
-               return "DateSelector [names=" + Arrays.toString(names) + ", day=" + day + ", month=" + month + ", year=" + year
-                       + "]";
-       }
-
-       public java.sql.Date getDate() {
-               Calendar gc = GregorianCalendar.getInstance();
-               gc.set(year, month - 1, day);
-               return new java.sql.Date(gc.getTime().getTime());
-       }
+
+    String[] names;
+
+    public DateSelector(String day, String month, String year) {
+        this.names = new String[] {
+                day, month, year
+        };
+    }
+
+    int day;
+
+    int month;
+
+    int year;
+
+    @Override
+    public void output(PrintWriter out, Language l, Map<String, Object> vars) {
+        out.print("<nobr><select name=\"");
+        out.print(names[0]);
+        out.println("\">");
+        for (int i = 1; i <= 31; i++) {
+            out.print("<option");
+            if (i == day) {
+                out.print(" selected=\"selected\"");
+            }
+            out.println(">" + i + "</option>");
+        }
+        out.println("</select>");
+        SimpleDateFormat sdf = new SimpleDateFormat("MMMM", l.getLocale());
+        out.print("<select name=\"");
+        out.print(names[1]);
+        out.println("\">");
+        Calendar c = sdf.getCalendar();
+        for (int i = 1; i <= 12; i++) {
+            c.set(Calendar.MONTH, i - 1);
+            out.print("<option value='" + i + "'");
+            if (i == month) {
+                out.print(" selected=\"selected\"");
+            }
+            out.println(">" + sdf.format(c.getTime()) + " (" + i + ")</option>");
+        }
+        out.println("</select>");
+        out.print("<input type=\"text\" name=\"");
+        out.print(names[2]);
+        out.print("\" value=\"");
+        if (year != 0) {
+            out.print(year);
+        }
+        out.print("\" size=\"4\" autocomplete=\"off\"></nobr>");
+    }
+
+    public void update(HttpServletRequest r) {
+        String dayS = r.getParameter(names[0]);
+        if (dayS != null) {
+            day = parseIntSafe(dayS);
+        }
+
+        String monthS = r.getParameter(names[1]);
+        if (monthS != null) {
+            month = parseIntSafe(monthS);
+        }
+
+        String yearS = r.getParameter(names[2]);
+        if (yearS != null) {
+            year = parseIntSafe(yearS);
+        }
+    }
+
+    private int parseIntSafe(String dayS) {
+        try {
+            return Integer.parseInt(dayS);
+        } catch (NumberFormatException e) {
+
+        }
+        return 0;
+    }
+
+    public boolean isValid() {
+        if ( !(1900 < year && 1 <= month && month <= 12 && 1 <= day && day <= 32)) {
+            return false;
+        }
+        return true; // TODO checkdate
+    }
+
+    @Override
+    public String toString() {
+        return "DateSelector [names=" + Arrays.toString(names) + ", day=" + day + ", month=" + month + ", year=" + year + "]";
+    }
+
+    public java.sql.Date getDate() {
+        Calendar gc = GregorianCalendar.getInstance();
+        gc.set(year, month - 1, day);
+        return new java.sql.Date(gc.getTime().getTime());
+    }
 
 }
index dd244d749afc36077bc49e55b5813268b17ddf4c..063eb124eeaf668ac710734e622ddc82ad525f32 100644 (file)
@@ -13,56 +13,58 @@ import org.cacert.gigi.pages.Page;
 import org.cacert.gigi.util.RandomToken;
 
 public abstract class Form implements Outputable {
-       public static final String CSRF_FIELD = "csrf";
-       String csrf;
-
-       public Form(HttpServletRequest hsr) {
-               csrf = RandomToken.generateToken(32);
-               HttpSession hs = hsr.getSession();
-               hs.setAttribute("form/" + getClass().getName() + "/" + csrf, this);
-
-       }
-
-       public abstract boolean submit(PrintWriter out, HttpServletRequest req);
-
-       @Override
-       public final void output(PrintWriter out, Language l, Map<String, Object> vars) {
-               out.println("<form method='POST' autocomplete='off'>");
-               outputContent(out, l, vars);
-               out.print("<input type='hidden' name='" + CSRF_FIELD + "' value='");
-               out.print(getCSRFToken());
-               out.println("'></form>");
-       }
-
-       protected abstract void outputContent(PrintWriter out, Language l, Map<String, Object> vars);
-
-       protected void outputError(PrintWriter out, ServletRequest req, String text) {
-               out.print("<div>");
-               out.print(Page.translate(req, text));
-               out.println("</div>");
-       }
-
-       protected String getCSRFToken() {
-               return csrf;
-       }
-
-       public static <T extends Form> T getForm(HttpServletRequest req, Class<T> target) throws CSRFException {
-               String csrf = req.getParameter(CSRF_FIELD);
-               if (csrf == null) {
-                       throw new CSRFException();
-               }
-               HttpSession hs = req.getSession();
-               if (hs == null) {
-                       throw new CSRFException();
-               }
-               Form f = (Form) hs.getAttribute("form/" + target.getName() + "/" + csrf);
-               if (f == null) {
-                       throw new CSRFException();
-               }
-               return (T) f;
-       }
-
-       public static class CSRFException extends IOException {
-
-       }
+
+    public static final String CSRF_FIELD = "csrf";
+
+    String csrf;
+
+    public Form(HttpServletRequest hsr) {
+        csrf = RandomToken.generateToken(32);
+        HttpSession hs = hsr.getSession();
+        hs.setAttribute("form/" + getClass().getName() + "/" + csrf, this);
+
+    }
+
+    public abstract boolean submit(PrintWriter out, HttpServletRequest req);
+
+    @Override
+    public final void output(PrintWriter out, Language l, Map<String, Object> vars) {
+        out.println("<form method='POST' autocomplete='off'>");
+        outputContent(out, l, vars);
+        out.print("<input type='hidden' name='" + CSRF_FIELD + "' value='");
+        out.print(getCSRFToken());
+        out.println("'></form>");
+    }
+
+    protected abstract void outputContent(PrintWriter out, Language l, Map<String, Object> vars);
+
+    protected void outputError(PrintWriter out, ServletRequest req, String text) {
+        out.print("<div>");
+        out.print(Page.translate(req, text));
+        out.println("</div>");
+    }
+
+    protected String getCSRFToken() {
+        return csrf;
+    }
+
+    public static <T extends Form> T getForm(HttpServletRequest req, Class<T> target) throws CSRFException {
+        String csrf = req.getParameter(CSRF_FIELD);
+        if (csrf == null) {
+            throw new CSRFException();
+        }
+        HttpSession hs = req.getSession();
+        if (hs == null) {
+            throw new CSRFException();
+        }
+        Form f = (Form) hs.getAttribute("form/" + target.getName() + "/" + csrf);
+        if (f == null) {
+            throw new CSRFException();
+        }
+        return (T) f;
+    }
+
+    public static class CSRFException extends IOException {
+
+    }
 }
index 09f4a21cfca394d64c0c36728c4e568acd1b2e9a..6e75eb900e97661d4901bd36498f5e57237805aa 100644 (file)
@@ -6,29 +6,32 @@ import java.util.Map;
 import org.cacert.gigi.Language;
 
 public class Menu implements Outputable {
-       String menuName;
-       String id;
-       private MenuItem[] content;
-
-       public Menu(String menuName, String id, MenuItem... content) {
-               this.menuName = menuName;
-               this.id = id;
-               this.content = content;
-       }
-
-       @Override
-       public void output(PrintWriter out, Language l, Map<String, Object> vars) {
-               out.println("<div>");
-               out.print("<h3>+ ");
-               out.print(l.getTranslation(menuName));
-               out.print("</h3>");
-               out.print("<ul class=\"menu\" id=\"");
-               out.print(id);
-               out.print("\">");
-               for (MenuItem mi : content) {
-                       mi.output(out, l, vars);
-               }
-
-               out.println("</ul></div>");
-       }
+
+    String menuName;
+
+    String id;
+
+    private MenuItem[] content;
+
+    public Menu(String menuName, String id, MenuItem... content) {
+        this.menuName = menuName;
+        this.id = id;
+        this.content = content;
+    }
+
+    @Override
+    public void output(PrintWriter out, Language l, Map<String, Object> vars) {
+        out.println("<div>");
+        out.print("<h3>+ ");
+        out.print(l.getTranslation(menuName));
+        out.print("</h3>");
+        out.print("<ul class=\"menu\" id=\"");
+        out.print(id);
+        out.print("\">");
+        for (MenuItem mi : content) {
+            mi.output(out, l, vars);
+        }
+
+        out.println("</ul></div>");
+    }
 }
index 66d629ff9f1a87b7fc9a5376c2ad59e5a16437c2..a0c1ed807d427ff8bd7e82d703fcc389dcf416d1 100644 (file)
@@ -6,21 +6,23 @@ import java.util.Map;
 import org.cacert.gigi.Language;
 
 public class MenuItem implements Outputable {
-       final String href;
-       final String name;
-
-       public MenuItem(String href, String name) {
-               this.href = href;
-               this.name = name;
-       }
-
-       @Override
-       public void output(PrintWriter out, Language l, Map<String, Object> vars) {
-               out.print("<li><a href=\"");
-               out.print(href);
-               out.print("\">");
-               out.print(l.getTranslation(name));
-               out.print("</a></li>");
-       }
+
+    final String href;
+
+    final String name;
+
+    public MenuItem(String href, String name) {
+        this.href = href;
+        this.name = name;
+    }
+
+    @Override
+    public void output(PrintWriter out, Language l, Map<String, Object> vars) {
+        out.print("<li><a href=\"");
+        out.print(href);
+        out.print("\">");
+        out.print(l.getTranslation(name));
+        out.print("</a></li>");
+    }
 
 }
index 4d5978e56bfc5f570f3bc3f12c234c6e110f6ac2..d228b33d42513a4997bd712e2e3f4f75f1a79ee2 100644 (file)
@@ -6,5 +6,6 @@ import java.util.Map;
 import org.cacert.gigi.Language;
 
 public interface Outputable {
-       public void output(PrintWriter out, Language l, Map<String, Object> vars);
+
+    public void output(PrintWriter out, Language l, Map<String, Object> vars);
 }
index cb74f84fc749d2cdc02bc07b34f9cc96ea23d99a..6cd1e0388809272a1808e43de2cc032aa4ad2ee8 100644 (file)
@@ -8,23 +8,25 @@ import org.cacert.gigi.Language;
 import org.cacert.gigi.output.Outputable;
 
 public final class ForeachStatement implements Outputable {
-       private final String variable;
-       private final TemplateBlock body;
 
-       public ForeachStatement(String variable, TemplateBlock body) {
-               this.variable = variable;
-               this.body = body;
-       }
+    private final String variable;
 
-       @Override
-       public void output(PrintWriter out, Language l, Map<String, Object> vars) {
-               Object o = vars.get(variable);
-               if (o instanceof IterableDataset) {
-                       IterableDataset id = (IterableDataset) o;
-                       Map<String, Object> subcontext = new HashMap<String, Object>(vars);
-                       while (id.next(l, subcontext)) {
-                               body.output(out, l, subcontext);
-                       }
-               }
-       }
-}
\ No newline at end of file
+    private final TemplateBlock body;
+
+    public ForeachStatement(String variable, TemplateBlock body) {
+        this.variable = variable;
+        this.body = body;
+    }
+
+    @Override
+    public void output(PrintWriter out, Language l, Map<String, Object> vars) {
+        Object o = vars.get(variable);
+        if (o instanceof IterableDataset) {
+            IterableDataset id = (IterableDataset) o;
+            Map<String, Object> subcontext = new HashMap<String, Object>(vars);
+            while (id.next(l, subcontext)) {
+                body.output(out, l, subcontext);
+            }
+        }
+    }
+}
index 453e0d05d41487d843006ab469945386cc1d1e23..24e71f7faf1e2ae133f5bf2e13ed87cc2ced2898 100644 (file)
@@ -7,24 +7,25 @@ import org.cacert.gigi.Language;
 
 public class HashAlgorithms implements IterableDataset {
 
-       int i = 0;
-       Digest selected;
+    int i = 0;
 
-       public HashAlgorithms(Digest selected) {
-               this.selected = selected;
-       }
+    Digest selected;
 
-       @Override
-       public boolean next(Language l, Map<String, Object> vars) {
-               Digest[] length = Digest.values();
-               if (i >= length.length) {
-                       return false;
-               }
-               Digest d = length[i++];
-               vars.put("algorithm", d.toString());
-               vars.put("name", d.toString());
-               vars.put("info", l.getTranslation(d.getExp()));
-               vars.put("checked", selected == d ? " checked='checked'" : "");
-               return true;
-       }
+    public HashAlgorithms(Digest selected) {
+        this.selected = selected;
+    }
+
+    @Override
+    public boolean next(Language l, Map<String, Object> vars) {
+        Digest[] length = Digest.values();
+        if (i >= length.length) {
+            return false;
+        }
+        Digest d = length[i++];
+        vars.put("algorithm", d.toString());
+        vars.put("name", d.toString());
+        vars.put("info", l.getTranslation(d.getExp()));
+        vars.put("checked", selected == d ? " checked='checked'" : "");
+        return true;
+    }
 }
index e33cd896546591def0fb346ad4c7e704b257688a..bed559ed41a2ad0144440155eac444d7225afba0 100644 (file)
@@ -7,19 +7,21 @@ import org.cacert.gigi.Language;
 import org.cacert.gigi.output.Outputable;
 
 public final class IfStatement implements Outputable {
-       private final String variable;
-       private final TemplateBlock body;
 
-       public IfStatement(String variable, TemplateBlock body) {
-               this.variable = variable;
-               this.body = body;
-       }
+    private final String variable;
 
-       @Override
-       public void output(PrintWriter out, Language l, Map<String, Object> vars) {
-               Object o = vars.get(variable);
-               if (!(o == Boolean.FALSE || o == null)) {
-                       body.output(out, l, vars);
-               }
-       }
-}
\ No newline at end of file
+    private final TemplateBlock body;
+
+    public IfStatement(String variable, TemplateBlock body) {
+        this.variable = variable;
+        this.body = body;
+    }
+
+    @Override
+    public void output(PrintWriter out, Language l, Map<String, Object> vars) {
+        Object o = vars.get(variable);
+        if ( !(o == Boolean.FALSE || o == null)) {
+            body.output(out, l, vars);
+        }
+    }
+}
index bd7b99b25b3d5cf9a975b7e92e924dfac18e11eb..3357be0916f67ef947333481d1cfec3b7971e0dc 100644 (file)
@@ -8,16 +8,17 @@ import org.cacert.gigi.Language;
  * Represents some kind of data, that may be iterated over in a template.
  */
 public interface IterableDataset {
-       /**
-        * Moves to the next Dataset.
-        * 
-        * @param l
-        *            the language for l10n-ed strings
-        * @param vars
-        *            the variables used in this template. They need to be updated
-        *            for each line.
-        * @return true, iff there was a data-line "installed". False of this set is
-        *         already empty.
-        */
-       public boolean next(Language l, Map<String, Object> vars);
+
+    /**
+     * Moves to the next Dataset.
+     * 
+     * @param l
+     *            the language for l10n-ed strings
+     * @param vars
+     *            the variables used in this template. They need to be updated
+     *            for each line.
+     * @return true, iff there was a data-line "installed". False of this set is
+     *         already empty.
+     */
+    public boolean next(Language l, Map<String, Object> vars);
 }
index b0f7849939ad8328e3303608a42a12881e3c4660..f3c424abaff826b3d6200be131accb6991a9ecea 100644 (file)
@@ -7,14 +7,15 @@ import org.cacert.gigi.Language;
 import org.cacert.gigi.output.Outputable;
 
 public final class OutputVariableCommand implements Outputable {
-       private final String raw;
 
-       public OutputVariableCommand(String raw) {
-               this.raw = raw;
-       }
+    private final String raw;
 
-       @Override
-       public void output(PrintWriter out, Language l, Map<String, Object> vars) {
-               Template.outputVar(out, l, vars, raw);
-       }
-}
\ No newline at end of file
+    public OutputVariableCommand(String raw) {
+        this.raw = raw;
+    }
+
+    @Override
+    public void output(PrintWriter out, Language l, Map<String, Object> vars) {
+        Template.outputVar(out, l, vars, raw);
+    }
+}
index 42ed9570d514fd3498c7ddd1504b50a3c4dce6e9..1a3c29084e5d95bf2384f9301575a3a07b5ae85a 100644 (file)
@@ -8,22 +8,24 @@ import org.cacert.gigi.Language;
 import org.cacert.gigi.output.Outputable;
 
 public final class SprintfCommand implements Outputable {
-       private final String text;
-       private final LinkedList<String> store;
 
-       public SprintfCommand(String text, LinkedList<String> store) {
-               this.text = text;
-               this.store = store;
-       }
+    private final String text;
 
-       @Override
-       public void output(PrintWriter out, Language l, Map<String, Object> vars) {
-               String[] parts = l.getTranslation(text).split("%s");
-               String[] myvars = store.toArray(new String[store.size()]);
-               out.print(parts[0]);
-               for (int j = 1; j < parts.length; j++) {
-                       Template.outputVar(out, l, vars, myvars[j - 1].substring(1));
-                       out.print(parts[j]);
-               }
-       }
-}
\ No newline at end of file
+    private final LinkedList<String> store;
+
+    public SprintfCommand(String text, LinkedList<String> store) {
+        this.text = text;
+        this.store = store;
+    }
+
+    @Override
+    public void output(PrintWriter out, Language l, Map<String, Object> vars) {
+        String[] parts = l.getTranslation(text).split("%s");
+        String[] myvars = store.toArray(new String[store.size()]);
+        out.print(parts[0]);
+        for (int j = 1; j < parts.length; j++) {
+            Template.outputVar(out, l, vars, myvars[j - 1].substring(1));
+            out.print(parts[j]);
+        }
+    }
+}
index b8dd7424c5248b9f1ca523988d488e9e9d8de637..2702f6c108fcb36b939ec9c77f3bcc4ec9bf61a4 100644 (file)
@@ -19,145 +19,147 @@ import org.cacert.gigi.Language;
 import org.cacert.gigi.output.Outputable;
 
 public class Template implements Outputable {
-       TemplateBlock data;
 
-       long lastLoaded;
-       File source;
+    TemplateBlock data;
 
-       private static final Pattern CONTROL_PATTERN = Pattern.compile(" ?([a-z]+)\\(\\$([^)]+)\\) ?\\{ ?");
+    long lastLoaded;
 
-       public Template(URL u) {
-               try {
-                       Reader r = new InputStreamReader(u.openStream(), "UTF-8");
-                       try {
-                               if (u.getProtocol().equals("file") && DevelLauncher.DEVEL) {
-                                       source = new File(u.toURI());
-                                       lastLoaded = source.lastModified() + 1000;
-                               }
-                       } catch (URISyntaxException e) {
-                               e.printStackTrace();
-                       }
-                       data = parse(r);
-                       r.close();
-               } catch (IOException e) {
-                       throw new Error(e);
-               }
-       }
+    File source;
 
-       public Template(Reader r) {
-               try {
-                       data = parse(r);
-                       r.close();
-               } catch (IOException e) {
-                       throw new Error(e);
-               }
-       }
+    private static final Pattern CONTROL_PATTERN = Pattern.compile(" ?([a-z]+)\\(\\$([^)]+)\\) ?\\{ ?");
 
-       private TemplateBlock parse(Reader r) throws IOException {
-               LinkedList<String> splitted = new LinkedList<String>();
-               LinkedList<Outputable> commands = new LinkedList<Outputable>();
-               StringBuffer buf = new StringBuffer();
-               outer: while (true) {
-                       while (!endsWith(buf, "<?")) {
-                               int ch = r.read();
-                               if (ch == -1) {
-                                       break outer;
-                               }
-                               buf.append((char) ch);
-                       }
-                       buf.delete(buf.length() - 2, buf.length());
-                       splitted.add(buf.toString());
-                       buf.delete(0, buf.length());
-                       while (!endsWith(buf, "?>")) {
-                               int ch = r.read();
-                               if (ch == -1) {
-                                       throw new EOFException();
-                               }
-                               buf.append((char) ch);
-                       }
-                       buf.delete(buf.length() - 2, buf.length());
-                       String com = buf.toString().replace("\n", "");
-                       buf.delete(0, buf.length());
-                       Matcher m = CONTROL_PATTERN.matcher(com);
-                       if (m.matches()) {
-                               String type = m.group(1);
-                               String variable = m.group(2);
-                               TemplateBlock body = parse(r);
-                               if (type.equals("if")) {
-                                       commands.add(new IfStatement(variable, body));
-                               } else if (type.equals("foreach")) {
-                                       commands.add(new ForeachStatement(variable, body));
-                               } else {
-                                       throw new IOException("Syntax error: unknown control structure: " + type);
-                               }
-                               continue;
-                       }
-                       if (com.matches(" ?\\} ?")) {
-                               break;
-                       }
-                       commands.add(parseCommand(com));
-               }
-               splitted.add(buf.toString());
-               String[] contents = splitted.toArray(new String[splitted.size()]);
-               Outputable[] vars = commands.toArray(new Outputable[commands.size()]);
-               return new TemplateBlock(contents, vars);
-       }
+    public Template(URL u) {
+        try {
+            Reader r = new InputStreamReader(u.openStream(), "UTF-8");
+            try {
+                if (u.getProtocol().equals("file") && DevelLauncher.DEVEL) {
+                    source = new File(u.toURI());
+                    lastLoaded = source.lastModified() + 1000;
+                }
+            } catch (URISyntaxException e) {
+                e.printStackTrace();
+            }
+            data = parse(r);
+            r.close();
+        } catch (IOException e) {
+            throw new Error(e);
+        }
+    }
 
-       private boolean endsWith(StringBuffer buf, String string) {
-               return buf.length() >= string.length()
-                       && buf.substring(buf.length() - string.length(), buf.length()).equals(string);
-       }
+    public Template(Reader r) {
+        try {
+            data = parse(r);
+            r.close();
+        } catch (IOException e) {
+            throw new Error(e);
+        }
+    }
 
-       private Outputable parseCommand(String s2) {
-               if (s2.startsWith("=_")) {
-                       final String raw = s2.substring(2);
-                       return new TranslateCommand(raw);
-               } else if (s2.startsWith("=$")) {
-                       final String raw = s2.substring(2);
-                       return new OutputVariableCommand(raw);
-               } else if (s2.startsWith("=s,")) {
-                       String command = s2.substring(3);
-                       final LinkedList<String> store = new LinkedList<String>();
-                       while (command.startsWith("$")) {
-                               int idx = command.indexOf(",");
-                               store.add(command.substring(0, idx));
-                               command = command.substring(idx + 1);
-                       }
-                       final String text = command;
-                       return new SprintfCommand(text, store);
-               } else {
-                       System.out.println("Unknown processing instruction: " + s2);
-               }
-               return null;
-       }
+    private TemplateBlock parse(Reader r) throws IOException {
+        LinkedList<String> splitted = new LinkedList<String>();
+        LinkedList<Outputable> commands = new LinkedList<Outputable>();
+        StringBuffer buf = new StringBuffer();
+        outer:
+        while (true) {
+            while ( !endsWith(buf, "<?")) {
+                int ch = r.read();
+                if (ch == -1) {
+                    break outer;
+                }
+                buf.append((char) ch);
+            }
+            buf.delete(buf.length() - 2, buf.length());
+            splitted.add(buf.toString());
+            buf.delete(0, buf.length());
+            while ( !endsWith(buf, "?>")) {
+                int ch = r.read();
+                if (ch == -1) {
+                    throw new EOFException();
+                }
+                buf.append((char) ch);
+            }
+            buf.delete(buf.length() - 2, buf.length());
+            String com = buf.toString().replace("\n", "");
+            buf.delete(0, buf.length());
+            Matcher m = CONTROL_PATTERN.matcher(com);
+            if (m.matches()) {
+                String type = m.group(1);
+                String variable = m.group(2);
+                TemplateBlock body = parse(r);
+                if (type.equals("if")) {
+                    commands.add(new IfStatement(variable, body));
+                } else if (type.equals("foreach")) {
+                    commands.add(new ForeachStatement(variable, body));
+                } else {
+                    throw new IOException("Syntax error: unknown control structure: " + type);
+                }
+                continue;
+            }
+            if (com.matches(" ?\\} ?")) {
+                break;
+            }
+            commands.add(parseCommand(com));
+        }
+        splitted.add(buf.toString());
+        String[] contents = splitted.toArray(new String[splitted.size()]);
+        Outputable[] vars = commands.toArray(new Outputable[commands.size()]);
+        return new TemplateBlock(contents, vars);
+    }
 
-       public void output(PrintWriter out, Language l, Map<String, Object> vars) {
-               if (source != null && DevelLauncher.DEVEL) {
-                       if (lastLoaded < source.lastModified()) {
-                               try {
-                                       System.out.println("Reloading template.... " + source);
-                                       InputStreamReader r = new InputStreamReader(new FileInputStream(source), "UTF-8");
-                                       data = parse(r);
-                                       r.close();
-                                       lastLoaded = source.lastModified() + 1000;
-                               } catch (IOException e) {
-                                       e.printStackTrace();
-                               }
-                       }
-               }
-               data.output(out, l, vars);
-       }
+    private boolean endsWith(StringBuffer buf, String string) {
+        return buf.length() >= string.length() && buf.substring(buf.length() - string.length(), buf.length()).equals(string);
+    }
 
-       protected static void outputVar(PrintWriter out, Language l, Map<String, Object> vars, String varname) {
-               Object s = vars.get(varname);
+    private Outputable parseCommand(String s2) {
+        if (s2.startsWith("=_")) {
+            final String raw = s2.substring(2);
+            return new TranslateCommand(raw);
+        } else if (s2.startsWith("=$")) {
+            final String raw = s2.substring(2);
+            return new OutputVariableCommand(raw);
+        } else if (s2.startsWith("=s,")) {
+            String command = s2.substring(3);
+            final LinkedList<String> store = new LinkedList<String>();
+            while (command.startsWith("$")) {
+                int idx = command.indexOf(",");
+                store.add(command.substring(0, idx));
+                command = command.substring(idx + 1);
+            }
+            final String text = command;
+            return new SprintfCommand(text, store);
+        } else {
+            System.out.println("Unknown processing instruction: " + s2);
+        }
+        return null;
+    }
 
-               if (s == null) {
-                       System.out.println("Empty variable: " + varname);
-               }
-               if (s instanceof Outputable) {
-                       ((Outputable) s).output(out, l, vars);
-               } else {
-                       out.print(s);
-               }
-       }
+    public void output(PrintWriter out, Language l, Map<String, Object> vars) {
+        if (source != null && DevelLauncher.DEVEL) {
+            if (lastLoaded < source.lastModified()) {
+                try {
+                    System.out.println("Reloading template.... " + source);
+                    InputStreamReader r = new InputStreamReader(new FileInputStream(source), "UTF-8");
+                    data = parse(r);
+                    r.close();
+                    lastLoaded = source.lastModified() + 1000;
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+            }
+        }
+        data.output(out, l, vars);
+    }
+
+    protected static void outputVar(PrintWriter out, Language l, Map<String, Object> vars, String varname) {
+        Object s = vars.get(varname);
+
+        if (s == null) {
+            System.out.println("Empty variable: " + varname);
+        }
+        if (s instanceof Outputable) {
+            ((Outputable) s).output(out, l, vars);
+        } else {
+            out.print(s);
+        }
+    }
 }
index 8f715773052a4d817446375ba137d14df592327d..2a7f452002e10daa41de4b14676b71b896931b98 100644 (file)
@@ -7,22 +7,24 @@ import org.cacert.gigi.Language;
 import org.cacert.gigi.output.Outputable;
 
 class TemplateBlock implements Outputable {
-       String[] contents;
-       Outputable[] vars;
-
-       public TemplateBlock(String[] contents, Outputable[] vars) {
-               this.contents = contents;
-               this.vars = vars;
-       }
-
-       @Override
-       public void output(PrintWriter out, Language l, Map<String, Object> vars) {
-               for (int i = 0; i < contents.length; i++) {
-                       out.print(contents[i]);
-                       if (i < this.vars.length) {
-                               this.vars[i].output(out, l, vars);
-                       }
-               }
-       }
-
-}
\ No newline at end of file
+
+    String[] contents;
+
+    Outputable[] vars;
+
+    public TemplateBlock(String[] contents, Outputable[] vars) {
+        this.contents = contents;
+        this.vars = vars;
+    }
+
+    @Override
+    public void output(PrintWriter out, Language l, Map<String, Object> vars) {
+        for (int i = 0; i < contents.length; i++) {
+            out.print(contents[i]);
+            if (i < this.vars.length) {
+                this.vars[i].output(out, l, vars);
+            }
+        }
+    }
+
+}
index 377c841bcd04615f1415a263acfdc280840fe81c..18bf44764a421b88d017151b4aa8afeb1449a249 100644 (file)
@@ -7,14 +7,15 @@ import org.cacert.gigi.Language;
 import org.cacert.gigi.output.Outputable;
 
 public final class TranslateCommand implements Outputable {
-       private final String raw;
 
-       public TranslateCommand(String raw) {
-               this.raw = raw;
-       }
+    private final String raw;
 
-       @Override
-       public void output(PrintWriter out, Language l, Map<String, Object> vars) {
-               out.print(l.getTranslation(raw));
-       }
-}
\ No newline at end of file
+    public TranslateCommand(String raw) {
+        this.raw = raw;
+    }
+
+    @Override
+    public void output(PrintWriter out, Language l, Map<String, Object> vars) {
+        out.print(l.getTranslation(raw));
+    }
+}
index 7be7117735599bf26fb28706b0764600a4009078..19b8853d30162e807eb9b2348f0ea9dfe0fd4cf8 100644 (file)
@@ -18,95 +18,91 @@ import org.cacert.gigi.database.DatabaseConnection;
 import org.cacert.gigi.util.PasswordHash;
 
 public class LoginPage extends Page {
-       public static final String LOGIN_RETURNPATH = "login-returnpath";
 
-       public LoginPage(String title) {
-               super(title);
-       }
+    public static final String LOGIN_RETURNPATH = "login-returnpath";
 
-       @Override
-       public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
-               resp.getWriter().println(
-                       "<form method='POST' action='/login'>" + "<input type='text' name='username'>"
-                               + "<input type='password' name='password'> <input type='submit' value='login'></form>");
-       }
+    public LoginPage(String title) {
+        super(title);
+    }
 
-       @Override
-       public boolean beforeTemplate(HttpServletRequest req, HttpServletResponse resp) throws IOException {
-               String redir = (String) req.getSession().getAttribute(LOGIN_RETURNPATH);
-               if (req.getSession().getAttribute("loggedin") == null) {
-                       X509Certificate[] cert = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
-                       if (cert != null && cert[0] != null) {
-                               tryAuthWithCertificate(req, cert[0]);
-                       }
-                       if (req.getMethod().equals("POST")) {
-                               tryAuthWithUnpw(req);
-                       }
-               }
+    @Override
+    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+        resp.getWriter().println("<form method='POST' action='/login'>" + "<input type='text' name='username'>" + "<input type='password' name='password'> <input type='submit' value='login'></form>");
+    }
 
-               if (req.getSession().getAttribute("loggedin") != null) {
-                       String s = redir;
-                       if (s != null) {
-                               if (!s.startsWith("/")) {
-                                       s = "/" + s;
-                               }
-                               resp.sendRedirect(s);
-                       } else {
-                               resp.sendRedirect("/");
-                       }
-                       return true;
-               }
-               return false;
-       }
+    @Override
+    public boolean beforeTemplate(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+        String redir = (String) req.getSession().getAttribute(LOGIN_RETURNPATH);
+        if (req.getSession().getAttribute("loggedin") == null) {
+            X509Certificate[] cert = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
+            if (cert != null && cert[0] != null) {
+                tryAuthWithCertificate(req, cert[0]);
+            }
+            if (req.getMethod().equals("POST")) {
+                tryAuthWithUnpw(req);
+            }
+        }
 
-       @Override
-       public boolean needsLogin() {
-               return false;
-       }
+        if (req.getSession().getAttribute("loggedin") != null) {
+            String s = redir;
+            if (s != null) {
+                if ( !s.startsWith("/")) {
+                    s = "/" + s;
+                }
+                resp.sendRedirect(s);
+            } else {
+                resp.sendRedirect("/");
+            }
+            return true;
+        }
+        return false;
+    }
 
-       private void tryAuthWithUnpw(HttpServletRequest req) {
-               String un = req.getParameter("username");
-               String pw = req.getParameter("password");
-               try {
-                       PreparedStatement ps = DatabaseConnection.getInstance().prepare(
-                               "SELECT `password`, `id` FROM `users` WHERE `email`=? AND locked='0' AND verified='1'");
-                       ps.setString(1, un);
-                       ResultSet rs = ps.executeQuery();
-                       if (rs.next()) {
-                               if (PasswordHash.verifyHash(pw, rs.getString(1))) {
-                                       req.getSession().invalidate();
-                                       HttpSession hs = req.getSession();
-                                       hs.setAttribute(LOGGEDIN, true);
-                                       hs.setAttribute(USER, new User(rs.getInt(2)));
-                               }
-                       }
-                       rs.close();
-               } catch (SQLException e) {
-                       e.printStackTrace();
-               }
-       }
+    @Override
+    public boolean needsLogin() {
+        return false;
+    }
 
-       public static User getUser(HttpServletRequest req) {
-               return (User) req.getSession().getAttribute(USER);
-       }
+    private void tryAuthWithUnpw(HttpServletRequest req) {
+        String un = req.getParameter("username");
+        String pw = req.getParameter("password");
+        try {
+            PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `password`, `id` FROM `users` WHERE `email`=? AND locked='0' AND verified='1'");
+            ps.setString(1, un);
+            ResultSet rs = ps.executeQuery();
+            if (rs.next()) {
+                if (PasswordHash.verifyHash(pw, rs.getString(1))) {
+                    req.getSession().invalidate();
+                    HttpSession hs = req.getSession();
+                    hs.setAttribute(LOGGEDIN, true);
+                    hs.setAttribute(USER, new User(rs.getInt(2)));
+                }
+            }
+            rs.close();
+        } catch (SQLException e) {
+            e.printStackTrace();
+        }
+    }
 
-       private void tryAuthWithCertificate(HttpServletRequest req, X509Certificate x509Certificate) {
-               String serial = x509Certificate.getSerialNumber().toString(16).toUpperCase();
-               try {
-                       PreparedStatement ps = DatabaseConnection.getInstance().prepare(
-                               "SELECT `memid` FROM `emailcerts` WHERE `serial`=? AND `disablelogin`='0' AND `revoked` = "
-                                       + "'0000-00-00 00:00:00'");
-                       ps.setString(1, serial);
-                       ResultSet rs = ps.executeQuery();
-                       if (rs.next()) {
-                               req.getSession().invalidate();
-                               HttpSession hs = req.getSession();
-                               hs.setAttribute(LOGGEDIN, true);
-                               hs.setAttribute(USER, new User(rs.getInt(1)));
-                       }
-                       rs.close();
-               } catch (SQLException e) {
-                       e.printStackTrace();
-               }
-       }
+    public static User getUser(HttpServletRequest req) {
+        return (User) req.getSession().getAttribute(USER);
+    }
+
+    private void tryAuthWithCertificate(HttpServletRequest req, X509Certificate x509Certificate) {
+        String serial = x509Certificate.getSerialNumber().toString(16).toUpperCase();
+        try {
+            PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `memid` FROM `emailcerts` WHERE `serial`=? AND `disablelogin`='0' AND `revoked` = " + "'0000-00-00 00:00:00'");
+            ps.setString(1, serial);
+            ResultSet rs = ps.executeQuery();
+            if (rs.next()) {
+                req.getSession().invalidate();
+                HttpSession hs = req.getSession();
+                hs.setAttribute(LOGGEDIN, true);
+                hs.setAttribute(USER, new User(rs.getInt(1)));
+            }
+            rs.close();
+        } catch (SQLException e) {
+            e.printStackTrace();
+        }
+    }
 }
index 96b30aed29908ce09c01ba23f827b0ca8a167741..bb9c71c3164e9cb7bf67ccb51bf8f2c17578f594 100644 (file)
@@ -6,17 +6,18 @@ import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
 public class MainPage extends Page {
-       public MainPage(String title) {
-               super(title);
-       }
 
-       @Override
-       public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
-               resp.getWriter().println("Access granted.");
-       }
+    public MainPage(String title) {
+        super(title);
+    }
 
-       @Override
-       public boolean needsLogin() {
-               return false;
-       }
+    @Override
+    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+        resp.getWriter().println("Access granted.");
+    }
+
+    @Override
+    public boolean needsLogin() {
+        return false;
+    }
 }
index 9a5c178a8d0a576422305094b7fe4383b5361e09..320107f84868c408467ec72d0fefa519afdc6536 100644 (file)
@@ -15,97 +15,99 @@ import org.cacert.gigi.output.template.Template;
  * class with name &lt;className&gt;.templ will be loaded automatically.
  */
 public abstract class Page {
-       private String title;
-       private Template defaultTemplate;
-
-       public Page(String title) {
-               this.title = title;
-               URL resource = getClass().getResource(getClass().getSimpleName() + ".templ");
-               if (resource != null) {
-                       defaultTemplate = new Template(resource);
-               }
-       }
-
-       /**
-        * Retrieves the default template (&lt;className&gt;.templ) which has
-        * already been loaded.
-        * 
-        * @return the default template.
-        */
-       public Template getDefaultTemplate() {
-               return defaultTemplate;
-       }
-
-       /**
-        * This method can be overridden to execute code and do stuff before the
-        * default template is applied.
-        * 
-        * @param req
-        *            the request to handle.
-        * @param resp
-        *            the response to write to
-        * @return true, if the request is consumed and the default template should
-        *         not be applied.
-        * @throws IOException
-        *             if output goes wrong.
-        */
-       public boolean beforeTemplate(HttpServletRequest req, HttpServletResponse resp) throws IOException {
-               return false;
-       }
-
-       /**
-        * This method is called to generate the content inside the default
-        * template.
-        * 
-        * @param req
-        *            the request to handle.
-        * @param resp
-        *            the response to write to
-        * @throws IOException
-        *             if output goes wrong.
-        */
-       public abstract void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException;
-
-       /**
-        * Same as {@link #doGet(HttpServletRequest, HttpServletResponse)} but for
-        * POST requests. By default they are redirected to
-        * {@link #doGet(HttpServletRequest, HttpServletResponse)};
-        * 
-        * @param req
-        *            the request to handle.
-        * @param resp
-        *            the response to write to
-        * @throws IOException
-        *             if output goes wrong.
-        */
-       public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
-               doGet(req, resp);
-       }
-
-       /**
-        * Returns true, if this page requires login. Default is <code>true</code>
-        * 
-        * @return if the page needs login.
-        */
-       public boolean needsLogin() {
-               return true;
-       }
-
-       public String getTitle() {
-               return title;
-       }
-
-       public void setTitle(String title) {
-               this.title = title;
-       }
-
-       public static Language getLanguage(ServletRequest req) {
-               return Language.getInstance("de");
-       }
-
-       public static String translate(ServletRequest req, String string) {
-               Language l = getLanguage(req);
-               return l.getTranslation(string);
-       }
+
+    private String title;
+
+    private Template defaultTemplate;
+
+    public Page(String title) {
+        this.title = title;
+        URL resource = getClass().getResource(getClass().getSimpleName() + ".templ");
+        if (resource != null) {
+            defaultTemplate = new Template(resource);
+        }
+    }
+
+    /**
+     * Retrieves the default template (&lt;className&gt;.templ) which has
+     * already been loaded.
+     * 
+     * @return the default template.
+     */
+    public Template getDefaultTemplate() {
+        return defaultTemplate;
+    }
+
+    /**
+     * This method can be overridden to execute code and do stuff before the
+     * default template is applied.
+     * 
+     * @param req
+     *            the request to handle.
+     * @param resp
+     *            the response to write to
+     * @return true, if the request is consumed and the default template should
+     *         not be applied.
+     * @throws IOException
+     *             if output goes wrong.
+     */
+    public boolean beforeTemplate(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+        return false;
+    }
+
+    /**
+     * This method is called to generate the content inside the default
+     * template.
+     * 
+     * @param req
+     *            the request to handle.
+     * @param resp
+     *            the response to write to
+     * @throws IOException
+     *             if output goes wrong.
+     */
+    public abstract void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException;
+
+    /**
+     * Same as {@link #doGet(HttpServletRequest, HttpServletResponse)} but for
+     * POST requests. By default they are redirected to
+     * {@link #doGet(HttpServletRequest, HttpServletResponse)};
+     * 
+     * @param req
+     *            the request to handle.
+     * @param resp
+     *            the response to write to
+     * @throws IOException
+     *             if output goes wrong.
+     */
+    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+        doGet(req, resp);
+    }
+
+    /**
+     * Returns true, if this page requires login. Default is <code>true</code>
+     * 
+     * @return if the page needs login.
+     */
+    public boolean needsLogin() {
+        return true;
+    }
+
+    public String getTitle() {
+        return title;
+    }
+
+    public void setTitle(String title) {
+        this.title = title;
+    }
+
+    public static Language getLanguage(ServletRequest req) {
+        return Language.getInstance("de");
+    }
+
+    public static String translate(ServletRequest req, String string) {
+        Language l = getLanguage(req);
+        return l.getTranslation(string);
+    }
 
 }
index 02c8ada8444be8e8b2a06416c9e317af7ecc81fa..5f8d38ca80b55bcdfd34081fcd4f9781a5c03a70 100644 (file)
@@ -7,13 +7,13 @@ import javax.servlet.http.HttpServletResponse;
 
 public class TestSecure extends Page {
 
-       public TestSecure() {
-               super("Secure testpage");
-       }
+    public TestSecure() {
+        super("Secure testpage");
+    }
 
-       @Override
-       public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
-               resp.getWriter().println("This page is secure.");
-       }
+    @Override
+    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+        resp.getWriter().println("This page is secure.");
+    }
 
 }
index 5f8aa8f976a0f9e5bf06aeb303d72e6fb871c941..fff626282e029d5a7790daeb18e528404bf7aa5f 100644 (file)
@@ -9,34 +9,35 @@ import org.cacert.gigi.EmailAddress;
 import org.cacert.gigi.GigiApiException;
 
 public class Verify extends Page {
-       public static final String PATH = "/verify";
-
-       public Verify() {
-               super("Verify email");
-       }
-
-       @Override
-       public boolean needsLogin() {
-               return false;
-       }
-
-       @Override
-       public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
-               PrintWriter out = resp.getWriter();
-               String hash = req.getParameter("hash");
-               String type = req.getParameter("type");
-               String id = req.getParameter("id");
-               if ("email".equals(type)) {
-                       try {
-                               EmailAddress ea = EmailAddress.getById(Integer.parseInt(id));
-                               ea.verify(hash);
-                               out.println("Email verification completed.");
-                       } catch (IllegalArgumentException e) {
-                               out.println(translate(req, "The email address is invalid."));
-                       } catch (GigiApiException e) {
-                               e.format(out, getLanguage(req));
-                       }
-               }
-       }
+
+    public static final String PATH = "/verify";
+
+    public Verify() {
+        super("Verify email");
+    }
+
+    @Override
+    public boolean needsLogin() {
+        return false;
+    }
+
+    @Override
+    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+        PrintWriter out = resp.getWriter();
+        String hash = req.getParameter("hash");
+        String type = req.getParameter("type");
+        String id = req.getParameter("id");
+        if ("email".equals(type)) {
+            try {
+                EmailAddress ea = EmailAddress.getById(Integer.parseInt(id));
+                ea.verify(hash);
+                out.println("Email verification completed.");
+            } catch (IllegalArgumentException e) {
+                out.println(translate(req, "The email address is invalid."));
+            } catch (GigiApiException e) {
+                e.format(out, getLanguage(req));
+            }
+        }
+    }
 
 }
index 5458b63d9f5ef9d94a9db148cccee44634194410..c678cf1f14032cf5c5d6e52694bcb9278c440d7f 100644 (file)
@@ -13,47 +13,48 @@ import org.cacert.gigi.output.template.Template;
 import org.cacert.gigi.pages.Page;
 
 public class ChangeForm extends Form {
-       User target;
-
-       public ChangeForm(HttpServletRequest hsr, User target) {
-               super(hsr);
-               this.target = target;
-       }
-
-       private static Template t;
-       static {
-               t = new Template(ChangePasswordPage.class.getResource("ChangePasswordForm.templ"));
-       }
-
-       @Override
-       public void outputContent(PrintWriter out, Language l, Map<String, Object> vars) {
-               t.output(out, l, vars);
-       }
-
-       @Override
-       public boolean submit(PrintWriter out, HttpServletRequest req) {
-               String oldpassword = req.getParameter("oldpassword");
-               String p1 = req.getParameter("pword1");
-               String p2 = req.getParameter("pword2");
-               GigiApiException error = new GigiApiException();
-               if (oldpassword == null || p1 == null || p2 == null) {
-                       new GigiApiException("All fields are required.").format(out, Page.getLanguage(req));
-                       return false;
-               }
-               if (!p1.equals(p2)) {
-                       new GigiApiException("New passwords do not match.").format(out, Page.getLanguage(req));
-                       return false;
-               }
-               try {
-                       target.changePassword(oldpassword, p1);
-               } catch (GigiApiException e) {
-                       error.mergeInto(e);
-               }
-               if (!error.isEmpty()) {
-                       error.format(out, Page.getLanguage(req));
-                       return false;
-               }
-               return true;
-       }
+
+    User target;
+
+    public ChangeForm(HttpServletRequest hsr, User target) {
+        super(hsr);
+        this.target = target;
+    }
+
+    private static Template t;
+    static {
+        t = new Template(ChangePasswordPage.class.getResource("ChangePasswordForm.templ"));
+    }
+
+    @Override
+    public void outputContent(PrintWriter out, Language l, Map<String, Object> vars) {
+        t.output(out, l, vars);
+    }
+
+    @Override
+    public boolean submit(PrintWriter out, HttpServletRequest req) {
+        String oldpassword = req.getParameter("oldpassword");
+        String p1 = req.getParameter("pword1");
+        String p2 = req.getParameter("pword2");
+        GigiApiException error = new GigiApiException();
+        if (oldpassword == null || p1 == null || p2 == null) {
+            new GigiApiException("All fields are required.").format(out, Page.getLanguage(req));
+            return false;
+        }
+        if ( !p1.equals(p2)) {
+            new GigiApiException("New passwords do not match.").format(out, Page.getLanguage(req));
+            return false;
+        }
+        try {
+            target.changePassword(oldpassword, p1);
+        } catch (GigiApiException e) {
+            error.mergeInto(e);
+        }
+        if ( !error.isEmpty()) {
+            error.format(out, Page.getLanguage(req));
+            return false;
+        }
+        return true;
+    }
 
 }
index 75fd6bb27812e8eccc4c52244f09a09b471a7c53..805c72d923958c0297e28134640d4d5dd1942482 100644 (file)
@@ -11,22 +11,22 @@ import org.cacert.gigi.pages.LoginPage;
 import org.cacert.gigi.pages.Page;
 
 public class ChangePasswordPage extends Page {
-       public static final String PATH = "/account/password";
-
-       public ChangePasswordPage() {
-               super("Change Password");
-       }
-
-       @Override
-       public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
-               new ChangeForm(req, LoginPage.getUser(req)).output(resp.getWriter(), getLanguage(req),
-                       new HashMap<String, Object>());
-       }
-
-       @Override
-       public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
-               ChangeForm f = Form.getForm(req, ChangeForm.class);
-               f.submit(resp.getWriter(), req);
-       }
+
+    public static final String PATH = "/account/password";
+
+    public ChangePasswordPage() {
+        super("Change Password");
+    }
+
+    @Override
+    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+        new ChangeForm(req, LoginPage.getUser(req)).output(resp.getWriter(), getLanguage(req), new HashMap<String, Object>());
+    }
+
+    @Override
+    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+        ChangeForm f = Form.getForm(req, ChangeForm.class);
+        f.submit(resp.getWriter(), req);
+    }
 
 }
index da3a85b3a6f945abfa56acd02f0674fe74e4f178..e470f21b515e9e6aa708ec9827c6c27c7eea2ba8 100644 (file)
@@ -29,125 +29,128 @@ import org.cacert.gigi.pages.LoginPage;
 import sun.security.pkcs10.PKCS10;
 
 /**
- * This class represents a form that is used for issuing certificates.
- * 
- * This class uses "sun.security" and therefore needs "-XDignore.symbol.file"
- * 
+ * This class represents a form that is used for issuing certificates. This
+ * class uses "sun.security" and therefore needs "-XDignore.symbol.file"
  */
 public class IssueCertificateForm extends Form {
-       User u;
-       Digest selectedDigest = Digest.getDefault();
-       boolean login;
-       String csr;
-
-       private final static Template t = new Template(IssueCertificateForm.class.getResource("IssueCertificateForm.templ"));
-
-       public IssueCertificateForm(HttpServletRequest hsr) {
-               super(hsr);
-               u = LoginPage.getUser(hsr);
-       }
-
-       Certificate result;
-       private CSRType csrType;
-
-       public Certificate getResult() {
-               return result;
-       }
-
-       @Override
-       public boolean submit(PrintWriter out, HttpServletRequest req) {
-               String csr = req.getParameter("CSR");
-               String spkac = req.getParameter("SPKAC");
-               try {
-                       if (csr != null) {
-                               PKCS10 parsed = parseCSR(csr);
-                               out.println(parsed.getSubjectName().getCommonName());
-                               out.println(parsed.getSubjectName().getCountry());
-                               out.println("CSR DN: " + parsed.getSubjectName() + "<br/>");
-                               PublicKey pk = parsed.getSubjectPublicKeyInfo();
-                               out.println("Type: " + pk.getAlgorithm() + "<br/>");
-                               if (pk instanceof RSAPublicKey) {
-                                       out.println("Exponent: " + ((RSAPublicKey) pk).getPublicExponent() + "<br/>");
-                                       out.println("Length: " + ((RSAPublicKey) pk).getModulus().bitLength());
-                               } else if (pk instanceof DSAPublicKey) {
-                                       DSAPublicKey dpk = (DSAPublicKey) pk;
-                                       out.println("Length: " + dpk.getY().bitLength() + "<br/>");
-                                       out.println(dpk.getParams());
-                               } else if (pk instanceof ECPublicKey) {
-                                       ECPublicKey epk = (ECPublicKey) pk;
-                                       out.println("Length-x: " + epk.getW().getAffineX().bitLength() + "<br/>");
-                                       out.println("Length-y: " + epk.getW().getAffineY().bitLength() + "<br/>");
-                                       out.println(epk.getParams().getCurve());
-                               }
-                               out.println("<br/>digest: sha256<br/>");
-                               this.csr = csr;
-                               this.csrType = CSRType.CSR;
-                       } else if (spkac != null) {
-                               this.csr = "SPKAC=" + spkac.replaceAll("[\r\n]", "");
-                               this.csrType = CSRType.SPKAC;
-                       } else {
-                               login = "1".equals(req.getParameter("login"));
-                               String hashAlg = req.getParameter("hash_alg");
-                               if (hashAlg != null) {
-                                       selectedDigest = Digest.valueOf(hashAlg);
-                               }
-                               if (req.getParameter("CCA") == null) {
-                                       outputError(out, req, "You need to accept the CCA.");
-                                       return false;
-                               }
-                               System.out.println("issuing " + selectedDigest);
-                               result = new Certificate(LoginPage.getUser(req).getId(), "/commonName=CAcert WoT User",
-                                       selectedDigest.toString(), this.csr, this.csrType);
-                               try {
-                                       result.issue().waitFor(60000);
-                                       return true;
-                               } catch (SQLException e) {
-                                       e.printStackTrace();
-                               } catch (InterruptedException e) {
-                                       e.printStackTrace();
-                               }
-                               return false;
-                       }
-               } catch (IOException e) {
-                       e.printStackTrace();
-               } catch (GeneralSecurityException e) {
-                       e.printStackTrace();
-               }
-               return false;
-       }
-
-       private PKCS10 parseCSR(String csr) throws IOException, GeneralSecurityException {
-               csr = csr.replaceFirst("-----BEGIN (NEW )?CERTIFICATE REQUEST-----", "");
-               csr = csr.replaceFirst("-----END (NEW )?CERTIFICATE REQUEST-----", "");
-               csr = csr.replace("\r", "");
-               csr = csr.replace("\n", "");
-               byte[] b = Base64.getDecoder().decode(csr);
-               // Also checks signature validity
-               return new PKCS10(b);
-       }
-
-       @Override
-       protected void outputContent(PrintWriter out, Language l, Map<String, Object> vars) {
-               HashMap<String, Object> vars2 = new HashMap<String, Object>(vars);
-               vars2.put("CCA", "<a href='/policy/CAcertCommunityAgreement.html'>CCA</a>");
-
-               final EmailAddress[] ea = u.getEmails();
-               vars2.put("emails", new IterableDataset() {
-                       int count;
-
-                       @Override
-                       public boolean next(Language l, Map<String, Object> vars) {
-                               if (count >= ea.length) {
-                                       return false;
-                               }
-                               vars.put("id", ea[count].getId());
-                               vars.put("value", ea[count].getAddress());
-                               count++;
-                               return true;
-                       }
-               });
-               vars2.put("hashs", new HashAlgorithms(selectedDigest));
-               t.output(out, l, vars2);
-       }
+
+    User u;
+
+    Digest selectedDigest = Digest.getDefault();
+
+    boolean login;
+
+    String csr;
+
+    private final static Template t = new Template(IssueCertificateForm.class.getResource("IssueCertificateForm.templ"));
+
+    public IssueCertificateForm(HttpServletRequest hsr) {
+        super(hsr);
+        u = LoginPage.getUser(hsr);
+    }
+
+    Certificate result;
+
+    private CSRType csrType;
+
+    public Certificate getResult() {
+        return result;
+    }
+
+    @Override
+    public boolean submit(PrintWriter out, HttpServletRequest req) {
+        String csr = req.getParameter("CSR");
+        String spkac = req.getParameter("SPKAC");
+        try {
+            if (csr != null) {
+                PKCS10 parsed = parseCSR(csr);
+                out.println(parsed.getSubjectName().getCommonName());
+                out.println(parsed.getSubjectName().getCountry());
+                out.println("CSR DN: " + parsed.getSubjectName() + "<br/>");
+                PublicKey pk = parsed.getSubjectPublicKeyInfo();
+                out.println("Type: " + pk.getAlgorithm() + "<br/>");
+                if (pk instanceof RSAPublicKey) {
+                    out.println("Exponent: " + ((RSAPublicKey) pk).getPublicExponent() + "<br/>");
+                    out.println("Length: " + ((RSAPublicKey) pk).getModulus().bitLength());
+                } else if (pk instanceof DSAPublicKey) {
+                    DSAPublicKey dpk = (DSAPublicKey) pk;
+                    out.println("Length: " + dpk.getY().bitLength() + "<br/>");
+                    out.println(dpk.getParams());
+                } else if (pk instanceof ECPublicKey) {
+                    ECPublicKey epk = (ECPublicKey) pk;
+                    out.println("Length-x: " + epk.getW().getAffineX().bitLength() + "<br/>");
+                    out.println("Length-y: " + epk.getW().getAffineY().bitLength() + "<br/>");
+                    out.println(epk.getParams().getCurve());
+                }
+                out.println("<br/>digest: sha256<br/>");
+                this.csr = csr;
+                this.csrType = CSRType.CSR;
+            } else if (spkac != null) {
+                this.csr = "SPKAC=" + spkac.replaceAll("[\r\n]", "");
+                this.csrType = CSRType.SPKAC;
+            } else {
+                login = "1".equals(req.getParameter("login"));
+                String hashAlg = req.getParameter("hash_alg");
+                if (hashAlg != null) {
+                    selectedDigest = Digest.valueOf(hashAlg);
+                }
+                if (req.getParameter("CCA") == null) {
+                    outputError(out, req, "You need to accept the CCA.");
+                    return false;
+                }
+                System.out.println("issuing " + selectedDigest);
+                result = new Certificate(LoginPage.getUser(req).getId(), "/commonName=CAcert WoT User", selectedDigest.toString(), this.csr, this.csrType);
+                try {
+                    result.issue().waitFor(60000);
+                    return true;
+                } catch (SQLException e) {
+                    e.printStackTrace();
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                }
+                return false;
+            }
+        } catch (IOException e) {
+            e.printStackTrace();
+        } catch (GeneralSecurityException e) {
+            e.printStackTrace();
+        }
+        return false;
+    }
+
+    private PKCS10 parseCSR(String csr) throws IOException, GeneralSecurityException {
+        csr = csr.replaceFirst("-----BEGIN (NEW )?CERTIFICATE REQUEST-----", "");
+        csr = csr.replaceFirst("-----END (NEW )?CERTIFICATE REQUEST-----", "");
+        csr = csr.replace("\r", "");
+        csr = csr.replace("\n", "");
+        byte[] b = Base64.getDecoder().decode(csr);
+        // Also checks signature validity
+        return new PKCS10(b);
+    }
+
+    @Override
+    protected void outputContent(PrintWriter out, Language l, Map<String, Object> vars) {
+        HashMap<String, Object> vars2 = new HashMap<String, Object>(vars);
+        vars2.put("CCA", "<a href='/policy/CAcertCommunityAgreement.html'>CCA</a>");
+
+        final EmailAddress[] ea = u.getEmails();
+        vars2.put("emails", new IterableDataset() {
+
+            int count;
+
+            @Override
+            public boolean next(Language l, Map<String, Object> vars) {
+                if (count >= ea.length) {
+                    return false;
+                }
+                vars.put("id", ea[count].getId());
+                vars.put("value", ea[count].getAddress());
+                count++;
+                return true;
+            }
+        });
+        vars2.put("hashs", new HashAlgorithms(selectedDigest));
+        t.output(out, l, vars2);
+    }
 
 }
index 14f5ddba245cc6faa6eed06c86307dc716e17b1c..99af485d7802f1d0dfe20024833cca4d4036e146 100644 (file)
@@ -13,35 +13,38 @@ import org.cacert.gigi.output.template.Template;
 import org.cacert.gigi.pages.Page;
 
 public class MailAddForm extends Form {
-       private static Template t;
-       private String mail;
-       static {
-               t = new Template(ChangePasswordPage.class.getResource("MailAddForm.templ"));
-       }
-       User target;
-
-       public MailAddForm(HttpServletRequest hsr, User target) {
-               super(hsr);
-               this.target = target;
-       }
-
-       @Override
-       public boolean submit(PrintWriter out, HttpServletRequest req) {
-               String formMail = req.getParameter("newemail");
-               mail = formMail;
-               try {
-                       EmailAddress addr = new EmailAddress(mail, target);
-                       addr.insert(Page.getLanguage(req));
-               } catch (IllegalArgumentException e) {
-                       out.println("<div class='formError'>Error: Invalid address!</div>");
-                       return false;
-               }
-               return true;
-       }
-
-       @Override
-       protected void outputContent(PrintWriter out, Language l, Map<String, Object> vars) {
-               t.output(out, l, vars);
-       }
+
+    private static Template t;
+
+    private String mail;
+    static {
+        t = new Template(ChangePasswordPage.class.getResource("MailAddForm.templ"));
+    }
+
+    User target;
+
+    public MailAddForm(HttpServletRequest hsr, User target) {
+        super(hsr);
+        this.target = target;
+    }
+
+    @Override
+    public boolean submit(PrintWriter out, HttpServletRequest req) {
+        String formMail = req.getParameter("newemail");
+        mail = formMail;
+        try {
+            EmailAddress addr = new EmailAddress(mail, target);
+            addr.insert(Page.getLanguage(req));
+        } catch (IllegalArgumentException e) {
+            out.println("<div class='formError'>Error: Invalid address!</div>");
+            return false;
+        }
+        return true;
+    }
+
+    @Override
+    protected void outputContent(PrintWriter out, Language l, Map<String, Object> vars) {
+        t.output(out, l, vars);
+    }
 
 }
index c25db15f89cf18f426ed9703f682a2740d9b4d47..9541a5ad49c9d3db66c7082da217f75c83f1b0a2 100644 (file)
@@ -12,36 +12,38 @@ import org.cacert.gigi.output.template.Template;
 import org.cacert.gigi.pages.Page;
 
 public class MailCertificateAdd extends Page {
-       public static final String PATH = "/account/certs/email/new";
-       Template t = new Template(MailCertificateAdd.class.getResource("RequestCertificate.templ"));
-
-       public MailCertificateAdd() {
-               super("Create Email certificate");
-       }
-
-       @Override
-       public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
-               HashMap<String, Object> vars = new HashMap<String, Object>();
-               vars.put("CCA", "<a href='/policy/CAcertCommunityAgreement.html'>CCA</a>");
-
-               t.output(resp.getWriter(), getLanguage(req), vars);
-       }
-
-       @Override
-       public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
-               IssueCertificateForm f;
-               if (req.getParameter(Form.CSRF_FIELD) != null) {
-                       f = Form.getForm(req, IssueCertificateForm.class);
-                       if (f.submit(resp.getWriter(), req)) {
-                               Certificate c = f.getResult();
-                               String ser = c.getSerial();
-                               resp.sendRedirect(MailCertificates.PATH + "/" + ser);
-                       }
-               } else {
-                       f = new IssueCertificateForm(req);
-                       f.submit(resp.getWriter(), req);
-               }
-               f.output(resp.getWriter(), getLanguage(req), Collections.<String, Object> emptyMap());
-
-       }
+
+    public static final String PATH = "/account/certs/email/new";
+
+    Template t = new Template(MailCertificateAdd.class.getResource("RequestCertificate.templ"));
+
+    public MailCertificateAdd() {
+        super("Create Email certificate");
+    }
+
+    @Override
+    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+        HashMap<String, Object> vars = new HashMap<String, Object>();
+        vars.put("CCA", "<a href='/policy/CAcertCommunityAgreement.html'>CCA</a>");
+
+        t.output(resp.getWriter(), getLanguage(req), vars);
+    }
+
+    @Override
+    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+        IssueCertificateForm f;
+        if (req.getParameter(Form.CSRF_FIELD) != null) {
+            f = Form.getForm(req, IssueCertificateForm.class);
+            if (f.submit(resp.getWriter(), req)) {
+                Certificate c = f.getResult();
+                String ser = c.getSerial();
+                resp.sendRedirect(MailCertificates.PATH + "/" + ser);
+            }
+        } else {
+            f = new IssueCertificateForm(req);
+            f.submit(resp.getWriter(), req);
+        }
+        f.output(resp.getWriter(), getLanguage(req), Collections.<String,Object>emptyMap());
+
+    }
 }
index de8c1ca010c1cde5d5fd2b7727896b3823cf6a81..d65a3ef073e7c4864214744598a058a3cb68362c 100644 (file)
@@ -22,127 +22,128 @@ import org.cacert.gigi.pages.LoginPage;
 import org.cacert.gigi.pages.Page;
 
 public class MailCertificates extends Page {
-       CertificateTable myTable = new CertificateTable("mailcerts");
-       public static final String PATH = "/account/certs/email";
-
-       public MailCertificates() {
-               super("Email Certificates");
-       }
-
-       @Override
-       public boolean beforeTemplate(HttpServletRequest req, HttpServletResponse resp) throws IOException {
-
-               String pi = req.getPathInfo().substring(PATH.length());
-               if (pi.length() == 0) {
-                       return false;
-               }
-               pi = pi.substring(1);
-               boolean crt = false;
-               boolean cer = false;
-               resp.setContentType("application/pkix-cert");
-               if (pi.endsWith(".crt")) {
-                       crt = true;
-                       pi = pi.substring(0, pi.length() - 4);
-               } else if (pi.endsWith(".cer")) {
-                       if (req.getParameter("install") != null) {
-                               resp.setContentType("application/x-x509-user-cert");
-                       }
-                       cer = true;
-                       pi = pi.substring(0, pi.length() - 4);
-               } else if (pi.endsWith(".cer")) {
-                       cer = true;
-                       pi = pi.substring(0, pi.length() - 4);
-               }
-               String serial = pi;
-               try {
-                       Certificate c = Certificate.getBySerial(serial);
-                       if (c == null || LoginPage.getUser(req).getId() != c.getOwnerId()) {
-                               resp.sendError(404);
-                               return true;
-                       }
-                       X509Certificate cert = c.cert();
-                       if (!crt && !cer) {
-                               return false;
-                       }
-                       ServletOutputStream out = resp.getOutputStream();
-                       if (crt) {
-                               out.println("-----BEGIN CERTIFICATE-----");
-                               String block = Base64.getEncoder().encodeToString(cert.getEncoded()).replaceAll("(.{64})(?=.)", "$1\n");
-                               out.println(block);
-                               out.println("-----END CERTIFICATE-----");
-                       } else if (cer) {
-                               out.write(cert.getEncoded());
-                       }
-               } catch (IllegalArgumentException e) {
-                       resp.sendError(404);
-                       return true;
-               } catch (GeneralSecurityException e) {
-                       resp.sendError(404);
-                       return true;
-               } catch (SQLException e) {
-                       resp.sendError(404);
-                       return true;
-               }
-
-               return true;
-       }
-
-       @Override
-       public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
-               PrintWriter out = resp.getWriter();
-               String pi = req.getPathInfo().substring(PATH.length());
-               if (pi.length() != 0) {
-                       pi = pi.substring(1);
-
-                       String serial = pi;
-                       Certificate c = Certificate.getBySerial(serial);
-                       if (c == null || LoginPage.getUser(req).getId() != c.getOwnerId()) {
-                               resp.sendError(404);
-                               return;
-                       }
-                       out.print("<a href='");
-                       out.print(serial);
-                       out.print(".crt'>");
-                       out.print(translate(req, "PEM encoded Certificate"));
-                       out.println("</a><br/>");
-
-                       out.print("<a href='");
-                       out.print(serial);
-                       out.print(".cer'>");
-                       out.print(translate(req, "DER encoded Certificate"));
-                       out.println("</a><br/>");
-                       out.print("<a href='");
-                       out.print(serial);
-                       out.print(".cer?install'>");
-                       out.print(translate(req, "Install into browser."));
-                       out.println("</a><br/>");
-
-                       out.println("<pre>");
-                       try {
-                               X509Certificate cert = c.cert();
-                               out.print(cert);
-                       } catch (GeneralSecurityException e) {
-                               e.printStackTrace();
-                       } catch (SQLException e) {
-                               e.printStackTrace();
-                       }
-                       out.println("</pre>");
-                       return;
-               }
-
-               HashMap<String, Object> vars = new HashMap<String, Object>();
-               User us = LoginPage.getUser(req);
-               try {
-                       PreparedStatement ps = DatabaseConnection.getInstance().prepare(
-                               "SELECT `id`, `CN`, `serial`, `revoked`, `expire`, `disablelogin` FROM `emailcerts` WHERE `memid`=?");
-                       ps.setInt(1, us.getId());
-                       ResultSet rs = ps.executeQuery();
-                       vars.put("mailcerts", rs);
-                       myTable.output(out, getLanguage(req), vars);
-                       rs.close();
-               } catch (SQLException e) {
-                       e.printStackTrace();
-               }
-       }
+
+    CertificateTable myTable = new CertificateTable("mailcerts");
+
+    public static final String PATH = "/account/certs/email";
+
+    public MailCertificates() {
+        super("Email Certificates");
+    }
+
+    @Override
+    public boolean beforeTemplate(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+
+        String pi = req.getPathInfo().substring(PATH.length());
+        if (pi.length() == 0) {
+            return false;
+        }
+        pi = pi.substring(1);
+        boolean crt = false;
+        boolean cer = false;
+        resp.setContentType("application/pkix-cert");
+        if (pi.endsWith(".crt")) {
+            crt = true;
+            pi = pi.substring(0, pi.length() - 4);
+        } else if (pi.endsWith(".cer")) {
+            if (req.getParameter("install") != null) {
+                resp.setContentType("application/x-x509-user-cert");
+            }
+            cer = true;
+            pi = pi.substring(0, pi.length() - 4);
+        } else if (pi.endsWith(".cer")) {
+            cer = true;
+            pi = pi.substring(0, pi.length() - 4);
+        }
+        String serial = pi;
+        try {
+            Certificate c = Certificate.getBySerial(serial);
+            if (c == null || LoginPage.getUser(req).getId() != c.getOwnerId()) {
+                resp.sendError(404);
+                return true;
+            }
+            X509Certificate cert = c.cert();
+            if ( !crt && !cer) {
+                return false;
+            }
+            ServletOutputStream out = resp.getOutputStream();
+            if (crt) {
+                out.println("-----BEGIN CERTIFICATE-----");
+                String block = Base64.getEncoder().encodeToString(cert.getEncoded()).replaceAll("(.{64})(?=.)", "$1\n");
+                out.println(block);
+                out.println("-----END CERTIFICATE-----");
+            } else if (cer) {
+                out.write(cert.getEncoded());
+            }
+        } catch (IllegalArgumentException e) {
+            resp.sendError(404);
+            return true;
+        } catch (GeneralSecurityException e) {
+            resp.sendError(404);
+            return true;
+        } catch (SQLException e) {
+            resp.sendError(404);
+            return true;
+        }
+
+        return true;
+    }
+
+    @Override
+    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+        PrintWriter out = resp.getWriter();
+        String pi = req.getPathInfo().substring(PATH.length());
+        if (pi.length() != 0) {
+            pi = pi.substring(1);
+
+            String serial = pi;
+            Certificate c = Certificate.getBySerial(serial);
+            if (c == null || LoginPage.getUser(req).getId() != c.getOwnerId()) {
+                resp.sendError(404);
+                return;
+            }
+            out.print("<a href='");
+            out.print(serial);
+            out.print(".crt'>");
+            out.print(translate(req, "PEM encoded Certificate"));
+            out.println("</a><br/>");
+
+            out.print("<a href='");
+            out.print(serial);
+            out.print(".cer'>");
+            out.print(translate(req, "DER encoded Certificate"));
+            out.println("</a><br/>");
+            out.print("<a href='");
+            out.print(serial);
+            out.print(".cer?install'>");
+            out.print(translate(req, "Install into browser."));
+            out.println("</a><br/>");
+
+            out.println("<pre>");
+            try {
+                X509Certificate cert = c.cert();
+                out.print(cert);
+            } catch (GeneralSecurityException e) {
+                e.printStackTrace();
+            } catch (SQLException e) {
+                e.printStackTrace();
+            }
+            out.println("</pre>");
+            return;
+        }
+
+        HashMap<String, Object> vars = new HashMap<String, Object>();
+        User us = LoginPage.getUser(req);
+        try {
+            PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `id`, `CN`, `serial`, `revoked`, `expire`, `disablelogin` FROM `emailcerts` WHERE `memid`=?");
+            ps.setInt(1, us.getId());
+            ResultSet rs = ps.executeQuery();
+            vars.put("mailcerts", rs);
+            myTable.output(out, getLanguage(req), vars);
+            rs.close();
+        } catch (SQLException e) {
+            e.printStackTrace();
+        }
+    }
 
 }
index 3e82bd2ac45cb526393155f0ceb916cff51eeb86..ffadc63ffd1b89d87596a8f0108f846398cd61ba 100644 (file)
@@ -14,54 +14,56 @@ import org.cacert.gigi.output.template.Template;
 import org.cacert.gigi.pages.Page;
 
 public class MailManagementForm extends Form {
-       private static Template t;
-       private User target;
-       static {
-               t = new Template(ChangePasswordPage.class.getResource("MailManagementForm.templ"));
-       }
 
-       public MailManagementForm(HttpServletRequest hsr, User target) {
-               super(hsr);
-               this.target = target;
-       }
+    private static Template t;
 
-       @Override
-       public boolean submit(PrintWriter out, HttpServletRequest req) {
-               if (req.getParameter("makedefault") != null) {
-                       try {
-                               String mailid = req.getParameter("emailid");
-                               if (mailid == null) {
-                                       return false;
-                               }
-                               target.updateDefaultEmail(EmailAddress.getById(Integer.parseInt(mailid.trim())));
-                       } catch (GigiApiException e) {
-                               e.format(out, Page.getLanguage(req));
-                               return false;
-                       }
-                       return true;
-               }
-               if (req.getParameter("delete") != null) {
-                       String[] toDel = req.getParameterValues("delid[]");
-                       if (toDel == null) {
-                               return false;
-                       }
-                       for (int i = 0; i < toDel.length; i++) {
-                               try {
-                                       target.deleteEmail(EmailAddress.getById(Integer.parseInt(toDel[i].trim())));
-                               } catch (GigiApiException e) {
-                                       e.format(out, Page.getLanguage(req));
-                                       return false;
-                               }
-                       }
-                       return true;
+    private User target;
+    static {
+        t = new Template(ChangePasswordPage.class.getResource("MailManagementForm.templ"));
+    }
 
-               }
-               return false;
-       }
+    public MailManagementForm(HttpServletRequest hsr, User target) {
+        super(hsr);
+        this.target = target;
+    }
 
-       @Override
-       protected void outputContent(PrintWriter out, Language l, Map<String, Object> vars) {
-               t.output(out, l, vars);
-       }
+    @Override
+    public boolean submit(PrintWriter out, HttpServletRequest req) {
+        if (req.getParameter("makedefault") != null) {
+            try {
+                String mailid = req.getParameter("emailid");
+                if (mailid == null) {
+                    return false;
+                }
+                target.updateDefaultEmail(EmailAddress.getById(Integer.parseInt(mailid.trim())));
+            } catch (GigiApiException e) {
+                e.format(out, Page.getLanguage(req));
+                return false;
+            }
+            return true;
+        }
+        if (req.getParameter("delete") != null) {
+            String[] toDel = req.getParameterValues("delid[]");
+            if (toDel == null) {
+                return false;
+            }
+            for (int i = 0; i < toDel.length; i++) {
+                try {
+                    target.deleteEmail(EmailAddress.getById(Integer.parseInt(toDel[i].trim())));
+                } catch (GigiApiException e) {
+                    e.format(out, Page.getLanguage(req));
+                    return false;
+                }
+            }
+            return true;
+
+        }
+        return false;
+    }
+
+    @Override
+    protected void outputContent(PrintWriter out, Language l, Map<String, Object> vars) {
+        t.output(out, l, vars);
+    }
 
 }
index 8547303e492d46edd35c598ce8d8084f28a837a2..9ce150f820810967d5c5e4d38a5c0fbffef245c1 100644 (file)
@@ -17,88 +17,91 @@ import org.cacert.gigi.pages.LoginPage;
 import org.cacert.gigi.pages.Page;
 
 public class MailOverview extends Page {
-       public static final String DEFAULT_PATH = "/account/mails";
-       private MailTable t;
 
-       public MailOverview(String title) {
-               super(title);
-               t = new MailTable("us");
-       }
+    public static final String DEFAULT_PATH = "/account/mails";
 
-       @Override
-       public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
-               final User us = LoginPage.getUser(req);
-               Language lang = Page.getLanguage(req);
-               HashMap<String, Object> vars = new HashMap<>();
-               vars.put("mailData", t);
-               vars.put("us", us);
-               vars.put("addForm", new MailAddForm(req, us));
-               vars.put("manForm", new MailManagementForm(req, us));
-               getDefaultTemplate().output(resp.getWriter(), lang, vars);
-       }
+    private MailTable t;
 
-       @Override
-       public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
-               PrintWriter out = resp.getWriter();
-               if (req.getParameter("addmail") != null) {
-                       MailAddForm f = Form.getForm(req, MailAddForm.class);
-                       if (f.submit(out, req)) {
-                               resp.sendRedirect(MailOverview.DEFAULT_PATH);
-                       }
-               } else if (req.getParameter("makedefault") != null || req.getParameter("delete") != null) {
-                       MailManagementForm f = Form.getForm(req, MailManagementForm.class);
-                       if (f.submit(out, req)) {
-                               resp.sendRedirect(MailOverview.DEFAULT_PATH);
-                       }
-               }
-               super.doPost(req, resp);
-       }
+    public MailOverview(String title) {
+        super(title);
+        t = new MailTable("us");
+    }
 
-       private class MailTable implements Outputable {
-               private String user;
+    @Override
+    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+        final User us = LoginPage.getUser(req);
+        Language lang = Page.getLanguage(req);
+        HashMap<String, Object> vars = new HashMap<>();
+        vars.put("mailData", t);
+        vars.put("us", us);
+        vars.put("addForm", new MailAddForm(req, us));
+        vars.put("manForm", new MailManagementForm(req, us));
+        getDefaultTemplate().output(resp.getWriter(), lang, vars);
+    }
 
-               public MailTable(String user) {
-                       this.user = user;
-               }
+    @Override
+    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+        PrintWriter out = resp.getWriter();
+        if (req.getParameter("addmail") != null) {
+            MailAddForm f = Form.getForm(req, MailAddForm.class);
+            if (f.submit(out, req)) {
+                resp.sendRedirect(MailOverview.DEFAULT_PATH);
+            }
+        } else if (req.getParameter("makedefault") != null || req.getParameter("delete") != null) {
+            MailManagementForm f = Form.getForm(req, MailManagementForm.class);
+            if (f.submit(out, req)) {
+                resp.sendRedirect(MailOverview.DEFAULT_PATH);
+            }
+        }
+        super.doPost(req, resp);
+    }
 
-               @Override
-               public void output(PrintWriter out, Language l, Map<String, Object> vars) {
-                       User us = (User) vars.get(user);
-                       String usM = us.getEmail();
-                       EmailAddress[] emails = us.getEmails();
+    private class MailTable implements Outputable {
 
-                       for (int i = 0; i < emails.length; i++) {
-                               out.println("<tr>");
-                               out.println("<td><input type=\"radio\" name=\"emailid\" value=\"");
-                               int mailID = emails[i].getId();
-                               out.print(mailID);
-                               out.print("\" ");
-                               if (emails[i].getAddress().equals(us.getEmail())) {
-                                       out.print("checked=\"yes\"");
-                               }
-                               out.print("/></td>");
-                               out.println("<td>");
-                               if (emails[i].isVerified()) {
-                                       out.print(l.getTranslation("Verified"));
-                               } else {
-                                       out.print(l.getTranslation("Unverified"));
-                               }
-                               out.print("</td>");
-                               out.println("<td>");
-                               String address = emails[i].getAddress();
-                               if (usM.equals(address)) {
-                                       out.print(l.getTranslation("N/A"));
-                               } else {
-                                       out.print("<input type=\"checkbox\" name=\"delid[]\" value=\"");
-                                       out.print(mailID);
-                                       out.print("\"/>");
-                               }
-                               out.print("</td>");
-                               out.println("<td>");
-                               out.print(address);
-                               out.print("</td>");
-                               out.println("</tr>");
-                       }
-               }
-       }
+        private String user;
+
+        public MailTable(String user) {
+            this.user = user;
+        }
+
+        @Override
+        public void output(PrintWriter out, Language l, Map<String, Object> vars) {
+            User us = (User) vars.get(user);
+            String usM = us.getEmail();
+            EmailAddress[] emails = us.getEmails();
+
+            for (int i = 0; i < emails.length; i++) {
+                out.println("<tr>");
+                out.println("<td><input type=\"radio\" name=\"emailid\" value=\"");
+                int mailID = emails[i].getId();
+                out.print(mailID);
+                out.print("\" ");
+                if (emails[i].getAddress().equals(us.getEmail())) {
+                    out.print("checked=\"yes\"");
+                }
+                out.print("/></td>");
+                out.println("<td>");
+                if (emails[i].isVerified()) {
+                    out.print(l.getTranslation("Verified"));
+                } else {
+                    out.print(l.getTranslation("Unverified"));
+                }
+                out.print("</td>");
+                out.println("<td>");
+                String address = emails[i].getAddress();
+                if (usM.equals(address)) {
+                    out.print(l.getTranslation("N/A"));
+                } else {
+                    out.print("<input type=\"checkbox\" name=\"delid[]\" value=\"");
+                    out.print(mailID);
+                    out.print("\"/>");
+                }
+                out.print("</td>");
+                out.println("<td>");
+                out.print(address);
+                out.print("</td>");
+                out.println("</tr>");
+            }
+        }
+    }
 }
index 753bdb2bb52e4c89b2b4e19811a33e8c975c4bef..abb88d6972239086a2cf0b070585f6f3d0720df9 100644 (file)
@@ -16,26 +16,26 @@ import org.cacert.gigi.util.HTMLEncoder;
 
 public class MyDetails extends Page {
 
-       public MyDetails() {
-               super("My Details");
-       }
-
-       public static final String PATH = "/account/details";
-
-       @Override
-       public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
-               User u = (User) req.getSession().getAttribute(USER);
-
-               PrintWriter out = resp.getWriter();
-               HashMap<String, Object> map = new HashMap<String, Object>();
-               map.put("fname", HTMLEncoder.encodeHTML(u.getFname()));
-               map.put("mname", u.getMname() == null ? "" : HTMLEncoder.encodeHTML(u.getMname()));
-               map.put("lname", HTMLEncoder.encodeHTML(u.getLname()));
-               map.put("suffix", u.getSuffix() == null ? "" : HTMLEncoder.encodeHTML(u.getSuffix()));
-               DateSelector ds = new DateSelector("day", "month", "year");
-               map.put("DoB", ds);
-               map.put("details", "");
-               getDefaultTemplate().output(out, getLanguage(req), map);
-
-       }
+    public MyDetails() {
+        super("My Details");
+    }
+
+    public static final String PATH = "/account/details";
+
+    @Override
+    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+        User u = (User) req.getSession().getAttribute(USER);
+
+        PrintWriter out = resp.getWriter();
+        HashMap<String, Object> map = new HashMap<String, Object>();
+        map.put("fname", HTMLEncoder.encodeHTML(u.getFname()));
+        map.put("mname", u.getMname() == null ? "" : HTMLEncoder.encodeHTML(u.getMname()));
+        map.put("lname", HTMLEncoder.encodeHTML(u.getLname()));
+        map.put("suffix", u.getSuffix() == null ? "" : HTMLEncoder.encodeHTML(u.getSuffix()));
+        DateSelector ds = new DateSelector("day", "month", "year");
+        map.put("DoB", ds);
+        map.put("details", "");
+        getDefaultTemplate().output(out, getLanguage(req), map);
+
+    }
 }
index 179908c1b9a2683a7b30ec1aad0b91a4cd3ab443..0d53524f8abec884ae16606d026c219b67fa6542 100644 (file)
@@ -9,18 +9,18 @@ import org.cacert.gigi.pages.Page;
 
 public class PageNotFound extends Page {
 
-       public PageNotFound() {
-               super("");
-       }
-
-       @Override
-       public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
-               getDefaultTemplate().output(resp.getWriter(), Page.getLanguage(req), null);
-       }
-
-       @Override
-       public boolean needsLogin() {
-               return false;
-       }
+    public PageNotFound() {
+        super("");
+    }
+
+    @Override
+    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+        getDefaultTemplate().output(resp.getWriter(), Page.getLanguage(req), null);
+    }
+
+    @Override
+    public boolean needsLogin() {
+        return false;
+    }
 
 }
index e243c2875f92e826ac4ed21acb5adbaabed894b7..e2e2a49397b347a6eb54e687e5fde3095ddf1a95 100644 (file)
@@ -13,47 +13,44 @@ import org.cacert.gigi.pages.Page;
 
 public class RegisterPage extends Page {
 
-       private static final String SIGNUP_PROCESS = "signupProcess";
-       public static final String PATH = "/register";
-
-       public RegisterPage() {
-               super("Register");
-       }
-
-       @Override
-       public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
-               Signup s = new Signup(req);
-               outputGet(req, resp, s);
-       }
-
-       private void outputGet(HttpServletRequest req, HttpServletResponse resp, Signup s) throws IOException {
-               PrintWriter out = resp.getWriter();
-               HashMap<String, Object> vars = new HashMap<String, Object>();
-               getDefaultTemplate().output(out, getLanguage(req), vars);
-               s.output(out, getLanguage(req), vars);
-       }
-
-       @Override
-       public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
-               Signup s = Form.getForm(req, Signup.class);
-               if (s == null) {
-                       resp.getWriter().println(translate(req, "CSRF token check failed."));
-               } else if (s.submit(resp.getWriter(), req)) {
-                       HttpSession hs = req.getSession();
-                       hs.setAttribute(SIGNUP_PROCESS, null);
-                       resp.getWriter().println(
-                               translate(req, "Your information has been submitted"
-                                       + " into our system. You will now be sent an email with a web link,"
-                                       + " you need to open that link in your web browser within 24 hours"
-                                       + " or your information will be removed from our system!"));
-                       return;
-               }
-
-               outputGet(req, resp, s);
-       }
-
-       @Override
-       public boolean needsLogin() {
-               return false;
-       }
+    private static final String SIGNUP_PROCESS = "signupProcess";
+
+    public static final String PATH = "/register";
+
+    public RegisterPage() {
+        super("Register");
+    }
+
+    @Override
+    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+        Signup s = new Signup(req);
+        outputGet(req, resp, s);
+    }
+
+    private void outputGet(HttpServletRequest req, HttpServletResponse resp, Signup s) throws IOException {
+        PrintWriter out = resp.getWriter();
+        HashMap<String, Object> vars = new HashMap<String, Object>();
+        getDefaultTemplate().output(out, getLanguage(req), vars);
+        s.output(out, getLanguage(req), vars);
+    }
+
+    @Override
+    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+        Signup s = Form.getForm(req, Signup.class);
+        if (s == null) {
+            resp.getWriter().println(translate(req, "CSRF token check failed."));
+        } else if (s.submit(resp.getWriter(), req)) {
+            HttpSession hs = req.getSession();
+            hs.setAttribute(SIGNUP_PROCESS, null);
+            resp.getWriter().println(translate(req, "Your information has been submitted" + " into our system. You will now be sent an email with a web link," + " you need to open that link in your web browser within 24 hours" + " or your information will be removed from our system!"));
+            return;
+        }
+
+        outputGet(req, resp, s);
+    }
+
+    @Override
+    public boolean needsLogin() {
+        return false;
+    }
 }
index 1847d9c29759168640b0b824ef28768dbd42b286..f2ed2ff51ef5ca3cef9e3388d74c7a0568008f5d 100644 (file)
@@ -25,198 +25,191 @@ import org.cacert.gigi.util.Notary;
 import org.cacert.gigi.util.PasswordStrengthChecker;
 
 public class Signup extends Form {
-       User buildup = new User();
-       Template t;
-       boolean general = true, country = true, regional = true, radius = true;
-
-       public Signup(HttpServletRequest hsr) {
-               super(hsr);
-               t = new Template(Signup.class.getResource("Signup.templ"));
-               buildup.setFname("");
-               buildup.setMname("");
-               buildup.setLname("");
-               buildup.setSuffix("");
-               buildup.setEmail("");
-               buildup.setDob(new Date(0));
-       }
-
-       DateSelector myDoB = new DateSelector("day", "month", "year");
-
-       @Override
-       public void outputContent(PrintWriter out, Language l, Map<String, Object> outerVars) {
-               HashMap<String, Object> vars = new HashMap<String, Object>();
-               vars.put("fname", HTMLEncoder.encodeHTML(buildup.getFname()));
-               vars.put("mname", HTMLEncoder.encodeHTML(buildup.getMname()));
-               vars.put("lname", HTMLEncoder.encodeHTML(buildup.getLname()));
-               vars.put("suffix", HTMLEncoder.encodeHTML(buildup.getSuffix()));
-               vars.put("dob", myDoB);
-               vars.put("email", HTMLEncoder.encodeHTML(buildup.getEmail()));
-               vars.put("general", general ? " checked=\"checked\"" : "");
-               vars.put("country", country ? " checked=\"checked\"" : "");
-               vars.put("regional", regional ? " checked=\"checked\"" : "");
-               vars.put("radius", radius ? " checked=\"checked\"" : "");
-               vars.put("helpOnNames", String.format(l.getTranslation("Help on Names %sin the wiki%s"),
-                       "<a href=\"//wiki.cacert.org/FAQ/HowToEnterNamesInJoinForm\" target=\"_blank\">", "</a>"));
-               vars.put("csrf", getCSRFToken());
-               t.output(out, l, vars);
-       }
-
-       private void update(HttpServletRequest r) {
-               if (r.getParameter("fname") != null) {
-                       buildup.setFname(r.getParameter("fname"));
-               }
-               if (r.getParameter("lname") != null) {
-                       buildup.setLname(r.getParameter("lname"));
-               }
-               if (r.getParameter("mname") != null) {
-                       buildup.setMname(r.getParameter("mname"));
-               }
-               if (r.getParameter("suffix") != null) {
-                       buildup.setSuffix(r.getParameter("suffix"));
-               }
-               if (r.getParameter("email") != null) {
-                       buildup.setEmail(r.getParameter("email"));
-               }
-               general = "1".equals(r.getParameter("general"));
-               country = "1".equals(r.getParameter("country"));
-               regional = "1".equals(r.getParameter("regional"));
-               radius = "1".equals(r.getParameter("radius"));
-               myDoB.update(r);
-       }
-
-       @Override
-       public synchronized boolean submit(PrintWriter out, HttpServletRequest req) {
-               update(req);
-               boolean failed = false;
-               out.println("<div class='formError'>");
-               if (buildup.getFname().equals("") || buildup.getLname().equals("")) {
-                       outputError(out, req, "First and/or last names were blank.");
-                       failed = true;
-               }
-               if (!myDoB.isValid()) {
-                       outputError(out, req, "Invalid date of birth");
-                       failed = true;
-               }
-               if (!"1".equals(req.getParameter("cca_agree"))) {
-                       outputError(out, req, "You have to agree to the CAcert Community agreement.");
-                       failed = true;
-               }
-               if (buildup.getEmail().equals("")) {
-                       outputError(out, req, "Email Address was blank");
-                       failed = true;
-               }
-               String pw1 = req.getParameter("pword1");
-               String pw2 = req.getParameter("pword2");
-               if (pw1 == null || pw1.equals("")) {
-                       outputError(out, req, "Pass Phrases were blank");
-                       failed = true;
-               } else if (!pw1.equals(pw2)) {
-                       outputError(out, req, "Pass Phrases don't match");
-                       failed = true;
-               }
-               int pwpoints = PasswordStrengthChecker.checkpw(pw1, buildup);
-               if (pwpoints < 3) {
-                       outputError(out, req, "The Pass Phrase you submitted failed to contain enough"
-                               + " differing characters and/or contained words from" + " your name and/or email address.");
-                       failed = true;
-               }
-               if (failed) {
-                       out.println("</div>");
-                       return false;
-               }
-               try {
-                       PreparedStatement q1 = DatabaseConnection.getInstance().prepare(
-                               "select * from `email` where `email`=? and `deleted`=0");
-                       PreparedStatement q2 = DatabaseConnection.getInstance().prepare(
-                               "select * from `users` where `email`=? and `deleted`=0");
-                       q1.setString(1, buildup.getEmail());
-                       q2.setString(1, buildup.getEmail());
-                       ResultSet r1 = q1.executeQuery();
-                       ResultSet r2 = q2.executeQuery();
-                       if (r1.next() || r2.next()) {
-                               outputError(out, req, "This email address is currently valid in the system.");
-                               failed = true;
-                       }
-                       r1.close();
-                       r2.close();
-                       PreparedStatement q3 = DatabaseConnection.getInstance().prepare(
-                               "select `domain` from `baddomains` where `domain`=RIGHT(?, LENGTH(`domain`))");
-                       q3.setString(1, buildup.getEmail());
-
-                       ResultSet r3 = q3.executeQuery();
-                       if (r3.next()) {
-                               String domain = r3.getString(1);
-                               out.print("<div>");
-                               out.print(String.format(
-                                       Page.translate(req, "We don't allow signups from people using email addresses from %s"), domain));
-                               out.println("</div>");
-                               failed = true;
-                       }
-                       r3.close();
-               } catch (SQLException e) {
-                       e.printStackTrace();
-                       failed = true;
-               }
-               String mailResult = EmailProvider.FAIL;
-               try {
-                       mailResult = EmailProvider.getInstance().checkEmailServer(0, buildup.getEmail());
-               } catch (IOException e) {
-               }
-               if (!mailResult.equals(EmailProvider.OK)) {
-                       if (mailResult.startsWith("4")) {
-                               outputError(out, req, "The mail server responsible for your domain indicated"
-                                       + " a temporary failure. This may be due to anti-SPAM measures, such"
-                                       + " as greylisting. Please try again in a few minutes.");
-                       } else {
-                               outputError(out, req, "Email Address given was invalid, or a test connection"
-                                       + " couldn't be made to your server, or the server" + " rejected the email address as invalid");
-                       }
-                       if (mailResult.equals(EmailProvider.FAIL)) {
-                               outputError(out, req, "Failed to make a connection to the mail server");
-                       } else {
-                               out.print("<div>");
-                               out.print(mailResult);
-                               out.println("</div>");
-                       }
-                       failed = true;
-               }
-
-               out.println("</div>");
-               if (failed) {
-                       return false;
-               }
-               try {
-                       run(req, pw1);
-               } catch (SQLException e) {
-                       e.printStackTrace();
-               }
-               return true;
-       }
-
-       private void run(HttpServletRequest req, String password) throws SQLException {
-               try {
-                       DatabaseConnection.getInstance().beginTransaction();
-
-                       buildup.setDob(myDoB.getDate());
-                       buildup.insert(password);
-                       int memid = buildup.getId();
-                       EmailAddress ea = new EmailAddress(buildup.getEmail(), buildup);
-                       ea.insert(Page.getLanguage(req));
-
-                       PreparedStatement ps = DatabaseConnection.getInstance().prepare(
-                               "insert into `alerts` set `memid`=?," + " `general`=?, `country`=?, `regional`=?, `radius`=?");
-                       ps.setInt(1, memid);
-                       ps.setString(2, general ? "1" : "0");
-                       ps.setString(3, country ? "1" : "0");
-                       ps.setString(4, regional ? "1" : "0");
-                       ps.setString(5, radius ? "1" : "0");
-                       ps.execute();
-                       Notary.writeUserAgreement(memid, "CCA", "account creation", "", true, 0);
-
-                       DatabaseConnection.getInstance().commitTransaction();
-               } finally {
-                       DatabaseConnection.getInstance().quitTransaction();
-               }
-
-       }
+
+    User buildup = new User();
+
+    Template t;
+
+    boolean general = true, country = true, regional = true, radius = true;
+
+    public Signup(HttpServletRequest hsr) {
+        super(hsr);
+        t = new Template(Signup.class.getResource("Signup.templ"));
+        buildup.setFname("");
+        buildup.setMname("");
+        buildup.setLname("");
+        buildup.setSuffix("");
+        buildup.setEmail("");
+        buildup.setDob(new Date(0));
+    }
+
+    DateSelector myDoB = new DateSelector("day", "month", "year");
+
+    @Override
+    public void outputContent(PrintWriter out, Language l, Map<String, Object> outerVars) {
+        HashMap<String, Object> vars = new HashMap<String, Object>();
+        vars.put("fname", HTMLEncoder.encodeHTML(buildup.getFname()));
+        vars.put("mname", HTMLEncoder.encodeHTML(buildup.getMname()));
+        vars.put("lname", HTMLEncoder.encodeHTML(buildup.getLname()));
+        vars.put("suffix", HTMLEncoder.encodeHTML(buildup.getSuffix()));
+        vars.put("dob", myDoB);
+        vars.put("email", HTMLEncoder.encodeHTML(buildup.getEmail()));
+        vars.put("general", general ? " checked=\"checked\"" : "");
+        vars.put("country", country ? " checked=\"checked\"" : "");
+        vars.put("regional", regional ? " checked=\"checked\"" : "");
+        vars.put("radius", radius ? " checked=\"checked\"" : "");
+        vars.put("helpOnNames", String.format(l.getTranslation("Help on Names %sin the wiki%s"), "<a href=\"//wiki.cacert.org/FAQ/HowToEnterNamesInJoinForm\" target=\"_blank\">", "</a>"));
+        vars.put("csrf", getCSRFToken());
+        t.output(out, l, vars);
+    }
+
+    private void update(HttpServletRequest r) {
+        if (r.getParameter("fname") != null) {
+            buildup.setFname(r.getParameter("fname"));
+        }
+        if (r.getParameter("lname") != null) {
+            buildup.setLname(r.getParameter("lname"));
+        }
+        if (r.getParameter("mname") != null) {
+            buildup.setMname(r.getParameter("mname"));
+        }
+        if (r.getParameter("suffix") != null) {
+            buildup.setSuffix(r.getParameter("suffix"));
+        }
+        if (r.getParameter("email") != null) {
+            buildup.setEmail(r.getParameter("email"));
+        }
+        general = "1".equals(r.getParameter("general"));
+        country = "1".equals(r.getParameter("country"));
+        regional = "1".equals(r.getParameter("regional"));
+        radius = "1".equals(r.getParameter("radius"));
+        myDoB.update(r);
+    }
+
+    @Override
+    public synchronized boolean submit(PrintWriter out, HttpServletRequest req) {
+        update(req);
+        boolean failed = false;
+        out.println("<div class='formError'>");
+        if (buildup.getFname().equals("") || buildup.getLname().equals("")) {
+            outputError(out, req, "First and/or last names were blank.");
+            failed = true;
+        }
+        if ( !myDoB.isValid()) {
+            outputError(out, req, "Invalid date of birth");
+            failed = true;
+        }
+        if ( !"1".equals(req.getParameter("cca_agree"))) {
+            outputError(out, req, "You have to agree to the CAcert Community agreement.");
+            failed = true;
+        }
+        if (buildup.getEmail().equals("")) {
+            outputError(out, req, "Email Address was blank");
+            failed = true;
+        }
+        String pw1 = req.getParameter("pword1");
+        String pw2 = req.getParameter("pword2");
+        if (pw1 == null || pw1.equals("")) {
+            outputError(out, req, "Pass Phrases were blank");
+            failed = true;
+        } else if ( !pw1.equals(pw2)) {
+            outputError(out, req, "Pass Phrases don't match");
+            failed = true;
+        }
+        int pwpoints = PasswordStrengthChecker.checkpw(pw1, buildup);
+        if (pwpoints < 3) {
+            outputError(out, req, "The Pass Phrase you submitted failed to contain enough" + " differing characters and/or contained words from" + " your name and/or email address.");
+            failed = true;
+        }
+        if (failed) {
+            out.println("</div>");
+            return false;
+        }
+        try {
+            PreparedStatement q1 = DatabaseConnection.getInstance().prepare("select * from `email` where `email`=? and `deleted`=0");
+            PreparedStatement q2 = DatabaseConnection.getInstance().prepare("select * from `users` where `email`=? and `deleted`=0");
+            q1.setString(1, buildup.getEmail());
+            q2.setString(1, buildup.getEmail());
+            ResultSet r1 = q1.executeQuery();
+            ResultSet r2 = q2.executeQuery();
+            if (r1.next() || r2.next()) {
+                outputError(out, req, "This email address is currently valid in the system.");
+                failed = true;
+            }
+            r1.close();
+            r2.close();
+            PreparedStatement q3 = DatabaseConnection.getInstance().prepare("select `domain` from `baddomains` where `domain`=RIGHT(?, LENGTH(`domain`))");
+            q3.setString(1, buildup.getEmail());
+
+            ResultSet r3 = q3.executeQuery();
+            if (r3.next()) {
+                String domain = r3.getString(1);
+                out.print("<div>");
+                out.print(String.format(Page.translate(req, "We don't allow signups from people using email addresses from %s"), domain));
+                out.println("</div>");
+                failed = true;
+            }
+            r3.close();
+        } catch (SQLException e) {
+            e.printStackTrace();
+            failed = true;
+        }
+        String mailResult = EmailProvider.FAIL;
+        try {
+            mailResult = EmailProvider.getInstance().checkEmailServer(0, buildup.getEmail());
+        } catch (IOException e) {
+        }
+        if ( !mailResult.equals(EmailProvider.OK)) {
+            if (mailResult.startsWith("4")) {
+                outputError(out, req, "The mail server responsible for your domain indicated" + " a temporary failure. This may be due to anti-SPAM measures, such" + " as greylisting. Please try again in a few minutes.");
+            } else {
+                outputError(out, req, "Email Address given was invalid, or a test connection" + " couldn't be made to your server, or the server" + " rejected the email address as invalid");
+            }
+            if (mailResult.equals(EmailProvider.FAIL)) {
+                outputError(out, req, "Failed to make a connection to the mail server");
+            } else {
+                out.print("<div>");
+                out.print(mailResult);
+                out.println("</div>");
+            }
+            failed = true;
+        }
+
+        out.println("</div>");
+        if (failed) {
+            return false;
+        }
+        try {
+            run(req, pw1);
+        } catch (SQLException e) {
+            e.printStackTrace();
+        }
+        return true;
+    }
+
+    private void run(HttpServletRequest req, String password) throws SQLException {
+        try {
+            DatabaseConnection.getInstance().beginTransaction();
+
+            buildup.setDob(myDoB.getDate());
+            buildup.insert(password);
+            int memid = buildup.getId();
+            EmailAddress ea = new EmailAddress(buildup.getEmail(), buildup);
+            ea.insert(Page.getLanguage(req));
+
+            PreparedStatement ps = DatabaseConnection.getInstance().prepare("insert into `alerts` set `memid`=?," + " `general`=?, `country`=?, `regional`=?, `radius`=?");
+            ps.setInt(1, memid);
+            ps.setString(2, general ? "1" : "0");
+            ps.setString(3, country ? "1" : "0");
+            ps.setString(4, regional ? "1" : "0");
+            ps.setString(5, radius ? "1" : "0");
+            ps.execute();
+            Notary.writeUserAgreement(memid, "CCA", "account creation", "", true, 0);
+
+            DatabaseConnection.getInstance().commitTransaction();
+        } finally {
+            DatabaseConnection.getInstance().quitTransaction();
+        }
+
+    }
 }
index e1c36886c9dac5641001d09ede433b169b9e6534..97dac246456fce9a9b48294281a8e8f4dd0b166c 100644 (file)
@@ -19,92 +19,91 @@ import org.cacert.gigi.util.Notary;
 import org.cacert.gigi.util.Notary.AssuranceResult;
 
 public class AssuranceForm extends Form {
-       User assuree;
-       static final Template templ;
-       static {
-               templ = new Template(AssuranceForm.class.getResource("AssuranceForm.templ"));
-       }
 
-       public AssuranceForm(HttpServletRequest hsr, int assuree) {
-               super(hsr);
-               this.assuree = new User(assuree);
-       }
+    User assuree;
 
-       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+    static final Template templ;
+    static {
+        templ = new Template(AssuranceForm.class.getResource("AssuranceForm.templ"));
+    }
 
-       @Override
-       public void outputContent(PrintWriter out, Language l, Map<String, Object> vars) {
-               HashMap<String, Object> res = new HashMap<String, Object>();
-               res.putAll(vars);
-               res.put("name", assuree.getName());
-               try {
-                       res.put("maxpoints", assuree.getMaxAssurePoints());
-               } catch (SQLException e) {
-                       e.printStackTrace();
-               }
-               res.put("dob", sdf.format(assuree.getDob()));
-               templ.output(out, l, res);
-       }
+    public AssuranceForm(HttpServletRequest hsr, int assuree) {
+        super(hsr);
+        this.assuree = new User(assuree);
+    }
 
-       @Override
-       public boolean submit(PrintWriter out, HttpServletRequest req) {
-               out.println("<div class='formError'>");
-               boolean failed = false;
+    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
 
-               if (!"1".equals(req.getParameter("certify")) || !"1".equals(req.getParameter("rules"))
-                       || !"1".equals(req.getParameter("CCAAgreed")) || !"1".equals(req.getParameter("assertion"))) {
-                       outputError(out, req, "You failed to check all boxes to validate"
-                               + " your adherence to the rules and policies of CAcert");
-                       failed = true;
+    @Override
+    public void outputContent(PrintWriter out, Language l, Map<String, Object> vars) {
+        HashMap<String, Object> res = new HashMap<String, Object>();
+        res.putAll(vars);
+        res.put("name", assuree.getName());
+        try {
+            res.put("maxpoints", assuree.getMaxAssurePoints());
+        } catch (SQLException e) {
+            e.printStackTrace();
+        }
+        res.put("dob", sdf.format(assuree.getDob()));
+        templ.output(out, l, res);
+    }
 
-               }
-               if (req.getParameter("date") == null || req.getParameter("date").equals("")) {
-                       outputError(out, req, "You must enter the date when you met the assuree.");
-                       failed = true;
-               } else {
-                       try {
-                               Date d = sdf.parse(req.getParameter("date"));
-                               if (d.getTime() > System.currentTimeMillis()) {
-                                       outputError(out, req, "You must not enter a date in the future.");
-                                       failed = true;
-                               }
-                       } catch (ParseException e) {
-                               outputError(out, req, "You must enter the date in this format: YYYY-MM-DD.");
-                               failed = true;
-                       }
-               }
-               // check location, min 3 characters
-               if (req.getParameter("location") == null || req.getParameter("location").equals("")) {
-                       outputError(out, req, "You failed to enter a location of your meeting.");
-                       failed = true;
-               } else if (req.getParameter("location").length() <= 2) {
-                       outputError(out, req, "You must enter a location with at least 3 characters eg town and country.");
-                       failed = true;
-               }
-               // TODO checkPoints
-               String points = req.getParameter("points");
-               if (points == null || "".equals(points)) {
-                       // TODO message
-                       failed = true;
-               }
-               if (failed) {
-                       out.println("</div>");
-                       return false;
-               }
-               try {
-                       AssuranceResult success = Notary.assure(LoginPage.getUser(req), assuree,
-                               Integer.parseInt(req.getParameter("points")), req.getParameter("location"), req.getParameter("date"));
-                       if (success != AssuranceResult.ASSURANCE_SUCCEDED) {
-                               outputError(out, req, success.getMessage());
-                       }
-                       out.println("</div>");
-                       return success == AssuranceResult.ASSURANCE_SUCCEDED;
-               } catch (SQLException e) {
-                       e.printStackTrace();
-               }
+    @Override
+    public boolean submit(PrintWriter out, HttpServletRequest req) {
+        out.println("<div class='formError'>");
+        boolean failed = false;
 
-               out.println("</div>");
-               return false;
-       }
+        if ( !"1".equals(req.getParameter("certify")) || !"1".equals(req.getParameter("rules")) || !"1".equals(req.getParameter("CCAAgreed")) || !"1".equals(req.getParameter("assertion"))) {
+            outputError(out, req, "You failed to check all boxes to validate" + " your adherence to the rules and policies of CAcert");
+            failed = true;
+
+        }
+        if (req.getParameter("date") == null || req.getParameter("date").equals("")) {
+            outputError(out, req, "You must enter the date when you met the assuree.");
+            failed = true;
+        } else {
+            try {
+                Date d = sdf.parse(req.getParameter("date"));
+                if (d.getTime() > System.currentTimeMillis()) {
+                    outputError(out, req, "You must not enter a date in the future.");
+                    failed = true;
+                }
+            } catch (ParseException e) {
+                outputError(out, req, "You must enter the date in this format: YYYY-MM-DD.");
+                failed = true;
+            }
+        }
+        // check location, min 3 characters
+        if (req.getParameter("location") == null || req.getParameter("location").equals("")) {
+            outputError(out, req, "You failed to enter a location of your meeting.");
+            failed = true;
+        } else if (req.getParameter("location").length() <= 2) {
+            outputError(out, req, "You must enter a location with at least 3 characters eg town and country.");
+            failed = true;
+        }
+        // TODO checkPoints
+        String points = req.getParameter("points");
+        if (points == null || "".equals(points)) {
+            // TODO message
+            failed = true;
+        }
+        if (failed) {
+            out.println("</div>");
+            return false;
+        }
+        try {
+            AssuranceResult success = Notary.assure(LoginPage.getUser(req), assuree, Integer.parseInt(req.getParameter("points")), req.getParameter("location"), req.getParameter("date"));
+            if (success != AssuranceResult.ASSURANCE_SUCCEDED) {
+                outputError(out, req, success.getMessage());
+            }
+            out.println("</div>");
+            return success == AssuranceResult.ASSURANCE_SUCCEDED;
+        } catch (SQLException e) {
+            e.printStackTrace();
+        }
+
+        out.println("</div>");
+        return false;
+    }
 
 }
index 464afd97a9b49c9235403b4018d63f0ef7663ab1..1dae379c18a7d69cebb9438b6f402e50a016d52d 100644 (file)
@@ -21,111 +21,112 @@ import org.cacert.gigi.util.Notary;
 import org.cacert.gigi.util.Notary.AssuranceResult;
 
 public class AssurePage extends Page {
-       public static final String PATH = "/wot/assure";
-       DateSelector ds = new DateSelector("day", "month", "year");
-       Template t;
-
-       public AssurePage() {
-               super("Assure someone");
-               t = new Template(AssuranceForm.class.getResource("AssureeSearch.templ"));
-
-       }
-
-       @Override
-       public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
-
-               PrintWriter out = resp.getWriter();
-               String pi = req.getPathInfo().substring(PATH.length());
-               if (pi.length() > 1) {
-                       int mid = Integer.parseInt(pi.substring(1));
-                       AssuranceForm form = new AssuranceForm(req, mid);
-                       outputForm(req, out, mid, form);
-
-               } else {
-                       HashMap<String, Object> vars = new HashMap<String, Object>();
-                       vars.put("DoB", ds);
-                       t.output(out, getLanguage(req), vars);
-               }
-       }
-
-       private void outputForm(HttpServletRequest req, PrintWriter out, int mid, AssuranceForm form) {
-               User myself = LoginPage.getUser(req);
-               AssuranceResult check = Notary.checkAssuranceIsPossible(myself, new User(mid));
-               if (check != AssuranceResult.ASSURANCE_SUCCEDED) {
-                       out.println(translate(req, check.getMessage()));
-                       return;
-               }
-               if (form == null || form.assuree.getId() != mid) {
-                       form = new AssuranceForm(req, mid);
-               }
-
-               form.output(out, getLanguage(req), new HashMap<String, Object>());
-       }
-
-       @Override
-       public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
-               PrintWriter out = resp.getWriter();
-               String pi = req.getPathInfo().substring(PATH.length());
-               if (pi.length() > 1) {
-                       User myself = LoginPage.getUser(req);
-                       int mid = Integer.parseInt(pi.substring(1));
-                       if (mid == myself.getId()) {
-                               out.println(translate(req, "Cannot assure myself."));
-                               return;
-                       }
-
-                       AssuranceForm form = Form.getForm(req, AssuranceForm.class);
-                       if (mid != form.assuree.getId()) {
-                               return;
-                       }
-                       if (form.submit(out, req)) {
-                               out.println(translate(req, "Assurance complete."));
-                       } else {
-                               outputForm(req, resp.getWriter(), mid, form);
-                       }
-
-                       return;
-               }
-
-               ResultSet rs = null;
-               try {
-                       PreparedStatement ps = DatabaseConnection.getInstance().prepare(
-                               "SELECT id, verified FROM users WHERE email=? AND dob=? AND deleted=0");
-                       ps.setString(1, req.getParameter("email"));
-                       String day = req.getParameter("year") + "-" + req.getParameter("month") + "-" + req.getParameter("day");
-                       ps.setString(2, day);
-                       rs = ps.executeQuery();
-                       int id = 0;
-                       if (rs.next()) {
-                               id = rs.getInt(1);
-                               int verified = rs.getInt(2);
-                               if (rs.next()) {
-                                       out.println("Error, ambigous user. Please contact support@cacert.org.");
-                               } else {
-                                       if (verified == 0) {
-                                               out.println(translate(req, "User is not yet verified. Please try again in 24 hours!"));
-                                       }
-                                       resp.sendRedirect(PATH + "/" + id);
-                               }
-                       } else {
-                               out.print("<div class='formError'>");
-
-                               out.println(translate(req, "I'm sorry, there was no email and date of birth matching"
-                                       + " what you entered in the system. Please double check" + " your information."));
-                               out.print("</div>");
-                       }
-
-                       rs.close();
-               } catch (SQLException e) {
-                       e.printStackTrace();
-               } finally {
-                       try {
-                               if (rs != null) {
-                                       rs.close();
-                               }
-                       } catch (SQLException e) {
-                               e.printStackTrace();
-                       }
-               }
-       }
+
+    public static final String PATH = "/wot/assure";
+
+    DateSelector ds = new DateSelector("day", "month", "year");
+
+    Template t;
+
+    public AssurePage() {
+        super("Assure someone");
+        t = new Template(AssuranceForm.class.getResource("AssureeSearch.templ"));
+
+    }
+
+    @Override
+    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+
+        PrintWriter out = resp.getWriter();
+        String pi = req.getPathInfo().substring(PATH.length());
+        if (pi.length() > 1) {
+            int mid = Integer.parseInt(pi.substring(1));
+            AssuranceForm form = new AssuranceForm(req, mid);
+            outputForm(req, out, mid, form);
+
+        } else {
+            HashMap<String, Object> vars = new HashMap<String, Object>();
+            vars.put("DoB", ds);
+            t.output(out, getLanguage(req), vars);
+        }
+    }
+
+    private void outputForm(HttpServletRequest req, PrintWriter out, int mid, AssuranceForm form) {
+        User myself = LoginPage.getUser(req);
+        AssuranceResult check = Notary.checkAssuranceIsPossible(myself, new User(mid));
+        if (check != AssuranceResult.ASSURANCE_SUCCEDED) {
+            out.println(translate(req, check.getMessage()));
+            return;
+        }
+        if (form == null || form.assuree.getId() != mid) {
+            form = new AssuranceForm(req, mid);
+        }
+
+        form.output(out, getLanguage(req), new HashMap<String, Object>());
+    }
+
+    @Override
+    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+        PrintWriter out = resp.getWriter();
+        String pi = req.getPathInfo().substring(PATH.length());
+        if (pi.length() > 1) {
+            User myself = LoginPage.getUser(req);
+            int mid = Integer.parseInt(pi.substring(1));
+            if (mid == myself.getId()) {
+                out.println(translate(req, "Cannot assure myself."));
+                return;
+            }
+
+            AssuranceForm form = Form.getForm(req, AssuranceForm.class);
+            if (mid != form.assuree.getId()) {
+                return;
+            }
+            if (form.submit(out, req)) {
+                out.println(translate(req, "Assurance complete."));
+            } else {
+                outputForm(req, resp.getWriter(), mid, form);
+            }
+
+            return;
+        }
+
+        ResultSet rs = null;
+        try {
+            PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id, verified FROM users WHERE email=? AND dob=? AND deleted=0");
+            ps.setString(1, req.getParameter("email"));
+            String day = req.getParameter("year") + "-" + req.getParameter("month") + "-" + req.getParameter("day");
+            ps.setString(2, day);
+            rs = ps.executeQuery();
+            int id = 0;
+            if (rs.next()) {
+                id = rs.getInt(1);
+                int verified = rs.getInt(2);
+                if (rs.next()) {
+                    out.println("Error, ambigous user. Please contact support@cacert.org.");
+                } else {
+                    if (verified == 0) {
+                        out.println(translate(req, "User is not yet verified. Please try again in 24 hours!"));
+                    }
+                    resp.sendRedirect(PATH + "/" + id);
+                }
+            } else {
+                out.print("<div class='formError'>");
+
+                out.println(translate(req, "I'm sorry, there was no email and date of birth matching" + " what you entered in the system. Please double check" + " your information."));
+                out.print("</div>");
+            }
+
+            rs.close();
+        } catch (SQLException e) {
+            e.printStackTrace();
+        } finally {
+            try {
+                if (rs != null) {
+                    rs.close();
+                }
+            } catch (SQLException e) {
+                e.printStackTrace();
+            }
+        }
+    }
 }
index 3b4593894d8e8d3e11f6b7d0d78cc1a73ebd9533..ece3d1b9b36389de762885a364be998444e87e1a 100644 (file)
@@ -8,57 +8,62 @@ import java.util.LinkedList;
 
 public class DNSPinger extends DomainPinger {
 
-       @Override
-       public void ping(String domain, String configuration, String expToken) {
-               try {
-                       Process p = Runtime.getRuntime().exec(new String[] { "dig", "+short", "NS", domain });
-                       BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
-                       String line;
-                       LinkedList<String> nameservers = new LinkedList<String>();
-                       while ((line = br.readLine()) != null) {
-                               nameservers.add(line);
-                       }
-                       p.destroy();
-                       StringBuffer result = new StringBuffer();
-                       result.append("failed: ");
-                       boolean failed = nameservers.isEmpty();
-                       nameservers: for (String NS : nameservers) {
-                               String[] call = new String[] { "dig", "+short", "TXT", "cacert." + domain, NS };
-                               System.out.println(Arrays.toString(call));
-                               p = Runtime.getRuntime().exec(call);
-                               br = new BufferedReader(new InputStreamReader(p.getInputStream()));
-                               String token = null;
-                               boolean found = false;
-                               while ((line = br.readLine()) != null) {
-                                       if (line.isEmpty()) {
-                                               continue;
-                                       }
-                                       found = true;
-                                       token = line.substring(1, line.length() - 1);
-                                       if (token.equals(expToken)) {
-                                               continue nameservers;
-                                       }
-                               }
-                               p.destroy();
-                               result.append(NS);
-                               if (found) {
-                                       result.append(" DIFFER;");
-                               } else {
-                                       result.append(" EMPTY;");
-                               }
-                               failed = true;
+    @Override
+    public void ping(String domain, String configuration, String expToken) {
+        try {
+            Process p = Runtime.getRuntime().exec(new String[] {
+                    "dig", "+short", "NS", domain
+            });
+            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
+            String line;
+            LinkedList<String> nameservers = new LinkedList<String>();
+            while ((line = br.readLine()) != null) {
+                nameservers.add(line);
+            }
+            p.destroy();
+            StringBuffer result = new StringBuffer();
+            result.append("failed: ");
+            boolean failed = nameservers.isEmpty();
+            nameservers:
+            for (String NS : nameservers) {
+                String[] call = new String[] {
+                        "dig", "+short", "TXT", "cacert." + domain, NS
+                };
+                System.out.println(Arrays.toString(call));
+                p = Runtime.getRuntime().exec(call);
+                br = new BufferedReader(new InputStreamReader(p.getInputStream()));
+                String token = null;
+                boolean found = false;
+                while ((line = br.readLine()) != null) {
+                    if (line.isEmpty()) {
+                        continue;
+                    }
+                    found = true;
+                    token = line.substring(1, line.length() - 1);
+                    if (token.equals(expToken)) {
+                        continue nameservers;
+                    }
+                }
+                p.destroy();
+                result.append(NS);
+                if (found) {
+                    result.append(" DIFFER;");
+                } else {
+                    result.append(" EMPTY;");
+                }
+                failed = true;
 
-                       }
-                       if (!failed) {
-                               // Success
-                               return;
-                       }
-                       System.out.println(result.toString());
-               } catch (IOException e) {
-                       e.printStackTrace();
-                       // FAIL
-               }
-               // FAIL
-       }
+            }
+            if ( !failed) {
+                // Success
+                return;
+            }
+            System.out.println(result.toString());
+        } catch (IOException e) {
+            e.printStackTrace();
+            // FAIL
+        }
+        // FAIL
+    }
 
 }
index 8be4c2bf227c7b1deb01d845493a143162c6d876..c9c1584d2c58d624946da465ac063763e4949c55 100644 (file)
@@ -1,5 +1,6 @@
 package org.cacert.gigi.ping;
 
 public abstract class DomainPinger {
-       public abstract void ping(String domain, String configuration, String token);
+
+    public abstract void ping(String domain, String configuration, String token);
 }
index b4e88ea4c650e25f7e7cdf24384f3a69891b0b2a..de4990fc3f897472f590ab18ff2c74834f91d1a2 100644 (file)
@@ -7,23 +7,23 @@ import java.net.URL;
 
 public class HTTPFetch extends DomainPinger {
 
-       @Override
-       public void ping(String domain, String configuration, String expToken) {
-               try {
-                       URL u = new URL("http://" + domain + "/cacert_rai.txt");
-                       BufferedReader br = new BufferedReader(new InputStreamReader(u.openStream(), "UTF-8"));
-                       String line = br.readLine();
-                       if (line == null) {
-                               // empty
-                               return;
-                       }
-                       if (line.equals(expToken)) {
-                               // found
-                       }
-                       // differ
-               } catch (IOException e) {
-                       e.printStackTrace();
-                       // error
-               }
-       }
+    @Override
+    public void ping(String domain, String configuration, String expToken) {
+        try {
+            URL u = new URL("http://" + domain + "/cacert_rai.txt");
+            BufferedReader br = new BufferedReader(new InputStreamReader(u.openStream(), "UTF-8"));
+            String line = br.readLine();
+            if (line == null) {
+                // empty
+                return;
+            }
+            if (line.equals(expToken)) {
+                // found
+            }
+            // differ
+        } catch (IOException e) {
+            e.printStackTrace();
+            // error
+        }
+    }
 }
index 78adc12ac9e6a76bc4d08ec34675c77445ff25b9..d6ebe71c2a3b3f3dd60f8463f82a6f51097202fe 100644 (file)
@@ -22,173 +22,171 @@ import javax.security.cert.X509Certificate;
 
 public class SSLPinger extends DomainPinger {
 
-       @Override
-       public void ping(String domain, String configuration, String expToken) {
-               try {
-                       SocketChannel sch = SocketChannel.open();
-                       String[] parts = configuration.split(":", 2);
-                       sch.connect(new InetSocketAddress(domain, Integer.parseInt(parts[0])));
-                       if (parts.length == 2) {
-                               switch (parts[1]) {
-                               case "xmpp":
-                                       startXMPP(sch, false, domain);
-                                       break;
-                               case "server-xmpp":
-                                       startXMPP(sch, true, domain);
-                                       break;
-                               case "smtp":
-                                       startSMTP(sch);
-                                       break;
-                               case "imap":
-                                       startIMAP(sch);
-                                       break;
+    @Override
+    public void ping(String domain, String configuration, String expToken) {
+        try {
+            SocketChannel sch = SocketChannel.open();
+            String[] parts = configuration.split(":", 2);
+            sch.connect(new InetSocketAddress(domain, Integer.parseInt(parts[0])));
+            if (parts.length == 2) {
+                switch (parts[1]) {
+                case "xmpp":
+                    startXMPP(sch, false, domain);
+                    break;
+                case "server-xmpp":
+                    startXMPP(sch, true, domain);
+                    break;
+                case "smtp":
+                    startSMTP(sch);
+                    break;
+                case "imap":
+                    startIMAP(sch);
+                    break;
 
-                               }
-                       }
-                       test(sch, domain);
-               } catch (IOException e) {
-                       e.printStackTrace();
-               }
+                }
+            }
+            test(sch, domain);
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
 
-       }
+    }
 
-       private void startIMAP(SocketChannel sch) throws IOException {
-               Socket s = sch.socket();
-               InputStream is = s.getInputStream();
-               OutputStream os = s.getOutputStream();
-               scanFor(is, "\n");
-               os.write("ENABLE STARTTLS\r\n".getBytes());
-               os.flush();
-               scanFor(is, "\n");
-       }
+    private void startIMAP(SocketChannel sch) throws IOException {
+        Socket s = sch.socket();
+        InputStream is = s.getInputStream();
+        OutputStream os = s.getOutputStream();
+        scanFor(is, "\n");
+        os.write("ENABLE STARTTLS\r\n".getBytes());
+        os.flush();
+        scanFor(is, "\n");
+    }
 
-       private void startXMPP(SocketChannel sch, boolean server, String domain) throws IOException {
-               Socket s = sch.socket();
-               InputStream is = s.getInputStream();
-               OutputStream os = s.getOutputStream();
-               os.write(("<stream:stream to=\"" + domain + "\" xmlns=\"jabber:" + (server ? "server" : "client") + "\"" + " xmlns:stream=\"http://etherx.jabber.org/streams\" version=\"1.0\">")
-                       .getBytes());
-               os.flush();
-               os.write("<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>".getBytes());
-               os.flush();
-               scanFor(is, "<proceed");
-               scanFor(is, ">");
+    private void startXMPP(SocketChannel sch, boolean server, String domain) throws IOException {
+        Socket s = sch.socket();
+        InputStream is = s.getInputStream();
+        OutputStream os = s.getOutputStream();
+        os.write(("<stream:stream to=\"" + domain + "\" xmlns=\"jabber:" + (server ? "server" : "client") + "\"" + " xmlns:stream=\"http://etherx.jabber.org/streams\" version=\"1.0\">").getBytes());
+        os.flush();
+        os.write("<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>".getBytes());
+        os.flush();
+        scanFor(is, "<proceed");
+        scanFor(is, ">");
 
-       }
+    }
 
-       private void scanFor(InputStream is, String scanFor) throws IOException {
-               int pos = 0;
-               while (pos < scanFor.length()) {
-                       if (is.read() == scanFor.charAt(pos)) {
-                               pos++;
-                       } else {
-                               pos = 0;
-                       }
-               }
-       }
+    private void scanFor(InputStream is, String scanFor) throws IOException {
+        int pos = 0;
+        while (pos < scanFor.length()) {
+            if (is.read() == scanFor.charAt(pos)) {
+                pos++;
+            } else {
+                pos = 0;
+            }
+        }
+    }
 
-       private void startSMTP(SocketChannel sch) throws IOException {
-               Socket s = sch.socket();
-               InputStream is = s.getInputStream();
-               readSMTP(is);
-               s.getOutputStream().write("EHLO ssl.pinger\r\n".getBytes());
-               s.getOutputStream().flush();
-               readSMTP(is);
-               s.getOutputStream().write("HELP\r\n".getBytes());
-               s.getOutputStream().flush();
-               readSMTP(is);
-               s.getOutputStream().write("STARTTLS\r\n".getBytes());
-               s.getOutputStream().flush();
-               readSMTP(is);
-       }
+    private void startSMTP(SocketChannel sch) throws IOException {
+        Socket s = sch.socket();
+        InputStream is = s.getInputStream();
+        readSMTP(is);
+        s.getOutputStream().write("EHLO ssl.pinger\r\n".getBytes());
+        s.getOutputStream().flush();
+        readSMTP(is);
+        s.getOutputStream().write("HELP\r\n".getBytes());
+        s.getOutputStream().flush();
+        readSMTP(is);
+        s.getOutputStream().write("STARTTLS\r\n".getBytes());
+        s.getOutputStream().flush();
+        readSMTP(is);
+    }
 
-       private void readSMTP(InputStream is) throws IOException {
-               int counter = 0;
-               boolean finish = true;
-               while (true) {
-                       char c = (char) is.read();
-                       if (counter == 3) {
-                               if (c == ' ') {
-                                       finish = true;
-                               } else if (c == '-') {
-                                       finish = false;
-                               } else {
-                                       throw new Error("Invalid smtp: " + c);
-                               }
-                       }
-                       if (c == '\n') {
-                               if (finish) {
-                                       return;
-                               }
-                               counter = 0;
-                       } else {
-                               counter++;
-                       }
-               }
-       }
+    private void readSMTP(InputStream is) throws IOException {
+        int counter = 0;
+        boolean finish = true;
+        while (true) {
+            char c = (char) is.read();
+            if (counter == 3) {
+                if (c == ' ') {
+                    finish = true;
+                } else if (c == '-') {
+                    finish = false;
+                } else {
+                    throw new Error("Invalid smtp: " + c);
+                }
+            }
+            if (c == '\n') {
+                if (finish) {
+                    return;
+                }
+                counter = 0;
+            } else {
+                counter++;
+            }
+        }
+    }
 
-       private void test(SocketChannel sch, String domain) {
-               try {
-                       SSLContext sc = SSLContext.getDefault();
-                       SSLEngine se = sc.createSSLEngine();
-                       ByteBuffer enc_in = ByteBuffer.allocate(se.getSession().getPacketBufferSize());
-                       ByteBuffer enc_out = ByteBuffer.allocate(se.getSession().getPacketBufferSize());
-                       ByteBuffer dec_in = ByteBuffer.allocate(se.getSession().getApplicationBufferSize());
-                       ByteBuffer dec_out = ByteBuffer.allocate(se.getSession().getApplicationBufferSize());
-                       se.setUseClientMode(true);
-                       SSLParameters sp = se.getSSLParameters();
-                       sp.setServerNames(Arrays.<SNIServerName> asList(new SNIHostName(domain)));
-                       se.setSSLParameters(sp);
-                       se.beginHandshake();
-                       enc_in.limit(0);
-                       while (se.getHandshakeStatus() != HandshakeStatus.FINISHED
-                               && se.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING) {
-                               switch (se.getHandshakeStatus()) {
-                               case NEED_WRAP:
-                                       dec_out.limit(0);
-                                       se.wrap(dec_out, enc_out);
-                                       enc_out.flip();
-                                       while (enc_out.remaining() > 0) {
-                                               sch.write(enc_out);
-                                       }
-                                       enc_out.clear();
-                                       break;
-                               case NEED_UNWRAP:
-                                       if (enc_in.remaining() == 0) {
-                                               enc_in.clear();
-                                               sch.read(enc_in);
-                                               enc_in.flip();
-                                       }
-                                       while (se.unwrap(enc_in, dec_in).getStatus() == Status.BUFFER_UNDERFLOW) {
-                                               enc_in.position(enc_in.limit());
-                                               enc_in.limit(enc_in.capacity());
-                                               sch.read(enc_in);
-                                               enc_in.flip();
-                                       }
-                                       enc_in.compact();
-                                       enc_in.flip();
-                                       break;
-                               case NEED_TASK:
-                                       se.getDelegatedTask().run();
-                                       break;
-                               case NOT_HANDSHAKING:
-                               case FINISHED:
+    private void test(SocketChannel sch, String domain) {
+        try {
+            SSLContext sc = SSLContext.getDefault();
+            SSLEngine se = sc.createSSLEngine();
+            ByteBuffer enc_in = ByteBuffer.allocate(se.getSession().getPacketBufferSize());
+            ByteBuffer enc_out = ByteBuffer.allocate(se.getSession().getPacketBufferSize());
+            ByteBuffer dec_in = ByteBuffer.allocate(se.getSession().getApplicationBufferSize());
+            ByteBuffer dec_out = ByteBuffer.allocate(se.getSession().getApplicationBufferSize());
+            se.setUseClientMode(true);
+            SSLParameters sp = se.getSSLParameters();
+            sp.setServerNames(Arrays.<SNIServerName>asList(new SNIHostName(domain)));
+            se.setSSLParameters(sp);
+            se.beginHandshake();
+            enc_in.limit(0);
+            while (se.getHandshakeStatus() != HandshakeStatus.FINISHED && se.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING) {
+                switch (se.getHandshakeStatus()) {
+                case NEED_WRAP:
+                    dec_out.limit(0);
+                    se.wrap(dec_out, enc_out);
+                    enc_out.flip();
+                    while (enc_out.remaining() > 0) {
+                        sch.write(enc_out);
+                    }
+                    enc_out.clear();
+                    break;
+                case NEED_UNWRAP:
+                    if (enc_in.remaining() == 0) {
+                        enc_in.clear();
+                        sch.read(enc_in);
+                        enc_in.flip();
+                    }
+                    while (se.unwrap(enc_in, dec_in).getStatus() == Status.BUFFER_UNDERFLOW) {
+                        enc_in.position(enc_in.limit());
+                        enc_in.limit(enc_in.capacity());
+                        sch.read(enc_in);
+                        enc_in.flip();
+                    }
+                    enc_in.compact();
+                    enc_in.flip();
+                    break;
+                case NEED_TASK:
+                    se.getDelegatedTask().run();
+                    break;
+                case NOT_HANDSHAKING:
+                case FINISHED:
 
-                               }
+                }
 
-                       }
-                       System.out.println("completed");
-                       System.out.println(se.getSession().getCipherSuite());
-                       X509Certificate[] peerCertificateChain = se.getSession().getPeerCertificateChain();
-                       for (X509Certificate x509Certificate : peerCertificateChain) {
-                               System.out.println(x509Certificate.getSubjectDN().getName());
-                       }
-               } catch (NoSuchAlgorithmException e) {
-                       e.printStackTrace();
-               } catch (SSLException e) {
-                       e.printStackTrace();
-               } catch (IOException e) {
-                       e.printStackTrace();
-               }
-       }
+            }
+            System.out.println("completed");
+            System.out.println(se.getSession().getCipherSuite());
+            X509Certificate[] peerCertificateChain = se.getSession().getPeerCertificateChain();
+            for (X509Certificate x509Certificate : peerCertificateChain) {
+                System.out.println(x509Certificate.getSubjectDN().getName());
+            }
+        } catch (NoSuchAlgorithmException e) {
+            e.printStackTrace();
+        } catch (SSLException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
 }
index 4c20710a7db980246d334e9fdeb13f54f0220130..2508fae738a5e400722ec874c0635996002355f7 100644 (file)
@@ -10,281 +10,298 @@ import java.util.TreeSet;
 import sun.security.ssl.SSLContextImpl;
 
 public class CipherInfo implements Comparable<CipherInfo> {
-       private static class CipherInfoGenerator {
-               private Class<?> cipherSuite;
-               private Field cipherSuiteNameMap;
-               private Field exchange;
-               private Field cipher;
-               private Field keySize;
-               private Field algortihm;
-               private Field transformation;
-               private HashMap<?, ?> names;
-               private Field macAlg;
-               private Field macName;
-               private Field macSize;
-
-               public CipherInfoGenerator() throws ReflectiveOperationException {
-                       SSLContextImpl sc = new SSLContextImpl.TLS12Context();
-                       Method m = SSLContextImpl.class.getDeclaredMethod("getSupportedCipherSuiteList");
-                       m.setAccessible(true);
-                       Object o = m.invoke(sc);
-                       Class<?> cipherSuiteList = o.getClass();
-                       Method collection = cipherSuiteList.getDeclaredMethod("collection");
-                       collection.setAccessible(true);
-                       Collection<?> suites = (Collection<?>) collection.invoke(o);
-                       Object oneSuite = suites.iterator().next();
-                       cipherSuite = oneSuite.getClass();
-                       cipherSuiteNameMap = cipherSuite.getDeclaredField("nameMap");
-                       cipherSuiteNameMap.setAccessible(true);
-                       names = (HashMap<?, ?>) cipherSuiteNameMap.get(null);
-                       exchange = cipherSuite.getDeclaredField("keyExchange");
-                       exchange.setAccessible(true);
-                       cipher = cipherSuite.getDeclaredField("cipher");
-                       cipher.setAccessible(true);
-                       Class<?> bulkCipher = cipher.getType();
-                       keySize = bulkCipher.getDeclaredField("keySize");
-                       keySize.setAccessible(true);
-                       algortihm = bulkCipher.getDeclaredField("algorithm");
-                       algortihm.setAccessible(true);
-                       transformation = bulkCipher.getDeclaredField("transformation");
-                       transformation.setAccessible(true);
-
-                       macAlg = cipherSuite.getDeclaredField("macAlg");
-                       macAlg.setAccessible(true);
-                       Class<?> mac = macAlg.getType();
-                       macName = mac.getDeclaredField("name");
-                       macName.setAccessible(true);
-                       macSize = mac.getDeclaredField("size");
-                       macSize.setAccessible(true);
-               }
-
-               public CipherInfo generateInfo(String suiteName) throws IllegalArgumentException, IllegalAccessException {
-                       Object suite = names.get(suiteName);
-                       String keyExchange = exchange.get(suite).toString();
-                       Object bulkCipher = cipher.get(suite);
-                       Object mac = macAlg.get(suite);
-
-                       String transform = (String) transformation.get(bulkCipher);
-                       String[] transformationParts = transform.split("/");
-                       int keysize = keySize.getInt(bulkCipher);
-
-                       String macNam = (String) macName.get(mac);
-                       int macSiz = macSize.getInt(mac);
-
-                       String chaining = null;
-                       String padding = null;
-                       if (transformationParts.length > 1) {
-                               chaining = transformationParts[1];
-                               padding = transformationParts[2];
-                       }
-
-                       return new CipherInfo(suiteName, keyExchange, transformationParts[0], keysize * 8, chaining, padding,
-                               macNam, macSiz * 8);
-
-               }
-       }
-
-       String keyExchange;
-       String cipher;
-       int keySize;
-       String cipherChaining;
-       String cipherPadding;
-       String macName;
-       int macSize;
-       String suiteName;
-
-       private CipherInfo(String suiteName, String keyExchange, String cipher, int keySize, String cipherChaining,
-               String cipherPadding, String macName, int macSize) {
-               this.suiteName = suiteName;
-               this.keyExchange = keyExchange;
-               this.cipher = cipher;
-               this.keySize = keySize;
-               this.cipherChaining = cipherChaining;
-               this.cipherPadding = cipherPadding;
-               this.macName = macName;
-               this.macSize = macSize;
-       }
-
-       static CipherInfoGenerator cig;
-       static {
-               try {
-                       cig = new CipherInfoGenerator();
-               } catch (ReflectiveOperationException e) {
-                       e.printStackTrace();
-               }
-       }
-
-       public static CipherInfo generateInfo(String name) {
-               if (cig == null) {
-                       return null;
-               }
-               try {
-                       return cig.generateInfo(name);
-               } catch (IllegalArgumentException e) {
-                       e.printStackTrace();
-               } catch (IllegalAccessException e) {
-                       e.printStackTrace();
-               }
-               return null;
-       }
-
-       public String getSuiteName() {
-               return suiteName;
-       }
-
-       /**
-        * 5: ECDHE, AES||CAMELLIA, keysize >=256 <br>
-        * 4: DHE, AES||CAMELLIA, keysize >= 256<br>
-        * 3: ECDHE|| DHE, AES||CAMELLIA<br>
-        * 2: ECDHE||DHE<br>
-        * 1: RSA||DSA <br>
-        * 0: Others
-        * 
-        * @return the strength
-        */
-       public int getStrength() {
-               if (cipher.equals("NULL") || cipher.equals("RC4") || cipher.contains("DES")) {
-                       return 0;
-               }
-               boolean ecdhe = keyExchange.startsWith("ECDHE");
-               boolean dhe = keyExchange.startsWith("DHE");
-               boolean pfs = ecdhe || dhe;
-               boolean goodCipher = cipher.equals("AES") || cipher.equals("CAMELLIA");
-               if (ecdhe && goodCipher && keySize >= 256) {
-                       return 5;
-               }
-               if (dhe && goodCipher && keySize >= 256) {
-                       return 4;
-               }
-               if (pfs && goodCipher) {
-                       return 3;
-               }
-               if (pfs) {
-                       return 2;
-               }
-               if (keyExchange.equals("RSA") || keyExchange.equals("DSA")) {
-                       return 1;
-               }
-               return 0;
-       }
-
-       private static final String[] CIPHER_RANKING = new String[] { "CAMELLIA", "AES", "RC4", "3DES", "DES", "DES40" };
-
-       @Override
-       public String toString() {
-               return "CipherInfo [keyExchange=" + keyExchange + ", cipher=" + cipher + ", keySize=" + keySize
-                       + ", cipherChaining=" + cipherChaining + ", cipherPadding=" + cipherPadding + ", macName=" + macName
-                       + ", macSize=" + macSize + "]";
-       }
-
-       /**
-        * ECDHE<br>
-        * GCM<br>
-        * Cipher {@link #CIPHER_RANKING}<br>
-        * Cipher {@link #keySize}<br>
-        * HMAC<br>
-        * HMAC size<br>
-        * 
-        * @return
-        */
-       @Override
-       public int compareTo(CipherInfo o) {
-               int myStrength = getStrength();
-               int oStrength = o.getStrength();
-               if (myStrength > oStrength) {
-                       return -1;
-               }
-               if (myStrength < oStrength) {
-                       return 1;
-               }
-               // TODO sort SSL/TLS
-               boolean myEcdhe = keyExchange.startsWith("ECDHE");
-               boolean oEcdhe = o.keyExchange.startsWith("ECDHE");
-               if (myEcdhe && !oEcdhe) {
-                       return -1;
-               }
-               if (!myEcdhe && oEcdhe) {
-                       return 1;
-               }
-               boolean myGCM = "GCM".equals(cipherChaining);
-               boolean oGCM = "GCM".equals(o.cipherChaining);
-               if (myGCM && !oGCM) {
-                       return -1;
-               }
-               if (!myGCM && oGCM) {
-                       return 1;
-               }
-               if (!cipher.equals(o.cipher)) {
-
-                       for (String testCipher : CIPHER_RANKING) {
-                               if (cipher.equals(testCipher)) {
-                                       return -1;
-                               }
-                               if (o.cipher.equals(testCipher)) {
-                                       return 1;
-                               }
-                       }
-                       if (cipher.equals("NULL")) {
-                               return 1;
-                       }
-                       if (o.cipher.equals("NULL")) {
-                               return -1;
-                       }
-               }
-               if (keySize > o.keySize) {
-                       return -1;
-               }
-               if (keySize < o.keySize) {
-                       return 1;
-               }
-               boolean mySHA = macName.startsWith("SHA");
-               boolean oSHA = o.macName.startsWith("SHA");
-               if (mySHA && !oSHA) {
-                       return -1;
-               }
-               if (mySHA && !oSHA) {
-                       return 1;
-               }
-               if (macSize > o.macSize) {
-                       return -1;
-               }
-               if (macSize < o.macSize) {
-                       return 1;
-               }
-
-               return suiteName.compareTo(o.suiteName);
-       }
-
-       static String[] cipherRanking = null;
-
-       public static String[] getCompleteRanking() {
-               if (cipherRanking == null) {
-                       String[] ciphers = filterCiphers((Iterable<String>) cig.names.keySet());
-                       cipherRanking = ciphers;
-               }
-               return cipherRanking;
-       }
-
-       private static String[] filterCiphers(Iterable<String> toFilter) {
-               TreeSet<CipherInfo> chosenCiphers = new TreeSet<CipherInfo>();
-               for (String o : toFilter) {
-                       String s = o;
-                       CipherInfo info = CipherInfo.generateInfo(s);
-                       if (info != null) {
-                               if (info.getStrength() > 1) {
-                                       chosenCiphers.add(info);
-                               }
-                       }
-               }
-               String[] ciphers = new String[chosenCiphers.size()];
-               int counter = 0;
-               for (CipherInfo i : chosenCiphers) {
-                       ciphers[counter++] = i.getSuiteName();
-               }
-               return ciphers;
-       }
-
-       public static String[] filter(String[] supportedCipherSuites) {
-               return filterCiphers(Arrays.asList(supportedCipherSuites));
-       }
+
+    private static class CipherInfoGenerator {
+
+        private Class<?> cipherSuite;
+
+        private Field cipherSuiteNameMap;
+
+        private Field exchange;
+
+        private Field cipher;
+
+        private Field keySize;
+
+        private Field algortihm;
+
+        private Field transformation;
+
+        private HashMap<?, ?> names;
+
+        private Field macAlg;
+
+        private Field macName;
+
+        private Field macSize;
+
+        public CipherInfoGenerator() throws ReflectiveOperationException {
+            SSLContextImpl sc = new SSLContextImpl.TLS12Context();
+            Method m = SSLContextImpl.class.getDeclaredMethod("getSupportedCipherSuiteList");
+            m.setAccessible(true);
+            Object o = m.invoke(sc);
+            Class<?> cipherSuiteList = o.getClass();
+            Method collection = cipherSuiteList.getDeclaredMethod("collection");
+            collection.setAccessible(true);
+            Collection<?> suites = (Collection<?>) collection.invoke(o);
+            Object oneSuite = suites.iterator().next();
+            cipherSuite = oneSuite.getClass();
+            cipherSuiteNameMap = cipherSuite.getDeclaredField("nameMap");
+            cipherSuiteNameMap.setAccessible(true);
+            names = (HashMap<?, ?>) cipherSuiteNameMap.get(null);
+            exchange = cipherSuite.getDeclaredField("keyExchange");
+            exchange.setAccessible(true);
+            cipher = cipherSuite.getDeclaredField("cipher");
+            cipher.setAccessible(true);
+            Class<?> bulkCipher = cipher.getType();
+            keySize = bulkCipher.getDeclaredField("keySize");
+            keySize.setAccessible(true);
+            algortihm = bulkCipher.getDeclaredField("algorithm");
+            algortihm.setAccessible(true);
+            transformation = bulkCipher.getDeclaredField("transformation");
+            transformation.setAccessible(true);
+
+            macAlg = cipherSuite.getDeclaredField("macAlg");
+            macAlg.setAccessible(true);
+            Class<?> mac = macAlg.getType();
+            macName = mac.getDeclaredField("name");
+            macName.setAccessible(true);
+            macSize = mac.getDeclaredField("size");
+            macSize.setAccessible(true);
+        }
+
+        public CipherInfo generateInfo(String suiteName) throws IllegalArgumentException, IllegalAccessException {
+            Object suite = names.get(suiteName);
+            String keyExchange = exchange.get(suite).toString();
+            Object bulkCipher = cipher.get(suite);
+            Object mac = macAlg.get(suite);
+
+            String transform = (String) transformation.get(bulkCipher);
+            String[] transformationParts = transform.split("/");
+            int keysize = keySize.getInt(bulkCipher);
+
+            String macNam = (String) macName.get(mac);
+            int macSiz = macSize.getInt(mac);
+
+            String chaining = null;
+            String padding = null;
+            if (transformationParts.length > 1) {
+                chaining = transformationParts[1];
+                padding = transformationParts[2];
+            }
+
+            return new CipherInfo(suiteName, keyExchange, transformationParts[0], keysize * 8, chaining, padding, macNam, macSiz * 8);
+
+        }
+    }
+
+    String keyExchange;
+
+    String cipher;
+
+    int keySize;
+
+    String cipherChaining;
+
+    String cipherPadding;
+
+    String macName;
+
+    int macSize;
+
+    String suiteName;
+
+    private CipherInfo(String suiteName, String keyExchange, String cipher, int keySize, String cipherChaining, String cipherPadding, String macName, int macSize) {
+        this.suiteName = suiteName;
+        this.keyExchange = keyExchange;
+        this.cipher = cipher;
+        this.keySize = keySize;
+        this.cipherChaining = cipherChaining;
+        this.cipherPadding = cipherPadding;
+        this.macName = macName;
+        this.macSize = macSize;
+    }
+
+    static CipherInfoGenerator cig;
+    static {
+        try {
+            cig = new CipherInfoGenerator();
+        } catch (ReflectiveOperationException e) {
+            e.printStackTrace();
+        }
+    }
+
+    public static CipherInfo generateInfo(String name) {
+        if (cig == null) {
+            return null;
+        }
+        try {
+            return cig.generateInfo(name);
+        } catch (IllegalArgumentException e) {
+            e.printStackTrace();
+        } catch (IllegalAccessException e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+    public String getSuiteName() {
+        return suiteName;
+    }
+
+    /**
+     * 5: ECDHE, AES||CAMELLIA, keysize >=256 <br>
+     * 4: DHE, AES||CAMELLIA, keysize >= 256<br>
+     * 3: ECDHE|| DHE, AES||CAMELLIA<br>
+     * 2: ECDHE||DHE<br>
+     * 1: RSA||DSA <br>
+     * 0: Others
+     * 
+     * @return the strength
+     */
+    public int getStrength() {
+        if (cipher.equals("NULL") || cipher.equals("RC4") || cipher.contains("DES")) {
+            return 0;
+        }
+        boolean ecdhe = keyExchange.startsWith("ECDHE");
+        boolean dhe = keyExchange.startsWith("DHE");
+        boolean pfs = ecdhe || dhe;
+        boolean goodCipher = cipher.equals("AES") || cipher.equals("CAMELLIA");
+        if (ecdhe && goodCipher && keySize >= 256) {
+            return 5;
+        }
+        if (dhe && goodCipher && keySize >= 256) {
+            return 4;
+        }
+        if (pfs && goodCipher) {
+            return 3;
+        }
+        if (pfs) {
+            return 2;
+        }
+        if (keyExchange.equals("RSA") || keyExchange.equals("DSA")) {
+            return 1;
+        }
+        return 0;
+    }
+
+    private static final String[] CIPHER_RANKING = new String[] {
+            "CAMELLIA", "AES", "RC4", "3DES", "DES", "DES40"
+    };
+
+    @Override
+    public String toString() {
+        return "CipherInfo [keyExchange=" + keyExchange + ", cipher=" + cipher + ", keySize=" + keySize + ", cipherChaining=" + cipherChaining + ", cipherPadding=" + cipherPadding + ", macName=" + macName + ", macSize=" + macSize + "]";
+    }
+
+    /**
+     * ECDHE<br>
+     * GCM<br>
+     * Cipher {@link #CIPHER_RANKING}<br>
+     * Cipher {@link #keySize}<br>
+     * HMAC<br>
+     * HMAC size<br>
+     * 
+     * @return
+     */
+    @Override
+    public int compareTo(CipherInfo o) {
+        int myStrength = getStrength();
+        int oStrength = o.getStrength();
+        if (myStrength > oStrength) {
+            return -1;
+        }
+        if (myStrength < oStrength) {
+            return 1;
+        }
+        // TODO sort SSL/TLS
+        boolean myEcdhe = keyExchange.startsWith("ECDHE");
+        boolean oEcdhe = o.keyExchange.startsWith("ECDHE");
+        if (myEcdhe && !oEcdhe) {
+            return -1;
+        }
+        if ( !myEcdhe && oEcdhe) {
+            return 1;
+        }
+        boolean myGCM = "GCM".equals(cipherChaining);
+        boolean oGCM = "GCM".equals(o.cipherChaining);
+        if (myGCM && !oGCM) {
+            return -1;
+        }
+        if ( !myGCM && oGCM) {
+            return 1;
+        }
+        if ( !cipher.equals(o.cipher)) {
+
+            for (String testCipher : CIPHER_RANKING) {
+                if (cipher.equals(testCipher)) {
+                    return -1;
+                }
+                if (o.cipher.equals(testCipher)) {
+                    return 1;
+                }
+            }
+            if (cipher.equals("NULL")) {
+                return 1;
+            }
+            if (o.cipher.equals("NULL")) {
+                return -1;
+            }
+        }
+        if (keySize > o.keySize) {
+            return -1;
+        }
+        if (keySize < o.keySize) {
+            return 1;
+        }
+        boolean mySHA = macName.startsWith("SHA");
+        boolean oSHA = o.macName.startsWith("SHA");
+        if (mySHA && !oSHA) {
+            return -1;
+        }
+        if (mySHA && !oSHA) {
+            return 1;
+        }
+        if (macSize > o.macSize) {
+            return -1;
+        }
+        if (macSize < o.macSize) {
+            return 1;
+        }
+
+        return suiteName.compareTo(o.suiteName);
+    }
+
+    static String[] cipherRanking = null;
+
+    public static String[] getCompleteRanking() {
+        if (cipherRanking == null) {
+            String[] ciphers = filterCiphers((Iterable<String>) cig.names.keySet());
+            cipherRanking = ciphers;
+        }
+        return cipherRanking;
+    }
+
+    private static String[] filterCiphers(Iterable<String> toFilter) {
+        TreeSet<CipherInfo> chosenCiphers = new TreeSet<CipherInfo>();
+        for (String o : toFilter) {
+            String s = o;
+            CipherInfo info = CipherInfo.generateInfo(s);
+            if (info != null) {
+                if (info.getStrength() > 1) {
+                    chosenCiphers.add(info);
+                }
+            }
+        }
+        String[] ciphers = new String[chosenCiphers.size()];
+        int counter = 0;
+        for (CipherInfo i : chosenCiphers) {
+            ciphers[counter++] = i.getSuiteName();
+        }
+        return ciphers;
+    }
+
+    public static String[] filter(String[] supportedCipherSuites) {
+        return filterCiphers(Arrays.asList(supportedCipherSuites));
+    }
 }
index 9303d8d95737dad979b40e05b91e4f7e89e852d6..ed943cbe103f435d631f109546ca955817cf0583 100644 (file)
@@ -1,12 +1,13 @@
 package org.cacert.gigi.util;
 
 public class HTMLEncoder {
-       public static String encodeHTML(String s) {
-               s = s.replace("&", "&amp;");
-               s = s.replace("<", "&lt;");
-               s = s.replace(">", "&gt;");
-               s = s.replace("\"", "&quot;");
-               s = s.replace("'", "&#39;");
-               return s;
-       }
+
+    public static String encodeHTML(String s) {
+        s = s.replace("&", "&amp;");
+        s = s.replace("<", "&lt;");
+        s = s.replace(">", "&gt;");
+        s = s.replace("\"", "&quot;");
+        s = s.replace("'", "&#39;");
+        return s;
+    }
 }
index 70c9d569714cd091788cbea36f9d8b8bcabd0c08..13e6c7e0c1c5c768f0888ee7c3c977b4a016a8e4 100644 (file)
@@ -8,48 +8,49 @@ import org.cacert.gigi.Certificate;
 import org.cacert.gigi.database.DatabaseConnection;
 
 public class Job {
-       int id;
-
-       private Job(int id) {
-               this.id = id;
-       }
-
-       public static enum JobType {
-               SIGN("sign"), REVOKE("revoke");
-               private final String name;
-
-               private JobType(String name) {
-                       this.name = name;
-               }
-
-               public String getName() {
-                       return name;
-               }
-       }
-
-       public static Job submit(Certificate targetId, JobType type) throws SQLException {
-               PreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `jobs` SET targetId=?, task=?");
-               ps.setInt(1, targetId.getId());
-               ps.setString(2, type.getName());
-               ps.execute();
-               return new Job(DatabaseConnection.lastInsertId(ps));
-       }
-
-       public boolean waitFor(int max) throws SQLException, InterruptedException {
-               long start = System.currentTimeMillis();
-               PreparedStatement ps = DatabaseConnection.getInstance().prepare(
-                       "SELECT 1 FROM `jobs` WHERE id=? AND state='open'");
-               ps.setInt(1, id);
-               ResultSet rs = ps.executeQuery();
-               while (rs.next()) {
-                       rs.close();
-                       if (max != 0 && System.currentTimeMillis() - start > max) {
-                               return false;
-                       }
-                       Thread.sleep((long) (2000 + Math.random() * 2000));
-                       rs = ps.executeQuery();
-               }
-               rs.close();
-               return true;
-       }
+
+    int id;
+
+    private Job(int id) {
+        this.id = id;
+    }
+
+    public static enum JobType {
+        SIGN("sign"), REVOKE("revoke");
+
+        private final String name;
+
+        private JobType(String name) {
+            this.name = name;
+        }
+
+        public String getName() {
+            return name;
+        }
+    }
+
+    public static Job submit(Certificate targetId, JobType type) throws SQLException {
+        PreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `jobs` SET targetId=?, task=?");
+        ps.setInt(1, targetId.getId());
+        ps.setString(2, type.getName());
+        ps.execute();
+        return new Job(DatabaseConnection.lastInsertId(ps));
+    }
+
+    public boolean waitFor(int max) throws SQLException, InterruptedException {
+        long start = System.currentTimeMillis();
+        PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT 1 FROM `jobs` WHERE id=? AND state='open'");
+        ps.setInt(1, id);
+        ResultSet rs = ps.executeQuery();
+        while (rs.next()) {
+            rs.close();
+            if (max != 0 && System.currentTimeMillis() - start > max) {
+                return false;
+            }
+            Thread.sleep((long) (2000 + Math.random() * 2000));
+            rs = ps.executeQuery();
+        }
+        rs.close();
+        return true;
+    }
 }
index 6bac57c011591987517879222460adf53dc46c28..9b3f11eb14dfd4a901a2f1bb7212382770f6f08e 100644 (file)
@@ -3,18 +3,20 @@ package org.cacert.gigi.util;
 import java.io.File;
 
 public class KeyStorage {
-       private static final File csr = new File("keys/csr");
-       private static final File crt = new File("keys/crt");
 
-       public static File locateCrt(int id) {
-               File parent = new File(crt, (id / 1000) + "");
-               parent.mkdirs();
-               return new File(parent, id + ".crt");
-       }
+    private static final File csr = new File("keys/csr");
 
-       public static File locateCsr(int id) {
-               File parent = new File(csr, (id / 1000) + "");
-               parent.mkdirs();
-               return new File(parent, id + ".csr");
-       }
+    private static final File crt = new File("keys/crt");
+
+    public static File locateCrt(int id) {
+        File parent = new File(crt, (id / 1000) + "");
+        parent.mkdirs();
+        return new File(parent, id + ".crt");
+    }
+
+    public static File locateCsr(int id) {
+        File parent = new File(csr, (id / 1000) + "");
+        parent.mkdirs();
+        return new File(parent, id + ".csr");
+    }
 }
index 7cd38e37080d9557978aadee889c086ecfc329d0..89fb5bc0837e90f4274272bfb621371f033461c9 100644 (file)
@@ -8,81 +8,75 @@ import org.cacert.gigi.User;
 import org.cacert.gigi.database.DatabaseConnection;
 
 public class Notary {
-       public static void writeUserAgreement(int memid, String document, String method, String comment, boolean active,
-               int secmemid) throws SQLException {
-               PreparedStatement q = DatabaseConnection.getInstance().prepare(
-                       "insert into `user_agreements` set `memid`=?, `secmemid`=?,"
-                               + " `document`=?,`date`=NOW(), `active`=?,`method`=?,`comment`=?");
-               q.setInt(1, memid);
-               q.setInt(2, secmemid);
-               q.setString(3, document);
-               q.setInt(4, active ? 1 : 0);
-               q.setString(5, method);
-               q.setString(6, comment);
-               q.execute();
-       }
 
-       public static AssuranceResult checkAssuranceIsPossible(User assurer, User target) {
-               if (assurer.getId() == target.getId()) {
-                       return AssuranceResult.CANNOT_ASSURE_SELF;
-               }
-               try {
-                       PreparedStatement ps = DatabaseConnection.getInstance().prepare(
-                               "SELECT 1 FROM `notary` where `to`=? and `from`=? AND `deleted`=0");
-                       ps.setInt(1, target.getId());
-                       ps.setInt(2, assurer.getId());
-                       ResultSet rs = ps.executeQuery();
-                       if (rs.next()) {
-                               rs.close();
-                               return AssuranceResult.ALREADY_ASSUREED;
-                       }
-                       rs.close();
-                       if (!assurer.canAssure()) {
-                               return AssuranceResult.CANNOT_ASSURE;
-                       }
-               } catch (SQLException e) {
-                       e.printStackTrace();
-               }
-               return AssuranceResult.ASSURANCE_SUCCEDED;
-       }
+    public static void writeUserAgreement(int memid, String document, String method, String comment, boolean active, int secmemid) throws SQLException {
+        PreparedStatement q = DatabaseConnection.getInstance().prepare("insert into `user_agreements` set `memid`=?, `secmemid`=?," + " `document`=?,`date`=NOW(), `active`=?,`method`=?,`comment`=?");
+        q.setInt(1, memid);
+        q.setInt(2, secmemid);
+        q.setString(3, document);
+        q.setInt(4, active ? 1 : 0);
+        q.setString(5, method);
+        q.setString(6, comment);
+        q.execute();
+    }
 
-       public enum AssuranceResult {
-               CANNOT_ASSURE("You cannot assure."), ALREADY_ASSUREED("You already assured this person."), CANNOT_ASSURE_SELF(
-                       "Cannot assure myself."), ASSURANCE_SUCCEDED(""), ASSUREE_CHANGED(
-                       "Person details changed. Please start over again."), POINTS_OUT_OF_RANGE("Points out of range.");
-               private final String message;
+    public static AssuranceResult checkAssuranceIsPossible(User assurer, User target) {
+        if (assurer.getId() == target.getId()) {
+            return AssuranceResult.CANNOT_ASSURE_SELF;
+        }
+        try {
+            PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT 1 FROM `notary` where `to`=? and `from`=? AND `deleted`=0");
+            ps.setInt(1, target.getId());
+            ps.setInt(2, assurer.getId());
+            ResultSet rs = ps.executeQuery();
+            if (rs.next()) {
+                rs.close();
+                return AssuranceResult.ALREADY_ASSUREED;
+            }
+            rs.close();
+            if ( !assurer.canAssure()) {
+                return AssuranceResult.CANNOT_ASSURE;
+            }
+        } catch (SQLException e) {
+            e.printStackTrace();
+        }
+        return AssuranceResult.ASSURANCE_SUCCEDED;
+    }
 
-               private AssuranceResult(String message) {
-                       this.message = message;
-               }
+    public enum AssuranceResult {
+        CANNOT_ASSURE("You cannot assure."), ALREADY_ASSUREED("You already assured this person."), CANNOT_ASSURE_SELF("Cannot assure myself."), ASSURANCE_SUCCEDED(""), ASSUREE_CHANGED("Person details changed. Please start over again."), POINTS_OUT_OF_RANGE("Points out of range.");
 
-               public String getMessage() {
-                       return message;
-               }
-       }
+        private final String message;
 
-       public synchronized static AssuranceResult assure(User assurer, User target, int awarded, String location,
-               String date) throws SQLException {
-               AssuranceResult can = checkAssuranceIsPossible(assurer, target);
-               if (can != AssuranceResult.ASSURANCE_SUCCEDED) {
-                       return can;
-               }
-               User u = new User(target.getId());
-               if (!u.equals(target)) {
-                       return AssuranceResult.ASSUREE_CHANGED;
-               }
-               if (awarded > assurer.getMaxAssurePoints() || awarded < 0) {
-                       return AssuranceResult.POINTS_OUT_OF_RANGE;
-               }
+        private AssuranceResult(String message) {
+            this.message = message;
+        }
 
-               PreparedStatement ps = DatabaseConnection.getInstance().prepare(
-                       "INSERT INTO `notary` SET `from`=?, `to`=?, `points`=?, `location`=?, `date`=?");
-               ps.setInt(1, assurer.getId());
-               ps.setInt(2, target.getId());
-               ps.setInt(3, awarded);
-               ps.setString(4, location);
-               ps.setString(5, date);
-               ps.execute();
-               return AssuranceResult.ASSURANCE_SUCCEDED;
-       }
+        public String getMessage() {
+            return message;
+        }
+    }
+
+    public synchronized static AssuranceResult assure(User assurer, User target, int awarded, String location, String date) throws SQLException {
+        AssuranceResult can = checkAssuranceIsPossible(assurer, target);
+        if (can != AssuranceResult.ASSURANCE_SUCCEDED) {
+            return can;
+        }
+        User u = new User(target.getId());
+        if ( !u.equals(target)) {
+            return AssuranceResult.ASSUREE_CHANGED;
+        }
+        if (awarded > assurer.getMaxAssurePoints() || awarded < 0) {
+            return AssuranceResult.POINTS_OUT_OF_RANGE;
+        }
+
+        PreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `notary` SET `from`=?, `to`=?, `points`=?, `location`=?, `date`=?");
+        ps.setInt(1, assurer.getId());
+        ps.setInt(2, target.getId());
+        ps.setInt(3, awarded);
+        ps.setString(4, location);
+        ps.setString(5, date);
+        ps.execute();
+        return AssuranceResult.ASSURANCE_SUCCEDED;
+    }
 }
index 71f7547979c9ae06c5a83ca2530fd0d9ca4763be..aaff22686389c974b7b856e9914f11a91d104146 100644 (file)
@@ -4,34 +4,35 @@ import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
 
 public class PasswordHash {
-       public static boolean verifyHash(String password, String hash) {
-               String newhash = sha1(password);
-               boolean match = true;
-               if (newhash.length() != hash.length()) {
-                       match = false;
-               }
-               for (int i = 0; i < newhash.length(); i++) {
-                       match &= newhash.charAt(i) == hash.charAt(i);
-               }
-               return match;
-       }
 
-       private static String sha1(String password) {
-               try {
-                       MessageDigest md = MessageDigest.getInstance("SHA1");
-                       byte[] digest = md.digest(password.getBytes());
-                       StringBuffer res = new StringBuffer(digest.length * 2);
-                       for (int i = 0; i < digest.length; i++) {
-                               res.append(Integer.toHexString((digest[i] & 0xF0) >> 4));
-                               res.append(Integer.toHexString(digest[i] & 0xF));
-                       }
-                       return res.toString();
-               } catch (NoSuchAlgorithmException e) {
-                       throw new Error(e);
-               }
-       }
+    public static boolean verifyHash(String password, String hash) {
+        String newhash = sha1(password);
+        boolean match = true;
+        if (newhash.length() != hash.length()) {
+            match = false;
+        }
+        for (int i = 0; i < newhash.length(); i++) {
+            match &= newhash.charAt(i) == hash.charAt(i);
+        }
+        return match;
+    }
 
-       public static String hash(String password) {
-               return sha1(password);
-       }
+    private static String sha1(String password) {
+        try {
+            MessageDigest md = MessageDigest.getInstance("SHA1");
+            byte[] digest = md.digest(password.getBytes());
+            StringBuffer res = new StringBuffer(digest.length * 2);
+            for (int i = 0; i < digest.length; i++) {
+                res.append(Integer.toHexString((digest[i] & 0xF0) >> 4));
+                res.append(Integer.toHexString(digest[i] & 0xF));
+            }
+            return res.toString();
+        } catch (NoSuchAlgorithmException e) {
+            throw new Error(e);
+        }
+    }
+
+    public static String hash(String password) {
+        return sha1(password);
+    }
 }
index 3e4760bbf2b86c47fd53766fbbe5be89b26e0327..e52c1dd07d080a5544fa3426bb3ed8a96e2d50e9 100644 (file)
@@ -6,88 +6,91 @@ import org.cacert.gigi.GigiApiException;
 import org.cacert.gigi.User;
 
 public class PasswordStrengthChecker {
-       static Pattern digits = Pattern.compile("\\d");
-       static Pattern lower = Pattern.compile("[a-z]");
-       static Pattern upper = Pattern.compile("[A-Z]");
-       static Pattern whitespace = Pattern.compile("\\s");
-       static Pattern special = Pattern.compile("(?!\\s)\\W");
 
-       private PasswordStrengthChecker() {
-       }
+    static Pattern digits = Pattern.compile("\\d");
 
-       private static int checkpwlight(String pw) {
-               int points = 0;
-               if (pw.length() > 15) {
-                       points++;
-               }
-               if (pw.length() > 20) {
-                       points++;
-               }
-               if (pw.length() > 25) {
-                       points++;
-               }
-               if (pw.length() > 30) {
-                       points++;
-               }
-               if (digits.matcher(pw).find()) {
-                       points++;
-               }
-               if (lower.matcher(pw).find()) {
-                       points++;
-               }
-               if (upper.matcher(pw).find()) {
-                       points++;
-               }
-               if (special.matcher(pw).find()) {
-                       points++;
-               }
-               if (whitespace.matcher(pw).find()) {
-                       points++;
-               }
-               return points;
-       }
+    static Pattern lower = Pattern.compile("[a-z]");
 
-       public static int checkpw(String pw, User u) {
-               if (pw == null) {
-                       return 0;
-               }
-               int light = checkpwlight(pw);
-               if (contained(pw, u.getEmail())) {
-                       light -= 2;
-               }
-               if (contained(pw, u.getFname())) {
-                       light -= 2;
-               }
-               if (contained(pw, u.getLname())) {
-                       light -= 2;
-               }
-               if (contained(pw, u.getMname())) {
-                       light -= 2;
-               }
-               if (contained(pw, u.getSuffix())) {
-                       light -= 2;
-               }
-               // TODO dictionary check
-               return light;
-       }
+    static Pattern upper = Pattern.compile("[A-Z]");
 
-       public static void assertStrongPassword(String pw, User u) throws GigiApiException {
-               if (checkpw(pw, u) < 3) {
-                       throw new GigiApiException("The Pass Phrase you submitted failed to contain enough"
-                               + " differing characters and/or contained words from" + " your name and/or email address.");
-               }
-       }
+    static Pattern whitespace = Pattern.compile("\\s");
 
-       private static boolean contained(String pw, String check) {
-               if (check == null || check.equals("")) {
-                       return false;
-               }
-               if (pw.contains(check)) {
-                       return true;
-               }
-               if (check.contains(pw)) {
-                       return true;
-               }
-               return false;
-       }
+    static Pattern special = Pattern.compile("(?!\\s)\\W");
+
+    private PasswordStrengthChecker() {}
+
+    private static int checkpwlight(String pw) {
+        int points = 0;
+        if (pw.length() > 15) {
+            points++;
+        }
+        if (pw.length() > 20) {
+            points++;
+        }
+        if (pw.length() > 25) {
+            points++;
+        }
+        if (pw.length() > 30) {
+            points++;
+        }
+        if (digits.matcher(pw).find()) {
+            points++;
+        }
+        if (lower.matcher(pw).find()) {
+            points++;
+        }
+        if (upper.matcher(pw).find()) {
+            points++;
+        }
+        if (special.matcher(pw).find()) {
+            points++;
+        }
+        if (whitespace.matcher(pw).find()) {
+            points++;
+        }
+        return points;
+    }
+
+    public static int checkpw(String pw, User u) {
+        if (pw == null) {
+            return 0;
+        }
+        int light = checkpwlight(pw);
+        if (contained(pw, u.getEmail())) {
+            light -= 2;
+        }
+        if (contained(pw, u.getFname())) {
+            light -= 2;
+        }
+        if (contained(pw, u.getLname())) {
+            light -= 2;
+        }
+        if (contained(pw, u.getMname())) {
+            light -= 2;
+        }
+        if (contained(pw, u.getSuffix())) {
+            light -= 2;
+        }
+        // TODO dictionary check
+        return light;
+    }
+
+    public static void assertStrongPassword(String pw, User u) throws GigiApiException {
+        if (checkpw(pw, u) < 3) {
+            throw new GigiApiException("The Pass Phrase you submitted failed to contain enough" + " differing characters and/or contained words from" + " your name and/or email address.");
+        }
+    }
+
+    private static boolean contained(String pw, String check) {
+        if (check == null || check.equals("")) {
+            return false;
+        }
+        if (pw.contains(check)) {
+            return true;
+        }
+        if (check.contains(pw)) {
+            return true;
+        }
+        return false;
+    }
 }
index b84ee0372e7a08f1c36aca99464fc63dedce7d80..0c1035d6f9813b5f0234c9af8b10487325de4feb 100644 (file)
@@ -3,24 +3,25 @@ package org.cacert.gigi.util;
 import java.security.SecureRandom;
 
 public class RandomToken {
-       static SecureRandom sr = new SecureRandom();
 
-       public static String generateToken(int length) {
-               StringBuffer token = new StringBuffer();
-               for (int i = 0; i < length; i++) {
-                       int rand = sr.nextInt(26 * 2 + 10);
-                       if (rand < 10) {
-                               token.append((char) ('0' + rand));
-                               continue;
-                       }
-                       rand -= 10;
-                       if (rand < 26) {
-                               token.append((char) ('a' + rand));
-                               continue;
-                       }
-                       rand -= 26;
-                       token.append((char) ('A' + rand));
-               }
-               return token.toString();
-       }
+    static SecureRandom sr = new SecureRandom();
+
+    public static String generateToken(int length) {
+        StringBuffer token = new StringBuffer();
+        for (int i = 0; i < length; i++) {
+            int rand = sr.nextInt(26 * 2 + 10);
+            if (rand < 10) {
+                token.append((char) ('0' + rand));
+                continue;
+            }
+            rand -= 10;
+            if (rand < 26) {
+                token.append((char) ('a' + rand));
+                continue;
+            }
+            rand -= 26;
+            token.append((char) ('A' + rand));
+        }
+        return token.toString();
+    }
 }
index eafe93933647b7519860cb4b4fea0917b8e7d1d6..49f5d050a86054eed7195ea1956afd404f3ad6c3 100644 (file)
@@ -3,53 +3,58 @@ package org.cacert.gigi.util;
 import java.util.Properties;
 
 public class ServerConstants {
-       private static String wwwHostName = "www.cacert.local";
-       private static String secureHostName = "secure.cacert.local";
-       private static String staticHostName = "static.cacert.local";
-       private static String apiHostName = "api.cacert.local";
-       private static String port;
-
-       public static void init(Properties conf) {
-               port = "";
-               if (!conf.getProperty("port").equals("443")) {
-                       port = ":" + conf.getProperty("port");
-               }
-               wwwHostName = conf.getProperty("name.www");
-               secureHostName = conf.getProperty("name.secure");
-               staticHostName = conf.getProperty("name.static");
-               apiHostName = conf.getProperty("name.api");
-       }
-
-       public static String getSecureHostName() {
-               return secureHostName;
-       }
-
-       public static String getStaticHostName() {
-               return staticHostName;
-       }
-
-       public static String getWwwHostName() {
-               return wwwHostName;
-       }
-
-       public static String getApiHostName() {
-               return apiHostName;
-       }
-
-       public static String getSecureHostNamePort() {
-               return secureHostName + port;
-       }
-
-       public static String getStaticHostNamePort() {
-               return staticHostName + port;
-       }
-
-       public static String getWwwHostNamePort() {
-               return wwwHostName + port;
-       }
-
-       public static String getApiHostNamePort() {
-               return apiHostName + port;
-       }
+
+    private static String wwwHostName = "www.cacert.local";
+
+    private static String secureHostName = "secure.cacert.local";
+
+    private static String staticHostName = "static.cacert.local";
+
+    private static String apiHostName = "api.cacert.local";
+
+    private static String port;
+
+    public static void init(Properties conf) {
+        port = "";
+        if ( !conf.getProperty("port").equals("443")) {
+            port = ":" + conf.getProperty("port");
+        }
+        wwwHostName = conf.getProperty("name.www");
+        secureHostName = conf.getProperty("name.secure");
+        staticHostName = conf.getProperty("name.static");
+        apiHostName = conf.getProperty("name.api");
+    }
+
+    public static String getSecureHostName() {
+        return secureHostName;
+    }
+
+    public static String getStaticHostName() {
+        return staticHostName;
+    }
+
+    public static String getWwwHostName() {
+        return wwwHostName;
+    }
+
+    public static String getApiHostName() {
+        return apiHostName;
+    }
+
+    public static String getSecureHostNamePort() {
+        return secureHostName + port;
+    }
+
+    public static String getStaticHostNamePort() {
+        return staticHostName + port;
+    }
+
+    public static String getWwwHostNamePort() {
+        return wwwHostName + port;
+    }
+
+    public static String getApiHostNamePort() {
+        return apiHostName + port;
+    }
 
 }
index e8353accdc2d724052c857ec4ae2385fb050d202..940664fa79052cf1ea60d055b0d8dfef196cf0f7 100644 (file)
@@ -7,21 +7,21 @@ import org.junit.Test;
 
 public class LoginTest extends ManagedTest {
 
-       @Test
-       public void testLoginUnverified() throws IOException {
-               long uniq = System.currentTimeMillis();
-               String email = "system" + uniq + "@testmail.org";
-               registerUser("an", "bn", email, TEST_PASSWORD);
-               waitForMail();
-               assertFalse(isLoggedin(login(email, TEST_PASSWORD)));
-       }
+    @Test
+    public void testLoginUnverified() throws IOException {
+        long uniq = System.currentTimeMillis();
+        String email = "system" + uniq + "@testmail.org";
+        registerUser("an", "bn", email, TEST_PASSWORD);
+        waitForMail();
+        assertFalse(isLoggedin(login(email, TEST_PASSWORD)));
+    }
 
-       @Test
-       public void testLoginVerified() throws IOException {
-               long uniq = System.currentTimeMillis();
-               String email = "system2" + uniq + "@testmail.org";
-               createVerifiedUser("an", "bn", email, TEST_PASSWORD);
-               assertTrue(isLoggedin(login(email, TEST_PASSWORD)));
-       }
+    @Test
+    public void testLoginVerified() throws IOException {
+        long uniq = System.currentTimeMillis();
+        String email = "system2" + uniq + "@testmail.org";
+        createVerifiedUser("an", "bn", email, TEST_PASSWORD);
+        assertTrue(isLoggedin(login(email, TEST_PASSWORD)));
+    }
 
 }
index f686498976fd8470ede64e3038e58bbd93ca100b..5784e2ca57ccec4b4fc0fb62bfa73c5fb87e7b9a 100644 (file)
@@ -15,62 +15,61 @@ import org.junit.Test;
 import static org.junit.Assert.*;
 
 public class TestCertificate extends ManagedTest {
-       @Test
-       public void testClientCertLoginStates() throws IOException, GeneralSecurityException, SQLException,
-               InterruptedException {
-               String[] key1 = generateCSR("/CN=testmail@example.com");
-               Certificate c = new Certificate(1, "/CN=testmail@example.com", "sha256", key1[1], CSRType.CSR);
-               final PrivateKey pk = PemKey.parsePEMPrivateKey(key1[0]);
-               c.issue().waitFor(60000);
-               final X509Certificate ce = c.cert();
-               assertNotNull(login(pk, ce));
-       }
 
-       @Test
-       public void testCertLifeCycle() throws IOException, GeneralSecurityException, SQLException, InterruptedException {
-               String[] key1 = generateCSR("/CN=testmail@example.com");
-               Certificate c = new Certificate(1, "/CN=testmail@example.com", "sha256", key1[1], CSRType.CSR);
-               final PrivateKey pk = PemKey.parsePEMPrivateKey(key1[0]);
+    @Test
+    public void testClientCertLoginStates() throws IOException, GeneralSecurityException, SQLException, InterruptedException {
+        String[] key1 = generateCSR("/CN=testmail@example.com");
+        Certificate c = new Certificate(1, "/CN=testmail@example.com", "sha256", key1[1], CSRType.CSR);
+        final PrivateKey pk = PemKey.parsePEMPrivateKey(key1[0]);
+        c.issue().waitFor(60000);
+        final X509Certificate ce = c.cert();
+        assertNotNull(login(pk, ce));
+    }
 
-               testFails(CertificateStatus.DRAFT, c);
-               c.issue().waitFor(60000);
+    @Test
+    public void testCertLifeCycle() throws IOException, GeneralSecurityException, SQLException, InterruptedException {
+        String[] key1 = generateCSR("/CN=testmail@example.com");
+        Certificate c = new Certificate(1, "/CN=testmail@example.com", "sha256", key1[1], CSRType.CSR);
+        final PrivateKey pk = PemKey.parsePEMPrivateKey(key1[0]);
 
-               testFails(CertificateStatus.ISSUED, c);
-               X509Certificate cert = c.cert();
-               assertNotNull(login(pk, cert));
-               c.revoke().waitFor(60000);
+        testFails(CertificateStatus.DRAFT, c);
+        c.issue().waitFor(60000);
 
-               testFails(CertificateStatus.REVOKED, c);
-               assertNull(login(pk, cert));
+        testFails(CertificateStatus.ISSUED, c);
+        X509Certificate cert = c.cert();
+        assertNotNull(login(pk, cert));
+        c.revoke().waitFor(60000);
 
-       }
+        testFails(CertificateStatus.REVOKED, c);
+        assertNull(login(pk, cert));
 
-       private void testFails(CertificateStatus status, Certificate c) throws IOException, GeneralSecurityException,
-               SQLException {
-               assertEquals(status, c.getStatus());
-               if (status != CertificateStatus.ISSUED) {
-                       try {
-                               c.revoke();
-                               fail(status + " is in invalid state");
-                       } catch (IllegalStateException ise) {
+    }
 
-                       }
-               }
-               if (status != CertificateStatus.DRAFT) {
-                       try {
-                               c.issue();
-                               fail(status + " is in invalid state");
-                       } catch (IllegalStateException ise) {
+    private void testFails(CertificateStatus status, Certificate c) throws IOException, GeneralSecurityException, SQLException {
+        assertEquals(status, c.getStatus());
+        if (status != CertificateStatus.ISSUED) {
+            try {
+                c.revoke();
+                fail(status + " is in invalid state");
+            } catch (IllegalStateException ise) {
 
-                       }
-               }
-               if (status != CertificateStatus.ISSUED) {
-                       try {
-                               c.cert();
-                               fail(status + " is in invalid state");
-                       } catch (IllegalStateException ise) {
+            }
+        }
+        if (status != CertificateStatus.DRAFT) {
+            try {
+                c.issue();
+                fail(status + " is in invalid state");
+            } catch (IllegalStateException ise) {
 
-                       }
-               }
-       }
+            }
+        }
+        if (status != CertificateStatus.ISSUED) {
+            try {
+                c.cert();
+                fail(status + " is in invalid state");
+            } catch (IllegalStateException ise) {
+
+            }
+        }
+    }
 }
index 3eecd03f7238af5c7242046afac39d6fb4736c7e..936395db3dc193b1d6740786b1fd3a07537796c9 100644 (file)
@@ -6,94 +6,95 @@ import org.cacert.gigi.testUtils.ManagedTest;
 import org.junit.Test;
 
 public class TestDomain extends ManagedTest {
-       private User us;
 
-       public TestDomain() {
-               int uid = createVerifiedUser("fn", "ln", createUniqueName() + "pr@test-email.de", TEST_PASSWORD);
-               us = User.getById(uid);
-       }
+    private User us;
 
-       @Test
-       public void testDomain() throws InterruptedException, GigiApiException {
-               assertEquals(0, us.getDomains().length);
-               Domain d = new Domain(us, "v1.example.org");
-               assertEquals(0, d.getId());
-               d.insert();
-               Domain[] domains = us.getDomains();
-               assertEquals(1, domains.length);
-               assertEquals("v1.example.org", domains[0].getSuffix());
-               assertEquals(domains[0].getOwner().getId(), us.getId());
-               assertNotEquals(0, domains[0].getId());
-               assertNotEquals(0, d.getId());
-               assertEquals(d.getId(), domains[0].getId());
+    public TestDomain() {
+        int uid = createVerifiedUser("fn", "ln", createUniqueName() + "pr@test-email.de", TEST_PASSWORD);
+        us = User.getById(uid);
+    }
 
-               Domain d2 = new Domain(us, "v2.example.org");
-               assertEquals(0, d2.getId());
-               d2.insert();
+    @Test
+    public void testDomain() throws InterruptedException, GigiApiException {
+        assertEquals(0, us.getDomains().length);
+        Domain d = new Domain(us, "v1.example.org");
+        assertEquals(0, d.getId());
+        d.insert();
+        Domain[] domains = us.getDomains();
+        assertEquals(1, domains.length);
+        assertEquals("v1.example.org", domains[0].getSuffix());
+        assertEquals(domains[0].getOwner().getId(), us.getId());
+        assertNotEquals(0, domains[0].getId());
+        assertNotEquals(0, d.getId());
+        assertEquals(d.getId(), domains[0].getId());
 
-               domains = us.getDomains();
-               assertEquals(2, domains.length);
-               assertEquals("v2.example.org", domains[1].getSuffix());
-               assertEquals(domains[0].getOwner().getId(), us.getId());
-               assertEquals(domains[1].getOwner().getId(), us.getId());
-               assertNotEquals(0, domains[0].getId());
-               assertNotEquals(0, d.getId());
-               assertEquals(d.getId(), domains[0].getId());
+        Domain d2 = new Domain(us, "v2.example.org");
+        assertEquals(0, d2.getId());
+        d2.insert();
 
-       }
+        domains = us.getDomains();
+        assertEquals(2, domains.length);
+        assertEquals("v2.example.org", domains[1].getSuffix());
+        assertEquals(domains[0].getOwner().getId(), us.getId());
+        assertEquals(domains[1].getOwner().getId(), us.getId());
+        assertNotEquals(0, domains[0].getId());
+        assertNotEquals(0, d.getId());
+        assertEquals(d.getId(), domains[0].getId());
 
-       @Test
-       public void testDoubleDomain() throws InterruptedException, GigiApiException {
-               Domain d = new Domain(us, "dub.example.org");
-               d.insert();
-               try {
-                       Domain d2 = new Domain(us, "dub.example.org");
-                       d2.insert();
-                       fail("expected exception");
-               } catch (GigiApiException e) {
-                       // expected
-               }
-       }
+    }
 
-       @Test
-       public void testDoubleDomainDelete() throws InterruptedException, GigiApiException {
-               Domain d = new Domain(us, "del.example.org");
-               d.insert();
-               d.delete();
-               Domain d2 = new Domain(us, "del.example.org");
-               d2.insert();
-       }
+    @Test
+    public void testDoubleDomain() throws InterruptedException, GigiApiException {
+        Domain d = new Domain(us, "dub.example.org");
+        d.insert();
+        try {
+            Domain d2 = new Domain(us, "dub.example.org");
+            d2.insert();
+            fail("expected exception");
+        } catch (GigiApiException e) {
+            // expected
+        }
+    }
 
-       @Test
-       public void testDoubleDomainPrefix() throws InterruptedException, GigiApiException {
-               Domain d = new Domain(us, "pref.aexample.org");
-               d.insert();
-               Domain d2 = new Domain(us, "a.pref.aexample.org");
-               try {
-                       d2.insert();
-                       fail("expected exception");
-               } catch (GigiApiException e) {
-                       // expected
-               }
-               Domain d3 = new Domain(us, "aexample.org");
-               try {
-                       d3.insert();
-                       fail("expected exception");
-               } catch (GigiApiException e) {
-                       // expected
-               }
-       }
+    @Test
+    public void testDoubleDomainDelete() throws InterruptedException, GigiApiException {
+        Domain d = new Domain(us, "del.example.org");
+        d.insert();
+        d.delete();
+        Domain d2 = new Domain(us, "del.example.org");
+        d2.insert();
+    }
 
-       @Test
-       public void testDoubleInsertDomain() throws InterruptedException, GigiApiException {
-               Domain d = new Domain(us, "dins.example.org");
-               d.insert();
-               try {
-                       d.insert();
-                       fail("expected exception");
-               } catch (GigiApiException e) {
-                       // expected
-               }
-       }
+    @Test
+    public void testDoubleDomainPrefix() throws InterruptedException, GigiApiException {
+        Domain d = new Domain(us, "pref.aexample.org");
+        d.insert();
+        Domain d2 = new Domain(us, "a.pref.aexample.org");
+        try {
+            d2.insert();
+            fail("expected exception");
+        } catch (GigiApiException e) {
+            // expected
+        }
+        Domain d3 = new Domain(us, "aexample.org");
+        try {
+            d3.insert();
+            fail("expected exception");
+        } catch (GigiApiException e) {
+            // expected
+        }
+    }
+
+    @Test
+    public void testDoubleInsertDomain() throws InterruptedException, GigiApiException {
+        Domain d = new Domain(us, "dins.example.org");
+        d.insert();
+        try {
+            d.insert();
+            fail("expected exception");
+        } catch (GigiApiException e) {
+            // expected
+        }
+    }
 
 }
index c39b20f5b07505cb9219c1ed22f6317616e96c38..83bc7f69b51214e5ab63675a3668c8288ac2a68e 100644 (file)
@@ -18,88 +18,91 @@ import org.cacert.gigi.testUtils.ManagedTest;
 import org.junit.Test;
 
 public class TestSSL extends ManagedTest {
-       private ByteBuffer in;
-       private ByteBuffer inC;
-       private ByteBuffer outC;
-       private ByteBuffer out;
-       static {
-               InitTruststore.run();
-       }
-
-       @Test
-       public void testClientIntitiatedRenegotiation() throws NoSuchAlgorithmException, IOException {
-               SSLContext sc = SSLContext.getDefault();
-               SSLEngine se = sc.createSSLEngine();
-               String[] serverParts = getServerName().split(":", 2);
-               SocketChannel s = SocketChannel.open(new InetSocketAddress(serverParts[0], Integer.parseInt(serverParts[1])));
-
-               in = ByteBuffer.allocate(se.getSession().getApplicationBufferSize());
-               inC = ByteBuffer.allocate(se.getSession().getPacketBufferSize());
-               inC.limit(0);
-               out = ByteBuffer.allocate(se.getSession().getApplicationBufferSize());
-               outC = ByteBuffer.allocate(se.getSession().getPacketBufferSize());
-               outC.limit(0);
-               se.setUseClientMode(true);
-               se.beginHandshake();
-
-               work(se, s);
-               se.beginHandshake();
-               try {
-                       work(se, s);
-                       throw new Error("Client re-negotiation succeded (possible DoS vulnerability");
-               } catch (EOFException e) {
-                       // Cool, server closed connection
-               }
-
-       }
-
-       private void work(SSLEngine se, SocketChannel s) throws SSLException, IOException {
-               while (se.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING
-                       && se.getHandshakeStatus() != HandshakeStatus.FINISHED) {
-                       switch (se.getHandshakeStatus()) {
-                       case NEED_WRAP:
-                               wrap(se, s);
-                               break;
-                       case NEED_UNWRAP:
-                               unwrap(se, s);
-                               break;
-                       case NEED_TASK:
-                               se.getDelegatedTask().run();
-                               break;
-                       default:
-                               System.out.println(se.getHandshakeStatus());
-                       }
-               }
-       }
-
-       private SSLEngineResult unwrap(SSLEngine se, SocketChannel s) throws IOException, SSLException {
-               if (inC.remaining() == 0) {
-                       inC.clear();
-                       s.read(inC);
-                       inC.flip();
-               }
-               SSLEngineResult result = se.unwrap(inC, in);
-               if (result.getStatus() == javax.net.ssl.SSLEngineResult.Status.BUFFER_UNDERFLOW) {
-                       int pos = inC.position();
-                       int limit = inC.limit();
-                       inC.limit(inC.capacity());
-                       inC.position(limit);
-                       int read = s.read(inC);
-                       if (read <= 0) {
-                               throw new EOFException();
-                       }
-                       inC.limit(inC.position());
-                       inC.position(pos);
-               }
-               return result;
-       }
-
-       private SSLEngineResult wrap(SSLEngine se, SocketChannel s) throws SSLException, IOException {
-               outC.clear();
-               SSLEngineResult result = se.wrap(out, outC);
-               outC.flip();
-               s.write(outC);
-
-               return result;
-       }
+
+    private ByteBuffer in;
+
+    private ByteBuffer inC;
+
+    private ByteBuffer outC;
+
+    private ByteBuffer out;
+    static {
+        InitTruststore.run();
+    }
+
+    @Test
+    public void testClientIntitiatedRenegotiation() throws NoSuchAlgorithmException, IOException {
+        SSLContext sc = SSLContext.getDefault();
+        SSLEngine se = sc.createSSLEngine();
+        String[] serverParts = getServerName().split(":", 2);
+        SocketChannel s = SocketChannel.open(new InetSocketAddress(serverParts[0], Integer.parseInt(serverParts[1])));
+
+        in = ByteBuffer.allocate(se.getSession().getApplicationBufferSize());
+        inC = ByteBuffer.allocate(se.getSession().getPacketBufferSize());
+        inC.limit(0);
+        out = ByteBuffer.allocate(se.getSession().getApplicationBufferSize());
+        outC = ByteBuffer.allocate(se.getSession().getPacketBufferSize());
+        outC.limit(0);
+        se.setUseClientMode(true);
+        se.beginHandshake();
+
+        work(se, s);
+        se.beginHandshake();
+        try {
+            work(se, s);
+            throw new Error("Client re-negotiation succeded (possible DoS vulnerability");
+        } catch (EOFException e) {
+            // Cool, server closed connection
+        }
+
+    }
+
+    private void work(SSLEngine se, SocketChannel s) throws SSLException, IOException {
+        while (se.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING && se.getHandshakeStatus() != HandshakeStatus.FINISHED) {
+            switch (se.getHandshakeStatus()) {
+            case NEED_WRAP:
+                wrap(se, s);
+                break;
+            case NEED_UNWRAP:
+                unwrap(se, s);
+                break;
+            case NEED_TASK:
+                se.getDelegatedTask().run();
+                break;
+            default:
+                System.out.println(se.getHandshakeStatus());
+            }
+        }
+    }
+
+    private SSLEngineResult unwrap(SSLEngine se, SocketChannel s) throws IOException, SSLException {
+        if (inC.remaining() == 0) {
+            inC.clear();
+            s.read(inC);
+            inC.flip();
+        }
+        SSLEngineResult result = se.unwrap(inC, in);
+        if (result.getStatus() == javax.net.ssl.SSLEngineResult.Status.BUFFER_UNDERFLOW) {
+            int pos = inC.position();
+            int limit = inC.limit();
+            inC.limit(inC.capacity());
+            inC.position(limit);
+            int read = s.read(inC);
+            if (read <= 0) {
+                throw new EOFException();
+            }
+            inC.limit(inC.position());
+            inC.position(pos);
+        }
+        return result;
+    }
+
+    private SSLEngineResult wrap(SSLEngine se, SocketChannel s) throws SSLException, IOException {
+        outC.clear();
+        SSLEngineResult result = se.wrap(out, outC);
+        outC.flip();
+        s.write(outC);
+
+        return result;
+    }
 }
index 75675c66f6fd44ecb6b5f7611b099dc7fafc40f6..ddff38ee2c096ac8b9d3e6da687d2014e503e35d 100644 (file)
@@ -10,20 +10,21 @@ import org.junit.Test;
 import static org.junit.Assert.*;
 
 public class TestSecurityHeaders extends ManagedTest {
-       @Test
-       public void testSTS() throws IOException {
-               HttpURLConnection uc = (HttpURLConnection) new URL("https://" + getServerName()).openConnection();
-               assertNotNull(uc.getHeaderField("Strict-Transport-Security"));
-       }
-
-       public void testCSP() throws IOException {
-               HttpURLConnection uc = (HttpURLConnection) new URL("https://" + getServerName()).openConnection();
-               assertNotNull(uc.getHeaderField("Content-Security-Policy"));
-       }
-
-       public void testAllowOrigin() throws IOException {
-               HttpURLConnection uc = (HttpURLConnection) new URL("https://" + getServerName()).openConnection();
-               assertNotNull(uc.getHeaderField("Access-Control-Allow-Origin"));
-
-       }
+
+    @Test
+    public void testSTS() throws IOException {
+        HttpURLConnection uc = (HttpURLConnection) new URL("https://" + getServerName()).openConnection();
+        assertNotNull(uc.getHeaderField("Strict-Transport-Security"));
+    }
+
+    public void testCSP() throws IOException {
+        HttpURLConnection uc = (HttpURLConnection) new URL("https://" + getServerName()).openConnection();
+        assertNotNull(uc.getHeaderField("Content-Security-Policy"));
+    }
+
+    public void testAllowOrigin() throws IOException {
+        HttpURLConnection uc = (HttpURLConnection) new URL("https://" + getServerName()).openConnection();
+        assertNotNull(uc.getHeaderField("Access-Control-Allow-Origin"));
+
+    }
 }
index a28def7c5abbc8b6a1d66137b89e89f310e1da53..e676e51bde2501c77e9b74b0c68e093190d768cc 100644 (file)
@@ -17,31 +17,31 @@ import org.junit.Test;
 
 public class TestSeparateSessionScope extends ManagedTest {
 
-       @Test
-       public void testSeparateScope() throws IOException, GeneralSecurityException, SQLException, InterruptedException {
-               String mail = "thisgo" + createUniqueName() + "@example.com";
-               int user = createAssuranceUser("test", "tugo", mail, TEST_PASSWORD);
-               String cookie = login(mail, TEST_PASSWORD);
-               String[] csr = generateCSR("/CN=felix@dogcraft.de");
-               Certificate c = new Certificate(user, "/CN=testmail@example.com", "sha256", csr[1], CSRType.CSR);
-               final PrivateKey pk = PemKey.parsePEMPrivateKey(csr[0]);
-               c.issue().waitFor(60000);
-               final X509Certificate ce = c.cert();
-               String scookie = login(pk, ce);
-
-               assertTrue(isLoggedin(cookie));
-               assertFalse(isLoggedin(scookie));
-
-               URL u = new URL("https://" + getServerName().replaceAll("^www", "secure") + SECURE_REFERENCE);
-               HttpURLConnection huc = (HttpURLConnection) u.openConnection();
-               authenticateClientCert(pk, ce, huc);
-               huc.setRequestProperty("Cookie", scookie);
-               assertEquals(200, huc.getResponseCode());
-
-               HttpURLConnection huc2 = (HttpURLConnection) u.openConnection();
-               authenticateClientCert(pk, ce, huc2);
-               huc2.setRequestProperty("Cookie", cookie);
-               assertEquals(302, huc2.getResponseCode());
-
-       }
+    @Test
+    public void testSeparateScope() throws IOException, GeneralSecurityException, SQLException, InterruptedException {
+        String mail = "thisgo" + createUniqueName() + "@example.com";
+        int user = createAssuranceUser("test", "tugo", mail, TEST_PASSWORD);
+        String cookie = login(mail, TEST_PASSWORD);
+        String[] csr = generateCSR("/CN=felix@dogcraft.de");
+        Certificate c = new Certificate(user, "/CN=testmail@example.com", "sha256", csr[1], CSRType.CSR);
+        final PrivateKey pk = PemKey.parsePEMPrivateKey(csr[0]);
+        c.issue().waitFor(60000);
+        final X509Certificate ce = c.cert();
+        String scookie = login(pk, ce);
+
+        assertTrue(isLoggedin(cookie));
+        assertFalse(isLoggedin(scookie));
+
+        URL u = new URL("https://" + getServerName().replaceAll("^www", "secure") + SECURE_REFERENCE);
+        HttpURLConnection huc = (HttpURLConnection) u.openConnection();
+        authenticateClientCert(pk, ce, huc);
+        huc.setRequestProperty("Cookie", scookie);
+        assertEquals(200, huc.getResponseCode());
+
+        HttpURLConnection huc2 = (HttpURLConnection) u.openConnection();
+        authenticateClientCert(pk, ce, huc2);
+        huc2.setRequestProperty("Cookie", cookie);
+        assertEquals(302, huc2.getResponseCode());
+
+    }
 }
index ed854498ab9b8b2ea1b44edab552862369f98875..2b783daa5ad73744e718f2b0d62b090685edb9a5 100644 (file)
@@ -7,48 +7,49 @@ import org.junit.Test;
 import static org.junit.Assert.*;
 
 public class TestUser extends ManagedTest {
-       @Test
-       public void testStoreAndLoad() throws SQLException {
-               User u = new User();
-               u.setFname("user");
-               u.setLname("last");
-               u.setMname("");
-               u.setSuffix("");
-               long dob = System.currentTimeMillis();
-               dob -= dob % (1000 * 60 * 60 * 24);
-               u.setDob(new java.sql.Date(dob));
-               u.setEmail(createUniqueName() + "a@email.org");
-               u.insert("password");
-               int id = u.getId();
-               User u2 = new User(id);
-               assertEquals(u, u2);
-       }
-
-       @Test
-       public void testWebStoreAndLoad() throws SQLException {
-               int id = createVerifiedUser("aä", "b", createUniqueName() + "a@email.org", TEST_PASSWORD);
-
-               User u = new User(id);
-               assertEquals("aä", u.getFname());
-               assertEquals("b", u.getLname());
-               assertEquals("", u.getMname());
-       }
-
-       @Test
-       public void testAssurerUtilMethods() throws SQLException {
-               int id = createAssuranceUser("aä", "b", createUniqueName() + "a@email.org", TEST_PASSWORD);
-
-               User u = new User(id);
-               assertTrue(u.canAssure());
-               int assurancePoints = u.getAssurancePoints();
-               int expPoints = u.getExperiencePoints();
-               assertEquals(100, assurancePoints);
-               assertEquals(2, expPoints);
-               assertTrue(u.hasPassedCATS());
-               assertEquals(10, u.getMaxAssurePoints());
-
-               assertEquals("aä", u.getFname());
-               assertEquals("b", u.getLname());
-               assertEquals("", u.getMname());
-       }
+
+    @Test
+    public void testStoreAndLoad() throws SQLException {
+        User u = new User();
+        u.setFname("user");
+        u.setLname("last");
+        u.setMname("");
+        u.setSuffix("");
+        long dob = System.currentTimeMillis();
+        dob -= dob % (1000 * 60 * 60 * 24);
+        u.setDob(new java.sql.Date(dob));
+        u.setEmail(createUniqueName() + "a@email.org");
+        u.insert("password");
+        int id = u.getId();
+        User u2 = new User(id);
+        assertEquals(u, u2);
+    }
+
+    @Test
+    public void testWebStoreAndLoad() throws SQLException {
+        int id = createVerifiedUser("aä", "b", createUniqueName() + "a@email.org", TEST_PASSWORD);
+
+        User u = new User(id);
+        assertEquals("aä", u.getFname());
+        assertEquals("b", u.getLname());
+        assertEquals("", u.getMname());
+    }
+
+    @Test
+    public void testAssurerUtilMethods() throws SQLException {
+        int id = createAssuranceUser("aä", "b", createUniqueName() + "a@email.org", TEST_PASSWORD);
+
+        User u = new User(id);
+        assertTrue(u.canAssure());
+        int assurancePoints = u.getAssurancePoints();
+        int expPoints = u.getExperiencePoints();
+        assertEquals(100, assurancePoints);
+        assertEquals(2, expPoints);
+        assertTrue(u.hasPassedCATS());
+        assertEquals(10, u.getMaxAssurePoints());
+
+        assertEquals("aä", u.getFname());
+        assertEquals("b", u.getLname());
+        assertEquals("", u.getMname());
+    }
 }
index 4b9e48d7711ab50b82aedbe369dd8986b23e8e8d..119df79f1e33df23723ef0596dd917b0195fc1c0 100644 (file)
@@ -11,98 +11,96 @@ import org.cacert.gigi.testUtils.ManagedTest;
 import org.junit.Test;
 
 public class TestChangePassword extends ManagedTest {
-       User u = User.getById(createVerifiedUser("fn", "ln", createUniqueName() + "uni@example.org", TEST_PASSWORD));
-       String cookie;
-       String path = ChangePasswordPage.PATH;
-
-       public TestChangePassword() throws IOException {
-               cookie = login(u.getEmail(), TEST_PASSWORD);
-               assertTrue(isLoggedin(cookie));
-       }
-
-       @Test
-       public void testChangePasswordInternal() throws IOException, GigiApiException {
-               try {
-                       u.changePassword(TEST_PASSWORD + "wrong", TEST_PASSWORD + "v2");
-                       fail("Password change must not succeed if old password is wrong.");
-               } catch (GigiApiException e) {
-                       // expected
-               }
-               ;
-               assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD)));
-               u.changePassword(TEST_PASSWORD, TEST_PASSWORD + "v2");
-               assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2")));
-       }
-
-       @Test
-       public void testChangePasswordWeb() throws IOException {
-               String error = executeBasicWebInteraction(cookie, path,
-                       "oldpassword=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") //
-                               + "&pword1=" + URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8")//
-                               + "&pword2=" + URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8"));
-               assertNull(error);
-               assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2")));
-               assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD)));
-
-       }
-
-       @Test
-       public void testChangePasswordWebOldWrong() throws IOException {
-               String error = executeBasicWebInteraction(cookie, path,
-                       "oldpassword=a" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") //
-                               + "&pword1=" + URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8")//
-                               + "&pword2=" + URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8"));
-               assertNotNull(error);
-               assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2")));
-               assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD)));
-
-       }
-
-       @Test
-       public void testChangePasswordWebNewWrong() throws IOException {
-               String error = executeBasicWebInteraction(cookie, path,
-                       "oldpassword=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") //
-                               + "&pword1=" + URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8")//
-                               + "&pword2=a" + URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8"));
-               assertNotNull(error);
-               assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2")));
-               assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD)));
-
-       }
-
-       @Test
-       public void testChangePasswordWebNewEasy() throws IOException {
-               String error = executeBasicWebInteraction(cookie, path,
-                       "oldpassword=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") //
-                               + "&pword1=a&pword2=a");
-               assertNotNull(error);
-               assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2")));
-               assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD)));
-
-       }
-
-       @Test
-       public void testChangePasswordWebMissingFields() throws IOException {
-               String np = URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8");
-               assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD)));
-               String error = executeBasicWebInteraction(cookie, path,
-                       "oldpassword=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") //
-                               + "&pword1=" + np);
-               assertNotNull(error);
-               assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2")));
-               assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD)));
-
-               error = executeBasicWebInteraction(cookie, path, "oldpassword=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") //
-                       + "&pword2=" + np);
-               assertNotNull(error);
-               assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2")));
-               assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD)));
-
-               error = executeBasicWebInteraction(cookie, path, "pword1=" + np + "&pword2=" + np);
-               assertNotNull(error);
-               assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2")));
-               assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD)));
-
-       }
+
+    User u = User.getById(createVerifiedUser("fn", "ln", createUniqueName() + "uni@example.org", TEST_PASSWORD));
+
+    String cookie;
+
+    String path = ChangePasswordPage.PATH;
+
+    public TestChangePassword() throws IOException {
+        cookie = login(u.getEmail(), TEST_PASSWORD);
+        assertTrue(isLoggedin(cookie));
+    }
+
+    @Test
+    public void testChangePasswordInternal() throws IOException, GigiApiException {
+        try {
+            u.changePassword(TEST_PASSWORD + "wrong", TEST_PASSWORD + "v2");
+            fail("Password change must not succeed if old password is wrong.");
+        } catch (GigiApiException e) {
+            // expected
+        }
+        ;
+        assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD)));
+        u.changePassword(TEST_PASSWORD, TEST_PASSWORD + "v2");
+        assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2")));
+    }
+
+    @Test
+    public void testChangePasswordWeb() throws IOException {
+        String error = executeBasicWebInteraction(cookie, path, "oldpassword=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") //
+                + "&pword1=" + URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8")//
+                + "&pword2=" + URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8"));
+        assertNull(error);
+        assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2")));
+        assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD)));
+
+    }
+
+    @Test
+    public void testChangePasswordWebOldWrong() throws IOException {
+        String error = executeBasicWebInteraction(cookie, path, "oldpassword=a" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") //
+                + "&pword1=" + URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8")//
+                + "&pword2=" + URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8"));
+        assertNotNull(error);
+        assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2")));
+        assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD)));
+
+    }
+
+    @Test
+    public void testChangePasswordWebNewWrong() throws IOException {
+        String error = executeBasicWebInteraction(cookie, path, "oldpassword=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") //
+                + "&pword1=" + URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8")//
+                + "&pword2=a" + URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8"));
+        assertNotNull(error);
+        assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2")));
+        assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD)));
+
+    }
+
+    @Test
+    public void testChangePasswordWebNewEasy() throws IOException {
+        String error = executeBasicWebInteraction(cookie, path, "oldpassword=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") //
+                + "&pword1=a&pword2=a");
+        assertNotNull(error);
+        assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2")));
+        assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD)));
+
+    }
+
+    @Test
+    public void testChangePasswordWebMissingFields() throws IOException {
+        String np = URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8");
+        assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD)));
+        String error = executeBasicWebInteraction(cookie, path, "oldpassword=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") //
+                + "&pword1=" + np);
+        assertNotNull(error);
+        assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2")));
+        assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD)));
+
+        error = executeBasicWebInteraction(cookie, path, "oldpassword=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") //
+                + "&pword2=" + np);
+        assertNotNull(error);
+        assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2")));
+        assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD)));
+
+        error = executeBasicWebInteraction(cookie, path, "pword1=" + np + "&pword2=" + np);
+        assertNotNull(error);
+        assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2")));
+        assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD)));
+
+    }
 
 }
index 053aa32f5c604714e4a7250fbbb4e8be188969d2..2adbf106ed0f9635ae8a6121099fb801c2962a3e 100644 (file)
@@ -15,125 +15,121 @@ import org.cacert.gigi.testUtils.ManagedTest;
 import org.junit.Test;
 
 public class TestMailManagement extends ManagedTest {
-       private User u = User
-               .getById(createVerifiedUser("fn", "ln", createUniqueName() + "uni@example.org", TEST_PASSWORD));
-       private String cookie;
-       private String path = MailOverview.DEFAULT_PATH;
-
-       public TestMailManagement() throws IOException {
-               cookie = login(u.getEmail(), TEST_PASSWORD);
-               assertTrue(isLoggedin(cookie));
-       }
-
-       @Test
-       public void testMailAddInternal() throws InterruptedException, GigiApiException {
-               createVerifiedEmail(u);
-       }
-
-       @Test
-       public void testMailAddInternalFaulty() {
-               try {
-                       new EmailAddress("kurti ", u);
-                       fail();
-               } catch (IllegalArgumentException e) {
-                       // Intended.
-               }
-       }
-
-       @Test
-       public void testMailAddWeb() throws MalformedURLException, UnsupportedEncodingException, IOException {
-               String newMail = createUniqueName() + "uni@example.org";
-               assertNull(executeBasicWebInteraction(cookie, path, "addmail&newemail=" + URLEncoder.encode(newMail, "UTF-8"),
-                       1));
-               EmailAddress[] addrs = u.getEmails();
-               for (int i = 0; i < addrs.length; i++) {
-                       if (addrs[i].getAddress().equals(newMail)) {
-                               return;
-                       }
-               }
-               fail();
-       }
-
-       @Test
-       public void testMailAddWebFaulty() throws MalformedURLException, UnsupportedEncodingException, IOException {
-               String newMail = createUniqueName() + "uniexample.org";
-               assertNotNull(executeBasicWebInteraction(cookie, path,
-                       "addmail&newemail=" + URLEncoder.encode(newMail, "UTF-8"), 1));
-               EmailAddress[] addrs = u.getEmails();
-               for (int i = 0; i < addrs.length; i++) {
-                       if (addrs[i].getAddress().equals(newMail)) {
-                               fail();
-                       }
-               }
-       }
-
-       @Test
-       public void testMailSetDefaultWeb() throws MalformedURLException, UnsupportedEncodingException, IOException,
-               InterruptedException, GigiApiException {
-               EmailAddress adrr = createVerifiedEmail(u);
-               assertNull(executeBasicWebInteraction(cookie, path, "makedefault&emailid=" + adrr.getId()));
-               assertEquals(User.getById(u.getId()).getEmail(), adrr.getAddress());
-       }
-
-       @Test
-       public void testMailSetDefaultWebUnverified() throws MalformedURLException, UnsupportedEncodingException,
-               IOException, InterruptedException, GigiApiException {
-               EmailAddress adrr = new EmailAddress(createUniqueName() + "test@test.tld", u);
-               adrr.insert(Language.getInstance("en"));
-               assertNotNull(executeBasicWebInteraction(cookie, path, "makedefault&emailid=" + adrr.getId()));
-               assertNotEquals(User.getById(u.getId()).getEmail(), adrr.getAddress());
-               getMailReciever().clearMails();
-       }
-
-       @Test
-       public void testMailSetDefaultWebInvalidID() throws MalformedURLException, UnsupportedEncodingException,
-               IOException, InterruptedException, GigiApiException {
-               User u2 = User.getById(createVerifiedUser("fn", "ln", createUniqueName() + "uni@example.org", TEST_PASSWORD));
-               int id = -1;
-               EmailAddress[] emails = u2.getEmails();
-               for (int i = 0; i < emails.length; i++) {
-                       if (emails[i].getAddress().equals(u2.getEmail())) {
-                               id = emails[i].getId();
-                       }
-               }
-               assertNotEquals(id, -1);
-               assertNotNull(executeBasicWebInteraction(cookie, path, "makedefault&emailid=" + id));
-               assertNotEquals(User.getById(u.getId()).getEmail(), u2.getEmail());
-               getMailReciever().clearMails();
-       }
-
-       @Test
-       public void testMailDeleteWeb() throws InterruptedException, GigiApiException, MalformedURLException,
-               UnsupportedEncodingException, IOException {
-               EmailAddress addr = createVerifiedEmail(u);
-               assertNull(executeBasicWebInteraction(cookie, path, "delete&delid[]=" + addr.getId(), 0));
-               User u = User.getById(this.u.getId());
-               EmailAddress[] addresses = u.getEmails();
-               for (int i = 0; i < addresses.length; i++) {
-                       assertNotEquals(addresses[i].getAddress(), addr.getAddress());
-               }
-       }
-
-       @Test
-       public void testMailDeleteWebMulti() throws InterruptedException, GigiApiException, MalformedURLException,
-               UnsupportedEncodingException, IOException {
-               EmailAddress[] addr = new EmailAddress[] { createVerifiedEmail(u), createVerifiedEmail(u) };
-               assertNull(executeBasicWebInteraction(cookie, path,
-                       "delete&delid[]=" + addr[0].getId() + "&delid[]=" + addr[1].getId(), 0));
-               User u = User.getById(this.u.getId());
-               EmailAddress[] addresses = u.getEmails();
-               for (int i = 0; i < addresses.length; i++) {
-                       assertNotEquals(addresses[i].getAddress(), addr[0].getAddress());
-                       assertNotEquals(addresses[i].getAddress(), addr[1].getAddress());
-               }
-       }
-
-       @Test
-       public void testMailDeleteWebFaulty() throws MalformedURLException, UnsupportedEncodingException, IOException {
-               User u2 = User.getById(createVerifiedUser("fn", "ln", createUniqueName() + "uni@test.tld", TEST_PASSWORD));
-               EmailAddress em = u2.getEmails()[0];
-               assertNotNull(executeBasicWebInteraction(cookie, path, "delete&delid[]=" + em.getId(), 0));
-               u2 = User.getById(u2.getId());
-               assertNotEquals(u2.getEmails().length, 0);
-       }
+
+    private User u = User.getById(createVerifiedUser("fn", "ln", createUniqueName() + "uni@example.org", TEST_PASSWORD));
+
+    private String cookie;
+
+    private String path = MailOverview.DEFAULT_PATH;
+
+    public TestMailManagement() throws IOException {
+        cookie = login(u.getEmail(), TEST_PASSWORD);
+        assertTrue(isLoggedin(cookie));
+    }
+
+    @Test
+    public void testMailAddInternal() throws InterruptedException, GigiApiException {
+        createVerifiedEmail(u);
+    }
+
+    @Test
+    public void testMailAddInternalFaulty() {
+        try {
+            new EmailAddress("kurti ", u);
+            fail();
+        } catch (IllegalArgumentException e) {
+            // Intended.
+        }
+    }
+
+    @Test
+    public void testMailAddWeb() throws MalformedURLException, UnsupportedEncodingException, IOException {
+        String newMail = createUniqueName() + "uni@example.org";
+        assertNull(executeBasicWebInteraction(cookie, path, "addmail&newemail=" + URLEncoder.encode(newMail, "UTF-8"), 1));
+        EmailAddress[] addrs = u.getEmails();
+        for (int i = 0; i < addrs.length; i++) {
+            if (addrs[i].getAddress().equals(newMail)) {
+                return;
+            }
+        }
+        fail();
+    }
+
+    @Test
+    public void testMailAddWebFaulty() throws MalformedURLException, UnsupportedEncodingException, IOException {
+        String newMail = createUniqueName() + "uniexample.org";
+        assertNotNull(executeBasicWebInteraction(cookie, path, "addmail&newemail=" + URLEncoder.encode(newMail, "UTF-8"), 1));
+        EmailAddress[] addrs = u.getEmails();
+        for (int i = 0; i < addrs.length; i++) {
+            if (addrs[i].getAddress().equals(newMail)) {
+                fail();
+            }
+        }
+    }
+
+    @Test
+    public void testMailSetDefaultWeb() throws MalformedURLException, UnsupportedEncodingException, IOException, InterruptedException, GigiApiException {
+        EmailAddress adrr = createVerifiedEmail(u);
+        assertNull(executeBasicWebInteraction(cookie, path, "makedefault&emailid=" + adrr.getId()));
+        assertEquals(User.getById(u.getId()).getEmail(), adrr.getAddress());
+    }
+
+    @Test
+    public void testMailSetDefaultWebUnverified() throws MalformedURLException, UnsupportedEncodingException, IOException, InterruptedException, GigiApiException {
+        EmailAddress adrr = new EmailAddress(createUniqueName() + "test@test.tld", u);
+        adrr.insert(Language.getInstance("en"));
+        assertNotNull(executeBasicWebInteraction(cookie, path, "makedefault&emailid=" + adrr.getId()));
+        assertNotEquals(User.getById(u.getId()).getEmail(), adrr.getAddress());
+        getMailReciever().clearMails();
+    }
+
+    @Test
+    public void testMailSetDefaultWebInvalidID() throws MalformedURLException, UnsupportedEncodingException, IOException, InterruptedException, GigiApiException {
+        User u2 = User.getById(createVerifiedUser("fn", "ln", createUniqueName() + "uni@example.org", TEST_PASSWORD));
+        int id = -1;
+        EmailAddress[] emails = u2.getEmails();
+        for (int i = 0; i < emails.length; i++) {
+            if (emails[i].getAddress().equals(u2.getEmail())) {
+                id = emails[i].getId();
+            }
+        }
+        assertNotEquals(id, -1);
+        assertNotNull(executeBasicWebInteraction(cookie, path, "makedefault&emailid=" + id));
+        assertNotEquals(User.getById(u.getId()).getEmail(), u2.getEmail());
+        getMailReciever().clearMails();
+    }
+
+    @Test
+    public void testMailDeleteWeb() throws InterruptedException, GigiApiException, MalformedURLException, UnsupportedEncodingException, IOException {
+        EmailAddress addr = createVerifiedEmail(u);
+        assertNull(executeBasicWebInteraction(cookie, path, "delete&delid[]=" + addr.getId(), 0));
+        User u = User.getById(this.u.getId());
+        EmailAddress[] addresses = u.getEmails();
+        for (int i = 0; i < addresses.length; i++) {
+            assertNotEquals(addresses[i].getAddress(), addr.getAddress());
+        }
+    }
+
+    @Test
+    public void testMailDeleteWebMulti() throws InterruptedException, GigiApiException, MalformedURLException, UnsupportedEncodingException, IOException {
+        EmailAddress[] addr = new EmailAddress[] {
+                createVerifiedEmail(u), createVerifiedEmail(u)
+        };
+        assertNull(executeBasicWebInteraction(cookie, path, "delete&delid[]=" + addr[0].getId() + "&delid[]=" + addr[1].getId(), 0));
+        User u = User.getById(this.u.getId());
+        EmailAddress[] addresses = u.getEmails();
+        for (int i = 0; i < addresses.length; i++) {
+            assertNotEquals(addresses[i].getAddress(), addr[0].getAddress());
+            assertNotEquals(addresses[i].getAddress(), addr[1].getAddress());
+        }
+    }
+
+    @Test
+    public void testMailDeleteWebFaulty() throws MalformedURLException, UnsupportedEncodingException, IOException {
+        User u2 = User.getById(createVerifiedUser("fn", "ln", createUniqueName() + "uni@test.tld", TEST_PASSWORD));
+        EmailAddress em = u2.getEmails()[0];
+        assertNotNull(executeBasicWebInteraction(cookie, path, "delete&delid[]=" + em.getId(), 0));
+        u2 = User.getById(u2.getId());
+        assertNotEquals(u2.getEmails().length, 0);
+    }
 }
index dd53ec50248b9f06104a51b160d9087221188d0e..be0124a7fd7c8100b7653dde090c02660c60d7cb 100644 (file)
@@ -14,171 +14,165 @@ import org.junit.Before;
 import org.junit.Test;
 
 public class RegisterPageTest extends ManagedTest {
-       static {
-               InitTruststore.run();
-               HttpURLConnection.setFollowRedirects(false);
-       }
-
-       @Before
-       public void setUp() throws Exception {
-       }
-
-       @Test
-       public void testSuccess() throws IOException, InterruptedException {
-               long uniq = System.currentTimeMillis();
-               registerUser("ab", "b", "correct" + uniq + "@email.de", TEST_PASSWORD);
-               assertSuccessfullRegMail();
-
-               String defaultSignup = "fname=" + URLEncoder.encode("ab", "UTF-8") + "&lname="
-                       + URLEncoder.encode("b", "UTF-8") + "&pword1=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") + "&pword2="
-                       + URLEncoder.encode(TEST_PASSWORD, "UTF-8")
-                       + "&day=1&month=1&year=1910&cca_agree=1&mname=mn&suffix=sf&email=";
-
-               String query = defaultSignup + URLEncoder.encode("correct3_" + uniq + "@email.de", "UTF-8")
-                       + "&general=1&country=1&regional=1&radius=1";
-               String data = fetchStartErrorMessage(runRegister(query));
-               assertTrue(data, data.startsWith("</div>"));
-               assertSuccessfullRegMail();
-
-               getMailReciever().setEmailCheckError("400 Greylisted");
-               getMailReciever().setApproveRegex(Pattern.compile("a"));
-               query = defaultSignup + URLEncoder.encode("correct4_" + uniq + "@email.de", "UTF-8")
-                       + "&general=1&country=1&regional=1&radius=1";
-               data = fetchStartErrorMessage(runRegister(query));
-               assertFalse(data, data.startsWith("</div>"));
-
-               assertNull(getMailReciever().recieve());
-
-       }
-
-       private void assertSuccessfullRegMail() {
-               TestMail tm = waitForMail();
-               String link = tm.extractLink();
-               assertTrue(link, link.startsWith("https://"));
-       }
-
-       @Test
-       public void testNoFname() throws IOException {
-               testFailedForm("lname=b&email=e&pword1=ap&pword2=ap&day=1&month=1&year=1910&cca_agree=1");
-       }
-
-       @Test
-       public void testNoLname() throws IOException {
-               testFailedForm("fname=a&email=e&pword1=ap&pword2=ap&day=1&month=1&year=1910&cca_agree=1");
-       }
-
-       @Test
-       public void testNoEmail() throws IOException {
-               testFailedForm("fname=a&lname=b&pword1=ap&pword2=ap&day=1&month=1&year=1910&cca_agree=1");
-       }
-
-       @Test
-       public void testNoPword() throws IOException {
-               testFailedForm("fname=a&lname=b&email=e&pword2=ap&day=1&month=1&year=1910&cca_agree=1");
-       }
-
-       @Test
-       public void testDiffPword() throws IOException {
-               testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap2&day=1&month=1&year=1910&cca_agree=1");
-       }
-
-       @Test
-       public void testNoDay() throws IOException {
-               testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&month=1&year=1910&cca_agree=1");
-       }
-
-       @Test
-       public void testNoMonth() throws IOException {
-               testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&year=1910&cca_agree=1");
-       }
-
-       @Test
-       public void testNoYear() throws IOException {
-               testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=1&cca_agree=1");
-       }
-
-       @Test
-       public void testInvDay() throws IOException {
-               testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=40&month=1&year=1910&cca_agree=1");
-               testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=0&month=1&year=1910&cca_agree=1");
-               testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=a&month=1&year=1910&cca_agree=1");
-       }
-
-       @Test
-       public void testInvMonth() throws IOException {
-               testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=20&year=1910&cca_agree=1");
-               testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=0&year=1910&cca_agree=1");
-               testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=-1&year=1910&cca_agree=1");
-               testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=a&year=1910&cca_agree=1");
-       }
-
-       @Test
-       public void testInvYear() throws IOException {
-               testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=1&year=0&cca_agree=1");
-               testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=1&year=100&cca_agree=1");
-               testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=1&year=a&cca_agree=1");
-               testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=1&year=-1&cca_agree=1");
-       }
-
-       @Test
-       public void testNoAgree() throws IOException {
-               testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=1&year=1910&cca_agree=a");
-       }
-
-       @Test
-       public void testDataStays() throws IOException {
-               long uniq = System.currentTimeMillis();
-               String run = runRegister("fname=fn" + uniq + "&lname=ln" + uniq + "&email=ma" + uniq + "@cacert.org&pword1=pas"
-                       + uniq + "&pword2=pas2" + uniq + "&day=1&month=1&year=0");
-               assertTrue(run.contains("fn" + uniq));
-               assertTrue(run.contains("ln" + uniq));
-               assertTrue(run.contains("ma" + uniq + "@cacert.org"));
-               assertTrue(!run.contains("pas" + uniq));
-               assertTrue(!run.contains("pas2" + uniq));
-
-       }
-
-       @Test
-       public void testCheckboxesStay() throws IOException {
-               String run2 = runRegister("general=1&country=a&regional=1&radius=0");
-               assertTrue(run2.contains("name=\"general\" value=\"1\" checked=\"checked\">"));
-               assertTrue(run2.contains("name=\"country\" value=\"1\">"));
-               assertTrue(run2.contains("name=\"regional\" value=\"1\" checked=\"checked\">"));
-               assertTrue(run2.contains("name=\"radius\" value=\"1\">"));
-               run2 = runRegister("general=0&country=1&radius=1");
-               assertTrue(run2.contains("name=\"general\" value=\"1\">"));
-               assertTrue(run2.contains("name=\"country\" value=\"1\" checked=\"checked\">"));
-               assertTrue(run2.contains("name=\"regional\" value=\"1\">"));
-               assertTrue(run2.contains("name=\"radius\" value=\"1\" checked=\"checked\">"));
-       }
-
-       @Test
-       public void testDoubleMail() throws IOException {
-               long uniq = System.currentTimeMillis();
-               registerUser("RegisterTest", "User", "testmail" + uniq + "@cacert.org", TEST_PASSWORD);
-               try {
-                       registerUser("RegisterTest", "User", "testmail" + uniq + "@cacert.org", TEST_PASSWORD);
-                       throw new Error("Registering a user with the same email needs to fail.");
-               } catch (AssertionError e) {
-
-               }
-       }
-
-       @Test
-       public void testInvalidMailbox() {
-               getMailReciever().setApproveRegex(Pattern.compile("a"));
-               long uniq = System.currentTimeMillis();
-               try {
-                       registerUser("RegisterTest", "User", "testInvalidMailbox" + uniq + "@cacert.org", TEST_PASSWORD);
-                       throw new Error("Registering a user with invalid mailbox must fail.");
-               } catch (AssertionError e) {
-
-               }
-       }
-
-       private void testFailedForm(String query) throws IOException {
-               String startError = fetchStartErrorMessage(runRegister(query));
-               assertTrue(startError, !startError.startsWith("</div>"));
-       }
+
+    static {
+        InitTruststore.run();
+        HttpURLConnection.setFollowRedirects(false);
+    }
+
+    @Before
+    public void setUp() throws Exception {}
+
+    @Test
+    public void testSuccess() throws IOException, InterruptedException {
+        long uniq = System.currentTimeMillis();
+        registerUser("ab", "b", "correct" + uniq + "@email.de", TEST_PASSWORD);
+        assertSuccessfullRegMail();
+
+        String defaultSignup = "fname=" + URLEncoder.encode("ab", "UTF-8") + "&lname=" + URLEncoder.encode("b", "UTF-8") + "&pword1=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") + "&pword2=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") + "&day=1&month=1&year=1910&cca_agree=1&mname=mn&suffix=sf&email=";
+
+        String query = defaultSignup + URLEncoder.encode("correct3_" + uniq + "@email.de", "UTF-8") + "&general=1&country=1&regional=1&radius=1";
+        String data = fetchStartErrorMessage(runRegister(query));
+        assertTrue(data, data.startsWith("</div>"));
+        assertSuccessfullRegMail();
+
+        getMailReciever().setEmailCheckError("400 Greylisted");
+        getMailReciever().setApproveRegex(Pattern.compile("a"));
+        query = defaultSignup + URLEncoder.encode("correct4_" + uniq + "@email.de", "UTF-8") + "&general=1&country=1&regional=1&radius=1";
+        data = fetchStartErrorMessage(runRegister(query));
+        assertFalse(data, data.startsWith("</div>"));
+
+        assertNull(getMailReciever().recieve());
+
+    }
+
+    private void assertSuccessfullRegMail() {
+        TestMail tm = waitForMail();
+        String link = tm.extractLink();
+        assertTrue(link, link.startsWith("https://"));
+    }
+
+    @Test
+    public void testNoFname() throws IOException {
+        testFailedForm("lname=b&email=e&pword1=ap&pword2=ap&day=1&month=1&year=1910&cca_agree=1");
+    }
+
+    @Test
+    public void testNoLname() throws IOException {
+        testFailedForm("fname=a&email=e&pword1=ap&pword2=ap&day=1&month=1&year=1910&cca_agree=1");
+    }
+
+    @Test
+    public void testNoEmail() throws IOException {
+        testFailedForm("fname=a&lname=b&pword1=ap&pword2=ap&day=1&month=1&year=1910&cca_agree=1");
+    }
+
+    @Test
+    public void testNoPword() throws IOException {
+        testFailedForm("fname=a&lname=b&email=e&pword2=ap&day=1&month=1&year=1910&cca_agree=1");
+    }
+
+    @Test
+    public void testDiffPword() throws IOException {
+        testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap2&day=1&month=1&year=1910&cca_agree=1");
+    }
+
+    @Test
+    public void testNoDay() throws IOException {
+        testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&month=1&year=1910&cca_agree=1");
+    }
+
+    @Test
+    public void testNoMonth() throws IOException {
+        testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&year=1910&cca_agree=1");
+    }
+
+    @Test
+    public void testNoYear() throws IOException {
+        testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=1&cca_agree=1");
+    }
+
+    @Test
+    public void testInvDay() throws IOException {
+        testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=40&month=1&year=1910&cca_agree=1");
+        testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=0&month=1&year=1910&cca_agree=1");
+        testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=a&month=1&year=1910&cca_agree=1");
+    }
+
+    @Test
+    public void testInvMonth() throws IOException {
+        testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=20&year=1910&cca_agree=1");
+        testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=0&year=1910&cca_agree=1");
+        testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=-1&year=1910&cca_agree=1");
+        testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=a&year=1910&cca_agree=1");
+    }
+
+    @Test
+    public void testInvYear() throws IOException {
+        testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=1&year=0&cca_agree=1");
+        testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=1&year=100&cca_agree=1");
+        testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=1&year=a&cca_agree=1");
+        testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=1&year=-1&cca_agree=1");
+    }
+
+    @Test
+    public void testNoAgree() throws IOException {
+        testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=1&year=1910&cca_agree=a");
+    }
+
+    @Test
+    public void testDataStays() throws IOException {
+        long uniq = System.currentTimeMillis();
+        String run = runRegister("fname=fn" + uniq + "&lname=ln" + uniq + "&email=ma" + uniq + "@cacert.org&pword1=pas" + uniq + "&pword2=pas2" + uniq + "&day=1&month=1&year=0");
+        assertTrue(run.contains("fn" + uniq));
+        assertTrue(run.contains("ln" + uniq));
+        assertTrue(run.contains("ma" + uniq + "@cacert.org"));
+        assertTrue( !run.contains("pas" + uniq));
+        assertTrue( !run.contains("pas2" + uniq));
+
+    }
+
+    @Test
+    public void testCheckboxesStay() throws IOException {
+        String run2 = runRegister("general=1&country=a&regional=1&radius=0");
+        assertTrue(run2.contains("name=\"general\" value=\"1\" checked=\"checked\">"));
+        assertTrue(run2.contains("name=\"country\" value=\"1\">"));
+        assertTrue(run2.contains("name=\"regional\" value=\"1\" checked=\"checked\">"));
+        assertTrue(run2.contains("name=\"radius\" value=\"1\">"));
+        run2 = runRegister("general=0&country=1&radius=1");
+        assertTrue(run2.contains("name=\"general\" value=\"1\">"));
+        assertTrue(run2.contains("name=\"country\" value=\"1\" checked=\"checked\">"));
+        assertTrue(run2.contains("name=\"regional\" value=\"1\">"));
+        assertTrue(run2.contains("name=\"radius\" value=\"1\" checked=\"checked\">"));
+    }
+
+    @Test
+    public void testDoubleMail() throws IOException {
+        long uniq = System.currentTimeMillis();
+        registerUser("RegisterTest", "User", "testmail" + uniq + "@cacert.org", TEST_PASSWORD);
+        try {
+            registerUser("RegisterTest", "User", "testmail" + uniq + "@cacert.org", TEST_PASSWORD);
+            throw new Error("Registering a user with the same email needs to fail.");
+        } catch (AssertionError e) {
+
+        }
+    }
+
+    @Test
+    public void testInvalidMailbox() {
+        getMailReciever().setApproveRegex(Pattern.compile("a"));
+        long uniq = System.currentTimeMillis();
+        try {
+            registerUser("RegisterTest", "User", "testInvalidMailbox" + uniq + "@cacert.org", TEST_PASSWORD);
+            throw new Error("Registering a user with invalid mailbox must fail.");
+        } catch (AssertionError e) {
+
+        }
+    }
+
+    private void testFailedForm(String query) throws IOException {
+        String startError = fetchStartErrorMessage(runRegister(query));
+        assertTrue(startError, !startError.startsWith("</div>"));
+    }
 
 }
index 98248933cd215b710d99fd9a2d22dde3e65a7b77..94f194a3a7bd7aa1a330e30c1f67e8e4b86d6fd5 100644 (file)
@@ -21,154 +21,153 @@ import org.junit.Test;
 import static org.junit.Assert.*;
 
 public class TestAssurance extends ManagedTest {
-       private String assurerM;
-       private String assureeM;
-       private int assurer;
-       private int assuree;
-       private String cookie;
-
-       @Before
-       public void setup() throws IOException {
-               assurerM = createUniqueName() + "@cacert-test.org";
-               assureeM = createUniqueName() + "@cacert-test.org";
-               assurer = createAssuranceUser("a", "b", assurerM, TEST_PASSWORD);
-               assuree = createAssuranceUser("a", "c", assureeM, TEST_PASSWORD);
-               cookie = login(assurerM, TEST_PASSWORD);
-
-       }
-
-       @Test
-       public void testAssureSearch() throws IOException {
-               String loc = search("email=" + URLEncoder.encode(assureeM, "UTF-8") + "&day=1&month=1&year=1910");
-               assertTrue(loc, loc.endsWith(AssurePage.PATH + "/" + assuree));
-       }
-
-       @Test
-       public void testAssureSearchEmail() throws IOException {
-               String loc = search("email=1" + URLEncoder.encode(assureeM, "UTF-8") + "&day=1&month=1&year=1910");
-               assertNull(loc);
-       }
-
-       @Test
-       public void testAssureSearchDob() throws IOException {
-               String loc = search("email=" + URLEncoder.encode(assureeM, "UTF-8") + "&day=2&month=1&year=1910");
-               assertNull(loc);
-               loc = search("email=" + URLEncoder.encode(assureeM, "UTF-8") + "&day=1&month=2&year=1910");
-               assertNull(loc);
-               loc = search("email=" + URLEncoder.encode(assureeM, "UTF-8") + "&day=1&month=1&year=1911");
-               assertNull(loc);
-       }
-
-       private String search(String query) throws MalformedURLException, IOException, UnsupportedEncodingException {
-               URL u = new URL("https://" + getServerName() + AssurePage.PATH);
-               URLConnection uc = u.openConnection();
-               uc.setDoOutput(true);
-               uc.addRequestProperty("Cookie", cookie);
-               uc.getOutputStream().write((query).getBytes());
-               uc.getOutputStream().flush();
-
-               String loc = uc.getHeaderField("Location");
-               return loc;
-       }
-
-       @Test
-       public void testAssureForm() throws IOException {
-               String error = getError("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10");
-               assertTrue(error, error.startsWith("</div>"));
-       }
-
-       @Test
-       public void testAssureFormNoCSRF() throws IOException {
-               // override csrf
-               HttpURLConnection uc = (HttpURLConnection) buildupAssureFormConnection(false);
-               uc.getOutputStream().write(
-                       ("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10").getBytes());
-               uc.getOutputStream().flush();
-               assertEquals(500, uc.getResponseCode());
-       }
-
-       @Test
-       public void testAssureFormWrongCSRF() throws IOException {
-               // override csrf
-               HttpURLConnection uc = (HttpURLConnection) buildupAssureFormConnection(false);
-               uc.getOutputStream().write(
-                       ("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10&csrf=aragc")
-                               .getBytes());
-               uc.getOutputStream().flush();
-               assertEquals(500, uc.getResponseCode());
-       }
-
-       @Test
-       public void testAssureFormRace() throws IOException, SQLException {
-               URLConnection uc = buildupAssureFormConnection(true);
-               PreparedStatement ps = DatabaseConnection.getInstance()
-                       .prepare("UPDATE `users` SET email='changed' WHERE id=?");
-               ps.setInt(1, assuree);
-               ps.execute();
-               uc.getOutputStream().write(
-                       ("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10").getBytes());
-               uc.getOutputStream().flush();
-               String error = fetchStartErrorMessage(IOUtils.readURL(uc));
-               assertTrue(error, !error.startsWith("</div>"));
-       }
-
-       @Test
-       public void testAssureFormFuture() throws IOException {
-               SimpleDateFormat sdf = new SimpleDateFormat("YYYY");
-               int year = Integer.parseInt(sdf.format(new Date(System.currentTimeMillis()))) + 2;
-               String error = getError("date=" + year
-                       + "-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10");
-               assertTrue(error, !error.startsWith("</div>"));
-       }
-
-       @Test
-       public void testAssureFormNoLoc() throws IOException {
-               String error = getError("date=2000-01-01&location=a&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10");
-               assertTrue(error, !error.startsWith("</div>"));
-               error = getError("date=2000-01-01&location=&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10");
-               assertTrue(error, !error.startsWith("</div>"));
-       }
-
-       @Test
-       public void testAssureFormInvalDate() throws IOException {
-               String error = getError("date=20000101&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10");
-               assertTrue(error, !error.startsWith("</div>"));
-               error = getError("date=&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10");
-               assertTrue(error, !error.startsWith("</div>"));
-       }
-
-       @Test
-       public void testAssureFormBoxes() throws IOException {
-               String error = getError("date=2000-01-01&location=testcase&certify=0&rules=1&CCAAgreed=1&assertion=1&points=10");
-               assertTrue(error, !error.startsWith("</div>"));
-               error = getError("date=2000-01-01&location=testcase&certify=1&rules=&CCAAgreed=1&assertion=1&points=10");
-               assertTrue(error, !error.startsWith("</div>"));
-               error = getError("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=a&assertion=1&points=10");
-               assertTrue(error, !error.startsWith("</div>"));
-               error = getError("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=z&points=10");
-               assertTrue(error, !error.startsWith("</div>"));
-       }
-
-       private String getError(String query) throws MalformedURLException, IOException {
-               URLConnection uc = buildupAssureFormConnection(true);
-               uc.getOutputStream().write((query).getBytes());
-               uc.getOutputStream().flush();
-               String error = fetchStartErrorMessage(IOUtils.readURL(uc));
-               return error;
-       }
-
-       private URLConnection buildupAssureFormConnection(boolean doCSRF) throws MalformedURLException, IOException {
-               URL u = new URL("https://" + getServerName() + AssurePage.PATH + "/" + assuree);
-               URLConnection uc = u.openConnection();
-               uc.addRequestProperty("Cookie", cookie);
-               String csrf = getCSRF(uc);
-               uc = u.openConnection();
-               uc.addRequestProperty("Cookie", cookie);
-               uc.setDoOutput(true);
-               if (doCSRF) {
-                       uc.getOutputStream().write(("csrf=" + csrf + "&").getBytes());
-               }
-               return uc;
-       }
+
+    private String assurerM;
+
+    private String assureeM;
+
+    private int assurer;
+
+    private int assuree;
+
+    private String cookie;
+
+    @Before
+    public void setup() throws IOException {
+        assurerM = createUniqueName() + "@cacert-test.org";
+        assureeM = createUniqueName() + "@cacert-test.org";
+        assurer = createAssuranceUser("a", "b", assurerM, TEST_PASSWORD);
+        assuree = createAssuranceUser("a", "c", assureeM, TEST_PASSWORD);
+        cookie = login(assurerM, TEST_PASSWORD);
+
+    }
+
+    @Test
+    public void testAssureSearch() throws IOException {
+        String loc = search("email=" + URLEncoder.encode(assureeM, "UTF-8") + "&day=1&month=1&year=1910");
+        assertTrue(loc, loc.endsWith(AssurePage.PATH + "/" + assuree));
+    }
+
+    @Test
+    public void testAssureSearchEmail() throws IOException {
+        String loc = search("email=1" + URLEncoder.encode(assureeM, "UTF-8") + "&day=1&month=1&year=1910");
+        assertNull(loc);
+    }
+
+    @Test
+    public void testAssureSearchDob() throws IOException {
+        String loc = search("email=" + URLEncoder.encode(assureeM, "UTF-8") + "&day=2&month=1&year=1910");
+        assertNull(loc);
+        loc = search("email=" + URLEncoder.encode(assureeM, "UTF-8") + "&day=1&month=2&year=1910");
+        assertNull(loc);
+        loc = search("email=" + URLEncoder.encode(assureeM, "UTF-8") + "&day=1&month=1&year=1911");
+        assertNull(loc);
+    }
+
+    private String search(String query) throws MalformedURLException, IOException, UnsupportedEncodingException {
+        URL u = new URL("https://" + getServerName() + AssurePage.PATH);
+        URLConnection uc = u.openConnection();
+        uc.setDoOutput(true);
+        uc.addRequestProperty("Cookie", cookie);
+        uc.getOutputStream().write((query).getBytes());
+        uc.getOutputStream().flush();
+
+        String loc = uc.getHeaderField("Location");
+        return loc;
+    }
+
+    @Test
+    public void testAssureForm() throws IOException {
+        String error = getError("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10");
+        assertTrue(error, error.startsWith("</div>"));
+    }
+
+    @Test
+    public void testAssureFormNoCSRF() throws IOException {
+        // override csrf
+        HttpURLConnection uc = (HttpURLConnection) buildupAssureFormConnection(false);
+        uc.getOutputStream().write(("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10").getBytes());
+        uc.getOutputStream().flush();
+        assertEquals(500, uc.getResponseCode());
+    }
+
+    @Test
+    public void testAssureFormWrongCSRF() throws IOException {
+        // override csrf
+        HttpURLConnection uc = (HttpURLConnection) buildupAssureFormConnection(false);
+        uc.getOutputStream().write(("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10&csrf=aragc").getBytes());
+        uc.getOutputStream().flush();
+        assertEquals(500, uc.getResponseCode());
+    }
+
+    @Test
+    public void testAssureFormRace() throws IOException, SQLException {
+        URLConnection uc = buildupAssureFormConnection(true);
+        PreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE `users` SET email='changed' WHERE id=?");
+        ps.setInt(1, assuree);
+        ps.execute();
+        uc.getOutputStream().write(("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10").getBytes());
+        uc.getOutputStream().flush();
+        String error = fetchStartErrorMessage(IOUtils.readURL(uc));
+        assertTrue(error, !error.startsWith("</div>"));
+    }
+
+    @Test
+    public void testAssureFormFuture() throws IOException {
+        SimpleDateFormat sdf = new SimpleDateFormat("YYYY");
+        int year = Integer.parseInt(sdf.format(new Date(System.currentTimeMillis()))) + 2;
+        String error = getError("date=" + year + "-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10");
+        assertTrue(error, !error.startsWith("</div>"));
+    }
+
+    @Test
+    public void testAssureFormNoLoc() throws IOException {
+        String error = getError("date=2000-01-01&location=a&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10");
+        assertTrue(error, !error.startsWith("</div>"));
+        error = getError("date=2000-01-01&location=&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10");
+        assertTrue(error, !error.startsWith("</div>"));
+    }
+
+    @Test
+    public void testAssureFormInvalDate() throws IOException {
+        String error = getError("date=20000101&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10");
+        assertTrue(error, !error.startsWith("</div>"));
+        error = getError("date=&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10");
+        assertTrue(error, !error.startsWith("</div>"));
+    }
+
+    @Test
+    public void testAssureFormBoxes() throws IOException {
+        String error = getError("date=2000-01-01&location=testcase&certify=0&rules=1&CCAAgreed=1&assertion=1&points=10");
+        assertTrue(error, !error.startsWith("</div>"));
+        error = getError("date=2000-01-01&location=testcase&certify=1&rules=&CCAAgreed=1&assertion=1&points=10");
+        assertTrue(error, !error.startsWith("</div>"));
+        error = getError("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=a&assertion=1&points=10");
+        assertTrue(error, !error.startsWith("</div>"));
+        error = getError("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=z&points=10");
+        assertTrue(error, !error.startsWith("</div>"));
+    }
+
+    private String getError(String query) throws MalformedURLException, IOException {
+        URLConnection uc = buildupAssureFormConnection(true);
+        uc.getOutputStream().write((query).getBytes());
+        uc.getOutputStream().flush();
+        String error = fetchStartErrorMessage(IOUtils.readURL(uc));
+        return error;
+    }
+
+    private URLConnection buildupAssureFormConnection(boolean doCSRF) throws MalformedURLException, IOException {
+        URL u = new URL("https://" + getServerName() + AssurePage.PATH + "/" + assuree);
+        URLConnection uc = u.openConnection();
+        uc.addRequestProperty("Cookie", cookie);
+        String csrf = getCSRF(uc);
+        uc = u.openConnection();
+        uc.addRequestProperty("Cookie", cookie);
+        uc.setDoOutput(true);
+        if (doCSRF) {
+            uc.getOutputStream().write(("csrf=" + csrf + "&").getBytes());
+        }
+        return uc;
+    }
 
 }
index 2db46f87832bb8acfeb2d90fb571b6cb22ec6cab..e33192e7d1fb893e228b40fad3372cc1c14ac45b 100644 (file)
@@ -8,38 +8,38 @@ import java.net.HttpURLConnection;
 import java.net.URLConnection;
 
 public class IOUtils {
-       private IOUtils() {
-
-       }
-
-       public static String readURL(URLConnection in) {
-               try {
-                       if (!in.getContentType().equals("text/html; charset=UTF-8")) {
-                               if (in instanceof HttpURLConnection && ((HttpURLConnection) in).getResponseCode() != 200) {
-                                       System.err
-                                               .println(readURL(new InputStreamReader(((HttpURLConnection) in).getErrorStream(), "UTF-8")));
-                               }
-                               throw new Error("Unrecognized content-type: " + in.getContentType());
-                       }
-                       return readURL(new InputStreamReader(in.getInputStream(), "UTF-8"));
-               } catch (IOException e) {
-                       throw new Error(e);
-               }
-
-       }
-
-       public static String readURL(Reader in) {
-               CharArrayWriter caw = new CharArrayWriter();
-               char[] buffer = new char[1024];
-               int len = 0;
-               try {
-                       while ((len = in.read(buffer)) > 0) {
-                               caw.write(buffer, 0, len);
-                       }
-                       return new String(caw.toCharArray());
-               } catch (IOException e) {
-                       throw new Error(e);
-               }
-
-       }
+
+    private IOUtils() {
+
+    }
+
+    public static String readURL(URLConnection in) {
+        try {
+            if ( !in.getContentType().equals("text/html; charset=UTF-8")) {
+                if (in instanceof HttpURLConnection && ((HttpURLConnection) in).getResponseCode() != 200) {
+                    System.err.println(readURL(new InputStreamReader(((HttpURLConnection) in).getErrorStream(), "UTF-8")));
+                }
+                throw new Error("Unrecognized content-type: " + in.getContentType());
+            }
+            return readURL(new InputStreamReader(in.getInputStream(), "UTF-8"));
+        } catch (IOException e) {
+            throw new Error(e);
+        }
+
+    }
+
+    public static String readURL(Reader in) {
+        CharArrayWriter caw = new CharArrayWriter();
+        char[] buffer = new char[1024];
+        int len = 0;
+        try {
+            while ((len = in.read(buffer)) > 0) {
+                caw.write(buffer, 0, len);
+            }
+            return new String(caw.toCharArray());
+        } catch (IOException e) {
+            throw new Error(e);
+        }
+
+    }
 }
index 7811470d8d9c984582301bf070063ff342fe2021..1207df930b3cd6b70e0d353f40dab0d45807ca9e 100644 (file)
@@ -1,15 +1,15 @@
 package org.cacert.gigi.testUtils;
 
 public class InitTruststore {
-       private InitTruststore() {
-       }
 
-       static {
-               System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
-               System.setProperty("javax.net.ssl.trustStore", "config/cacerts.jks");
-       }
+    private InitTruststore() {}
 
-       public static void run() {
+    static {
+        System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
+        System.setProperty("javax.net.ssl.trustStore", "config/cacerts.jks");
+    }
 
-       }
+    public static void run() {
+
+    }
 }
index 5d4db1299df473caf6a8e3849f76bcc711ad0b0b..a021427e861e08d659c2f5c3249af43cbd5b5288 100644 (file)
@@ -50,392 +50,394 @@ import org.junit.AfterClass;
 import org.junit.BeforeClass;
 
 public class ManagedTest {
-       /**
-        * Some password that fullfills the password criteria.
-        */
-       protected static final String TEST_PASSWORD = "xvXV12°§";
-
-       private final String registerService = "/register";
-
-       private static TestEmailReciever ter;
-       private static Process gigi;
-       private static String url = "localhost:4443";
-
-       public static String getServerName() {
-               return url;
-       }
-
-       static Properties testProps = new Properties();
-       static {
-               InitTruststore.run();
-               HttpURLConnection.setFollowRedirects(false);
-       }
-
-       @BeforeClass
-       public static void connectToServer() {
-               try {
-                       testProps.load(new FileInputStream("config/test.properties"));
-                       if (!DatabaseConnection.isInited()) {
-                               DatabaseConnection.init(testProps);
-                       }
-                       System.out.println("... purging Database");
-                       DatabaseManager.run(new String[] { testProps.getProperty("sql.driver"), testProps.getProperty("sql.url"),
-                                       testProps.getProperty("sql.user"), testProps.getProperty("sql.password") });
-                       String type = testProps.getProperty("type");
-                       Properties mainProps = generateMainProps();
-                       ServerConstants.init(mainProps);
-                       if (type.equals("local")) {
-                               url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort");
-                               String[] parts = testProps.getProperty("mail").split(":", 2);
-                               ter = new TestEmailReciever(new InetSocketAddress(parts[0], Integer.parseInt(parts[1])));
-                               return;
-                       }
-                       url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort");
-                       gigi = Runtime.getRuntime().exec(testProps.getProperty("java"));
-                       DataOutputStream toGigi = new DataOutputStream(gigi.getOutputStream());
-                       System.out.println("... starting server");
-
-                       byte[] cacerts = Files.readAllBytes(Paths.get("config/cacerts.jks"));
-                       byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12"));
-
-                       DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes(), "changeit".getBytes(), mainProps, cacerts,
-                               keystore);
-                       toGigi.flush();
-
-                       final BufferedReader br = new BufferedReader(new InputStreamReader(gigi.getErrorStream()));
-                       String line;
-                       while ((line = br.readLine()) != null && !line.contains("Server:main: Started")) {
-                       }
-                       new Thread() {
-                               @Override
-                               public void run() {
-                                       String line;
-                                       try {
-                                               while ((line = br.readLine()) != null) {
-                                                       System.err.println(line);
-                                               }
-                                       } catch (IOException e) {
-                                               e.printStackTrace();
-                                       }
-                               }
-                       }.start();
-                       if (line == null) {
-                               throw new Error("Server startup failed");
-                       }
-                       ter = new TestEmailReciever(new InetSocketAddress("localhost", 8473));
-                       SimpleSigner.runSigner();
-               } catch (IOException e) {
-                       throw new Error(e);
-               } catch (ClassNotFoundException e1) {
-                       e1.printStackTrace();
-               } catch (SQLException e1) {
-                       e1.printStackTrace();
-               } catch (InterruptedException e) {
-                       e.printStackTrace();
-               }
-
-       }
-
-       private static Properties generateMainProps() {
-               Properties mainProps = new Properties();
-               mainProps.setProperty("host", "127.0.0.1");
-               mainProps.setProperty("name.secure", testProps.getProperty("name.secure"));
-               mainProps.setProperty("name.www", testProps.getProperty("name.www"));
-               mainProps.setProperty("name.static", testProps.getProperty("name.static"));
-
-               mainProps.setProperty("port", testProps.getProperty("serverPort"));
-               mainProps.setProperty("emailProvider", "org.cacert.gigi.email.TestEmailProvider");
-               mainProps.setProperty("emailProvider.port", "8473");
-               mainProps.setProperty("sql.driver", testProps.getProperty("sql.driver"));
-               mainProps.setProperty("sql.url", testProps.getProperty("sql.url"));
-               mainProps.setProperty("sql.user", testProps.getProperty("sql.user"));
-               mainProps.setProperty("sql.password", testProps.getProperty("sql.password"));
-               return mainProps;
-       }
-
-       @AfterClass
-       public static void tearDownServer() {
-               String type = testProps.getProperty("type");
-               ter.destroy();
-               if (type.equals("local")) {
-                       return;
-               }
-               gigi.destroy();
-               try {
-                       SimpleSigner.stopSigner();
-               } catch (InterruptedException e) {
-                       e.printStackTrace();
-               }
-       }
-
-       @After
-       public void removeMails() {
-               ter.reset();
-       }
-
-       public TestMail waitForMail() {
-               try {
-                       return ter.recieve();
-               } catch (InterruptedException e) {
-                       throw new Error(e);
-               }
-       }
-
-       public static TestEmailReciever getMailReciever() {
-               return ter;
-       }
-
-       public String runRegister(String param) throws IOException {
-               URL regist = new URL("https://" + getServerName() + registerService);
-               HttpURLConnection uc = (HttpURLConnection) regist.openConnection();
-               HttpURLConnection csrfConn = (HttpURLConnection) regist.openConnection();
-
-               String headerField = csrfConn.getHeaderField("Set-Cookie");
-               headerField = stripCookie(headerField);
-
-               String csrf = getCSRF(csrfConn);
-               uc.addRequestProperty("Cookie", headerField);
-               uc.setDoOutput(true);
-               uc.getOutputStream().write((param + "&csrf=" + csrf).getBytes());
-               String d = IOUtils.readURL(uc);
-               return d;
-       }
-
-       public String fetchStartErrorMessage(String d) throws IOException {
-               String formFail = "<div class='formError'>";
-               int idx = d.indexOf(formFail);
-               if (idx == -1) {
-                       return null;
-               }
-               String startError = d.substring(idx + formFail.length(), idx + 100).trim();
-               return startError;
-       }
-
-       public void registerUser(String firstName, String lastName, String email, String password) {
-               try {
-                       String query = "fname=" + URLEncoder.encode(firstName, "UTF-8") + "&lname="
-                               + URLEncoder.encode(lastName, "UTF-8") + "&email=" + URLEncoder.encode(email, "UTF-8") + "&pword1="
-                               + URLEncoder.encode(password, "UTF-8") + "&pword2=" + URLEncoder.encode(password, "UTF-8")
-                               + "&day=1&month=1&year=1910&cca_agree=1";
-                       String data = fetchStartErrorMessage(runRegister(query));
-                       assertTrue(data, data.startsWith("</div>"));
-               } catch (UnsupportedEncodingException e) {
-                       throw new Error(e);
-               } catch (IOException e) {
-                       throw new Error(e);
-               }
-       }
-
-       public int createVerifiedUser(String firstName, String lastName, String email, String password) {
-               registerUser(firstName, lastName, email, password);
-               try {
-                       TestMail tm = ter.recieve();
-                       String verifyLink = tm.extractLink();
-                       String[] parts = verifyLink.split("\\?");
-                       URL u = new URL("https://" + getServerName() + "/verify?" + parts[1]);
-                       u.openStream().close();
-                       ;
-                       PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM users where email=?");
-                       ps.setString(1, email);
-                       ResultSet rs = ps.executeQuery();
-                       if (rs.next()) {
-                               return rs.getInt(1);
-                       }
-                       throw new Error();
-               } catch (InterruptedException e) {
-                       throw new Error(e);
-               } catch (IOException e) {
-                       throw new Error(e);
-               } catch (SQLException e) {
-                       throw new Error(e);
-               }
-       }
-
-       /**
-        * Creates a new user with 100 Assurance points given by an (invalid)
-        * assurance.
-        * 
-        * @param firstName
-        *            the first name
-        * @param lastName
-        *            the last name
-        * @param email
-        *            the email
-        * @param password
-        *            the password
-        * @return a new userid.
-        */
-       public int createAssuranceUser(String firstName, String lastName, String email, String password) {
-               int uid = createVerifiedUser(firstName, lastName, email, password);
-               try {
-                       PreparedStatement ps = DatabaseConnection.getInstance().prepare(
-                               "INSERT INTO `cats_passed` SET `user_id`=?, `variant_id`=?");
-                       ps.setInt(1, uid);
-                       ps.setInt(2, 0);
-                       ps.execute();
-                       ps = DatabaseConnection.getInstance().prepare("INSERT INTO `notary` SET `from`=?, `to`=?, points='100'");
-                       ps.setInt(1, uid);
-                       ps.setInt(2, uid);
-                       ps.execute();
-
-               } catch (SQLException e) {
-                       throw new Error(e);
-               }
-               return uid;
-       }
-
-       static int count = 0;
-
-       public static String createUniqueName() {
-               return "test" + System.currentTimeMillis() + "a" + (count++);
-       }
-
-       private String stripCookie(String headerField) {
-               return headerField.substring(0, headerField.indexOf(';'));
-       }
-
-       public static final String SECURE_REFERENCE = "/account/certs/email";
-
-       public boolean isLoggedin(String cookie) throws IOException {
-               URL u = new URL("https://" + getServerName() + SECURE_REFERENCE);
-               HttpURLConnection huc = (HttpURLConnection) u.openConnection();
-               huc.addRequestProperty("Cookie", cookie);
-               return huc.getResponseCode() == 200;
-       }
-
-       public String login(String email, String pw) throws IOException {
-               URL u = new URL("https://" + getServerName() + "/login");
-               HttpURLConnection huc = (HttpURLConnection) u.openConnection();
-               huc.setDoOutput(true);
-               OutputStream os = huc.getOutputStream();
-               String data = "username=" + URLEncoder.encode(email, "UTF-8") + "&password=" + URLEncoder.encode(pw, "UTF-8");
-               os.write(data.getBytes());
-               os.flush();
-               String headerField = huc.getHeaderField("Set-Cookie");
-               return stripCookie(headerField);
-       }
-
-       public String login(final PrivateKey pk, final X509Certificate ce) throws NoSuchAlgorithmException,
-               KeyManagementException, IOException, MalformedURLException {
-
-               HttpURLConnection connection = (HttpURLConnection) new URL("https://"
-                       + getServerName().replaceFirst("^www.", "secure.") + "/login").openConnection();
-               authenticateClientCert(pk, ce, connection);
-               if (connection.getResponseCode() == 302) {
-                       assertEquals("https://" + getServerName().replaceFirst("^www.", "secure.").replaceFirst(":443$", "") + "/",
-                               connection.getHeaderField("Location").replaceFirst(":443$", ""));
-                       return stripCookie(connection.getHeaderField("Set-Cookie"));
-               } else {
-                       return null;
-               }
-       }
-
-       public void authenticateClientCert(final PrivateKey pk, final X509Certificate ce, HttpURLConnection connection)
-               throws NoSuchAlgorithmException, KeyManagementException {
-               KeyManager km = new X509KeyManager() {
-
-                       @Override
-                       public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) {
-                               return "client";
-                       }
-
-                       @Override
-                       public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) {
-                               return null;
-                       }
-
-                       @Override
-                       public X509Certificate[] getCertificateChain(String arg0) {
-                               return new X509Certificate[] { ce };
-                       }
-
-                       @Override
-                       public String[] getClientAliases(String arg0, Principal[] arg1) {
-                               return new String[] { "client" };
-                       }
-
-                       @Override
-                       public PrivateKey getPrivateKey(String arg0) {
-                               if (arg0.equals("client")) {
-                                       return pk;
-                               }
-                               return null;
-                       }
-
-                       @Override
-                       public String[] getServerAliases(String arg0, Principal[] arg1) {
-                               return new String[] { "client" };
-                       }
-               };
-               SSLContext sc = SSLContext.getInstance("TLS");
-               sc.init(new KeyManager[] { km }, null, null);
-               if (connection instanceof HttpsURLConnection) {
-                       ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory());
-               }
-       }
-
-       public String getCSRF(URLConnection u) throws IOException {
-               return getCSRF(u, 0);
-       }
-
-       public String getCSRF(URLConnection u, int formIndex) throws IOException {
-               String content = IOUtils.readURL(u);
-               Pattern p = Pattern.compile("<input type='hidden' name='csrf' value='([^']+)'>");
-               Matcher m = p.matcher(content);
-               for (int i = 0; i < formIndex + 1; i++) {
-                       if (!m.find()) {
-                               throw new Error("No CSRF Token");
-                       }
-               }
-               return m.group(1);
-       }
-
-       public static String[] generateCSR(String dn) throws IOException {
-               Process p = Runtime.getRuntime().exec(
-                       new String[] { "openssl", "req", "-newkey", "rsa:1024", "-nodes", "-subj", dn, "-config",
-                                       "keys/selfsign.config" });
-               String csr = IOUtils.readURL(new InputStreamReader(p.getInputStream()));
-
-               String[] parts = csr.split("(?<=-----)\n(?=-----)");
-               if (parts.length != 2) {
-                       System.err.println(IOUtils.readURL(new InputStreamReader(p.getErrorStream())));
-                       throw new Error();
-               }
-               return parts;
-       }
-
-       public String executeBasicWebInteraction(String cookie, String path, String query) throws MalformedURLException,
-               UnsupportedEncodingException, IOException {
-               return executeBasicWebInteraction(cookie, path, query, 0);
-       }
-
-       public String executeBasicWebInteraction(String cookie, String path, String query, int formIndex)
-               throws IOException, MalformedURLException, UnsupportedEncodingException {
-               URLConnection uc = new URL("https://" + getServerName() + path).openConnection();
-               uc.addRequestProperty("Cookie", cookie);
-               String csrf = getCSRF(uc, formIndex);
-
-               uc = new URL("https://" + getServerName() + path).openConnection();
-               uc.addRequestProperty("Cookie", cookie);
-               uc.setDoOutput(true);
-               OutputStream os = uc.getOutputStream();
-               os.write(("csrf=" + URLEncoder.encode(csrf, "UTF-8") + "&" //
-               + query//
-               ).getBytes());
-               os.flush();
-               String error = fetchStartErrorMessage(IOUtils.readURL(uc));
-               return error;
-       }
-
-       public static EmailAddress createVerifiedEmail(User u) throws InterruptedException, GigiApiException {
-               EmailAddress adrr = new EmailAddress(createUniqueName() + "test@test.tld", u);
-               adrr.insert(Language.getInstance("en"));
-               TestMail testMail = getMailReciever().recieve();
-               assertTrue(adrr.getAddress().equals(testMail.getTo()));
-               String hash = testMail.extractLink().substring(testMail.extractLink().lastIndexOf('=') + 1);
-               adrr.verify(hash);
-               getMailReciever().clearMails();
-               return adrr;
-       }
+
+    /**
+     * Some password that fullfills the password criteria.
+     */
+    protected static final String TEST_PASSWORD = "xvXV12°§";
+
+    private final String registerService = "/register";
+
+    private static TestEmailReciever ter;
+
+    private static Process gigi;
+
+    private static String url = "localhost:4443";
+
+    public static String getServerName() {
+        return url;
+    }
+
+    static Properties testProps = new Properties();
+    static {
+        InitTruststore.run();
+        HttpURLConnection.setFollowRedirects(false);
+    }
+
+    @BeforeClass
+    public static void connectToServer() {
+        try {
+            testProps.load(new FileInputStream("config/test.properties"));
+            if ( !DatabaseConnection.isInited()) {
+                DatabaseConnection.init(testProps);
+            }
+            System.out.println("... purging Database");
+            DatabaseManager.run(new String[] {
+                    testProps.getProperty("sql.driver"), testProps.getProperty("sql.url"), testProps.getProperty("sql.user"), testProps.getProperty("sql.password")
+            });
+            String type = testProps.getProperty("type");
+            Properties mainProps = generateMainProps();
+            ServerConstants.init(mainProps);
+            if (type.equals("local")) {
+                url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort");
+                String[] parts = testProps.getProperty("mail").split(":", 2);
+                ter = new TestEmailReciever(new InetSocketAddress(parts[0], Integer.parseInt(parts[1])));
+                return;
+            }
+            url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort");
+            gigi = Runtime.getRuntime().exec(testProps.getProperty("java"));
+            DataOutputStream toGigi = new DataOutputStream(gigi.getOutputStream());
+            System.out.println("... starting server");
+
+            byte[] cacerts = Files.readAllBytes(Paths.get("config/cacerts.jks"));
+            byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12"));
+
+            DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes(), "changeit".getBytes(), mainProps, cacerts, keystore);
+            toGigi.flush();
+
+            final BufferedReader br = new BufferedReader(new InputStreamReader(gigi.getErrorStream()));
+            String line;
+            while ((line = br.readLine()) != null && !line.contains("Server:main: Started")) {
+            }
+            new Thread() {
+
+                @Override
+                public void run() {
+                    String line;
+                    try {
+                        while ((line = br.readLine()) != null) {
+                            System.err.println(line);
+                        }
+                    } catch (IOException e) {
+                        e.printStackTrace();
+                    }
+                }
+            }.start();
+            if (line == null) {
+                throw new Error("Server startup failed");
+            }
+            ter = new TestEmailReciever(new InetSocketAddress("localhost", 8473));
+            SimpleSigner.runSigner();
+        } catch (IOException e) {
+            throw new Error(e);
+        } catch (ClassNotFoundException e1) {
+            e1.printStackTrace();
+        } catch (SQLException e1) {
+            e1.printStackTrace();
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+        }
+
+    }
+
+    private static Properties generateMainProps() {
+        Properties mainProps = new Properties();
+        mainProps.setProperty("host", "127.0.0.1");
+        mainProps.setProperty("name.secure", testProps.getProperty("name.secure"));
+        mainProps.setProperty("name.www", testProps.getProperty("name.www"));
+        mainProps.setProperty("name.static", testProps.getProperty("name.static"));
+
+        mainProps.setProperty("port", testProps.getProperty("serverPort"));
+        mainProps.setProperty("emailProvider", "org.cacert.gigi.email.TestEmailProvider");
+        mainProps.setProperty("emailProvider.port", "8473");
+        mainProps.setProperty("sql.driver", testProps.getProperty("sql.driver"));
+        mainProps.setProperty("sql.url", testProps.getProperty("sql.url"));
+        mainProps.setProperty("sql.user", testProps.getProperty("sql.user"));
+        mainProps.setProperty("sql.password", testProps.getProperty("sql.password"));
+        return mainProps;
+    }
+
+    @AfterClass
+    public static void tearDownServer() {
+        String type = testProps.getProperty("type");
+        ter.destroy();
+        if (type.equals("local")) {
+            return;
+        }
+        gigi.destroy();
+        try {
+            SimpleSigner.stopSigner();
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+        }
+    }
+
+    @After
+    public void removeMails() {
+        ter.reset();
+    }
+
+    public TestMail waitForMail() {
+        try {
+            return ter.recieve();
+        } catch (InterruptedException e) {
+            throw new Error(e);
+        }
+    }
+
+    public static TestEmailReciever getMailReciever() {
+        return ter;
+    }
+
+    public String runRegister(String param) throws IOException {
+        URL regist = new URL("https://" + getServerName() + registerService);
+        HttpURLConnection uc = (HttpURLConnection) regist.openConnection();
+        HttpURLConnection csrfConn = (HttpURLConnection) regist.openConnection();
+
+        String headerField = csrfConn.getHeaderField("Set-Cookie");
+        headerField = stripCookie(headerField);
+
+        String csrf = getCSRF(csrfConn);
+        uc.addRequestProperty("Cookie", headerField);
+        uc.setDoOutput(true);
+        uc.getOutputStream().write((param + "&csrf=" + csrf).getBytes());
+        String d = IOUtils.readURL(uc);
+        return d;
+    }
+
+    public String fetchStartErrorMessage(String d) throws IOException {
+        String formFail = "<div class='formError'>";
+        int idx = d.indexOf(formFail);
+        if (idx == -1) {
+            return null;
+        }
+        String startError = d.substring(idx + formFail.length(), idx + 100).trim();
+        return startError;
+    }
+
+    public void registerUser(String firstName, String lastName, String email, String password) {
+        try {
+            String query = "fname=" + URLEncoder.encode(firstName, "UTF-8") + "&lname=" + URLEncoder.encode(lastName, "UTF-8") + "&email=" + URLEncoder.encode(email, "UTF-8") + "&pword1=" + URLEncoder.encode(password, "UTF-8") + "&pword2=" + URLEncoder.encode(password, "UTF-8") + "&day=1&month=1&year=1910&cca_agree=1";
+            String data = fetchStartErrorMessage(runRegister(query));
+            assertTrue(data, data.startsWith("</div>"));
+        } catch (UnsupportedEncodingException e) {
+            throw new Error(e);
+        } catch (IOException e) {
+            throw new Error(e);
+        }
+    }
+
+    public int createVerifiedUser(String firstName, String lastName, String email, String password) {
+        registerUser(firstName, lastName, email, password);
+        try {
+            TestMail tm = ter.recieve();
+            String verifyLink = tm.extractLink();
+            String[] parts = verifyLink.split("\\?");
+            URL u = new URL("https://" + getServerName() + "/verify?" + parts[1]);
+            u.openStream().close();
+            ;
+            PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM users where email=?");
+            ps.setString(1, email);
+            ResultSet rs = ps.executeQuery();
+            if (rs.next()) {
+                return rs.getInt(1);
+            }
+            throw new Error();
+        } catch (InterruptedException e) {
+            throw new Error(e);
+        } catch (IOException e) {
+            throw new Error(e);
+        } catch (SQLException e) {
+            throw new Error(e);
+        }
+    }
+
+    /**
+     * Creates a new user with 100 Assurance points given by an (invalid)
+     * assurance.
+     * 
+     * @param firstName
+     *            the first name
+     * @param lastName
+     *            the last name
+     * @param email
+     *            the email
+     * @param password
+     *            the password
+     * @return a new userid.
+     */
+    public int createAssuranceUser(String firstName, String lastName, String email, String password) {
+        int uid = createVerifiedUser(firstName, lastName, email, password);
+        try {
+            PreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `cats_passed` SET `user_id`=?, `variant_id`=?");
+            ps.setInt(1, uid);
+            ps.setInt(2, 0);
+            ps.execute();
+            ps = DatabaseConnection.getInstance().prepare("INSERT INTO `notary` SET `from`=?, `to`=?, points='100'");
+            ps.setInt(1, uid);
+            ps.setInt(2, uid);
+            ps.execute();
+
+        } catch (SQLException e) {
+            throw new Error(e);
+        }
+        return uid;
+    }
+
+    static int count = 0;
+
+    public static String createUniqueName() {
+        return "test" + System.currentTimeMillis() + "a" + (count++);
+    }
+
+    private String stripCookie(String headerField) {
+        return headerField.substring(0, headerField.indexOf(';'));
+    }
+
+    public static final String SECURE_REFERENCE = "/account/certs/email";
+
+    public boolean isLoggedin(String cookie) throws IOException {
+        URL u = new URL("https://" + getServerName() + SECURE_REFERENCE);
+        HttpURLConnection huc = (HttpURLConnection) u.openConnection();
+        huc.addRequestProperty("Cookie", cookie);
+        return huc.getResponseCode() == 200;
+    }
+
+    public String login(String email, String pw) throws IOException {
+        URL u = new URL("https://" + getServerName() + "/login");
+        HttpURLConnection huc = (HttpURLConnection) u.openConnection();
+        huc.setDoOutput(true);
+        OutputStream os = huc.getOutputStream();
+        String data = "username=" + URLEncoder.encode(email, "UTF-8") + "&password=" + URLEncoder.encode(pw, "UTF-8");
+        os.write(data.getBytes());
+        os.flush();
+        String headerField = huc.getHeaderField("Set-Cookie");
+        return stripCookie(headerField);
+    }
+
+    public String login(final PrivateKey pk, final X509Certificate ce) throws NoSuchAlgorithmException, KeyManagementException, IOException, MalformedURLException {
+
+        HttpURLConnection connection = (HttpURLConnection) new URL("https://" + getServerName().replaceFirst("^www.", "secure.") + "/login").openConnection();
+        authenticateClientCert(pk, ce, connection);
+        if (connection.getResponseCode() == 302) {
+            assertEquals("https://" + getServerName().replaceFirst("^www.", "secure.").replaceFirst(":443$", "") + "/", connection.getHeaderField("Location").replaceFirst(":443$", ""));
+            return stripCookie(connection.getHeaderField("Set-Cookie"));
+        } else {
+            return null;
+        }
+    }
+
+    public void authenticateClientCert(final PrivateKey pk, final X509Certificate ce, HttpURLConnection connection) throws NoSuchAlgorithmException, KeyManagementException {
+        KeyManager km = new X509KeyManager() {
+
+            @Override
+            public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) {
+                return "client";
+            }
+
+            @Override
+            public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) {
+                return null;
+            }
+
+            @Override
+            public X509Certificate[] getCertificateChain(String arg0) {
+                return new X509Certificate[] {
+                    ce
+                };
+            }
+
+            @Override
+            public String[] getClientAliases(String arg0, Principal[] arg1) {
+                return new String[] {
+                    "client"
+                };
+            }
+
+            @Override
+            public PrivateKey getPrivateKey(String arg0) {
+                if (arg0.equals("client")) {
+                    return pk;
+                }
+                return null;
+            }
+
+            @Override
+            public String[] getServerAliases(String arg0, Principal[] arg1) {
+                return new String[] {
+                    "client"
+                };
+            }
+        };
+        SSLContext sc = SSLContext.getInstance("TLS");
+        sc.init(new KeyManager[] {
+            km
+        }, null, null);
+        if (connection instanceof HttpsURLConnection) {
+            ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory());
+        }
+    }
+
+    public String getCSRF(URLConnection u) throws IOException {
+        return getCSRF(u, 0);
+    }
+
+    public String getCSRF(URLConnection u, int formIndex) throws IOException {
+        String content = IOUtils.readURL(u);
+        Pattern p = Pattern.compile("<input type='hidden' name='csrf' value='([^']+)'>");
+        Matcher m = p.matcher(content);
+        for (int i = 0; i < formIndex + 1; i++) {
+            if ( !m.find()) {
+                throw new Error("No CSRF Token");
+            }
+        }
+        return m.group(1);
+    }
+
+    public static String[] generateCSR(String dn) throws IOException {
+        Process p = Runtime.getRuntime().exec(new String[] {
+                "openssl", "req", "-newkey", "rsa:1024", "-nodes", "-subj", dn, "-config", "keys/selfsign.config"
+        });
+        String csr = IOUtils.readURL(new InputStreamReader(p.getInputStream()));
+
+        String[] parts = csr.split("(?<=-----)\n(?=-----)");
+        if (parts.length != 2) {
+            System.err.println(IOUtils.readURL(new InputStreamReader(p.getErrorStream())));
+            throw new Error();
+        }
+        return parts;
+    }
+
+    public String executeBasicWebInteraction(String cookie, String path, String query) throws MalformedURLException, UnsupportedEncodingException, IOException {
+        return executeBasicWebInteraction(cookie, path, query, 0);
+    }
+
+    public String executeBasicWebInteraction(String cookie, String path, String query, int formIndex) throws IOException, MalformedURLException, UnsupportedEncodingException {
+        URLConnection uc = new URL("https://" + getServerName() + path).openConnection();
+        uc.addRequestProperty("Cookie", cookie);
+        String csrf = getCSRF(uc, formIndex);
+
+        uc = new URL("https://" + getServerName() + path).openConnection();
+        uc.addRequestProperty("Cookie", cookie);
+        uc.setDoOutput(true);
+        OutputStream os = uc.getOutputStream();
+        os.write(("csrf=" + URLEncoder.encode(csrf, "UTF-8") + "&" //
+        + query//
+        ).getBytes());
+        os.flush();
+        String error = fetchStartErrorMessage(IOUtils.readURL(uc));
+        return error;
+    }
+
+    public static EmailAddress createVerifiedEmail(User u) throws InterruptedException, GigiApiException {
+        EmailAddress adrr = new EmailAddress(createUniqueName() + "test@test.tld", u);
+        adrr.insert(Language.getInstance("en"));
+        TestMail testMail = getMailReciever().recieve();
+        assertTrue(adrr.getAddress().equals(testMail.getTo()));
+        String hash = testMail.extractLink().substring(testMail.extractLink().lastIndexOf('=') + 1);
+        adrr.verify(hash);
+        getMailReciever().clearMails();
+        return adrr;
+    }
 
 }
index 170c00a1351e6a31e0a5868ae0b17598c2ff9508..c790dd7250d45cd67ef2e104ddd3da1fa1b41b50 100644 (file)
@@ -10,29 +10,31 @@ import java.security.spec.PKCS8EncodedKeySpec;
 import java.util.Base64;
 
 public class PemKey {
-       public static PrivateKey parsePEMPrivateKey(String privKeyPEM) throws NoSuchAlgorithmException,
-               InvalidKeySpecException {
-               if (privKeyPEM.startsWith("-----BEGIN RSA PRIVATE KEY-----")) {
-                       // key is pkcs1 convert to p8
-                       try {
-                               Process p = Runtime.getRuntime().exec(new String[] { "openssl", "pkcs8", "-topk8", "-nocrypt" });
-                               p.getOutputStream().write(privKeyPEM.getBytes());
-                               p.getOutputStream().close();
-                               privKeyPEM = IOUtils.readURL(new InputStreamReader(p.getInputStream()));
-                       } catch (IOException e) {
-                               e.printStackTrace();
-                       }
-               }
-               privKeyPEM = privKeyPEM.replaceAll("-----BEGIN PRIVATE KEY-----", "").replace("\n", "");
-               // Remove the first and last lines
-               privKeyPEM = privKeyPEM.replaceAll("-----END PRIVATE KEY-----", "");
-               // Base64 decode the data
-               byte[] encoded = Base64.getDecoder().decode(privKeyPEM);
 
-               // PKCS8 decode the encoded RSA private key
-               PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
-               KeyFactory kf = KeyFactory.getInstance("RSA");
-               PrivateKey privKey = kf.generatePrivate(keySpec);
-               return privKey;
-       }
+    public static PrivateKey parsePEMPrivateKey(String privKeyPEM) throws NoSuchAlgorithmException, InvalidKeySpecException {
+        if (privKeyPEM.startsWith("-----BEGIN RSA PRIVATE KEY-----")) {
+            // key is pkcs1 convert to p8
+            try {
+                Process p = Runtime.getRuntime().exec(new String[] {
+                        "openssl", "pkcs8", "-topk8", "-nocrypt"
+                });
+                p.getOutputStream().write(privKeyPEM.getBytes());
+                p.getOutputStream().close();
+                privKeyPEM = IOUtils.readURL(new InputStreamReader(p.getInputStream()));
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+        privKeyPEM = privKeyPEM.replaceAll("-----BEGIN PRIVATE KEY-----", "").replace("\n", "");
+        // Remove the first and last lines
+        privKeyPEM = privKeyPEM.replaceAll("-----END PRIVATE KEY-----", "");
+        // Base64 decode the data
+        byte[] encoded = Base64.getDecoder().decode(privKeyPEM);
+
+        // PKCS8 decode the encoded RSA private key
+        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
+        KeyFactory kf = KeyFactory.getInstance("RSA");
+        PrivateKey privKey = kf.generatePrivate(keySpec);
+        return privKey;
+    }
 }
index 93cd7e4540f17e0d3024b6216117cd3fa42530b7..40b4e0312eebd5f57f8c282e8917770ef4971e2d 100644 (file)
@@ -13,150 +13,157 @@ import java.util.regex.Pattern;
 import org.cacert.gigi.email.EmailProvider;
 
 public class TestEmailReciever extends EmailProvider implements Runnable {
-       public class TestMail {
-               String to;
-               String subject;
-               String message;
-               String from;
-               String replyto;
-
-               public TestMail(String to, String subject, String message, String from, String replyto) {
-                       this.to = to;
-                       this.subject = subject;
-                       this.message = message;
-                       this.from = from;
-                       this.replyto = replyto;
-               }
-
-               public String getTo() {
-                       return to;
-               }
-
-               public String getSubject() {
-                       return subject;
-               }
-
-               public String getMessage() {
-                       return message;
-               }
-
-               public String getFrom() {
-                       return from;
-               }
-
-               public String getReplyto() {
-                       return replyto;
-               }
-
-               public String extractLink() {
-                       Pattern link = Pattern.compile("https?://[^\\s]+(?=\\s)");
-                       Matcher m = link.matcher(getMessage());
-                       m.find();
-                       return m.group(0);
-               }
-
-       }
-
-       private Socket s;
-       private DataInputStream dis;
-       private DataOutputStream dos;
-
-       public TestEmailReciever(SocketAddress target) throws IOException {
-               s = new Socket();
-               s.connect(target);
-               s.setKeepAlive(true);
-               s.setSoTimeout(1000 * 60 * 60);
-               dis = new DataInputStream(s.getInputStream());
-               dos = new DataOutputStream(s.getOutputStream());
-               new Thread(this).start();
-               setInstance(this);
-       }
-
-       LinkedBlockingQueue<TestMail> mails = new LinkedBlockingQueue<TestEmailReciever.TestMail>();
-
-       public TestMail recieve() throws InterruptedException {
-               return mails.poll(5, TimeUnit.SECONDS);
-       }
-
-       @Override
-       public void run() {
-               try {
-                       while (true) {
-                               String type = dis.readUTF();
-                               if (type.equals("mail")) {
-                                       String to = dis.readUTF();
-                                       String subject = dis.readUTF();
-                                       String message = dis.readUTF();
-                                       String from = dis.readUTF();
-                                       String replyto = dis.readUTF();
-                                       mails.add(new TestMail(to, subject, message, from, replyto));
-                               } else if (type.equals("challengeAddrBox")) {
-                                       String email = dis.readUTF();
-                                       dos.writeUTF(quickEmailCheck(email));
-                                       dos.flush();
-                               } else if (type.equals("ping")) {
-                               } else {
-                                       System.err.println("Unknown type: " + type);
-                               }
-                       }
-               } catch (IOException e) {
-                       if (!closed) {
-                               e.printStackTrace();
-                       }
-               }
-
-       }
-
-       private String quickEmailCheck(String email) throws IOException {
-               if (approveRegex.matcher(email).matches()) {
-                       return "OK";
-               } else {
-                       return error;
-               }
-       }
-
-       String error = "FAIL";
-
-       public void setEmailCheckError(String error) {
-               this.error = error;
-       }
-
-       Pattern approveRegex = Pattern.compile(".*");
-
-       public void setApproveRegex(Pattern approveRegex) {
-               this.approveRegex = approveRegex;
-       }
-
-       public void clearMails() {
-               mails.clear();
-       }
-
-       public void reset() {
-               clearMails();
-               error = "FAIL";
-               approveRegex = Pattern.compile(".*");
-       }
-
-       boolean closed = false;
-
-       public void destroy() {
-               try {
-                       closed = true;
-                       s.close();
-               } catch (IOException e) {
-                       e.printStackTrace();
-               }
-       }
-
-       @Override
-       public String checkEmailServer(int forUid, String address) throws IOException {
-               return quickEmailCheck(address);
-       }
-
-       @Override
-       public void sendmail(String to, String subject, String message, String from, String replyto, String toname,
-               String fromname, String errorsto, boolean extra) throws IOException {
-               mails.add(new TestMail(to, subject, message, from, replyto));
-       }
+
+    public class TestMail {
+
+        String to;
+
+        String subject;
+
+        String message;
+
+        String from;
+
+        String replyto;
+
+        public TestMail(String to, String subject, String message, String from, String replyto) {
+            this.to = to;
+            this.subject = subject;
+            this.message = message;
+            this.from = from;
+            this.replyto = replyto;
+        }
+
+        public String getTo() {
+            return to;
+        }
+
+        public String getSubject() {
+            return subject;
+        }
+
+        public String getMessage() {
+            return message;
+        }
+
+        public String getFrom() {
+            return from;
+        }
+
+        public String getReplyto() {
+            return replyto;
+        }
+
+        public String extractLink() {
+            Pattern link = Pattern.compile("https?://[^\\s]+(?=\\s)");
+            Matcher m = link.matcher(getMessage());
+            m.find();
+            return m.group(0);
+        }
+
+    }
+
+    private Socket s;
+
+    private DataInputStream dis;
+
+    private DataOutputStream dos;
+
+    public TestEmailReciever(SocketAddress target) throws IOException {
+        s = new Socket();
+        s.connect(target);
+        s.setKeepAlive(true);
+        s.setSoTimeout(1000 * 60 * 60);
+        dis = new DataInputStream(s.getInputStream());
+        dos = new DataOutputStream(s.getOutputStream());
+        new Thread(this).start();
+        setInstance(this);
+    }
+
+    LinkedBlockingQueue<TestMail> mails = new LinkedBlockingQueue<TestEmailReciever.TestMail>();
+
+    public TestMail recieve() throws InterruptedException {
+        return mails.poll(5, TimeUnit.SECONDS);
+    }
+
+    @Override
+    public void run() {
+        try {
+            while (true) {
+                String type = dis.readUTF();
+                if (type.equals("mail")) {
+                    String to = dis.readUTF();
+                    String subject = dis.readUTF();
+                    String message = dis.readUTF();
+                    String from = dis.readUTF();
+                    String replyto = dis.readUTF();
+                    mails.add(new TestMail(to, subject, message, from, replyto));
+                } else if (type.equals("challengeAddrBox")) {
+                    String email = dis.readUTF();
+                    dos.writeUTF(quickEmailCheck(email));
+                    dos.flush();
+                } else if (type.equals("ping")) {
+                } else {
+                    System.err.println("Unknown type: " + type);
+                }
+            }
+        } catch (IOException e) {
+            if ( !closed) {
+                e.printStackTrace();
+            }
+        }
+
+    }
+
+    private String quickEmailCheck(String email) throws IOException {
+        if (approveRegex.matcher(email).matches()) {
+            return "OK";
+        } else {
+            return error;
+        }
+    }
+
+    String error = "FAIL";
+
+    public void setEmailCheckError(String error) {
+        this.error = error;
+    }
+
+    Pattern approveRegex = Pattern.compile(".*");
+
+    public void setApproveRegex(Pattern approveRegex) {
+        this.approveRegex = approveRegex;
+    }
+
+    public void clearMails() {
+        mails.clear();
+    }
+
+    public void reset() {
+        clearMails();
+        error = "FAIL";
+        approveRegex = Pattern.compile(".*");
+    }
+
+    boolean closed = false;
+
+    public void destroy() {
+        try {
+            closed = true;
+            s.close();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
+
+    @Override
+    public String checkEmailServer(int forUid, String address) throws IOException {
+        return quickEmailCheck(address);
+    }
+
+    @Override
+    public void sendmail(String to, String subject, String message, String from, String replyto, String toname, String fromname, String errorsto, boolean extra) throws IOException {
+        mails.add(new TestMail(to, subject, message, from, replyto));
+    }
 
 }
index f7c21ab3adc46ffd6664c655fe99c1f89ebcbc43..5d3a2aed493d1731dff21a468992d44b4845729d 100644 (file)
@@ -6,23 +6,23 @@ import org.junit.Test;
 
 public class TestHTMLEncoder {
 
-       @Test
-       public void testEncodeSimpleString() {
-               assertEquals("1234_ä", HTMLEncoder.encodeHTML("1234_ä"));
-       }
+    @Test
+    public void testEncodeSimpleString() {
+        assertEquals("1234_ä", HTMLEncoder.encodeHTML("1234_ä"));
+    }
 
-       @Test
-       public void testEncodeQuotes() {
-               assertEquals("\\&quot;_ä.", HTMLEncoder.encodeHTML("\\\"_ä."));
-       }
+    @Test
+    public void testEncodeQuotes() {
+        assertEquals("\\&quot;_ä.", HTMLEncoder.encodeHTML("\\\"_ä."));
+    }
 
-       @Test
-       public void testEncodeTagString() {
-               assertEquals("&lt;td class=&quot;&amp;amp;&quot;&gt;", HTMLEncoder.encodeHTML("<td class=\"&amp;\">"));
-       }
+    @Test
+    public void testEncodeTagString() {
+        assertEquals("&lt;td class=&quot;&amp;amp;&quot;&gt;", HTMLEncoder.encodeHTML("<td class=\"&amp;\">"));
+    }
 
-       @Test
-       public void testEncodeSingleQuoteString() {
-               assertEquals("&#39;&amp;#39;", HTMLEncoder.encodeHTML("'&#39;"));
-       }
+    @Test
+    public void testEncodeSingleQuoteString() {
+        assertEquals("&#39;&amp;#39;", HTMLEncoder.encodeHTML("'&#39;"));
+    }
 }
index d3570e522bf3d5d864006ded0fd381677e7da7c6..9797a03eea4016a74dd756bac81bd0f7d58abd52 100644 (file)
@@ -12,56 +12,50 @@ import org.junit.Test;
 import static org.junit.Assert.*;
 
 public class TestNotary extends ManagedTest {
-       @Test
-       public void testNormalAssurance() throws SQLException {
-               User[] users = new User[30];
-               for (int i = 0; i < users.length; i++) {
-                       int id = createVerifiedUser("fn" + i, "ln" + i, createUniqueName() + "@email.org", TEST_PASSWORD);
-                       users[i] = new User(id);
-               }
-               User assurer = new User(createAssuranceUser("fn", "ln", createUniqueName() + "@email.org", TEST_PASSWORD));
-               int[] result = new int[] { 10, 10, 10, 10, 15, 15, 15, 15, 15, 20, 20, 20, 20, 20, 25, 25, 25, 25, 25, 30, 30,
-                               30, 30, 30, 35, 35, 35, 35, 35, 35 };
 
-               assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED,
-                       Notary.assure(assurer, users[0], -1, "test-notary", "2014-01-01"));
-               for (int i = 0; i < result.length; i++) {
-                       assertEquals(result[i], assurer.getMaxAssurePoints());
-                       assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED,
-                               Notary.assure(assurer, users[i], result[i] + 1, "test-notary", "2014-01-01"));
-                       assertEquals(AssuranceResult.ASSURANCE_SUCCEDED,
-                               Notary.assure(assurer, users[i], result[i], "test-notary", "2014-01-01"));
-                       assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED,
-                               Notary.assure(assurer, users[i], result[i], "test-notary", "2014-01-01"));
-               }
-
-               assertEquals(35, assurer.getMaxAssurePoints());
-
-               assertEquals(2 + 60, assurer.getExperiencePoints());
-
-       }
-
-       @Test
-       public void testPoJam() throws SQLException {
-               User[] users = new User[30];
-               for (int i = 0; i < users.length; i++) {
-                       int id = createVerifiedUser("fn" + i, "ln" + i, createUniqueName() + "@email.org", TEST_PASSWORD);
-                       users[i] = new User(id);
-               }
-               int id = createAssuranceUser("fn", "ln", createUniqueName() + "@email.org", TEST_PASSWORD);
-               PreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE users SET dob=NOW() WHERE id=?");
-               ps.setInt(1, id);
-               ps.execute();
-               User assurer = new User(id);
-               for (int i = 0; i < users.length; i++) {
-                       assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED,
-                               Notary.assure(assurer, users[i], -1, "test-notary", "2014-01-01"));
-                       assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED,
-                               Notary.assure(assurer, users[i], 11, "test-notary", "2014-01-01"));
-                       assertEquals(AssuranceResult.ASSURANCE_SUCCEDED,
-                               Notary.assure(assurer, users[i], 10, "test-notary", "2014-01-01"));
-                       assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED,
-                               Notary.assure(assurer, users[i], 10, "test-notary", "2014-01-01"));
-               }
-       }
+    @Test
+    public void testNormalAssurance() throws SQLException {
+        User[] users = new User[30];
+        for (int i = 0; i < users.length; i++) {
+            int id = createVerifiedUser("fn" + i, "ln" + i, createUniqueName() + "@email.org", TEST_PASSWORD);
+            users[i] = new User(id);
+        }
+        User assurer = new User(createAssuranceUser("fn", "ln", createUniqueName() + "@email.org", TEST_PASSWORD));
+        int[] result = new int[] {
+                10, 10, 10, 10, 15, 15, 15, 15, 15, 20, 20, 20, 20, 20, 25, 25, 25, 25, 25, 30, 30, 30, 30, 30, 35, 35, 35, 35, 35, 35
+        };
+
+        assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED, Notary.assure(assurer, users[0], -1, "test-notary", "2014-01-01"));
+        for (int i = 0; i < result.length; i++) {
+            assertEquals(result[i], assurer.getMaxAssurePoints());
+            assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED, Notary.assure(assurer, users[i], result[i] + 1, "test-notary", "2014-01-01"));
+            assertEquals(AssuranceResult.ASSURANCE_SUCCEDED, Notary.assure(assurer, users[i], result[i], "test-notary", "2014-01-01"));
+            assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED, Notary.assure(assurer, users[i], result[i], "test-notary", "2014-01-01"));
+        }
+
+        assertEquals(35, assurer.getMaxAssurePoints());
+
+        assertEquals(2 + 60, assurer.getExperiencePoints());
+
+    }
+
+    @Test
+    public void testPoJam() throws SQLException {
+        User[] users = new User[30];
+        for (int i = 0; i < users.length; i++) {
+            int id = createVerifiedUser("fn" + i, "ln" + i, createUniqueName() + "@email.org", TEST_PASSWORD);
+            users[i] = new User(id);
+        }
+        int id = createAssuranceUser("fn", "ln", createUniqueName() + "@email.org", TEST_PASSWORD);
+        PreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE users SET dob=NOW() WHERE id=?");
+        ps.setInt(1, id);
+        ps.execute();
+        User assurer = new User(id);
+        for (int i = 0; i < users.length; i++) {
+            assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED, Notary.assure(assurer, users[i], -1, "test-notary", "2014-01-01"));
+            assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED, Notary.assure(assurer, users[i], 11, "test-notary", "2014-01-01"));
+            assertEquals(AssuranceResult.ASSURANCE_SUCCEDED, Notary.assure(assurer, users[i], 10, "test-notary", "2014-01-01"));
+            assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED, Notary.assure(assurer, users[i], 10, "test-notary", "2014-01-01"));
+        }
+    }
 }
index 21f5f8bde2a97e72c0826401d8b000de88cad14f..2e323f781cfe23f06ca40650f155c1961dd82f16 100644 (file)
@@ -4,17 +4,18 @@ import org.junit.Test;
 import static org.junit.Assert.*;
 
 public class TestPasswordHash {
-       @Test
-       public void testVerify() {
-               assertTrue(PasswordHash.verifyHash("a", PasswordHash.hash("a")));
-               assertTrue(PasswordHash.verifyHash("", PasswordHash.hash("")));
-               assertTrue(PasswordHash.verifyHash("a1234", PasswordHash.hash("a1234")));
-               assertTrue(PasswordHash.verifyHash("auhlcb4 9x,IUQẞ&lvrvä", PasswordHash.hash("auhlcb4 9x,IUQẞ&lvrvä")));
-       }
 
-       @Test
-       public void testVerifyNegative() {
-               assertFalse(PasswordHash.verifyHash("b", PasswordHash.hash("a")));
-               assertFalse(PasswordHash.verifyHash("ae", PasswordHash.hash("auhlcb4 9x,IUQẞ&lvrvä")));
-       }
+    @Test
+    public void testVerify() {
+        assertTrue(PasswordHash.verifyHash("a", PasswordHash.hash("a")));
+        assertTrue(PasswordHash.verifyHash("", PasswordHash.hash("")));
+        assertTrue(PasswordHash.verifyHash("a1234", PasswordHash.hash("a1234")));
+        assertTrue(PasswordHash.verifyHash("auhlcb4 9x,IUQẞ&lvrvä", PasswordHash.hash("auhlcb4 9x,IUQẞ&lvrvä")));
+    }
+
+    @Test
+    public void testVerifyNegative() {
+        assertFalse(PasswordHash.verifyHash("b", PasswordHash.hash("a")));
+        assertFalse(PasswordHash.verifyHash("ae", PasswordHash.hash("auhlcb4 9x,IUQẞ&lvrvä")));
+    }
 }
index f57e71af7dff3c1b68d30dc506013dcc80ff0c48..e6cac695d91874d4d1fc62d83f4555fc1b578d74 100644 (file)
@@ -5,69 +5,70 @@ import org.junit.Test;
 import static org.junit.Assert.*;
 
 public class TestPasswordStrengthChecker {
-       User u;
 
-       public TestPasswordStrengthChecker() {
-               u = new User();
-               u.setFname("fname");
-               u.setLname("lname");
-               u.setMname("mname");
-               u.setEmail("email");
-               u.setSuffix("suffix");
-       }
+    User u;
 
-       @Test
-       public void testPasswordLength() {
-               assertEquals(1, PasswordStrengthChecker.checkpw("01234", u));
-               assertEquals(2, PasswordStrengthChecker.checkpw("0123456789012345", u));
-               assertEquals(3, PasswordStrengthChecker.checkpw("012345678901234567890", u));
-               assertEquals(4, PasswordStrengthChecker.checkpw("01234567890123456789012345", u));
-               assertEquals(5, PasswordStrengthChecker.checkpw("0123456789012345678901234567890", u));
-       }
+    public TestPasswordStrengthChecker() {
+        u = new User();
+        u.setFname("fname");
+        u.setLname("lname");
+        u.setMname("mname");
+        u.setEmail("email");
+        u.setSuffix("suffix");
+    }
 
-       @Test
-       public void testPasswordNonASCII() {
-               assertEquals(2, PasswordStrengthChecker.checkpw("0ä", u));
-               assertEquals(3, PasswordStrengthChecker.checkpw("0aä", u));
-               assertEquals(3, PasswordStrengthChecker.checkpw("0azä", u));
-               assertEquals(3, PasswordStrengthChecker.checkpw("0az.ä", u));
-       }
+    @Test
+    public void testPasswordLength() {
+        assertEquals(1, PasswordStrengthChecker.checkpw("01234", u));
+        assertEquals(2, PasswordStrengthChecker.checkpw("0123456789012345", u));
+        assertEquals(3, PasswordStrengthChecker.checkpw("012345678901234567890", u));
+        assertEquals(4, PasswordStrengthChecker.checkpw("01234567890123456789012345", u));
+        assertEquals(5, PasswordStrengthChecker.checkpw("0123456789012345678901234567890", u));
+    }
 
-       @Test
-       public void testPasswordCharTypes() {
-               assertEquals(1, PasswordStrengthChecker.checkpw("0", u));
-               assertEquals(2, PasswordStrengthChecker.checkpw("0a", u));
-               assertEquals(2, PasswordStrengthChecker.checkpw("0az", u));
-               assertEquals(3, PasswordStrengthChecker.checkpw("0azZ", u));
-               assertEquals(4, PasswordStrengthChecker.checkpw("0a zZ", u));
-               assertEquals(5, PasswordStrengthChecker.checkpw("0a. zZ", u));
+    @Test
+    public void testPasswordNonASCII() {
+        assertEquals(2, PasswordStrengthChecker.checkpw("0ä", u));
+        assertEquals(3, PasswordStrengthChecker.checkpw("0aä", u));
+        assertEquals(3, PasswordStrengthChecker.checkpw("0azä", u));
+        assertEquals(3, PasswordStrengthChecker.checkpw("0az.ä", u));
+    }
 
-               assertEquals(1, PasswordStrengthChecker.checkpw(".", u));
-               assertEquals(1, PasswordStrengthChecker.checkpw(" ", u));
-               assertEquals(1, PasswordStrengthChecker.checkpw("b", u));
-               assertEquals(1, PasswordStrengthChecker.checkpw("Z", u));
+    @Test
+    public void testPasswordCharTypes() {
+        assertEquals(1, PasswordStrengthChecker.checkpw("0", u));
+        assertEquals(2, PasswordStrengthChecker.checkpw("0a", u));
+        assertEquals(2, PasswordStrengthChecker.checkpw("0az", u));
+        assertEquals(3, PasswordStrengthChecker.checkpw("0azZ", u));
+        assertEquals(4, PasswordStrengthChecker.checkpw("0a zZ", u));
+        assertEquals(5, PasswordStrengthChecker.checkpw("0a. zZ", u));
 
-               assertEquals(2, PasswordStrengthChecker.checkpw("0.", u));
-               assertEquals(2, PasswordStrengthChecker.checkpw("0 ", u));
-               assertEquals(2, PasswordStrengthChecker.checkpw("0a", u));
-               assertEquals(2, PasswordStrengthChecker.checkpw("0Z", u));
+        assertEquals(1, PasswordStrengthChecker.checkpw(".", u));
+        assertEquals(1, PasswordStrengthChecker.checkpw(" ", u));
+        assertEquals(1, PasswordStrengthChecker.checkpw("b", u));
+        assertEquals(1, PasswordStrengthChecker.checkpw("Z", u));
 
-               assertEquals(2, PasswordStrengthChecker.checkpw(" .", u));
-               assertEquals(2, PasswordStrengthChecker.checkpw(" a", u));
-               assertEquals(2, PasswordStrengthChecker.checkpw(" Z", u));
+        assertEquals(2, PasswordStrengthChecker.checkpw("0.", u));
+        assertEquals(2, PasswordStrengthChecker.checkpw("0 ", u));
+        assertEquals(2, PasswordStrengthChecker.checkpw("0a", u));
+        assertEquals(2, PasswordStrengthChecker.checkpw("0Z", u));
 
-       }
+        assertEquals(2, PasswordStrengthChecker.checkpw(" .", u));
+        assertEquals(2, PasswordStrengthChecker.checkpw(" a", u));
+        assertEquals(2, PasswordStrengthChecker.checkpw(" Z", u));
 
-       @Test
-       public void testPasswordContains() {
-               assertEquals(-1, PasswordStrengthChecker.checkpw("fnamea", u));
-               assertEquals(-5, PasswordStrengthChecker.checkpw("na", u));
-               assertEquals(0, PasswordStrengthChecker.checkpw("1lname", u));
-               assertEquals(0, PasswordStrengthChecker.checkpw("1email", u));
-               assertEquals(-1, PasswordStrengthChecker.checkpw("mai", u));
-               assertEquals(-1, PasswordStrengthChecker.checkpw("suff", u));
-               assertEquals(0, PasswordStrengthChecker.checkpw("1suffix", u));
+    }
 
-       }
+    @Test
+    public void testPasswordContains() {
+        assertEquals( -1, PasswordStrengthChecker.checkpw("fnamea", u));
+        assertEquals( -5, PasswordStrengthChecker.checkpw("na", u));
+        assertEquals(0, PasswordStrengthChecker.checkpw("1lname", u));
+        assertEquals(0, PasswordStrengthChecker.checkpw("1email", u));
+        assertEquals( -1, PasswordStrengthChecker.checkpw("mai", u));
+        assertEquals( -1, PasswordStrengthChecker.checkpw("suff", u));
+        assertEquals(0, PasswordStrengthChecker.checkpw("1suffix", u));
+
+    }
 
 }
index 471083953b8d2b2f1362f8d440eca5016c7789de..9fe3f5fb3ec774416152fe2a5433193b667350a6 100644 (file)
@@ -11,44 +11,46 @@ import java.sql.Statement;
 import java.util.Properties;
 
 public class DatabaseManager {
-       public static String readFile(File f) throws IOException {
-               return new String(Files.readAllBytes(f.toPath()));
-       }
 
-       public static void main(String[] args) throws SQLException, ClassNotFoundException, IOException {
-               if (args.length == 0) {
-                       Properties p = new Properties();
-                       p.load(new FileReader("config/gigi.properties"));
-                       args = new String[] { p.getProperty("sql.driver"), p.getProperty("sql.url"), p.getProperty("sql.user"),
-                                       p.getProperty("sql.password") };
-               }
-               if (args.length < 4) {
-                       System.err.println("Usage: com.mysql.jdbc.Driver jdbc:mysql://localhost/cacert user password");
-                       return;
-               }
-               run(args);
-       }
+    public static String readFile(File f) throws IOException {
+        return new String(Files.readAllBytes(f.toPath()));
+    }
 
-       public static void run(String[] args) throws ClassNotFoundException, SQLException, IOException {
-               Class.forName(args[0]);
-               Connection conn = DriverManager.getConnection(args[1], args[2], args[3]);
-               Statement stmt = conn.createStatement();
-               addFile(stmt, new File("doc/tableStructure.sql"));
-               File localData = new File("doc/sampleData.sql");
-               if (localData.exists()) {
-                       addFile(stmt, localData);
-               }
-               stmt.executeBatch();
-               stmt.close();
-       }
+    public static void main(String[] args) throws SQLException, ClassNotFoundException, IOException {
+        if (args.length == 0) {
+            Properties p = new Properties();
+            p.load(new FileReader("config/gigi.properties"));
+            args = new String[] {
+                    p.getProperty("sql.driver"), p.getProperty("sql.url"), p.getProperty("sql.user"), p.getProperty("sql.password")
+            };
+        }
+        if (args.length < 4) {
+            System.err.println("Usage: com.mysql.jdbc.Driver jdbc:mysql://localhost/cacert user password");
+            return;
+        }
+        run(args);
+    }
 
-       private static void addFile(Statement stmt, File f) throws IOException, SQLException {
-               String sql = readFile(f);
-               String[] stmts = sql.split(";");
-               for (String string : stmts) {
-                       if (!string.trim().equals("")) {
-                               stmt.addBatch(string);
-                       }
-               }
-       }
+    public static void run(String[] args) throws ClassNotFoundException, SQLException, IOException {
+        Class.forName(args[0]);
+        Connection conn = DriverManager.getConnection(args[1], args[2], args[3]);
+        Statement stmt = conn.createStatement();
+        addFile(stmt, new File("doc/tableStructure.sql"));
+        File localData = new File("doc/sampleData.sql");
+        if (localData.exists()) {
+            addFile(stmt, localData);
+        }
+        stmt.executeBatch();
+        stmt.close();
+    }
+
+    private static void addFile(Statement stmt, File f) throws IOException, SQLException {
+        String sql = readFile(f);
+        String[] stmts = sql.split(";");
+        for (String string : stmts) {
+            if ( !string.trim().equals("")) {
+                stmt.addBatch(string);
+            }
+        }
+    }
 }
index 0c936b9c036129ca8b626a84bfcd9f7d7862ea7f..4c93021e9e38acf9f44e3ef947e2a885e27c9c8e 100644 (file)
@@ -22,94 +22,98 @@ import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 
 public class FetchLocales {
-       public static final String DOWNLOAD_SERVER = "translations.cacert.org";
-       public static final String PO_URL_TEMPLATE = "http://" + DOWNLOAD_SERVER + "/export/cacert/%/messages.po";
-       public static final String[] AUTO_LANGS = new String[] { "en", "de", "nl", "pt_BR", "fr", "sv", "it", "es", "hu",
-                       "fi", "ja", "bg", "pt", "da", "pl", "zh_CN", "ru", "lv", "cs", "zh_TW", "el", "tr", "ar" };
 
-       public static void main(String[] args) throws IOException, ParserConfigurationException, TransformerException {
-               System.out.println("downloading locales ...");
-               File locale = new File("locale");
-               locale.mkdir();
+    public static final String DOWNLOAD_SERVER = "translations.cacert.org";
 
-               DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
-               DocumentBuilder db = dbf.newDocumentBuilder();
-               for (String lang : AUTO_LANGS) {
-                       Document doc = db.newDocument();
-                       doc.appendChild(doc.createElement("translations"));
-                       URL fetch = new URL(PO_URL_TEMPLATE.replace("%", lang));
-                       URLConnection uc = fetch.openConnection();
-                       Scanner sc = new Scanner(uc.getInputStream());
-                       String s = readLine(sc);
-                       StringBuffer contents = new StringBuffer();
-                       String id = "";
-                       while (s != null) {
-                               if (s.startsWith("msgid")) {
-                                       contents.delete(0, contents.length());
-                                       s = readString(s, sc, contents);
-                                       id = contents.toString();
-                                       continue;
-                               } else if (s.startsWith("msgstr")) {
-                                       contents.delete(0, contents.length());
-                                       // System.out.println("msgstr");
-                                       s = readString(s, sc, contents);
-                                       String msg = contents.toString().replace("\\\"", "\"").replace("\\n", "\n");
-                                       insertTranslation(doc, id, msg);
-                               } else if (s.startsWith("#")) {
-                                       // System.out.println(s);
-                               } else if (s.equals("") || s.equals("\r")) {
+    public static final String PO_URL_TEMPLATE = "http://" + DOWNLOAD_SERVER + "/export/cacert/%/messages.po";
 
-                               } else {
-                                       System.out.println("unknown line: " + s);
-                               }
-                               s = readLine(sc);
-                       }
-                       TransformerFactory tFactory = TransformerFactory.newInstance();
-                       Transformer transformer = tFactory.newTransformer();
+    public static final String[] AUTO_LANGS = new String[] {
+            "en", "de", "nl", "pt_BR", "fr", "sv", "it", "es", "hu", "fi", "ja", "bg", "pt", "da", "pl", "zh_CN", "ru", "lv", "cs", "zh_TW", "el", "tr", "ar"
+    };
 
-                       DOMSource source = new DOMSource(doc);
-                       FileOutputStream fos = new FileOutputStream(new File(locale, lang + ".xml"));
-                       StreamResult result = new StreamResult(fos);
-                       transformer.setOutputProperty(OutputKeys.INDENT, "yes");
-                       transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
-                       transformer.transform(source, result);
-                       fos.close();
-               }
-               System.out.println("Done.");
-       }
+    public static void main(String[] args) throws IOException, ParserConfigurationException, TransformerException {
+        System.out.println("downloading locales ...");
+        File locale = new File("locale");
+        locale.mkdir();
 
-       private static String readLine(Scanner sc) {
-               String line = sc.findWithinHorizon("[^\n]*\n", 0);
-               if (line == null) {
-                       return null;
-               }
-               return line.substring(0, line.length() - 1);
-       }
+        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+        DocumentBuilder db = dbf.newDocumentBuilder();
+        for (String lang : AUTO_LANGS) {
+            Document doc = db.newDocument();
+            doc.appendChild(doc.createElement("translations"));
+            URL fetch = new URL(PO_URL_TEMPLATE.replace("%", lang));
+            URLConnection uc = fetch.openConnection();
+            Scanner sc = new Scanner(uc.getInputStream());
+            String s = readLine(sc);
+            StringBuffer contents = new StringBuffer();
+            String id = "";
+            while (s != null) {
+                if (s.startsWith("msgid")) {
+                    contents.delete(0, contents.length());
+                    s = readString(s, sc, contents);
+                    id = contents.toString();
+                    continue;
+                } else if (s.startsWith("msgstr")) {
+                    contents.delete(0, contents.length());
+                    // System.out.println("msgstr");
+                    s = readString(s, sc, contents);
+                    String msg = contents.toString().replace("\\\"", "\"").replace("\\n", "\n");
+                    insertTranslation(doc, id, msg);
+                } else if (s.startsWith("#")) {
+                    // System.out.println(s);
+                } else if (s.equals("") || s.equals("\r")) {
 
-       private static void insertTranslation(Document doc, String id, String msg) {
-               Node idN = doc.createTextNode(id);
-               Node textN = doc.createTextNode(msg);
-               Element tr = doc.createElement("translation");
-               Element e = doc.createElement("id");
-               e.appendChild(idN);
-               tr.appendChild(e);
-               e = doc.createElement("msg");
-               e.appendChild(textN);
-               tr.appendChild(e);
-               doc.getDocumentElement().appendChild(tr);
-       }
+                } else {
+                    System.out.println("unknown line: " + s);
+                }
+                s = readLine(sc);
+            }
+            TransformerFactory tFactory = TransformerFactory.newInstance();
+            Transformer transformer = tFactory.newTransformer();
 
-       private static String readString(String head, Scanner sc, StringBuffer contents) throws IOException {
-               head = head.split(" ", 2)[1];
-               contents.append(head.substring(1, head.length() - 1));
-               String s;
-               while ((s = readLine(sc)) != null) {
-                       if (!s.startsWith("\"")) {
-                               break;
-                       }
-                       contents.append(s.substring(1, s.length() - 1));
-               }
-               return s;
-       }
+            DOMSource source = new DOMSource(doc);
+            FileOutputStream fos = new FileOutputStream(new File(locale, lang + ".xml"));
+            StreamResult result = new StreamResult(fos);
+            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
+            transformer.transform(source, result);
+            fos.close();
+        }
+        System.out.println("Done.");
+    }
+
+    private static String readLine(Scanner sc) {
+        String line = sc.findWithinHorizon("[^\n]*\n", 0);
+        if (line == null) {
+            return null;
+        }
+        return line.substring(0, line.length() - 1);
+    }
+
+    private static void insertTranslation(Document doc, String id, String msg) {
+        Node idN = doc.createTextNode(id);
+        Node textN = doc.createTextNode(msg);
+        Element tr = doc.createElement("translation");
+        Element e = doc.createElement("id");
+        e.appendChild(idN);
+        tr.appendChild(e);
+        e = doc.createElement("msg");
+        e.appendChild(textN);
+        tr.appendChild(e);
+        doc.getDocumentElement().appendChild(tr);
+    }
+
+    private static String readString(String head, Scanner sc, StringBuffer contents) throws IOException {
+        head = head.split(" ", 2)[1];
+        contents.append(head.substring(1, head.length() - 1));
+        String s;
+        while ((s = readLine(sc)) != null) {
+            if ( !s.startsWith("\"")) {
+                break;
+            }
+            contents.append(s.substring(1, s.length() - 1));
+        }
+        return s;
+    }
 
 }
index c471586c90447fab868b35c0a4469be98913be0f..3290298bd6dbd0f76b9572e247245deaaabe7fdd 100644 (file)
@@ -21,196 +21,215 @@ import org.cacert.gigi.Certificate.CSRType;
 import org.cacert.gigi.database.DatabaseConnection;
 
 public class SimpleSigner {
-       private static PreparedStatement warnMail;
-       private static PreparedStatement updateMail;
-       private static PreparedStatement readyMail;
-       private static PreparedStatement revoke;
-       private static PreparedStatement revokeCompleted;
-       private static PreparedStatement finishJob;
-       private static boolean running = true;
-       private static Thread runner;
-
-       public static void main(String[] args) throws IOException, SQLException, InterruptedException {
-               Properties p = new Properties();
-               p.load(new FileReader("config/gigi.properties"));
-               DatabaseConnection.init(p);
-
-               runSigner();
-       }
-
-       public synchronized static void stopSigner() throws InterruptedException {
-               if (runner == null) {
-                       throw new IllegalStateException("already stopped");
-               }
-               running = false;
-               runner.interrupt();
-               runner.join();
-               runner = null;
-       }
-
-       public synchronized static void runSigner() throws SQLException, IOException, InterruptedException {
-               if (runner != null) {
-                       throw new IllegalStateException("already running");
-               }
-               running = true;
-               readyMail = DatabaseConnection
-                       .getInstance()
-                       .prepare(
-                               "SELECT emailcerts.id,emailcerts.csr_name,emailcerts.subject, jobs.id,csr_type FROM jobs INNER JOIN emailcerts ON emailcerts.id=jobs.targetId"
-                                       + " WHERE jobs.state='open'"//
-                                       + " AND task='sign'");
-
-               updateMail = DatabaseConnection.getInstance().prepare(
-                       "UPDATE emailcerts SET crt_name=?," + " created=NOW(), serial=? WHERE id=?");
-               warnMail = DatabaseConnection.getInstance().prepare(
-                       "UPDATE jobs SET warning=warning+1, state=IF(warning<3, 'open','error') WHERE id=?");
-
-               revoke = DatabaseConnection.getInstance().prepare(
-                       "SELECT emailcerts.id, emailcerts.csr_name,jobs.id FROM jobs INNER JOIN emailcerts ON jobs.targetId=emailcerts.id"
-                               + " WHERE jobs.state='open' AND task='revoke'");
-               revokeCompleted = DatabaseConnection.getInstance().prepare("UPDATE emailcerts SET revoked=NOW() WHERE id=?");
-
-               finishJob = DatabaseConnection.getInstance().prepare("UPDATE jobs SET state='done' WHERE id=?");
-
-               runner = new Thread() {
-                       @Override
-                       public void run() {
-                               work();
-                       }
-
-               };
-               runner.start();
-       }
-
-       private static void work() {
-               try {
-                       gencrl();
-               } catch (IOException e2) {
-                       e2.printStackTrace();
-               } catch (InterruptedException e2) {
-                       e2.printStackTrace();
-               }
-               while (running) {
-                       try {
-                               signCertificates();
-                               revokeCertificates();
-                               Thread.sleep(5000);
-                       } catch (IOException e) {
-                               e.printStackTrace();
-                       } catch (SQLException e) {
-                               e.printStackTrace();
-                       } catch (InterruptedException e1) {
-                       }
-               }
-       }
-
-       private static void revokeCertificates() throws SQLException, IOException, InterruptedException {
-               ResultSet rs = revoke.executeQuery();
-               boolean worked = false;
-               while (rs.next()) {
-                       int id = rs.getInt(1);
-                       File crt = KeyStorage.locateCrt(id);
-                       String[] call = new String[] { "openssl", "ca",//
-                                       "-cert", "testca.crt",//
-                                       "-keyfile", "testca.key",//
-                                       "-revoke", "../" + crt.getPath(),//
-                                       "-batch",//
-                                       "-config", "selfsign.config"
-
-                       };
-                       Process p1 = Runtime.getRuntime().exec(call, null, new File("keys"));
-                       System.out.println("revoking: " + crt.getPath());
-                       if (p1.waitFor() == 0) {
-                               worked = true;
-                               revokeCompleted.setInt(1, id);
-                               revokeCompleted.execute();
-                               finishJob.setInt(1, rs.getInt(3));
-                               finishJob.execute();
-                       } else {
-                               System.out.println("Failed");
-                       }
-               }
-               if (worked) {
-                       gencrl();
-               }
-       }
-
-       private static void gencrl() throws IOException, InterruptedException {
-               String[] call = new String[] { "openssl", "ca",//
-                               "-cert", "testca.crt",//
-                               "-keyfile", "testca.key",//
-                               "-gencrl",//
-                               "-crlhours",//
-                               "12",//
-                               "-out", "testca.crl",//
-                               "-config", "selfsign.config"
-
-               };
-               Process p1 = Runtime.getRuntime().exec(call, null, new File("keys"));
-               if (p1.waitFor() != 0) {
-                       System.out.println("Error while generating crl.");
-               }
-       }
-
-       private static void signCertificates() throws SQLException, IOException, InterruptedException {
-               ResultSet rs = readyMail.executeQuery();
-               while (rs.next()) {
-                       String csrname = rs.getString(2);
-                       System.out.println("sign: " + csrname);
-                       int id = rs.getInt(1);
-                       String csrType = rs.getString(5);
-                       CSRType ct = CSRType.valueOf(csrType);
-                       File crt = KeyStorage.locateCrt(id);
-                       String[] call = new String[] { "openssl", "ca",//
-                                       "-in", "../" + csrname,//
-                                       "-cert", "testca.crt",//
-                                       "-keyfile", "testca.key",//
-                                       "-out", "../" + crt.getPath(),//
-                                       "-days", "356",//
-                                       "-batch",//
-                                       "-subj", rs.getString(3),//
-                                       "-config", "selfsign.config"//
-
-                       };
-                       if (ct == CSRType.SPKAC) {
-                               call[2] = "-spkac";
-                       }
-                       Process p1 = Runtime.getRuntime().exec(call, null, new File("keys"));
-
-                       int waitFor = p1.waitFor();
-                       if (waitFor == 0) {
-                               try (InputStream is = new FileInputStream(crt)) {
-                                       CertificateFactory cf = CertificateFactory.getInstance("X.509");
-                                       X509Certificate crtp = (X509Certificate) cf.generateCertificate(is);
-                                       BigInteger serial = crtp.getSerialNumber();
-                                       updateMail.setString(1, crt.getPath());
-                                       updateMail.setString(2, serial.toString(16));
-                                       updateMail.setInt(3, id);
-                                       updateMail.execute();
-
-                                       finishJob.setInt(1, rs.getInt(4));
-                                       finishJob.execute();
-                                       System.out.println("signed: " + id);
-                                       continue;
-                               } catch (GeneralSecurityException e) {
-                                       e.printStackTrace();
-                               }
-                               System.out.println("ERROR Afterwards: " + id);
-                               warnMail.setInt(1, rs.getInt(4));
-                               warnMail.execute();
-                       } else {
-                               BufferedReader br = new BufferedReader(new InputStreamReader(p1.getErrorStream()));
-                               String s;
-                               while ((s = br.readLine()) != null) {
-                                       System.out.println(s);
-                               }
-                               System.out.println(Arrays.toString(call));
-                               System.out.println("ERROR: " + id);
-                               warnMail.setInt(1, rs.getInt(4));
-                               warnMail.execute();
-                       }
-
-               }
-               rs.close();
-       }
+
+    private static PreparedStatement warnMail;
+
+    private static PreparedStatement updateMail;
+
+    private static PreparedStatement readyMail;
+
+    private static PreparedStatement revoke;
+
+    private static PreparedStatement revokeCompleted;
+
+    private static PreparedStatement finishJob;
+
+    private static boolean running = true;
+
+    private static Thread runner;
+
+    public static void main(String[] args) throws IOException, SQLException, InterruptedException {
+        Properties p = new Properties();
+        p.load(new FileReader("config/gigi.properties"));
+        DatabaseConnection.init(p);
+
+        runSigner();
+    }
+
+    public synchronized static void stopSigner() throws InterruptedException {
+        if (runner == null) {
+            throw new IllegalStateException("already stopped");
+        }
+        running = false;
+        runner.interrupt();
+        runner.join();
+        runner = null;
+    }
+
+    public synchronized static void runSigner() throws SQLException, IOException, InterruptedException {
+        if (runner != null) {
+            throw new IllegalStateException("already running");
+        }
+        running = true;
+        readyMail = DatabaseConnection.getInstance().prepare("SELECT emailcerts.id,emailcerts.csr_name,emailcerts.subject, jobs.id,csr_type FROM jobs INNER JOIN emailcerts ON emailcerts.id=jobs.targetId" + " WHERE jobs.state='open'"//
+                + " AND task='sign'");
+
+        updateMail = DatabaseConnection.getInstance().prepare("UPDATE emailcerts SET crt_name=?," + " created=NOW(), serial=? WHERE id=?");
+        warnMail = DatabaseConnection.getInstance().prepare("UPDATE jobs SET warning=warning+1, state=IF(warning<3, 'open','error') WHERE id=?");
+
+        revoke = DatabaseConnection.getInstance().prepare("SELECT emailcerts.id, emailcerts.csr_name,jobs.id FROM jobs INNER JOIN emailcerts ON jobs.targetId=emailcerts.id" + " WHERE jobs.state='open' AND task='revoke'");
+        revokeCompleted = DatabaseConnection.getInstance().prepare("UPDATE emailcerts SET revoked=NOW() WHERE id=?");
+
+        finishJob = DatabaseConnection.getInstance().prepare("UPDATE jobs SET state='done' WHERE id=?");
+
+        runner = new Thread() {
+
+            @Override
+            public void run() {
+                work();
+            }
+
+        };
+        runner.start();
+    }
+
+    private static void work() {
+        try {
+            gencrl();
+        } catch (IOException e2) {
+            e2.printStackTrace();
+        } catch (InterruptedException e2) {
+            e2.printStackTrace();
+        }
+        while (running) {
+            try {
+                signCertificates();
+                revokeCertificates();
+                Thread.sleep(5000);
+            } catch (IOException e) {
+                e.printStackTrace();
+            } catch (SQLException e) {
+                e.printStackTrace();
+            } catch (InterruptedException e1) {
+            }
+        }
+    }
+
+    private static void revokeCertificates() throws SQLException, IOException, InterruptedException {
+        ResultSet rs = revoke.executeQuery();
+        boolean worked = false;
+        while (rs.next()) {
+            int id = rs.getInt(1);
+            File crt = KeyStorage.locateCrt(id);
+            String[] call = new String[] {
+                    "openssl", "ca",//
+                    "-cert",
+                    "testca.crt",//
+                    "-keyfile",
+                    "testca.key",//
+                    "-revoke",
+                    "../" + crt.getPath(),//
+                    "-batch",//
+                    "-config",
+                    "selfsign.config"
+
+            };
+            Process p1 = Runtime.getRuntime().exec(call, null, new File("keys"));
+            System.out.println("revoking: " + crt.getPath());
+            if (p1.waitFor() == 0) {
+                worked = true;
+                revokeCompleted.setInt(1, id);
+                revokeCompleted.execute();
+                finishJob.setInt(1, rs.getInt(3));
+                finishJob.execute();
+            } else {
+                System.out.println("Failed");
+            }
+        }
+        if (worked) {
+            gencrl();
+        }
+    }
+
+    private static void gencrl() throws IOException, InterruptedException {
+        String[] call = new String[] {
+                "openssl", "ca",//
+                "-cert",
+                "testca.crt",//
+                "-keyfile",
+                "testca.key",//
+                "-gencrl",//
+                "-crlhours",//
+                "12",//
+                "-out",
+                "testca.crl",//
+                "-config",
+                "selfsign.config"
+
+        };
+        Process p1 = Runtime.getRuntime().exec(call, null, new File("keys"));
+        if (p1.waitFor() != 0) {
+            System.out.println("Error while generating crl.");
+        }
+    }
+
+    private static void signCertificates() throws SQLException, IOException, InterruptedException {
+        ResultSet rs = readyMail.executeQuery();
+        while (rs.next()) {
+            String csrname = rs.getString(2);
+            System.out.println("sign: " + csrname);
+            int id = rs.getInt(1);
+            String csrType = rs.getString(5);
+            CSRType ct = CSRType.valueOf(csrType);
+            File crt = KeyStorage.locateCrt(id);
+            String[] call = new String[] {
+                    "openssl", "ca",//
+                    "-in",
+                    "../" + csrname,//
+                    "-cert",
+                    "testca.crt",//
+                    "-keyfile",
+                    "testca.key",//
+                    "-out",
+                    "../" + crt.getPath(),//
+                    "-days",
+                    "356",//
+                    "-batch",//
+                    "-subj",
+                    rs.getString(3),//
+                    "-config",
+                    "selfsign.config"//
+
+            };
+            if (ct == CSRType.SPKAC) {
+                call[2] = "-spkac";
+            }
+            Process p1 = Runtime.getRuntime().exec(call, null, new File("keys"));
+
+            int waitFor = p1.waitFor();
+            if (waitFor == 0) {
+                try (InputStream is = new FileInputStream(crt)) {
+                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
+                    X509Certificate crtp = (X509Certificate) cf.generateCertificate(is);
+                    BigInteger serial = crtp.getSerialNumber();
+                    updateMail.setString(1, crt.getPath());
+                    updateMail.setString(2, serial.toString(16));
+                    updateMail.setInt(3, id);
+                    updateMail.execute();
+
+                    finishJob.setInt(1, rs.getInt(4));
+                    finishJob.execute();
+                    System.out.println("signed: " + id);
+                    continue;
+                } catch (GeneralSecurityException e) {
+                    e.printStackTrace();
+                }
+                System.out.println("ERROR Afterwards: " + id);
+                warnMail.setInt(1, rs.getInt(4));
+                warnMail.execute();
+            } else {
+                BufferedReader br = new BufferedReader(new InputStreamReader(p1.getErrorStream()));
+                String s;
+                while ((s = br.readLine()) != null) {
+                    System.out.println(s);
+                }
+                System.out.println(Arrays.toString(call));
+                System.out.println("ERROR: " + id);
+                warnMail.setInt(1, rs.getInt(4));
+                warnMail.execute();
+            }
+
+        }
+        rs.close();
+    }
 }