]> WPIA git - gigi.git/blob - src/org/cacert/gigi/dbObjects/Domain.java
6093f6d85b74b82ce64083cbdadc2563f4ec3371
[gigi.git] / src / org / cacert / gigi / dbObjects / Domain.java
1 package org.cacert.gigi.dbObjects;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.net.IDN;
6 import java.util.Arrays;
7 import java.util.Collections;
8 import java.util.HashSet;
9 import java.util.LinkedList;
10 import java.util.List;
11 import java.util.Properties;
12 import java.util.Set;
13
14 import org.cacert.gigi.GigiApiException;
15 import org.cacert.gigi.database.DatabaseConnection;
16 import org.cacert.gigi.database.GigiPreparedStatement;
17 import org.cacert.gigi.database.GigiResultSet;
18 import org.cacert.gigi.util.PublicSuffixes;
19
20 public class Domain implements IdCachable, Verifyable {
21
22     private CertificateOwner owner;
23
24     private String suffix;
25
26     private int id;
27
28     private static final Set<String> IDNEnabledTLDs;
29
30     static {
31         Properties CPS = new Properties();
32         try (InputStream resourceAsStream = Domain.class.getResourceAsStream("CPS.properties")) {
33             CPS.load(resourceAsStream);
34             IDNEnabledTLDs = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(CPS.getProperty("IDN-enabled").split(","))));
35         } catch (IOException e) {
36             throw new Error(e);
37         }
38     }
39
40     private Domain(int id) {
41         GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `memid`, `domain` FROM `domains` WHERE `id`=? AND `deleted` IS NULL");
42         ps.setInt(1, id);
43
44         GigiResultSet rs = ps.executeQuery();
45         if ( !rs.next()) {
46             throw new IllegalArgumentException("Invalid domain id " + id);
47         }
48         this.id = id;
49         owner = CertificateOwner.getById(rs.getInt(1));
50         suffix = rs.getString(2);
51         rs.close();
52     }
53
54     public Domain(User actor, CertificateOwner owner, String suffix) throws GigiApiException {
55         synchronized (Domain.class) {
56             checkCertifyableDomain(suffix, actor.isInGroup(Group.CODESIGNING));
57             this.owner = owner;
58             this.suffix = suffix;
59             insert();
60         }
61     }
62
63     public static void checkCertifyableDomain(String s, boolean hasPunycodeRight) throws GigiApiException {
64         String[] parts = s.split("\\.", -1);
65         if (parts.length < 2) {
66             throw new GigiApiException("Domain does not contain '.'.");
67         }
68         for (int i = parts.length - 1; i >= 0; i--) {
69             if ( !isVaildDomainPart(parts[i], hasPunycodeRight)) {
70                 throw new GigiApiException("Syntax error in Domain");
71             }
72         }
73         String publicSuffix = PublicSuffixes.getInstance().getRegistrablePart(s);
74         if ( !s.equals(publicSuffix)) {
75             throw new GigiApiException("You may only register a domain with exactly one lable before the public suffix.");
76         }
77         checkPunycode(parts[0], s.substring(parts[0].length() + 1));
78     }
79
80     private static void checkPunycode(String label, String domainContext) throws GigiApiException {
81         if (label.charAt(2) != '-' || label.charAt(3) != '-') {
82             return; // is no punycode
83         }
84         if ( !IDNEnabledTLDs.contains(domainContext)) {
85             throw new GigiApiException("Punycode label could not be positively verified.");
86         }
87         if ( !label.startsWith("xn--")) {
88             throw new GigiApiException("Unknown ACE prefix.");
89         }
90         try {
91             String unicode = IDN.toUnicode(label);
92             if (unicode.startsWith("xn--")) {
93                 throw new GigiApiException("Punycode label could not be positively verified.");
94             }
95         } catch (IllegalArgumentException e) {
96             throw new GigiApiException("Punycode label could not be positively verified.");
97         }
98     }
99
100     public static boolean isVaildDomainPart(String s, boolean allowPunycode) {
101         if ( !s.matches("[a-z0-9-]+")) {
102             return false;
103         }
104         if (s.charAt(0) == '-' || s.charAt(s.length() - 1) == '-') {
105             return false;
106         }
107         if (s.length() > 63) {
108             return false;
109         }
110         boolean canBePunycode = s.length() >= 4 && s.charAt(2) == '-' && s.charAt(3) == '-';
111         if (canBePunycode && !allowPunycode) {
112             return false;
113         }
114         return true;
115     }
116
117     private static void checkInsert(String suffix) throws GigiApiException {
118         GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT 1 FROM `domains` WHERE (`domain`=? OR (CONCAT('.', `domain`)=RIGHT(?,LENGTH(`domain`)+1)  OR RIGHT(`domain`,LENGTH(?)+1)=CONCAT('.',?))) AND `deleted` IS NULL");
119         ps.setString(1, suffix);
120         ps.setString(2, suffix);
121         ps.setString(3, suffix);
122         ps.setString(4, suffix);
123         GigiResultSet rs = ps.executeQuery();
124         boolean existed = rs.next();
125         rs.close();
126         if (existed) {
127             throw new GigiApiException("Domain could not be inserted. Domain is already valid.");
128         }
129     }
130
131     private void insert() throws GigiApiException {
132         if (id != 0) {
133             throw new GigiApiException("already inserted.");
134         }
135         checkInsert(suffix);
136         GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `domains` SET memid=?, domain=?");
137         ps.setInt(1, owner.getId());
138         ps.setString(2, suffix);
139         ps.execute();
140         id = ps.lastInsertId();
141         myCache.put(this);
142     }
143
144     public void delete() throws GigiApiException {
145         if (id == 0) {
146             throw new GigiApiException("not inserted.");
147         }
148         GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE `domains` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?");
149         ps.setInt(1, id);
150         ps.execute();
151     }
152
153     public CertificateOwner getOwner() {
154         return owner;
155     }
156
157     @Override
158     public int getId() {
159         return id;
160     }
161
162     public String getSuffix() {
163         return suffix;
164     }
165
166     private LinkedList<DomainPingConfiguration> configs = null;
167
168     public List<DomainPingConfiguration> getConfiguredPings() throws GigiApiException {
169         LinkedList<DomainPingConfiguration> configs = this.configs;
170         if (configs == null) {
171             configs = new LinkedList<>();
172             GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM pingconfig WHERE domainid=?");
173             ps.setInt(1, id);
174             GigiResultSet rs = ps.executeQuery();
175             while (rs.next()) {
176                 configs.add(DomainPingConfiguration.getById(rs.getInt(1)));
177             }
178             rs.close();
179             this.configs = configs;
180
181         }
182         return Collections.unmodifiableList(configs);
183     }
184
185     public void addPing(DomainPingType type, String config) throws GigiApiException {
186         GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `pingconfig` SET `domainid`=?, `type`=?::`pingType`, `info`=?");
187         ps.setInt(1, id);
188         ps.setString(2, type.toString().toLowerCase());
189         ps.setString(3, config);
190         ps.execute();
191         configs = null;
192     }
193
194     public synchronized void verify(String hash) throws GigiApiException {
195         GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE `domainPinglog` SET `state`='success' WHERE `challenge`=? AND `state`='open' AND `configId` IN (SELECT `id` FROM `pingconfig` WHERE `domainid`=? AND `type`='email')");
196         ps.setString(1, hash);
197         ps.setInt(2, id);
198         ps.executeUpdate();
199     }
200
201     public boolean isVerified() {
202         GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT 1 FROM `domainPinglog` INNER JOIN `pingconfig` ON `pingconfig`.`id`=`domainPinglog`.`configId` WHERE `domainid`=? AND `state`='success'");
203         ps.setInt(1, id);
204         GigiResultSet rs = ps.executeQuery();
205         return rs.next();
206     }
207
208     public DomainPingExecution[] getPings() throws GigiApiException {
209         GigiPreparedStatement ps = DatabaseConnection.getInstance().prepareScrollable("SELECT `state`, `type`, `info`, `result`, `configId`, `when` FROM `domainPinglog` INNER JOIN `pingconfig` ON `pingconfig`.`id`=`domainPinglog`.`configId` WHERE `pingconfig`.`domainid`=? ORDER BY `when` DESC;");
210         ps.setInt(1, id);
211         GigiResultSet rs = ps.executeQuery();
212         rs.last();
213         DomainPingExecution[] contents = new DomainPingExecution[rs.getRow()];
214         rs.beforeFirst();
215         for (int i = 0; i < contents.length && rs.next(); i++) {
216             contents[i] = new DomainPingExecution(rs);
217         }
218         return contents;
219
220     }
221
222     private static final ObjectCache<Domain> myCache = new ObjectCache<>();
223
224     public static synchronized Domain getById(int id) throws IllegalArgumentException {
225         Domain em = myCache.get(id);
226         if (em == null) {
227             myCache.put(em = new Domain(id));
228         }
229         return em;
230     }
231
232     public static int searchUserIdByDomain(String domain) {
233         GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `memid` FROM `domains` WHERE `domain` = ?");
234         ps.setString(1, domain);
235         GigiResultSet res = ps.executeQuery();
236         if (res.next()) {
237             return res.getInt(1);
238         } else {
239             return -1;
240         }
241     }
242
243 }