]> WPIA git - gigi.git/blob - src/club/wpia/gigi/dbObjects/Domain.java
Merge changes If5eed01f,I88c94e39,If36f5b0a
[gigi.git] / src / club / wpia / gigi / dbObjects / Domain.java
1 package club.wpia.gigi.dbObjects;
2
3 import java.util.Collections;
4 import java.util.LinkedList;
5 import java.util.List;
6
7 import club.wpia.gigi.GigiApiException;
8 import club.wpia.gigi.database.GigiPreparedStatement;
9 import club.wpia.gigi.database.GigiResultSet;
10 import club.wpia.gigi.dbObjects.Certificate.RevocationType;
11 import club.wpia.gigi.util.DomainAssessment;
12
13 public class Domain implements IdCachable, Verifyable {
14
15     private CertificateOwner owner;
16
17     private String suffix;
18
19     private int id;
20
21     private Domain(GigiResultSet rs, int id) {
22         this.id = id;
23         owner = CertificateOwner.getById(rs.getInt(1));
24         suffix = rs.getString(2);
25     }
26
27     public Domain(User actor, CertificateOwner owner, String suffix) throws GigiApiException {
28         suffix = suffix.toLowerCase();
29         synchronized (Domain.class) {
30             DomainAssessment.checkCertifiableDomain(suffix, actor.isInGroup(Group.CODESIGNING), true);
31             this.owner = owner;
32             this.suffix = suffix;
33             insert();
34         }
35     }
36
37     private static void checkInsert(String suffix) throws GigiApiException {
38         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT 1 FROM `domains` WHERE (`domain`=? OR (CONCAT('.', `domain`)=RIGHT(?,LENGTH(`domain`)+1)  OR RIGHT(`domain`,LENGTH(?)+1)=CONCAT('.',?::VARCHAR))) AND `deleted` IS NULL")) {
39             ps.setString(1, suffix);
40             ps.setString(2, suffix);
41             ps.setString(3, suffix);
42             ps.setString(4, suffix);
43             GigiResultSet rs = ps.executeQuery();
44             boolean existed = rs.next();
45             rs.close();
46             if (existed) {
47                 throw new GigiApiException("Domain could not be inserted. Domain is already known to the system.");
48             }
49         }
50     }
51
52     private void insert() throws GigiApiException {
53         if (id != 0) {
54             throw new GigiApiException("already inserted.");
55         }
56         checkInsert(suffix);
57         try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `domains` SET memid=?, domain=?")) {
58             ps.setInt(1, owner.getId());
59             ps.setString(2, suffix);
60             ps.execute();
61             id = ps.lastInsertId();
62         }
63         myCache.put(this);
64     }
65
66     public void delete() throws GigiApiException {
67         if (id == 0) {
68             throw new GigiApiException("not inserted.");
69         }
70         synchronized (Domain.class) {
71             myCache.remove(this);
72             try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `domains` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
73                 ps.setInt(1, id);
74                 ps.execute();
75             }
76             LinkedList<Job> revokes = new LinkedList<Job>();
77             for (Certificate cert : fetchActiveCertificates()) {
78                 revokes.add(cert.revoke(RevocationType.USER));
79             }
80             long start = System.currentTimeMillis();
81             for (Job job : revokes) {
82                 int toWait = (int) (60000 + start - System.currentTimeMillis());
83                 if (toWait > 0) {
84                     job.waitFor(toWait);
85                 } else {
86                     break; // canceled... waited too log
87                 }
88             }
89         }
90     }
91
92     public CertificateOwner getOwner() {
93         return owner;
94     }
95
96     @Override
97     public int getId() {
98         return id;
99     }
100
101     public String getSuffix() {
102         return suffix;
103     }
104
105     private LinkedList<DomainPingConfiguration> configs = null;
106
107     public List<DomainPingConfiguration> getConfiguredPings() {
108         LinkedList<DomainPingConfiguration> configs = this.configs;
109         if (configs == null) {
110             configs = new LinkedList<>();
111             try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT id FROM pingconfig WHERE domainid=? AND `deleted` IS NULL")) {
112                 ps.setInt(1, id);
113                 GigiResultSet rs = ps.executeQuery();
114                 while (rs.next()) {
115                     configs.add(DomainPingConfiguration.getById(rs.getInt(1)));
116                 }
117             }
118             this.configs = configs;
119
120         }
121         return Collections.unmodifiableList(configs);
122     }
123
124     public void addPing(DomainPingType type, String config) throws GigiApiException {
125         try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `pingconfig` SET `domainid`=?, `type`=?::`pingType`, `info`=?")) {
126             ps.setInt(1, id);
127             ps.setEnum(2, type);
128             ps.setString(3, config);
129             ps.execute();
130         }
131         configs = null;
132     }
133
134     public void clearPings() throws GigiApiException {
135         try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `pingconfig` SET `deleted`=CURRENT_TIMESTAMP WHERE `deleted` is NULL AND `domainid`=?")) {
136             ps.setInt(1, id);
137             ps.execute();
138         }
139         configs = null;
140     }
141
142     public synchronized boolean isVerifyable(String hash) throws GigiApiException {
143         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT 1 FROM `domainPinglog` WHERE `challenge`=? AND `state`='open' AND `configId` IN (SELECT `id` FROM `pingconfig` WHERE `domainid`=? AND `type`='email')")) {
144             ps.setString(1, hash);
145             ps.setInt(2, id);
146             return ps.executeQuery().next();
147         }
148     }
149
150     public synchronized void verify(String hash) throws GigiApiException {
151         try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `domainPinglog` SET `state`='success' WHERE `challenge`=? AND `state`='open' AND `configId` IN (SELECT `id` FROM `pingconfig` WHERE `domainid`=? AND `type`='email')")) {
152             ps.setString(1, hash);
153             ps.setInt(2, id);
154             if ( !ps.executeMaybeUpdate()) {
155                 throw new IllegalArgumentException("Given token could not be found to complete the verification process (Domain Ping).");
156             }
157         }
158     }
159
160     /**
161      * Determines current domain validity. A domain is valid, iff at least two
162      * configured pings are currently successful.
163      * 
164      * @return true, iff domain is valid
165      * @throws GigiApiException
166      */
167     public boolean isVerified() {
168         int count = 0;
169         boolean[] used = new boolean[DomainPingType.values().length];
170         for (DomainPingConfiguration config : getConfiguredPings()) {
171             if (config.isValid() && !used[config.getType().ordinal()]) {
172                 count++;
173                 used[config.getType().ordinal()] = true;
174             }
175             if (count >= 2) {
176                 return true;
177             }
178         }
179         return false;
180     }
181
182     public DomainPingExecution[] getPings() throws GigiApiException {
183         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `state`, `type`, `info`, `result`, `configId`, `when` FROM `domainPinglog` INNER JOIN `pingconfig` ON `pingconfig`.`id`=`domainPinglog`.`configId` WHERE `pingconfig`.`domainid`=? ORDER BY `when` DESC;", true)) {
184             ps.setInt(1, id);
185             GigiResultSet rs = ps.executeQuery();
186             rs.last();
187             DomainPingExecution[] contents = new DomainPingExecution[rs.getRow()];
188             rs.beforeFirst();
189             for (int i = 0; i < contents.length && rs.next(); i++) {
190                 contents[i] = new DomainPingExecution(rs);
191             }
192             return contents;
193         }
194
195     }
196
197     private static final ObjectCache<Domain> myCache = new ObjectCache<>();
198
199     public static synchronized Domain getById(int id) {
200         Domain em = myCache.get(id);
201         if (em == null) {
202             try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid`, `domain` FROM `domains` WHERE `id`=? AND `deleted` IS NULL")) {
203                 ps.setInt(1, id);
204                 GigiResultSet rs = ps.executeQuery();
205                 if ( !rs.next()) {
206                     return null;
207                 }
208                 myCache.put(em = new Domain(rs, id));
209             }
210         }
211         return em;
212     }
213
214     public static Domain searchDomain(String domain) {
215         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `domains` WHERE `domain` = ? AND `deleted` IS NULL")) {
216             ps.setString(1, domain);
217             GigiResultSet res = ps.executeQuery();
218             if (res.next()) {
219                 return getById(res.getInt(1));
220             } else {
221                 return null;
222             }
223         }
224     }
225
226     public Certificate[] fetchActiveCertificates() {
227         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `certs`.`id` FROM `certs` INNER JOIN `subjectAlternativeNames` ON `subjectAlternativeNames`.`certId` = `certs`.`id` WHERE (`contents`=? OR RIGHT(`contents`,LENGTH(?)+1)=CONCAT('.',?::VARCHAR)) AND `type`='DNS' AND `revoked` IS NULL AND `expire` > CURRENT_TIMESTAMP AND `memid`=? GROUP BY `certs`.`id`", true)) {
228             ps.setString(1, suffix);
229             ps.setString(2, suffix);
230             ps.setString(3, suffix);
231             ps.setInt(4, owner.getId());
232             GigiResultSet rs = ps.executeQuery();
233             rs.last();
234             Certificate[] res = new Certificate[rs.getRow()];
235             rs.beforeFirst();
236             int i = 0;
237             while (rs.next()) {
238                 res[i++] = Certificate.getById(rs.getInt(1));
239             }
240             return res;
241         }
242     }
243
244 }