]> WPIA git - gigi.git/commitdiff
[EMPTY] Formatting with configured formatter.
authorFelix Dörre <felix@dogcraft.de>
Wed, 9 Jul 2014 23:22:51 +0000 (01:22 +0200)
committerFelix Dörre <felix@dogcraft.de>
Thu, 10 Jul 2014 22:35:15 +0000 (00:35 +0200)
62 files changed:
src/org/cacert/gigi/Certificate.java
src/org/cacert/gigi/DevelLauncher.java
src/org/cacert/gigi/Gigi.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/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/Template.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/MailCertificateAdd.java
src/org/cacert/gigi/pages/account/MailCertificates.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/HTTPFetch.java
src/org/cacert/gigi/ping/SSLPinger.java
src/org/cacert/gigi/util/CipherInfo.java
src/org/cacert/gigi/util/KeyStorage.java
src/org/cacert/gigi/util/Notary.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/TestSSL.java
tests/org/cacert/gigi/TestSecurityHeaders.java
tests/org/cacert/gigi/TestUser.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/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 f2011052c7b4fb16b84a3a3bd5e51bec99b9af5c..9d6d5d8d39f30a1fb36c04aa9fa377454749b5ed 100644 (file)
@@ -23,6 +23,7 @@ public class Certificate {
        private String csrName;
        private String crtName;
        private String csr = null;
+
        public Certificate(String dn, String md, String csr) {
                this.dn = dn;
                this.md = md;
@@ -31,10 +32,8 @@ public class Certificate {
 
        public Certificate(int id) {
                try {
-                       PreparedStatement ps = DatabaseConnection
-                                       .getInstance()
-                                       .prepare(
-                                                       "SELECT subject, md, csr_name, crt_name FROM `emailcerts` WHERE id=?");
+                       PreparedStatement ps = DatabaseConnection.getInstance().prepare(
+                               "SELECT subject, md, csr_name, crt_name FROM `emailcerts` WHERE id=?");
                        ps.setInt(1, id);
                        ResultSet rs = ps.executeQuery();
                        if (!rs.next()) {
@@ -88,6 +87,7 @@ public class Certificate {
                private CertificateStatus(boolean unstable) {
                        this.unstable = unstable;
                }
+
                /**
                 * Checks, iff this certificate stage will be left by signer actions.
                 * 
@@ -99,14 +99,13 @@ public class Certificate {
                }
 
        }
+
        public CertificateStatus getStatus() throws SQLException {
                if (id == 0) {
                        return CertificateStatus.DRAFT;
                }
-               PreparedStatement searcher = DatabaseConnection
-                               .getInstance()
-                               .prepare(
-                                               "SELECT crt_name, created, revoked, warning FROM emailcerts WHERE id=?");
+               PreparedStatement searcher = DatabaseConnection.getInstance().prepare(
+                       "SELECT crt_name, created, revoked, warning FROM emailcerts WHERE id=?");
                searcher.setInt(1, id);
                ResultSet rs = searcher.executeQuery();
                if (!rs.next()) {
@@ -124,8 +123,7 @@ public class Certificate {
                if (rs.getTime(2) != null && rs.getTime(3) == null) {
                        return CertificateStatus.ISSUED;
                }
-               if (rs.getTime(2) != null
-                               && rs.getString(3).equals("1970-01-01 00:00:00.0")) {
+               if (rs.getTime(2) != null && rs.getString(3).equals("1970-01-01 00:00:00.0")) {
                        return CertificateStatus.BEING_REVOKED;
                }
                return CertificateStatus.REVOKED;
@@ -136,10 +134,8 @@ public class Certificate {
                        if (getStatus() != CertificateStatus.DRAFT) {
                                throw new IllegalStateException();
                        }
-                       PreparedStatement inserter = DatabaseConnection
-                                       .getInstance()
-                                       .prepare(
-                                                       "INSERT INTO emailcerts SET md=?, subject=?, coll_found=0, crt_name=''");
+                       PreparedStatement inserter = DatabaseConnection.getInstance().prepare(
+                               "INSERT INTO emailcerts SET md=?, subject=?, coll_found=0, crt_name=''");
                        inserter.setString(1, md);
                        inserter.setString(2, dn);
                        inserter.execute();
@@ -150,8 +146,8 @@ public class Certificate {
                        fos.write(csr.getBytes());
                        fos.close();
 
-                       PreparedStatement updater = DatabaseConnection.getInstance()
-                                       .prepare("UPDATE emailcerts SET csr_name=? WHERE id=?");
+                       PreparedStatement updater = DatabaseConnection.getInstance().prepare(
+                               "UPDATE emailcerts SET csr_name=? WHERE id=?");
                        updater.setString(1, csrName);
                        updater.setInt(2, id);
                        updater.execute();
@@ -160,6 +156,7 @@ public class Certificate {
                }
 
        }
+
        public boolean waitFor(int max) throws SQLException, InterruptedException {
                long start = System.currentTimeMillis();
                while (getStatus().isUnstable()) {
@@ -170,15 +167,14 @@ public class Certificate {
                }
                return true;
        }
+
        public void revoke() {
                try {
                        if (getStatus() != CertificateStatus.ISSUED) {
                                throw new IllegalStateException();
                        }
-                       PreparedStatement inserter = DatabaseConnection
-                                       .getInstance()
-                                       .prepare(
-                                                       "UPDATE emailcerts SET revoked = '1970-01-01' WHERE id=?");
+                       PreparedStatement inserter = DatabaseConnection.getInstance().prepare(
+                               "UPDATE emailcerts SET revoked = '1970-01-01' WHERE id=?");
                        inserter.setInt(1, id);
                        inserter.execute();
                } catch (SQLException e) {
@@ -187,8 +183,7 @@ public class Certificate {
 
        }
 
-       public X509Certificate cert() throws IOException, GeneralSecurityException,
-                       SQLException {
+       public X509Certificate cert() throws IOException, GeneralSecurityException, SQLException {
                CertificateStatus status = getStatus();
                if (status != CertificateStatus.ISSUED) {
                        throw new IllegalStateException(status + " is not wanted here.");
@@ -206,18 +201,23 @@ public class Certificate {
                }
                return crt;
        }
+
        public Certificate renew() {
                return null;
        }
+
        public int getId() {
                return id;
        }
+
        public int getSerial() {
                return serial;
        }
+
        public String getDistinguishedName() {
                return dn;
        }
+
        public String getMessageDigest() {
                return md;
        }
index e8df9f5bdf2d048ff54569471f12bf4ccb425167..6fa8a29a8cada7de1c5d1f27326168b34bddc8b4 100644 (file)
@@ -30,20 +30,18 @@ public class DevelLauncher {
                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"));
+               byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12"));
 
-               DevelLauncher.writeGigiConfig(dos, "changeit".getBytes(),
-                               "changeit".getBytes(), mainProps, cacerts, keystore);
+               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);
        }
-       public static void writeGigiConfig(OutputStream target, byte[] keystorepw,
-                       byte[] truststorepw, Properties mainprop, byte[] cacerts,
-                       byte[] keystore) throws IOException {
+
+       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, "");
@@ -56,21 +54,21 @@ public class DevelLauncher {
                tos.close();
 
        }
-       private static void putTarEntry(byte[] data, TarOutputStream tos,
-                       String name) throws IOException {
+
+       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 {
+
+       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 {
+
+       public static void launch(Properties props, File cacerts, File keystore) throws IOException {
                ByteArrayOutputStream config = new ByteArrayOutputStream();
                props.store(config, "");
        }
index 2741b7329ca6eb491f72cd524891ae1b820fde70..a0f8671a190f220d3ce6e780eae52998ad1b9f26 100644 (file)
@@ -62,14 +62,14 @@ public class Gigi extends HttpServlet {
                pages.put(MailOverview.DEFAULT_PATH, new MailOverview("My email addresses"));
                baseTemplate = new Template(new InputStreamReader(Gigi.class.getResourceAsStream("Gigi.templ")));
                m = new Menu("Certificates", "cert", new MenuItem(MailOverview.DEFAULT_PATH, "Emails"), new MenuItem("",
-                               "Client Certificates"), new MenuItem("", "Domains"), new MenuItem("", "Server Certificates"));
+                       "Client Certificates"), new MenuItem("", "Domains"), new MenuItem("", "Server Certificates"));
                super.init();
 
        }
 
        @Override
        protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException,
-                       IOException {
+               IOException {
                addXSSHeaders(resp);
                // if (req.getHeader("Origin") != null) {
                // resp.getWriter().println("No cross domain access allowed.");
@@ -154,7 +154,7 @@ public class Gigi extends HttpServlet {
 
        public static void addXSSHeaders(HttpServletResponse hsr) {
                hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePort() + " https://"
-                               + ServerConstants.getSecureHostNamePort());
+                       + ServerConstants.getSecureHostNamePort());
                hsr.addHeader("Access-Control-Max-Age", "60");
 
                hsr.addHeader("Content-Security-Policy", getDefaultCSP());
@@ -174,7 +174,7 @@ public class Gigi extends HttpServlet {
                        csp.append("script-src https://" + ServerConstants.getStaticHostNamePort());
                        csp.append(";style-src https://" + ServerConstants.getStaticHostNamePort());
                        csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://"
-                                       + ServerConstants.getWwwHostNamePort());
+                               + ServerConstants.getWwwHostNamePort());
                        csp.append("report-url https://api.cacert.org/security/csp/report");
                        defaultCSP = csp.toString();
                }
index f8cf76378aa1f6539e6e18403b95fa77191c08bc..86738007eb237b6ccd66ee490e603b8e1068c59a 100644 (file)
@@ -21,12 +21,15 @@ public class GigiConfig {
 
        private GigiConfig() {
        }
+
        public byte[] getCacerts() {
                return cacerts;
        }
+
        public byte[] getKeystore() {
                return keystore;
        }
+
        public Properties getMainProps() {
                return mainProps;
        }
@@ -53,6 +56,7 @@ public class GigiConfig {
                tis.close();
                return gc;
        }
+
        public static byte[] readFully(InputStream is) throws IOException {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
@@ -63,6 +67,7 @@ public class GigiConfig {
                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++) {
@@ -72,18 +77,18 @@ public class GigiConfig {
                return res;
        }
 
-       public KeyStore getPrivateStore() throws GeneralSecurityException,
-                       IOException {
+       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 {
+
+       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 5841c3c35dc918b025df178735d3e1500706f12e..fc94ce1b766fecb897f6ad3a9804d6bb501328bb 100644 (file)
@@ -18,8 +18,8 @@ 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 {
+
+       private Language(String language) throws ParserConfigurationException, IOException, SAXException {
                if (language.contains("_")) {
                        String[] parts = language.split("_");
                        l = new Locale(parts[0], parts[1]);
@@ -29,8 +29,7 @@ public class Language {
 
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
-               Document d = db.parse(new FileInputStream(new File("locale", language
-                               + ".xml")));
+               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)) {
@@ -43,6 +42,7 @@ public class Language {
                }
                System.out.println(translations.size() + " strings loaded.");
        }
+
        public String getTranslation(String text) {
                String string = translations.get(text);
                if (string == null || string.equals("")) {
@@ -50,6 +50,7 @@ public class Language {
                }
                return string;
        }
+
        public static Language getInstance(String language) {
                Language l = langs.get(language);
                if (l == null) {
@@ -66,6 +67,7 @@ public class Language {
                }
                return l;
        }
+
        public Locale getLocale() {
                return l;
        }
index 2d8ab7abc7d6146b1afc98f52422cdfc1bb3a1c3..6eb5976a6698e504aa3e249714821bfe3186e0df 100644 (file)
@@ -1,4 +1,5 @@
 package org.cacert.gigi;
+
 import java.io.IOException;
 import java.security.GeneralSecurityException;
 import java.security.KeyStore;
@@ -49,21 +50,18 @@ public class Launcher {
                // for client-cert auth
                https_config.addCustomizer(new SecureRequestCustomizer());
 
-               ServerConnector connector = new ServerConnector(s,
-                               createConnectionFactory(conf), new HttpConnectionFactory(
-                                               https_config));
+               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});
+               connector.setPort(Integer.parseInt(conf.getMainProps().getProperty("port")));
+               s.setConnectors(new Connector[] { connector });
 
                HandlerList hl = new HandlerList();
-               hl.setHandlers(new Handler[]{generateStaticContext(),
-                               generateGigiContext(conf.getMainProps()), generateAPIContext()});
+               hl.setHandlers(new Handler[] { generateStaticContext(), generateGigiContext(conf.getMainProps()),
+                               generateAPIContext() });
                s.setHandler(hl);
                s.start();
-               if (connector.getPort() <= 1024
-                               && !System.getProperty("os.name").toLowerCase().contains("win")) {
+               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!");
@@ -71,17 +69,13 @@ public class Launcher {
                }
        }
 
-       private static SslConnectionFactory createConnectionFactory(GigiConfig conf)
-                       throws GeneralSecurityException, IOException {
-               final SslContextFactory sslContextFactory = generateSSLContextFactory(
-                               conf, "www");
-               final SslContextFactory secureContextFactory = generateSSLContextFactory(
-                               conf, "secure");
+       private static SslConnectionFactory createConnectionFactory(GigiConfig conf) throws GeneralSecurityException,
+               IOException {
+               final SslContextFactory sslContextFactory = generateSSLContextFactory(conf, "www");
+               final SslContextFactory secureContextFactory = generateSSLContextFactory(conf, "secure");
                secureContextFactory.setNeedClientAuth(true);
-               final SslContextFactory staticContextFactory = generateSSLContextFactory(
-                               conf, "static");
-               final SslContextFactory apiContextFactory = generateSSLContextFactory(
-                               conf, "api");
+               final SslContextFactory staticContextFactory = generateSSLContextFactory(conf, "static");
+               final SslContextFactory apiContextFactory = generateSSLContextFactory(conf, "api");
                try {
                        secureContextFactory.start();
                        staticContextFactory.start();
@@ -89,12 +83,12 @@ public class Launcher {
                } catch (Exception e) {
                        e.printStackTrace();
                }
-               return new SslConnectionFactory(sslContextFactory,
-                               HttpVersion.HTTP_1_1.asString()) {
+               return new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()) {
                        @Override
                        public boolean shouldRestartSSL() {
                                return true;
                        }
+
                        @Override
                        public SSLEngine restartSSL(SSLSession sslSession) {
                                SSLEngine e2 = null;
@@ -105,17 +99,13 @@ public class Launcher {
                                                if (sniServerName instanceof SNIHostName) {
                                                        SNIHostName host = (SNIHostName) sniServerName;
                                                        String hostname = host.getAsciiName();
-                                                       if (hostname.equals(ServerConstants
-                                                                       .getWwwHostName())) {
+                                                       if (hostname.equals(ServerConstants.getWwwHostName())) {
                                                                e2 = sslContextFactory.newSSLEngine();
-                                                       } else if (hostname.equals(ServerConstants
-                                                                       .getStaticHostName())) {
+                                                       } else if (hostname.equals(ServerConstants.getStaticHostName())) {
                                                                e2 = staticContextFactory.newSSLEngine();
-                                                       } else if (hostname.equals(ServerConstants
-                                                                       .getSecureHostName())) {
+                                                       } else if (hostname.equals(ServerConstants.getSecureHostName())) {
                                                                e2 = secureContextFactory.newSSLEngine();
-                                                       } else if (hostname.equals(ServerConstants
-                                                                       .getApiHostName())) {
+                                                       } else if (hostname.equals(ServerConstants.getApiHostName())) {
                                                                e2 = apiContextFactory.newSSLEngine();
                                                        }
                                                        break;
@@ -123,8 +113,7 @@ public class Launcher {
                                        }
                                }
                                if (e2 == null) {
-                                       e2 = sslContextFactory.newSSLEngine(
-                                                       sslSession.getPeerHost(), sslSession.getPeerPort());
+                                       e2 = sslContextFactory.newSSLEngine(sslSession.getPeerHost(), sslSession.getPeerPort());
                                }
                                e2.setUseClientMode(false);
                                return e2;
@@ -139,18 +128,15 @@ public class Launcher {
                HandlerWrapper hw = new PolicyRedirector();
                hw.setHandler(rh);
 
-               ServletContextHandler servlet = new ServletContextHandler(
-                               ServletContextHandler.SESSIONS);
-               servlet.setInitParameter(SessionManager.__SessionCookieProperty,
-                               "CACert-Session");
+               ServletContextHandler servlet = new ServletContextHandler(ServletContextHandler.SESSIONS);
+               servlet.setInitParameter(SessionManager.__SessionCookieProperty, "CACert-Session");
                servlet.addServlet(new ServletHolder(new Gigi(conf)), "/*");
 
                HandlerList hl = new HandlerList();
-               hl.setHandlers(new Handler[]{hw, servlet});
+               hl.setHandlers(new Handler[] { hw, servlet });
 
                ContextHandler ch = new ContextHandler();
-               ch.setVirtualHosts(new String[]{ServerConstants.getWwwHostName(),
-                               ServerConstants.getSecureHostName()});
+               ch.setVirtualHosts(new String[] { ServerConstants.getWwwHostName(), ServerConstants.getSecureHostName() });
                ch.setHandler(hl);
 
                return ch;
@@ -162,7 +148,7 @@ public class Launcher {
 
                ContextHandler ch = new ContextHandler();
                ch.setHandler(rh);
-               ch.setVirtualHosts(new String[]{ServerConstants.getStaticHostName()});
+               ch.setVirtualHosts(new String[] { ServerConstants.getStaticHostName() });
 
                return ch;
        }
@@ -170,13 +156,13 @@ public class Launcher {
        private static Handler generateAPIContext() {
                ServletContextHandler sch = new ServletContextHandler();
 
-               sch.addVirtualHosts(new String[]{ServerConstants.getApiHostName()});
+               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 {
+       private static SslContextFactory generateSSLContextFactory(GigiConfig conf, String alias)
+               throws GeneralSecurityException, IOException {
                SslContextFactory scf = new SslContextFactory() {
 
                        String[] ciphers = null;
@@ -188,8 +174,7 @@ public class Launcher {
                                SSLParameters ssl = sslEngine.getSSLParameters();
                                ssl.setUseCipherSuitesOrder(true);
                                if (ciphers == null) {
-                                       ciphers = CipherInfo.filter(sslEngine
-                                                       .getSupportedCipherSuites());
+                                       ciphers = CipherInfo.filter(sslEngine.getSupportedCipherSuites());
                                }
 
                                ssl.setCipherSuites(ciphers);
index bf6265b998e61eafde6301ac6b51653b89a1cbe5..865090f0071670d50dcfc20847c1c61b99924370 100644 (file)
@@ -29,6 +29,7 @@ public class Name implements Outputable {
                out.print("</span>");
                out.println("</span>");
        }
+
        @Override
        public boolean equals(Object obj) {
                if (!(obj instanceof Name)) {
index 6fd8969b3fd43cf849ffd661f42cd269614db34c..d96ed732f58c5e0eefef858448447722d7edb4a9 100644 (file)
@@ -11,9 +11,8 @@ 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 {
+       public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
+               throws IOException, ServletException {
                if (target.equals("/")) {
                        return;
                }
index b492de48525130148b3bc1ac9f919449f5bc637f..95630394ad862470675662f5e9c1cbf21947e4d1 100644 (file)
@@ -20,15 +20,12 @@ public class User {
        public User(int id) {
                this.id = id;
                try {
-                       PreparedStatement ps = DatabaseConnection
-                                       .getInstance()
-                                       .prepare(
-                                                       "SELECT `fname`, `lname`,`mname`, `suffix`, `dob`, `email` FROM `users` WHERE id=?");
+                       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));
+                               name = new Name(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4));
                                dob = rs.getDate(5);
                                email = rs.getString(6);
                        }
@@ -37,61 +34,77 @@ public class User {
                        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");
+                       "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);
@@ -112,9 +125,10 @@ public class User {
                return hasPassedCATS();
 
        }
+
        public boolean hasPassedCATS() throws SQLException {
                PreparedStatement query = DatabaseConnection.getInstance().prepare(
-                               "SELECT 1 FROM `cats_passed` where `user_id`=?");
+                       "SELECT 1 FROM `cats_passed` where `user_id`=?");
                query.setInt(1, id);
                ResultSet rs = query.executeQuery();
                if (rs.next()) {
@@ -123,11 +137,10 @@ public class User {
                        return false;
                }
        }
+
        public int getAssurancePoints() throws SQLException {
-               PreparedStatement query = DatabaseConnection
-                               .getInstance()
-                               .prepare(
-                                               "SELECT sum(points) FROM `notary` where `to`=? AND `deleted`=0");
+               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;
@@ -137,9 +150,10 @@ public class User {
                rs.close();
                return points;
        }
+
        public int getExperiencePoints() throws SQLException {
                PreparedStatement query = DatabaseConnection.getInstance().prepare(
-                               "SELECT count(*) FROM `notary` where `from`=? AND `deleted`=0");
+                       "SELECT count(*) FROM `notary` where `from`=? AND `deleted`=0");
                query.setInt(1, id);
                ResultSet rs = query.executeQuery();
                int points = 0;
@@ -149,15 +163,19 @@ public class User {
                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
+               return name.equals(s.name) && email.equals(s.email) && dob.toString().equals(s.dob.toString()); // This
+                                                                                                                                                                                                               // is
+                                                                                                                                                                                                               // due
+                                                                                                                                                                                                               // to
+                                                                                                                                                                                                               // day
+                                                                                                                                                                                                               // cutoff
        }
 
        /**
index 88c8da81b3a99b4c794040b155cab5ca14599390..4104feb3f78a1940517763d72dbef8ca3c9ffee9 100644 (file)
@@ -11,8 +11,7 @@ import javax.servlet.http.HttpServletResponse;
 
 public class GigiAPI extends HttpServlet {
        @Override
-       protected void service(HttpServletRequest req, HttpServletResponse resp)
-                       throws ServletException, IOException {
+       protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                String pi = req.getPathInfo();
                if (pi == null) {
                        return;
index 6bed8bd979c2f62aec1b7922779bed3048716063..b52b63debeef44748860b861fb63a4f558a01ad4 100644 (file)
@@ -15,6 +15,7 @@ public class DatabaseConnection {
        HashMap<String, PreparedStatement> statements = new HashMap<String, PreparedStatement>();
        private static Properties credentials;
        Statement adHoc;
+
        public DatabaseConnection() {
                try {
                        Class.forName(credentials.getProperty("sql.driver"));
@@ -24,14 +25,12 @@ public class DatabaseConnection {
                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=?;");
+                       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();
@@ -40,17 +39,19 @@ public class DatabaseConnection {
                        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);
+                       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 {
@@ -65,6 +66,7 @@ public class DatabaseConnection {
                }
                lastAction = System.currentTimeMillis();
        }
+
        public static int lastInsertId(PreparedStatement query) throws SQLException {
                ResultSet rs = query.getGeneratedKeys();
                rs.next();
@@ -72,31 +74,38 @@ public class DatabaseConnection {
                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()) {
index 2f7502b5211ca15b000a41d01b0ba77ebac608b4..a9149fab1ccadf8d17df7f8a6afca50cb4df3eaf 100644 (file)
@@ -8,9 +8,8 @@ public class CommandlineEmailProvider extends EmailProvider {
        }
 
        @Override
-       public void sendmail(String to, String subject, String message,
-                       String from, String replyto, String toname, String fromname,
-                       String errorsto, boolean extra) throws IOException {
+       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);
@@ -22,9 +21,9 @@ public class CommandlineEmailProvider extends EmailProvider {
                }
 
        }
+
        @Override
-       public String checkEmailServer(int forUid, String address)
-                       throws IOException {
+       public String checkEmailServer(int forUid, String address) throws IOException {
                System.out.println("checkMailBox: " + address);
                return OK;
        }
index 644c46218709f6fc8d28e6551c093d1fceae12ec..0efe603e42cf77fc161049566d5f4a0bcd519533 100644 (file)
@@ -14,18 +14,19 @@ 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;
+       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;
        }
+
        public static void init(Properties conf) {
                try {
                        Class<?> c = Class.forName(conf.getProperty("emailProvider"));
-                       instance = (EmailProvider) c.getDeclaredConstructor(
-                                       Properties.class).newInstance(conf);
+                       instance = (EmailProvider) c.getDeclaredConstructor(Properties.class).newInstance(conf);
                } catch (ReflectiveOperationException e) {
                        e.printStackTrace();
                }
@@ -34,10 +35,9 @@ public abstract class EmailProvider {
        public static final String OK = "OK";
        public static final String FAIL = "FAIL";
        private static final Pattern MAIL = Pattern
-                       .compile("^([a-zA-Z0-9])+([a-zA-Z0-9\\+\\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\\._-]+)+$");
+               .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 {
+       public String checkEmailServer(int forUid, String address) throws IOException {
                if (MAIL.matcher(address).matches()) {
                        String[] parts = address.split("@", 2);
                        String domain = parts[1];
@@ -46,12 +46,10 @@ public abstract class EmailProvider {
 
                        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())) {
+                                       BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
+                                       PrintWriter pw = new PrintWriter(s.getOutputStream())) {
                                        String line;
-                                       while ((line = br.readLine()) != null
-                                                       && line.startsWith("220-")) {
+                                       while ((line = br.readLine()) != null && line.startsWith("220-")) {
                                        }
                                        if (line == null || !line.startsWith("220")) {
                                                continue;
@@ -60,8 +58,7 @@ public abstract class EmailProvider {
                                        pw.print("HELO www.cacert.org\r\n");
                                        pw.flush();
 
-                                       while ((line = br.readLine()) != null
-                                                       && line.startsWith("220")) {
+                                       while ((line = br.readLine()) != null && line.startsWith("220")) {
                                        }
 
                                        if (line == null || !line.startsWith("250")) {
@@ -83,10 +80,8 @@ public abstract class EmailProvider {
                                        pw.flush();
 
                                        try {
-                                               PreparedStatement statmt = DatabaseConnection
-                                                               .getInstance()
-                                                               .prepare(
-                                                                               "insert into `pinglog` set `when`=NOW(), `email`=?, `result`=?, `uid`=?");
+                                               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);
@@ -105,13 +100,10 @@ public abstract class EmailProvider {
                        }
                }
                try {
-                       PreparedStatement statmt = DatabaseConnection
-                                       .getInstance()
-                                       .prepare(
-                                                       "insert into `pinglog` set `when`=NOW(), `email`=?, `result`=?, `uid`=?");
+                       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.setString(2, "Failed to make a connection to the mail server");
                        statmt.setInt(3, forUid);
                        statmt.execute();
                } catch (SQLException e) {
@@ -119,13 +111,11 @@ public abstract class EmailProvider {
                }
                return FAIL;
        }
-       private static LinkedList<String> getMxHosts(String domain)
-                       throws IOException {
+
+       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()))) {
+               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);
index c61494b7eb4fe96cf9923c41e687b21ea7f69660..f47d2bc3cbefdba25a40a95f20c5557f4b7e5c1e 100644 (file)
@@ -15,20 +15,18 @@ 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 .-\\[\\]!_@]");
+
+       private static final Pattern NON_ASCII = Pattern.compile("[^a-zA-Z0-9 .-\\[\\]!_@]");
 
        @Override
-       public void sendmail(String to, String subject, String message,
-                       String from, String replyto, String toname, String fromname,
-                       String errorsto, boolean extra) throws IOException {
+       public void sendmail(String to, String subject, String message, String from, String replyto, String toname,
+               String fromname, String errorsto, boolean extra) throws IOException {
 
                String[] bits = from.split(",");
 
                Socket smtp = new Socket("dogcraft.de", 25);
                PrintWriter out = new PrintWriter(smtp.getOutputStream());
-               BufferedReader in = new BufferedReader(new InputStreamReader(
-                               smtp.getInputStream()));
+               BufferedReader in = new BufferedReader(new InputStreamReader(smtp.getInputStream()));
                readResponse(in);
                out.print("HELO www.cacert.org\r\n");
                out.flush();
@@ -50,11 +48,8 @@ public class Sendmail extends EmailProvider {
                // 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");
+               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) {
@@ -66,9 +61,7 @@ public class Sendmail extends EmailProvider {
                out.print("To: " + to + "\r\n");
                if (NON_ASCII.matcher(subject).matches()) {
 
-                       out.print("Subject: =?utf-8?B?"
-                                       + Base64.getEncoder().encodeToString(subject.getBytes())
-                                       + "?=\r\n");
+                       out.print("Subject: =?utf-8?B?" + Base64.getEncoder().encodeToString(subject.getBytes()) + "?=\r\n");
                } else {
                        out.print("Subject: " + subject + "\r\n");
                }
@@ -87,9 +80,8 @@ public class Sendmail extends EmailProvider {
                // $message)))."\r\n.\r\n");
                message = message + "\r\n";
 
-               String sendM = message.replace("\r", "").replace("\n.\n", "\n")
-                               .replace("\n.\n", "\n").replace("\n", "\r\n")
-                               + ".\r\n";
+               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);
@@ -98,6 +90,7 @@ public class Sendmail extends EmailProvider {
                readResponse(in);
                smtp.close();
        }
+
        private static void readResponse(BufferedReader in) throws IOException {
                String line;
                while ((line = in.readLine()) != null && line.matches("\\d+-")) {
index 07343502303073313a9c7002d96c8bcac39f8b23..35c4b3fe81351af1aaf6df7a44a983899a92ee30 100644 (file)
@@ -13,19 +13,19 @@ class TestEmailProvider extends EmailProvider {
        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"));
+                       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 {
+       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 {
@@ -42,6 +42,7 @@ class TestEmailProvider extends EmailProvider {
                        }
                }
        }
+
        private void assureLocalConnection() throws IOException {
                if (out != null) {
                        try {
@@ -56,9 +57,9 @@ class TestEmailProvider extends EmailProvider {
                        in = new DataInputStream(client.getInputStream());
                }
        }
+
        @Override
-       public synchronized String checkEmailServer(int forUid, String address)
-                       throws IOException {
+       public synchronized String checkEmailServer(int forUid, String address) throws IOException {
                while (true) {
                        assureLocalConnection();
                        try {
index 413de877b9235bb0988f33fe0ee99b1dfe076cbe..9f310f1919960a94a531ab2b9feac7e18f8edca3 100644 (file)
@@ -9,12 +9,13 @@ import org.cacert.gigi.Language;
 
 public class CertificateTable implements Outputable {
        String resultSet;
+
        public CertificateTable(String resultSet) {
                this.resultSet = resultSet;
        }
-       private static final String[] columnNames = new String[]{
-                       "Renew/Revoke/Delete", "Status", "Email Address", "SerialNumber",
-                       "Revoked", "Expires", "Login"};
+
+       private static final String[] columnNames = new String[] { "Renew/Revoke/Delete", "Status", "Email Address",
+                       "SerialNumber", "Revoked", "Expires", "Login" };
 
        @Override
        public void output(PrintWriter out, Language l, Map<String, Object> vars) {
index aeb7d9b81cf5b6f30a32830b59e9500011d1f95c..9398c2200d2e50efa51441ed97267c5fe435d83c 100644 (file)
@@ -15,21 +15,17 @@ public class ClientCSRGenerate {
        static Template IE;
        static {
                normal = new Template(new InputStreamReader(
-                               ClientCSRGenerate.class
-                                               .getResourceAsStream("ClientCSRGenerate.templ")));
+                       ClientCSRGenerate.class.getResourceAsStream("ClientCSRGenerate.templ")));
                IE = new Template(new InputStreamReader(
-                               ClientCSRGenerate.class
-                                               .getResourceAsStream("ClientCSRGenerateIE.templ")));
+                       ClientCSRGenerate.class.getResourceAsStream("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());
+               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) {
index c8cc0f10e1db0f2fe792cc1a1f042a3f44164937..4c162cfc7408f95c69d681be403bfcc86e51366e 100644 (file)
@@ -13,12 +13,15 @@ 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};
+               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=\"");
@@ -71,6 +74,7 @@ public class DateSelector implements Outputable {
                        year = parseIntSafe(yearS);
                }
        }
+
        private int parseIntSafe(String dayS) {
                try {
                        return Integer.parseInt(dayS);
@@ -79,6 +83,7 @@ public class DateSelector implements Outputable {
                }
                return 0;
        }
+
        public boolean isValid() {
                if (!(1900 < year && 1 <= month && month <= 12 && 1 <= day && day <= 32)) {
                        return false;
@@ -88,8 +93,8 @@ public class DateSelector implements Outputable {
 
        @Override
        public String toString() {
-               return "DateSelector [names=" + Arrays.toString(names) + ", day=" + day
-                               + ", month=" + month + ", year=" + year + "]";
+               return "DateSelector [names=" + Arrays.toString(names) + ", day=" + day + ", month=" + month + ", year=" + year
+                       + "]";
        }
 
        public java.sql.Date getDate() {
index 69fb22878e3fa6a76b8944e8c0d586c62717d870..d321fc31238f76c151c4aae5cc74991ce9c1e051 100644 (file)
@@ -12,14 +12,15 @@ import org.cacert.gigi.util.RandomToken;
 
 public abstract class Form implements Outputable {
        String csrf;
+
        public Form() {
                csrf = RandomToken.generateToken(32);
        }
 
        public abstract boolean submit(PrintWriter out, HttpServletRequest req);
+
        @Override
-       public final void output(PrintWriter out, Language l,
-                       Map<String, Object> vars) {
+       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='csrf' value='");
@@ -27,8 +28,7 @@ public abstract class Form implements Outputable {
                out.println("'></form>");
        }
 
-       protected abstract void outputContent(PrintWriter out, Language l,
-                       Map<String, Object> vars);
+       protected abstract void outputContent(PrintWriter out, Language l, Map<String, Object> vars);
 
        protected void outputError(PrintWriter out, ServletRequest req, String text) {
                out.print("<div>");
@@ -39,6 +39,7 @@ public abstract class Form implements Outputable {
        protected String getCSRFToken() {
                return csrf;
        }
+
        protected void checkCSRF(HttpServletRequest req) {
                if (!csrf.equals(req.getParameter("csrf"))) {
                        throw new CSRFError();
index b6fb111e20e5419d31651a78a81df2429e59399f..337200349b2b9555e2506930b3666fb5f4812962 100644 (file)
@@ -19,7 +19,7 @@ public class Template implements Outputable {
                        LinkedList<Outputable> commands = new LinkedList<Outputable>();
                        StringBuffer buf = new StringBuffer();
                        int ch = r.read();
-                       outer : while (true) {
+                       outer: while (true) {
                                while (!endsWith(buf, "<?")) {
                                        if (ch == -1) {
                                                break outer;
@@ -49,11 +49,12 @@ public class Template implements Outputable {
                        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);
+                       && buf.substring(buf.length() - string.length(), buf.length()).equals(string);
        }
+
        private Outputable parseCommand(String s2) {
                s2 = s2.replace("\n", "");
                if (s2.startsWith("=_")) {
@@ -61,8 +62,7 @@ public class Template implements Outputable {
                        return new Outputable() {
 
                                @Override
-                               public void output(PrintWriter out, Language l,
-                                               Map<String, Object> vars) {
+                               public void output(PrintWriter out, Language l, Map<String, Object> vars) {
                                        out.print(l.getTranslation(raw));
                                }
                        };
@@ -71,8 +71,7 @@ public class Template implements Outputable {
                        return new Outputable() {
 
                                @Override
-                               public void output(PrintWriter out, Language l,
-                                               Map<String, Object> vars) {
+                               public void output(PrintWriter out, Language l, Map<String, Object> vars) {
                                        outputVar(out, l, vars, raw);
                                }
                        };
@@ -88,8 +87,7 @@ public class Template implements Outputable {
                        return new Outputable() {
 
                                @Override
-                               public void output(PrintWriter out, Language l,
-                                               Map<String, Object> vars) {
+                               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]);
@@ -104,6 +102,7 @@ public class Template implements Outputable {
                }
                return null;
        }
+
        public void output(PrintWriter out, Language l, Map<String, Object> vars) {
                for (int i = 0; i < contents.length; i++) {
                        out.print(contents[i]);
@@ -112,8 +111,8 @@ public class Template implements Outputable {
                        }
                }
        }
-       private void outputVar(PrintWriter out, Language l,
-                       Map<String, Object> vars, String varname) {
+
+       private void outputVar(PrintWriter out, Language l, Map<String, Object> vars, String varname) {
                Object s = vars.get(varname);
 
                if (s == null) {
index 7febf2e5d5da3ff0b68ec0d05f3b0beb70e0d0c0..7be7117735599bf26fb28706b0764600a4009078 100644 (file)
@@ -25,22 +25,17 @@ public class LoginPage extends Page {
        }
 
        @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 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>");
        }
 
        @Override
-       public boolean beforeTemplate(HttpServletRequest req,
-                       HttpServletResponse resp) throws IOException {
+       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");
+                       X509Certificate[] cert = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
                        if (cert != null && cert[0] != null) {
                                tryAuthWithCertificate(req, cert[0]);
                        }
@@ -63,18 +58,18 @@ public class LoginPage extends Page {
                }
                return false;
        }
+
        @Override
        public boolean needsLogin() {
                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'");
+                       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()) {
@@ -90,19 +85,17 @@ public class LoginPage extends Page {
                        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();
+
+       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'");
+                       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()) {
index adeaa8024fbb5fb4319bf56f12b1b188a71dd2b7..96b30aed29908ce09c01ba23f827b0ca8a167741 100644 (file)
@@ -11,10 +11,10 @@ public class MainPage extends Page {
        }
 
        @Override
-       public void doGet(HttpServletRequest req, HttpServletResponse resp)
-                       throws IOException {
+       public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
                resp.getWriter().println("Access granted.");
        }
+
        @Override
        public boolean needsLogin() {
                return false;
index 04f1dc67292176643ad43848cee92635be030775..b6a30573fe2a254c58456632c01d664688195883 100644 (file)
@@ -23,11 +23,9 @@ public abstract class Page {
        public Page(String title) {
                this.title = title;
                try {
-                       InputStream resource = getClass().getResourceAsStream(
-                                       getClass().getSimpleName() + ".templ");
+                       InputStream resource = getClass().getResourceAsStream(getClass().getSimpleName() + ".templ");
                        if (resource != null) {
-                               defaultTemplate = new Template(new InputStreamReader(resource,
-                                               "UTF-8"));
+                               defaultTemplate = new Template(new InputStreamReader(resource, "UTF-8"));
                        }
                } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
@@ -57,8 +55,7 @@ public abstract class Page {
         * @throws IOException
         *             if output goes wrong.
         */
-       public boolean beforeTemplate(HttpServletRequest req,
-                       HttpServletResponse resp) throws IOException {
+       public boolean beforeTemplate(HttpServletRequest req, HttpServletResponse resp) throws IOException {
                return false;
        }
 
@@ -73,8 +70,7 @@ public abstract class Page {
         * @throws IOException
         *             if output goes wrong.
         */
-       public abstract void doGet(HttpServletRequest req, HttpServletResponse resp)
-                       throws IOException;
+       public abstract void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException;
 
        /**
         * Same as {@link #doGet(HttpServletRequest, HttpServletResponse)} but for
@@ -88,8 +84,7 @@ public abstract class Page {
         * @throws IOException
         *             if output goes wrong.
         */
-       public void doPost(HttpServletRequest req, HttpServletResponse resp)
-                       throws IOException {
+       public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
                doGet(req, resp);
        }
 
@@ -109,6 +104,7 @@ public abstract class Page {
        public void setTitle(String title) {
                this.title = title;
        }
+
        public static Language getLanguage(ServletRequest req) {
                return Language.getInstance("de");
        }
index e3d2f3cbf2c3f79a3c6176a8dfed46a2f51a8e6f..02c8ada8444be8e8b2a06416c9e317af7ecc81fa 100644 (file)
@@ -12,8 +12,7 @@ public class TestSecure extends Page {
        }
 
        @Override
-       public void doGet(HttpServletRequest req, HttpServletResponse resp)
-                       throws IOException {
+       public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
                resp.getWriter().println("This page is secure.");
        }
 
index 8d292667df203c07f99907dee14c862f4a750207..32da54250c0d4b1096658ac62f82ebc0b9bf0ba0 100644 (file)
@@ -13,41 +13,37 @@ import org.cacert.gigi.database.DatabaseConnection;
 
 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 {
+       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 {
-                               PreparedStatement ps = DatabaseConnection
-                                               .getInstance()
-                                               .prepare(
-                                                               "select email, memid from `email` where `id`=? and `hash`=? and `hash` != '' and `deleted` = 0");
+                               PreparedStatement ps = DatabaseConnection.getInstance().prepare(
+                                       "select email, memid from `email` where `id`=? and `hash`=? and `hash` != '' and `deleted` = 0");
                                ps.setString(1, id);
                                ps.setString(2, hash);
                                ResultSet rs = ps.executeQuery();
                                rs.last();
                                if (rs.getRow() == 1) {
-                                       PreparedStatement ps1 = DatabaseConnection
-                                                       .getInstance()
-                                                       .prepare(
-                                                                       "update `email` set `hash`='', `modified`=NOW() where `id`=?");
+                                       PreparedStatement ps1 = DatabaseConnection.getInstance().prepare(
+                                               "update `email` set `hash`='', `modified`=NOW() where `id`=?");
                                        ps1.setString(1, id);
                                        ps1.execute();
-                                       PreparedStatement ps2 = DatabaseConnection
-                                                       .getInstance()
-                                                       .prepare(
-                                                                       "update `users` set `verified`='1' where `id`=? and `email`=? and `verified`='0'");
+                                       PreparedStatement ps2 = DatabaseConnection.getInstance().prepare(
+                                               "update `users` set `verified`='1' where `id`=? and `email`=? and `verified`='0'");
                                        ps2.setString(1, rs.getString(2));
                                        ps2.setString(2, rs.getString(1));
                                        ps2.execute();
@@ -60,9 +56,9 @@ public class Verify extends Page {
                        }
                }
        }
+
        @Override
-       public void doPost(HttpServletRequest req, HttpServletResponse resp)
-                       throws IOException {
+       public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
                String hash = req.getParameter("hash");
                String type = req.getParameter("type");
                if ("email".equals(type)) {
index 95975eadcb18bb4c7a30a3d17782770f82a6af0f..f69dbd11d458c7e771e4cde800d1eb277a98ee3b 100644 (file)
@@ -13,14 +13,12 @@ import org.cacert.gigi.output.Template;
 public class ChangeForm extends Form {
        private static Template t;
        static {
-               t = new Template(new InputStreamReader(
-                               ChangePasswordPage.class
-                                               .getResourceAsStream("ChangePasswordForm.templ")));
+               t = new Template(
+                       new InputStreamReader(ChangePasswordPage.class.getResourceAsStream("ChangePasswordForm.templ")));
        }
 
        @Override
-       public void outputContent(PrintWriter out, Language l,
-                       Map<String, Object> vars) {
+       public void outputContent(PrintWriter out, Language l, Map<String, Object> vars) {
                t.output(out, l, vars);
        }
 
index fd4c9b2d6382338f952c73b1f443e13c9d213d7f..703bbdc33bb4d47d3be65a1405357be7f91838ea 100644 (file)
@@ -16,10 +16,8 @@ public class ChangePasswordPage extends Page {
        }
 
        @Override
-       public void doGet(HttpServletRequest req, HttpServletResponse resp)
-                       throws IOException {
-               new ChangeForm().output(resp.getWriter(), getLanguage(req),
-                               new HashMap<String, Object>());
+       public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+               new ChangeForm().output(resp.getWriter(), getLanguage(req), new HashMap<String, Object>());
        }
 
 }
index fe93959da6493118dd312c466e7441065ac43ec6..f01b8f0c79dad505fa6b88b8160cba6737ebbfe4 100644 (file)
@@ -20,19 +20,16 @@ public class MailCertificateAdd extends Page {
        }
 
        @Override
-       public void doGet(HttpServletRequest req, HttpServletResponse resp)
-                       throws IOException {
+       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>");
+               vars.put("CCA", "<a href='/policy/CAcertCommunityAgreement.html'>CCA</a>");
                getDefaultTemplate().output(resp.getWriter(), getLanguage(req), vars);
        }
+
        @Override
-       public void doPost(HttpServletRequest req, HttpServletResponse resp)
-                       throws IOException {
+       public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
                PrintWriter out = resp.getWriter();
-               if (req.getParameter("optionalCSR") == null
-                               || req.getParameter("optionalCSR").equals("")) {
+               if (req.getParameter("optionalCSR") == null || req.getParameter("optionalCSR").equals("")) {
                        out.println("csr missing");
                        ClientCSRGenerate.output(req, resp);
                }
@@ -41,8 +38,7 @@ public class MailCertificateAdd extends Page {
                        // Error.
                        return;
                }
-               Certificate c = new Certificate("/commonName=CAcert WoT User",
-                               "sha256", csr);
+               Certificate c = new Certificate("/commonName=CAcert WoT User", "sha256", csr);
                c.issue();
                try {
                        c.waitFor(60000);
index 6eae585a2c787cee2ab2691712e58346713feffc..72a14a312b94bf5e41773c17f61ef353c6116434 100644 (file)
@@ -27,8 +27,7 @@ public class MailCertificates extends Page {
        }
 
        @Override
-       public void doGet(HttpServletRequest req, HttpServletResponse resp)
-                       throws IOException {
+       public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
                PrintWriter out = resp.getWriter();
                String pi = req.getPathInfo().substring(PATH.length());
                if (pi.length() != 0) {
@@ -51,10 +50,8 @@ public class MailCertificates extends Page {
                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`=?");
+                       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);
index 54eda005753ad85758dc7154731d6f234fd28766..3e8da14a657db2c7d0e88f63065f6ee661e30280 100644 (file)
@@ -28,14 +28,13 @@ public class MailOverview extends Page {
        }
 
        @Override
-       public void doGet(HttpServletRequest req, HttpServletResponse resp)
-                       throws IOException {
+       public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
                final User us = LoginPage.getUser(req);
                Language lang = Page.getLanguage(req);
                int id = us.getId();
                try {
                        PreparedStatement ps = DatabaseConnection.getInstance().prepare(
-                                       "SELECT * from `email` WHERE `memid`=? AND `deleted`=0");
+                               "SELECT * from `email` WHERE `memid`=? AND `deleted`=0");
                        ps.setInt(1, id);
                        ResultSet rs = ps.executeQuery();
                        HashMap<String, Object> vars = new HashMap<>();
index 6bce47b8cac5e1e7a7271dc3896f13c686359fc0..753bdb2bb52e4c89b2b4e19811a33e8c975c4bef 100644 (file)
@@ -23,21 +23,15 @@ public class MyDetails extends Page {
        public static final String PATH = "/account/details";
 
        @Override
-       public void doGet(HttpServletRequest req, HttpServletResponse resp)
-                       throws IOException {
+       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("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()));
+               map.put("suffix", u.getSuffix() == null ? "" : HTMLEncoder.encodeHTML(u.getSuffix()));
                DateSelector ds = new DateSelector("day", "month", "year");
                map.put("DoB", ds);
                map.put("details", "");
index 72057a6678859ff44be8e552d0bf5a8717c96d9e..0033f2397c74f5894c1f90539ca93662095cc26c 100644 (file)
@@ -14,10 +14,8 @@ public class PageNotFound extends Page {
        }
 
        @Override
-       public void doGet(HttpServletRequest req, HttpServletResponse resp)
-                       throws IOException {
-               getDefaultTemplate().output(resp.getWriter(), Page.getLanguage(req),
-                               null);
+       public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+               getDefaultTemplate().output(resp.getWriter(), Page.getLanguage(req), null);
        }
 
 }
index b38194994bb69044907a3f3910feaae618482311..38c699741bb8ffb9090b8ad28592057b37c0a08b 100644 (file)
@@ -20,14 +20,14 @@ public class RegisterPage extends Page {
        }
 
        @Override
-       public void doGet(HttpServletRequest req, HttpServletResponse resp)
-                       throws IOException {
+       public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
                PrintWriter out = resp.getWriter();
                HashMap<String, Object> vars = new HashMap<String, Object>();
                getDefaultTemplate().output(out, getLanguage(req), vars);
                Signup s = getForm(req);
                s.output(out, getLanguage(req), vars);
        }
+
        public Signup getForm(HttpServletRequest req) {
                HttpSession hs = req.getSession();
                Signup s = (Signup) hs.getAttribute(SIGNUP_PROCESS);
@@ -38,26 +38,24 @@ public class RegisterPage extends Page {
                return s;
 
        }
+
        @Override
-       public void doPost(HttpServletRequest req, HttpServletResponse resp)
-                       throws IOException {
+       public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
                Signup s = getForm(req);
                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!"));
+                       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;
                }
 
                super.doPost(req, resp);
        }
+
        @Override
        public boolean needsLogin() {
                return false;
index bd4037a1d5c8e9fa18ecfc2418ef789de2b97291..560b2727bbadb7750c708911eda053fb6f655a59 100644 (file)
@@ -31,10 +31,10 @@ public class Signup extends Form {
        User buildup = new User();
        Template t;
        boolean general = true, country = true, regional = true, radius = true;
+
        public Signup() {
                try {
-                       t = new Template(new InputStreamReader(
-                                       Signup.class.getResourceAsStream("Signup.templ"), "UTF-8"));
+                       t = new Template(new InputStreamReader(Signup.class.getResourceAsStream("Signup.templ"), "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                }
@@ -45,11 +45,11 @@ public class Signup extends Form {
                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) {
+       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()));
@@ -61,14 +61,11 @@ public class Signup extends Form {
                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("helpOnNames", String.format(l.getTranslation("Help on Names %sin the wiki%s"),
+                       "<a href=\"//wiki.cacert.org/FAQ/HowToEnterNamesInJoinForm\" target=\"_blank\">", "</a>"));
                t.output(out, l, vars);
        }
+
        private void update(HttpServletRequest r) {
                if (r.getParameter("fname") != null) {
                        buildup.setFname(r.getParameter("fname"));
@@ -106,8 +103,7 @@ public class Signup extends Form {
                        failed = true;
                }
                if (!"1".equals(req.getParameter("cca_agree"))) {
-                       outputError(out, req,
-                                       "You have to agree to the CAcert Community agreement.");
+                       outputError(out, req, "You have to agree to the CAcert Community agreement.");
                        failed = true;
                }
                if (buildup.getEmail().equals("")) {
@@ -125,12 +121,8 @@ public class Signup extends Form {
                }
                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.");
+                       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) {
@@ -139,24 +131,21 @@ public class Signup extends Form {
                }
                try {
                        PreparedStatement q1 = DatabaseConnection.getInstance().prepare(
-                                       "select * from `email` where `email`=? and `deleted`=0");
+                               "select * from `email` where `email`=? and `deleted`=0");
                        PreparedStatement q2 = DatabaseConnection.getInstance().prepare(
-                                       "select * from `users` where `email`=? and `deleted`=0");
+                               "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.");
+                               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`))");
+                       PreparedStatement q3 = DatabaseConnection.getInstance().prepare(
+                               "select `domain` from `baddomains` where `domain`=RIGHT(?, LENGTH(`domain`))");
                        q3.setString(1, buildup.getEmail());
 
                        ResultSet r3 = q3.executeQuery();
@@ -164,9 +153,7 @@ public class Signup extends Form {
                                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));
+                                       Page.translate(req, "We don't allow signups from people using email addresses from %s"), domain));
                                out.println("</div>");
                                failed = true;
                        }
@@ -177,29 +164,20 @@ public class Signup extends Form {
                }
                String mailResult = EmailProvider.FAIL;
                try {
-                       mailResult = EmailProvider.getInstance().checkEmailServer(0,
-                                       buildup.getEmail());
+                       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.");
+                               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");
+                               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");
+                               outputError(out, req, "Failed to make a connection to the mail server");
                        } else {
                                out.print("<div>");
                                out.print(mailResult);
@@ -220,8 +198,7 @@ public class Signup extends Form {
                return true;
        }
 
-       private void run(HttpServletRequest req, String password)
-                       throws SQLException {
+       private void run(HttpServletRequest req, String password) throws SQLException {
                try {
                        DatabaseConnection.getInstance().beginTransaction();
                        String hash = RandomToken.generateToken(16);
@@ -230,32 +207,27 @@ public class Signup extends Form {
                        buildup.insert(password);
                        int memid = buildup.getId();
                        PreparedStatement ps = DatabaseConnection.getInstance().prepare(
-                                       "insert into `email` set `email`=?,"
-                                                       + " `hash`=?, `created`=NOW(),`memid`=?");
+                               "insert into `email` set `email`=?," + " `hash`=?, `created`=NOW(),`memid`=?");
                        ps.setString(1, buildup.getEmail());
                        ps.setString(2, hash);
                        ps.setInt(3, memid);
                        ps.execute();
                        int emailid = DatabaseConnection.lastInsertId(ps);
-                       ps = DatabaseConnection
-                                       .getInstance()
-                                       .prepare(
-                                                       "insert into `alerts` set `memid`=?,"
-                                                                       + " `general`=?, `country`=?, `regional`=?, `radius`=?");
+                       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);
+                       Notary.writeUserAgreement(memid, "CCA", "account creation", "", true, 0);
 
                        StringBuffer body = new StringBuffer();
                        body.append(Page
-                                       .translate(
-                                                       req,
-                                                       "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!"));
+                               .translate(
+                                       req,
+                                       "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=");
@@ -268,9 +240,8 @@ public class Signup extends Form {
                        body.append(Page.translate(req, "CAcert.org Support!"));
                        try {
                                EmailProvider.getInstance().sendmail(buildup.getEmail(),
-                                               "[CAcert.org] " + Page.translate(req, "Mail Probe"),
-                                               body.toString(), "support@cacert.org", null, null,
-                                               null, null, false);
+                                       "[CAcert.org] " + Page.translate(req, "Mail Probe"), body.toString(), "support@cacert.org", null,
+                                       null, null, null, false);
                        } catch (IOException e) {
                                e.printStackTrace();
                        }
index 9bb87af512d49165c6c6105c393a403282e24971..3743e3214b50f4c41a70b84609584d7234ca7f42 100644 (file)
@@ -23,18 +23,17 @@ public class AssuranceForm extends Form {
        User assuree;
        static final Template templ;
        static {
-               templ = new Template(new InputStreamReader(
-                               AssuranceForm.class.getResourceAsStream("AssuranceForm.templ")));
+               templ = new Template(new InputStreamReader(AssuranceForm.class.getResourceAsStream("AssuranceForm.templ")));
        }
 
        public AssuranceForm(int assuree) {
                this.assuree = new User(assuree);
        }
+
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
 
        @Override
-       public void outputContent(PrintWriter out, Language l,
-                       Map<String, Object> vars) {
+       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());
@@ -54,43 +53,34 @@ public class AssuranceForm extends Form {
                out.println("<div class='formError'>");
                boolean failed = false;
 
-               if (!"1".equals(req.getParameter("certify"))
-                               || !"1".equals(req.getParameter("rules"))
-                               || !"1".equals(req.getParameter("CCAAgreed"))
-                               || !"1".equals(req.getParameter("assertion"))) {
+               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");
+                               + " 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.");
+               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.");
+                                       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.");
+                               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.");
+               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.");
+                       outputError(out, req, "You must enter a location with at least 3 characters eg town and country.");
                        failed = true;
                }
                // TODO checkPoints
@@ -104,9 +94,8 @@ public class AssuranceForm extends Form {
                        return false;
                }
                try {
-                       AssuranceResult success = Notary.assure(LoginPage.getUser(req),
-                                       assuree, Integer.parseInt(req.getParameter("points")),
-                                       req.getParameter("location"), req.getParameter("date"));
+                       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());
                        }
index f553793e5d3d4ebd47d1e0e1cc9ff5d557f0a942..70b5985ef8f5a747e1bb36bfc5d7f6a33e503e96 100644 (file)
@@ -30,22 +30,19 @@ public class AssurePage extends Page {
 
        public AssurePage() {
                super("Assure someone");
-               t = new Template(new InputStreamReader(
-                               AssuranceForm.class.getResourceAsStream("AssureeSearch.templ")));
+               t = new Template(new InputStreamReader(AssuranceForm.class.getResourceAsStream("AssureeSearch.templ")));
 
        }
 
        @Override
-       public void doGet(HttpServletRequest req, HttpServletResponse resp)
-                       throws IOException {
+       public void doGet(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));
-                       AssuranceResult check = Notary.checkAssuranceIsPossible(myself,
-                                       new User(mid));
+                       AssuranceResult check = Notary.checkAssuranceIsPossible(myself, new User(mid));
                        if (check != AssuranceResult.ASSURANCE_SUCCEDED) {
                                out.println(translate(req, check.getMessage()));
                                return;
@@ -57,16 +54,17 @@ public class AssurePage extends Page {
                                hs.setAttribute(SESSION, form);
                        }
 
-                       form.output(out, getLanguage(req), new HashMap<String, Object>());;
+                       form.output(out, getLanguage(req), new HashMap<String, Object>());
+                       ;
                } else {
                        HashMap<String, Object> vars = new HashMap<String, Object>();
                        vars.put("DoB", ds);
                        t.output(out, getLanguage(req), vars);
                }
        }
+
        @Override
-       public void doPost(HttpServletRequest req, HttpServletResponse resp)
-                       throws IOException {
+       public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
                PrintWriter out = resp.getWriter();
                String pi = req.getPathInfo().substring(PATH.length());
                if (pi.length() > 1) {
@@ -77,8 +75,7 @@ public class AssurePage extends Page {
                                return;
                        }
 
-                       AssuranceForm form = (AssuranceForm) req.getSession().getAttribute(
-                                       SESSION);
+                       AssuranceForm form = (AssuranceForm) req.getSession().getAttribute(SESSION);
                        if (form == null) {
                                out.println("No form found. This is an Error. Fill in the form again.");
                                return;
@@ -96,13 +93,10 @@ public class AssurePage extends Page {
                System.out.println("searching for");
                ResultSet rs = null;
                try {
-                       PreparedStatement ps = DatabaseConnection
-                                       .getInstance()
-                                       .prepare(
-                                                       "SELECT id, verified FROM users WHERE email=? AND dob=? AND deleted=0");
+                       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");
+                       String day = req.getParameter("year") + "-" + req.getParameter("month") + "-" + req.getParameter("day");
                        ps.setString(2, day);
                        rs = ps.executeQuery();
                        int id = 0;
@@ -113,19 +107,15 @@ public class AssurePage extends Page {
                                        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!"));
+                                               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.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>");
                        }
 
index 3231c0f05ac8791a764328d3a5791ad61d61e6fe..3b4593894d8e8d3e11f6b7d0d78cc1a73ebd9533 100644 (file)
@@ -11,10 +11,8 @@ 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()));
+                       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) {
@@ -24,13 +22,11 @@ public class DNSPinger extends DomainPinger {
                        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};
+                       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()));
+                               br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                                String token = null;
                                boolean found = false;
                                while ((line = br.readLine()) != null) {
index de5ec0da4f8fa5df3ee796cd8f2237e3147225bc..b4e88ea4c650e25f7e7cdf24384f3a69891b0b2a 100644 (file)
@@ -11,8 +11,7 @@ public class HTTPFetch extends DomainPinger {
        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"));
+                       BufferedReader br = new BufferedReader(new InputStreamReader(u.openStream(), "UTF-8"));
                        String line = br.readLine();
                        if (line == null) {
                                // empty
index fd113ec2683afded4aa08b817c49434c937dc063..78adc12ac9e6a76bc4d08ec34675c77445ff25b9 100644 (file)
@@ -27,22 +27,21 @@ public class SSLPinger extends DomainPinger {
                try {
                        SocketChannel sch = SocketChannel.open();
                        String[] parts = configuration.split(":", 2);
-                       sch.connect(new InetSocketAddress(domain, Integer
-                                       .parseInt(parts[0])));
+                       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;
+                               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;
 
                                }
                        }
@@ -52,6 +51,7 @@ public class SSLPinger extends DomainPinger {
                }
 
        }
+
        private void startIMAP(SocketChannel sch) throws IOException {
                Socket s = sch.socket();
                InputStream is = s.getInputStream();
@@ -61,22 +61,21 @@ public class SSLPinger extends DomainPinger {
                os.flush();
                scanFor(is, "\n");
        }
-       private void startXMPP(SocketChannel sch, boolean server, String domain)
-                       throws IOException {
+
+       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.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.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()) {
@@ -87,6 +86,7 @@ public class SSLPinger extends DomainPinger {
                        }
                }
        }
+
        private void startSMTP(SocketChannel sch) throws IOException {
                Socket s = sch.socket();
                InputStream is = s.getInputStream();
@@ -101,6 +101,7 @@ public class SSLPinger extends DomainPinger {
                s.getOutputStream().flush();
                readSMTP(is);
        }
+
        private void readSMTP(InputStream is) throws IOException {
                int counter = 0;
                boolean finish = true;
@@ -125,65 +126,60 @@ public class SSLPinger extends DomainPinger {
                        }
                }
        }
+
        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());
+                       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)));
+                       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) {
+                               && 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();
+                               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();
-                                               break;
-                                       case NEED_TASK :
-                                               se.getDelegatedTask().run();
-                                               break;
-                                       case NOT_HANDSHAKING :
-                                       case FINISHED :
+                                       }
+                                       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();
+                       X509Certificate[] peerCertificateChain = se.getSession().getPeerCertificateChain();
                        for (X509Certificate x509Certificate : peerCertificateChain) {
                                System.out.println(x509Certificate.getSubjectDN().getName());
                        }
index 5860c119903a17407c7dea83010af02954c3d909..4c20710a7db980246d334e9fdeb13f54f0220130 100644 (file)
@@ -25,8 +25,7 @@ public class CipherInfo implements Comparable<CipherInfo> {
 
                public CipherInfoGenerator() throws ReflectiveOperationException {
                        SSLContextImpl sc = new SSLContextImpl.TLS12Context();
-                       Method m = SSLContextImpl.class
-                                       .getDeclaredMethod("getSupportedCipherSuiteList");
+                       Method m = SSLContextImpl.class.getDeclaredMethod("getSupportedCipherSuiteList");
                        m.setAccessible(true);
                        Object o = m.invoke(sc);
                        Class<?> cipherSuiteList = o.getClass();
@@ -58,8 +57,8 @@ public class CipherInfo implements Comparable<CipherInfo> {
                        macSize = mac.getDeclaredField("size");
                        macSize.setAccessible(true);
                }
-               public CipherInfo generateInfo(String suiteName)
-                               throws IllegalArgumentException, IllegalAccessException {
+
+               public CipherInfo generateInfo(String suiteName) throws IllegalArgumentException, IllegalAccessException {
                        Object suite = names.get(suiteName);
                        String keyExchange = exchange.get(suite).toString();
                        Object bulkCipher = cipher.get(suite);
@@ -79,12 +78,12 @@ public class CipherInfo implements Comparable<CipherInfo> {
                                padding = transformationParts[2];
                        }
 
-                       return new CipherInfo(suiteName, keyExchange,
-                                       transformationParts[0], keysize * 8, chaining, padding,
-                                       macNam, macSiz * 8);
+                       return new CipherInfo(suiteName, keyExchange, transformationParts[0], keysize * 8, chaining, padding,
+                               macNam, macSiz * 8);
 
                }
        }
+
        String keyExchange;
        String cipher;
        int keySize;
@@ -94,9 +93,8 @@ public class CipherInfo implements Comparable<CipherInfo> {
        int macSize;
        String suiteName;
 
-       private CipherInfo(String suiteName, String keyExchange, String cipher,
-                       int keySize, String cipherChaining, String cipherPadding,
-                       String macName, int macSize) {
+       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;
@@ -129,9 +127,11 @@ public class CipherInfo implements Comparable<CipherInfo> {
                }
                return null;
        }
+
        public String getSuiteName() {
                return suiteName;
        }
+
        /**
         * 5: ECDHE, AES||CAMELLIA, keysize >=256 <br>
         * 4: DHE, AES||CAMELLIA, keysize >= 256<br>
@@ -143,8 +143,7 @@ public class CipherInfo implements Comparable<CipherInfo> {
         * @return the strength
         */
        public int getStrength() {
-               if (cipher.equals("NULL") || cipher.equals("RC4")
-                               || cipher.contains("DES")) {
+               if (cipher.equals("NULL") || cipher.equals("RC4") || cipher.contains("DES")) {
                        return 0;
                }
                boolean ecdhe = keyExchange.startsWith("ECDHE");
@@ -168,16 +167,16 @@ public class CipherInfo implements Comparable<CipherInfo> {
                }
                return 0;
        }
-       private static final String[] CIPHER_RANKING = new String[]{"CAMELLIA",
-                       "AES", "RC4", "3DES", "DES", "DES40"};
+
+       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 + "]";
+               return "CipherInfo [keyExchange=" + keyExchange + ", cipher=" + cipher + ", keySize=" + keySize
+                       + ", cipherChaining=" + cipherChaining + ", cipherPadding=" + cipherPadding + ", macName=" + macName
+                       + ", macSize=" + macSize + "]";
        }
+
        /**
         * ECDHE<br>
         * GCM<br>
@@ -255,15 +254,17 @@ public class CipherInfo implements Comparable<CipherInfo> {
 
                return suiteName.compareTo(o.suiteName);
        }
+
        static String[] cipherRanking = null;
+
        public static String[] getCompleteRanking() {
                if (cipherRanking == null) {
-                       String[] ciphers = filterCiphers((Iterable<String>) cig.names
-                                       .keySet());
+                       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) {
@@ -282,6 +283,7 @@ public class CipherInfo implements Comparable<CipherInfo> {
                }
                return ciphers;
        }
+
        public static String[] filter(String[] supportedCipherSuites) {
                return filterCiphers(Arrays.asList(supportedCipherSuites));
        }
index 2149f808b33dfd2bbd51fa6ac972724415d0033c..6bac57c011591987517879222460adf53dc46c28 100644 (file)
@@ -11,6 +11,7 @@ public class KeyStorage {
                parent.mkdirs();
                return new File(parent, id + ".crt");
        }
+
        public static File locateCsr(int id) {
                File parent = new File(csr, (id / 1000) + "");
                parent.mkdirs();
index 515b25cd30a23601e77a04ea5e6499e47d1bf378..7cd38e37080d9557978aadee889c086ecfc329d0 100644 (file)
@@ -8,14 +8,11 @@ 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`=?");
+       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);
@@ -25,16 +22,13 @@ public class Notary {
                q.execute();
        }
 
-       public static AssuranceResult checkAssuranceIsPossible(User assurer,
-                       User target) {
+       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");
+                       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();
@@ -53,23 +47,22 @@ public class Notary {
        }
 
        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.");
+               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;
+
                private AssuranceResult(String message) {
                        this.message = message;
                }
+
                public String getMessage() {
                        return message;
                }
        }
 
-       public synchronized static AssuranceResult assure(User assurer,
-                       User target, int awarded, String location, String date)
-                       throws SQLException {
+       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;
@@ -82,10 +75,8 @@ public class Notary {
                        return AssuranceResult.POINTS_OUT_OF_RANGE;
                }
 
-               PreparedStatement ps = DatabaseConnection
-                               .getInstance()
-                               .prepare(
-                                               "INSERT INTO `notary` SET `from`=?, `to`=?, `points`=?, `location`=?, `date`=?");
+               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);
index 07898f263b681715f141d5405ce236bf4d07efd5..cad2aba58106f21a872a41d32f80f5094174f4e6 100644 (file)
@@ -10,8 +10,10 @@ public class PasswordStrengthChecker {
        static Pattern upper = Pattern.compile("[A-Z]");
        static Pattern whitespace = Pattern.compile("\\s");
        static Pattern special = Pattern.compile("(?!\\s)\\W");
+
        private PasswordStrengthChecker() {
        }
+
        private static int checkpwlight(String pw) {
                int points = 0;
                if (pw.length() > 15) {
@@ -43,6 +45,7 @@ public class PasswordStrengthChecker {
                }
                return points;
        }
+
        public static int checkpw(String pw, User u) {
                if (pw == null) {
                        return 0;
@@ -66,6 +69,7 @@ public class PasswordStrengthChecker {
                // TODO dictionary check
                return light;
        }
+
        private static boolean contained(String pw, String check) {
                if (check == null || check.equals("")) {
                        return false;
index 7d87b7bd7273c1f62f58b8d506cdcf8c409746d2..b84ee0372e7a08f1c36aca99464fc63dedce7d80 100644 (file)
@@ -4,6 +4,7 @@ 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++) {
index 2f22d4396b4a38abfe26ed99149a4b1849ae8317..eafe93933647b7519860cb4b4fea0917b8e7d1d6 100644 (file)
@@ -8,6 +8,7 @@ public class ServerConstants {
        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")) {
@@ -18,27 +19,35 @@ public class ServerConstants {
                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 729a5988e8053f4f4cf4e3b26828acec9b801a63..f4bfe85fb5e71fa622d83cd46806dc30370c998c 100644 (file)
@@ -12,6 +12,7 @@ import org.junit.Test;
 
 public class LoginTest extends ManagedTest {
        public static final String secureReference = "/account/certs/email";
+
        @Test
        public void testLoginUnverified() throws IOException {
                long uniq = System.currentTimeMillis();
@@ -21,6 +22,7 @@ public class LoginTest extends ManagedTest {
                waitForMail();
                assertFalse(isLoggedin(login(email, pw)));
        }
+
        @Test
        public void testLoginVerified() throws IOException {
                long uniq = System.currentTimeMillis();
@@ -29,6 +31,7 @@ public class LoginTest extends ManagedTest {
                createVerifiedUser("an", "bn", email, pw);
                assertTrue(isLoggedin(login(email, pw)));
        }
+
        public boolean isLoggedin(String cookie) throws IOException {
                URL u = new URL("https://" + getServerName() + secureReference);
                HttpURLConnection huc = (HttpURLConnection) u.openConnection();
index 9756a7f3f4e2a044acd5860d1b58c000bf84fee5..c39b20f5b07505cb9219c1ed22f6317616e96c38 100644 (file)
@@ -25,14 +25,13 @@ public class TestSSL extends ManagedTest {
        static {
                InitTruststore.run();
        }
+
        @Test
-       public void testClientIntitiatedRenegotiation()
-                       throws NoSuchAlgorithmException, IOException {
+       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])));
+               SocketChannel s = SocketChannel.open(new InetSocketAddress(serverParts[0], Integer.parseInt(serverParts[1])));
 
                in = ByteBuffer.allocate(se.getSession().getApplicationBufferSize());
                inC = ByteBuffer.allocate(se.getSession().getPacketBufferSize());
@@ -47,34 +46,33 @@ public class TestSSL extends ManagedTest {
                se.beginHandshake();
                try {
                        work(se, s);
-                       throw new Error(
-                                       "Client re-negotiation succeded (possible DoS vulnerability");
+                       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 {
+
+       private void work(SSLEngine se, SocketChannel s) throws SSLException, IOException {
                while (se.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING
-                               && se.getHandshakeStatus() != HandshakeStatus.FINISHED) {
+                       && 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());
+                       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 {
+
+       private SSLEngineResult unwrap(SSLEngine se, SocketChannel s) throws IOException, SSLException {
                if (inC.remaining() == 0) {
                        inC.clear();
                        s.read(inC);
@@ -95,8 +93,8 @@ public class TestSSL extends ManagedTest {
                }
                return result;
        }
-       private SSLEngineResult wrap(SSLEngine se, SocketChannel s)
-                       throws SSLException, IOException {
+
+       private SSLEngineResult wrap(SSLEngine se, SocketChannel s) throws SSLException, IOException {
                outC.clear();
                SSLEngineResult result = se.wrap(out, outC);
                outC.flip();
index 9df4e22c978de866e2ce3140ee566005ad75a9e1..75675c66f6fd44ecb6b5f7611b099dc7fafc40f6 100644 (file)
@@ -12,19 +12,17 @@ import static org.junit.Assert.*;
 public class TestSecurityHeaders extends ManagedTest {
        @Test
        public void testSTS() throws IOException {
-               HttpURLConnection uc = (HttpURLConnection) new URL("https://"
-                               + getServerName()).openConnection();
+               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();
+               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();
+               HttpURLConnection uc = (HttpURLConnection) new URL("https://" + getServerName()).openConnection();
                assertNotNull(uc.getHeaderField("Access-Control-Allow-Origin"));
 
        }
index 61fc752990e700dd1920da62c13eb9abf6e5dfa9..72d72491cf5c61a25da9be8d989d93f48a5190fc 100644 (file)
@@ -26,8 +26,7 @@ public class TestUser extends ManagedTest {
 
        @Test
        public void testWebStoreAndLoad() throws SQLException {
-               int id = createVerifiedUser("aä", "b", createUniqueName()
-                               + "a@email.org", "xvXV12°§");
+               int id = createVerifiedUser("aä", "b", createUniqueName() + "a@email.org", "xvXV12°§");
 
                User u = new User(id);
                assertEquals("aä", u.getFname());
@@ -37,8 +36,7 @@ public class TestUser extends ManagedTest {
 
        @Test
        public void testAssurerUtilMethods() throws SQLException {
-               int id = createAssuranceUser("aä", "b", createUniqueName()
-                               + "a@email.org", "xvXV12°§");
+               int id = createAssuranceUser("aä", "b", createUniqueName() + "a@email.org", "xvXV12°§");
 
                User u = new User(id);
                assertTrue(u.canAssure());
index af56fdf3479a1311a3218fcb941b59ae0bdea982..87d8a9d4e5f42509f5c92da49328a1720005d10e 100644 (file)
@@ -21,6 +21,7 @@ public class RegisterPageTest extends ManagedTest {
        @Before
        public void setUp() throws Exception {
        }
+
        @Test
        public void testSuccess() throws IOException {
                long uniq = System.currentTimeMillis();
@@ -29,14 +30,17 @@ public class RegisterPageTest extends ManagedTest {
                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");
@@ -56,20 +60,24 @@ public class RegisterPageTest extends ManagedTest {
        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");
@@ -77,6 +85,7 @@ public class RegisterPageTest extends ManagedTest {
                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");
@@ -84,6 +93,7 @@ public class RegisterPageTest extends ManagedTest {
                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");
@@ -92,9 +102,8 @@ public class RegisterPageTest extends ManagedTest {
        @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");
+               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"));
@@ -106,48 +115,41 @@ public class RegisterPageTest extends ManagedTest {
        @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=\"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=\"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=\"country\" value=\"1\" checked=\"checked\">"));
                assertTrue(run2.contains("name=\"regional\" value=\"1\">"));
-               assertTrue(run2
-                               .contains("name=\"radius\" value=\"1\" checked=\"checked\">"));
+               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",
-                               "registerPW'1");
+               registerUser("RegisterTest", "User", "testmail" + uniq + "@cacert.org", "registerPW'1");
                try {
-                       registerUser("RegisterTest", "User", "testmail" + uniq
-                                       + "@cacert.org", "registerPW");
-                       throw new Error(
-                                       "Registering a user with the same email needs to fail.");
+                       registerUser("RegisterTest", "User", "testmail" + uniq + "@cacert.org", "registerPW");
+                       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", "registerPW");
-                       throw new Error(
-                                       "Registering a user with invalid mailbox must fail.");
+                       registerUser("RegisterTest", "User", "testInvalidMailbox" + uniq + "@cacert.org", "registerPW");
+                       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 cedbcde619f2a14d9b242745b3ce9ad318bcfc08..42e2c18a40c2778e370c5047b492b9203a228b89 100644 (file)
@@ -26,6 +26,7 @@ public class TestAssurance extends ManagedTest {
        private int assurer;
        private int assuree;
        private String cookie;
+
        @Before
        public void setup() throws IOException {
                assurerM = createUniqueName() + "@cacert-test.org";
@@ -35,33 +36,30 @@ public class TestAssurance extends ManagedTest {
                cookie = login(assurerM, "xvXV.1");
 
        }
+
        @Test
        public void testAssureSearch() throws IOException {
-               String loc = search("email=" + URLEncoder.encode(assureeM, "UTF-8")
-                               + "&day=1&month=1&year=1910");
+               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");
+               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");
+               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");
+               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");
+               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 {
+
+       private String search(String query) throws MalformedURLException, IOException, UnsupportedEncodingException {
                URL u = new URL("https://" + getServerName() + AssurePage.PATH);
                URLConnection uc = u.openConnection();
                uc.setDoOutput(true);
@@ -72,6 +70,7 @@ public class TestAssurance extends ManagedTest {
                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");
@@ -82,46 +81,46 @@ public class TestAssurance extends ManagedTest {
        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().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().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=?");
+               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().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");
+               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");
@@ -137,6 +136,7 @@ public class TestAssurance extends ManagedTest {
                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");
@@ -148,18 +148,17 @@ public class TestAssurance extends ManagedTest {
                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 {
+
+       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);
+
+       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);
index ab18ee2ed6ba38068bc0900da6bddeb5ad92b180..b7452d2a4422d8acc1fd18d6d8b6fc54fa2e6c64 100644 (file)
@@ -10,11 +10,11 @@ public class IOUtils {
        private IOUtils() {
 
        }
+
        public static String readURL(URLConnection in) {
                try {
                        if (!in.getContentType().equals("text/html; charset=UTF-8")) {
-                               throw new Error("Unrecognized content-type: "
-                                               + in.getContentType());
+                               throw new Error("Unrecognized content-type: " + in.getContentType());
                        }
                        return readURL(new InputStreamReader(in.getInputStream(), "UTF-8"));
                } catch (IOException e) {
@@ -22,6 +22,7 @@ public class IOUtils {
                }
 
        }
+
        public static String readURL(Reader in) {
                CharArrayWriter caw = new CharArrayWriter();
                char[] buffer = new char[1024];
index 39c1d370ea7bc70aad956c9943956679f127e161..7811470d8d9c984582301bf070063ff342fe2021 100644 (file)
@@ -3,10 +3,12 @@ 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");
        }
+
        public static void run() {
 
        }
index 9a545323b9eda28fc85f351ec673e2fe118d7458..2f685dbf9c1a4bb95c5a807db9f67d0de16be730 100644 (file)
@@ -42,6 +42,7 @@ public class ManagedTest {
        public static String getServerName() {
                return url;
        }
+
        static Properties testProps = new Properties();
        static {
                InitTruststore.run();
@@ -56,59 +57,44 @@ public class ManagedTest {
                                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")});
+                       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");
                        if (type.equals("local")) {
                                url = testProps.getProperty("server");
                                String[] parts = testProps.getProperty("mail").split(":", 2);
-                               ter = new TestEmailReciever(new InetSocketAddress(parts[0],
-                                               Integer.parseInt(parts[1])));
+                               ter = new TestEmailReciever(new InetSocketAddress(parts[0], Integer.parseInt(parts[1])));
                                return;
                        }
-                       url = testProps.getProperty("name.www") + ":"
-                                       + testProps.getProperty("serverPort");
+                       url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort");
                        gigi = Runtime.getRuntime().exec(testProps.getProperty("java"));
-                       DataOutputStream toGigi = new DataOutputStream(
-                                       gigi.getOutputStream());
+                       DataOutputStream toGigi = new DataOutputStream(gigi.getOutputStream());
                        System.out.println("... starting server");
                        Properties mainProps = new Properties();
                        mainProps.setProperty("host", "127.0.0.1");
                        mainProps.setProperty("name.secure", "sec");
-                       mainProps
-                                       .setProperty("name.www", testProps.getProperty("name.www"));
+                       mainProps.setProperty("name.www", testProps.getProperty("name.www"));
                        mainProps.setProperty("name.static", "stat");
 
                        mainProps.setProperty("port", testProps.getProperty("serverPort"));
-                       mainProps.setProperty("emailProvider",
-                                       "org.cacert.gigi.email.TestEmailProvider");
+                       mainProps.setProperty("emailProvider", "org.cacert.gigi.email.TestEmailProvider");
                        mainProps.setProperty("emailProvider.port", "8473");
-                       mainProps.setProperty("sql.driver",
-                                       testProps.getProperty("sql.driver"));
+                       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"));
+                       mainProps.setProperty("sql.user", testProps.getProperty("sql.user"));
+                       mainProps.setProperty("sql.password", testProps.getProperty("sql.password"));
 
-                       byte[] cacerts = Files
-                                       .readAllBytes(Paths.get("config/cacerts.jks"));
-                       byte[] keystore = Files.readAllBytes(Paths
-                                       .get("config/keystore.pkcs12"));
+                       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);
+                       DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes(), "changeit".getBytes(), mainProps, cacerts,
+                               keystore);
                        toGigi.flush();
 
-                       final BufferedReader br = new BufferedReader(new InputStreamReader(
-                                       gigi.getErrorStream()));
+                       final BufferedReader br = new BufferedReader(new InputStreamReader(gigi.getErrorStream()));
                        String line;
-                       while ((line = br.readLine()) != null
-                                       && !line.contains("Server:main: Started")) {
+                       while ((line = br.readLine()) != null && !line.contains("Server:main: Started")) {
                        }
                        new Thread() {
                                @Override
@@ -126,8 +112,7 @@ public class ManagedTest {
                        if (line == null) {
                                throw new Error("Server startup failed");
                        }
-                       ter = new TestEmailReciever(
-                                       new InetSocketAddress("localhost", 8473));
+                       ter = new TestEmailReciever(new InetSocketAddress("localhost", 8473));
                } catch (IOException e) {
                        throw new Error(e);
                } catch (ClassNotFoundException e1) {
@@ -137,6 +122,7 @@ public class ManagedTest {
                }
 
        }
+
        @AfterClass
        public static void tearDownServer() {
                String type = testProps.getProperty("type");
@@ -146,6 +132,7 @@ public class ManagedTest {
                }
                gigi.destroy();
        }
+
        @After
        public void removeMails() {
                ter.reset();
@@ -158,35 +145,34 @@ public class ManagedTest {
                        throw new Error(e);
                }
        }
+
        public static TestEmailReciever getMailReciever() {
                return ter;
        }
+
        public String runRegister(String param) throws IOException {
-               HttpURLConnection uc = (HttpURLConnection) new URL("https://"
-                               + getServerName() + registerService).openConnection();
+               HttpURLConnection uc = (HttpURLConnection) new URL("https://" + getServerName() + registerService)
+                       .openConnection();
                uc.setDoOutput(true);
                uc.getOutputStream().write(param.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);
                assertNotEquals(-1, idx);
-               String startError = d.substring(idx + formFail.length(), idx + 100)
-                               .trim();
+               String startError = d.substring(idx + formFail.length(), idx + 100).trim();
                return startError;
        }
 
-       public void registerUser(String firstName, String lastName, String email,
-                       String password) {
+       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 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) {
@@ -195,18 +181,17 @@ public class ManagedTest {
                        throw new Error(e);
                }
        }
-       public int createVerifiedUser(String firstName, String lastName,
-                       String email, String password) {
+
+       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=?");
+                       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()) {
@@ -221,6 +206,7 @@ public class ManagedTest {
                        throw new Error(e);
                }
        }
+
        /**
         * Creates a new user with 100 Assurance points given by an (invalid)
         * assurance.
@@ -235,19 +221,15 @@ public class ManagedTest {
         *            the password
         * @return a new userid.
         */
-       public int createAssuranceUser(String firstName, String lastName,
-                       String email, String password) {
+       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`=?");
+                       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 = DatabaseConnection.getInstance().prepare("INSERT INTO `notary` SET `from`=?, `to`=?, points='100'");
                        ps.setInt(1, uid);
                        ps.setInt(2, uid);
                        ps.execute();
@@ -257,17 +239,19 @@ public class ManagedTest {
                }
                return uid;
        }
+
        static int count = 0;
+
        public String createUniqueName() {
                return "test" + System.currentTimeMillis() + "a" + (count++);
        }
+
        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");
+               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");
index d9ffdf3fd97bbea4548638c97f392827adc2e32a..4aa4cbfecddad0683d936dd44e2a38542b2aba67 100644 (file)
@@ -17,29 +17,35 @@ public class TestEmailReciever implements Runnable {
                String message;
                String from;
                String replyto;
-               public 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());
@@ -48,6 +54,7 @@ public class TestEmailReciever implements Runnable {
                }
 
        }
+
        private Socket s;
        private DataInputStream dis;
        private DataOutputStream dos;
@@ -61,11 +68,13 @@ public class TestEmailReciever implements Runnable {
                dos = new DataOutputStream(s.getOutputStream());
                new Thread(this).start();
        }
+
        LinkedBlockingQueue<TestMail> mails = new LinkedBlockingQueue<TestEmailReciever.TestMail>();
 
        public TestMail recieve() throws InterruptedException {
                return mails.poll(5, TimeUnit.SECONDS);
        }
+
        @Override
        public void run() {
                try {
@@ -98,7 +107,9 @@ public class TestEmailReciever implements Runnable {
                }
 
        }
+
        Pattern approveRegex = Pattern.compile(".*");
+
        public void setApproveRegex(Pattern approveRegex) {
                this.approveRegex = approveRegex;
        }
@@ -106,11 +117,14 @@ public class TestEmailReciever implements Runnable {
        public void clearMails() {
                mails.clear();
        }
+
        public void reset() {
                clearMails();
                approveRegex = Pattern.compile(".*");
        }
+
        boolean closed = false;
+
        public void destroy() {
                try {
                        closed = true;
index 7875df935896a6d50c8990585df4d33dfa4e018c..f7c21ab3adc46ffd6664c655fe99c1f89ebcbc43 100644 (file)
@@ -10,15 +10,17 @@ public class TestHTMLEncoder {
        public void testEncodeSimpleString() {
                assertEquals("1234_ä", HTMLEncoder.encodeHTML("1234_ä"));
        }
+
        @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;\">"));
+               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;"));
index 274b323967acd2c6b2a2d1ce225ea5e5d599ba4b..faccd4a428fee211a0f4bbeb3ebb159bbb96ce07 100644 (file)
@@ -16,28 +16,24 @@ public class TestNotary extends ManagedTest {
        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", "xvXV12°§");
+                       int id = createVerifiedUser("fn" + i, "ln" + i, createUniqueName() + "@email.org", "xvXV12°§");
                        users[i] = new User(id);
                }
-               User assurer = new User(createAssuranceUser("fn", "ln",
-                               createUniqueName() + "@email.org", "xvXV12°§"));
-               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};
+               User assurer = new User(createAssuranceUser("fn", "ln", createUniqueName() + "@email.org", "xvXV12°§"));
+               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 };
 
                System.out.println(result.length);
-               assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED, Notary.assure(
-                               assurer, users[0], -1, "test-notary", "2014-01-01"));
+               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"));
+                       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());
@@ -50,26 +46,23 @@ public class TestNotary extends ManagedTest {
        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", "xvXV12°§");
+                       int id = createVerifiedUser("fn" + i, "ln" + i, createUniqueName() + "@email.org", "xvXV12°§");
                        users[i] = new User(id);
                }
-               int id = createAssuranceUser("fn", "ln", createUniqueName()
-                               + "@email.org", "xvXV12°§");
-               PreparedStatement ps = DatabaseConnection.getInstance().prepare(
-                               "UPDATE users SET dob=NOW() WHERE id=?");
+               int id = createAssuranceUser("fn", "ln", createUniqueName() + "@email.org", "xvXV12°§");
+               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"));
+                       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 0e79ae6bb054179cbfea2e22b1e6a590cb6b59ca..21f5f8bde2a97e72c0826401d8b000de88cad14f 100644 (file)
@@ -9,13 +9,12 @@ public class TestPasswordHash {
                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ä")));
+               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ä")));
+               assertFalse(PasswordHash.verifyHash("ae", PasswordHash.hash("auhlcb4 9x,IUQẞ&lvrvä")));
        }
 }
index c271735b6554defa1b862ceeae36a3c9bf2e1eea..f57e71af7dff3c1b68d30dc506013dcc80ff0c48 100644 (file)
@@ -6,6 +6,7 @@ import static org.junit.Assert.*;
 
 public class TestPasswordStrengthChecker {
        User u;
+
        public TestPasswordStrengthChecker() {
                u = new User();
                u.setFname("fname");
@@ -14,17 +15,16 @@ public class TestPasswordStrengthChecker {
                u.setEmail("email");
                u.setSuffix("suffix");
        }
+
        @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));
+               assertEquals(3, PasswordStrengthChecker.checkpw("012345678901234567890", u));
+               assertEquals(4, PasswordStrengthChecker.checkpw("01234567890123456789012345", u));
+               assertEquals(5, PasswordStrengthChecker.checkpw("0123456789012345678901234567890", u));
        }
+
        @Test
        public void testPasswordNonASCII() {
                assertEquals(2, PasswordStrengthChecker.checkpw("0ä", u));
@@ -32,6 +32,7 @@ public class TestPasswordStrengthChecker {
                assertEquals(3, PasswordStrengthChecker.checkpw("0azä", u));
                assertEquals(3, PasswordStrengthChecker.checkpw("0az.ä", u));
        }
+
        @Test
        public void testPasswordCharTypes() {
                assertEquals(1, PasswordStrengthChecker.checkpw("0", u));
@@ -56,6 +57,7 @@ public class TestPasswordStrengthChecker {
                assertEquals(2, PasswordStrengthChecker.checkpw(" Z", u));
 
        }
+
        @Test
        public void testPasswordContains() {
                assertEquals(-1, PasswordStrengthChecker.checkpw("fnamea", u));
index 547922e6130cb78f02c2d8b7e1fad29e361791d1..471083953b8d2b2f1362f8d440eca5016c7789de 100644 (file)
@@ -14,27 +14,24 @@ 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 {
+
+       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")};
+                       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");
+                       System.err.println("Usage: com.mysql.jdbc.Driver jdbc:mysql://localhost/cacert user password");
                        return;
                }
                run(args);
        }
-       public static void run(String[] args) throws ClassNotFoundException,
-                       SQLException, IOException {
+
+       public static void run(String[] args) throws ClassNotFoundException, SQLException, IOException {
                Class.forName(args[0]);
-               Connection conn = DriverManager
-                               .getConnection(args[1], args[2], args[3]);
+               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");
@@ -44,8 +41,8 @@ public class DatabaseManager {
                stmt.executeBatch();
                stmt.close();
        }
-       private static void addFile(Statement stmt, File f) throws IOException,
-                       SQLException {
+
+       private static void addFile(Statement stmt, File f) throws IOException, SQLException {
                String sql = readFile(f);
                String[] stmts = sql.split(";");
                for (String string : stmts) {
index c5378438623f217e29b7c5d365fb1736ed601121..731ba7c8ff074ed3d642b8d4d327d74cbe3f8a34 100644 (file)
@@ -23,13 +23,11 @@ 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 {
+       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();
@@ -55,8 +53,7 @@ public class FetchLocales {
                                        contents.delete(0, contents.length());
                                        // System.out.println("msgstr");
                                        s = readString(s, sc, contents);
-                                       String msg = contents.toString().replace("\\\"", "\"")
-                                                       .replace("\\n", "\n");
+                                       String msg = contents.toString().replace("\\\"", "\"").replace("\\n", "\n");
                                        insertTranslation(doc, id, msg);
                                } else if (s.startsWith("#")) {
                                        // System.out.println(s);
@@ -71,16 +68,15 @@ public class FetchLocales {
                        Transformer transformer = tFactory.newTransformer();
 
                        DOMSource source = new DOMSource(doc);
-                       FileOutputStream fos = new FileOutputStream(new File(locale, lang
-                                       + ".xml"));
+                       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.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
                        transformer.transform(source, result);
                        fos.close();
                }
        }
+
        private static String readLine(Scanner sc) {
                String line = sc.findWithinHorizon("[^\n]*\n", 0);
                if (line == null) {
@@ -88,6 +84,7 @@ public class FetchLocales {
                }
                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);
@@ -100,8 +97,8 @@ public class FetchLocales {
                tr.appendChild(e);
                doc.getDocumentElement().appendChild(tr);
        }
-       private static String readString(String head, Scanner sc,
-                       StringBuffer contents) throws IOException {
+
+       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;
index 36da084a39da76e18df82d68e90935a49d4d9929..d67cb8e874f563fff235f73d724cb045e2ff2742 100644 (file)
@@ -29,19 +29,19 @@ public class SimpleSigner {
                DatabaseConnection.init(p);
 
                readyMail = DatabaseConnection.getInstance().prepare(
-                               "SELECT id, csr_name, subject FROM emailcerts" + " WHERE csr_name is not null"//
-                                               + " AND created=0"//
-                                               + " AND crt_name=''"//
-                                               + " AND warning<3");
+                       "SELECT id, csr_name, subject FROM emailcerts" + " WHERE csr_name is not null"//
+                               + " AND created=0"//
+                               + " AND crt_name=''"//
+                               + " AND warning<3");
 
                updateMail = DatabaseConnection.getInstance().prepare(
-                               "UPDATE emailcerts SET crt_name=?," + " created=NOW(), serial=? WHERE id=?");
+                       "UPDATE emailcerts SET crt_name=?," + " created=NOW(), serial=? WHERE id=?");
                warnMail = DatabaseConnection.getInstance().prepare("UPDATE emailcerts SET warning=warning+1 WHERE id=?");
 
                revoke = DatabaseConnection.getInstance().prepare(
-                               "SELECT id, csr_name FROM emailcerts" + " WHERE csr_name is not null"//
-                                               + " AND created != 0"//
-                                               + " AND revoked = '1970-01-01'");
+                       "SELECT id, csr_name FROM emailcerts" + " WHERE csr_name is not null"//
+                               + " AND created != 0"//
+                               + " AND revoked = '1970-01-01'");
                revokeCompleted = DatabaseConnection.getInstance().prepare("UPDATE emailcerts SET revoked=NOW() WHERE id=?");
                gencrl();
                while (true) {