]> WPIA git - gigi.git/blob - src/org/cacert/gigi/dbObjects/Domain.java
c165c4abdbcaedc7e1e457715a5a021090304a19
[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 User 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 = User.getById(rs.getInt(1));
50         suffix = rs.getString(2);
51         rs.close();
52     }
53
54     public Domain(User owner, String suffix) throws GigiApiException {
55         checkCertifyableDomain(suffix, owner.isInGroup(Group.CODESIGNING));
56         this.owner = owner;
57         this.suffix = suffix;
58
59     }
60
61     public static void checkCertifyableDomain(String s, boolean hasPunycodeRight) throws GigiApiException {
62         String[] parts = s.split("\\.", -1);
63         if (parts.length < 2) {
64             throw new GigiApiException("Domain does not contain '.'.");
65         }
66         for (int i = parts.length - 1; i >= 0; i--) {
67             if ( !isVaildDomainPart(parts[i], hasPunycodeRight)) {
68                 throw new GigiApiException("Syntax error in Domain");
69             }
70         }
71         String publicSuffix = PublicSuffixes.getInstance().getRegistrablePart(s);
72         if ( !s.equals(publicSuffix)) {
73             throw new GigiApiException("You may only register a domain with exactly one lable before the public suffix.");
74         }
75         checkPunycode(parts[0], s.substring(parts[0].length() + 1));
76     }
77
78     private static void checkPunycode(String label, String domainContext) throws GigiApiException {
79         if (label.charAt(2) != '-' || label.charAt(3) != '-') {
80             return; // is no punycode
81         }
82         if ( !IDNEnabledTLDs.contains(domainContext)) {
83             throw new GigiApiException("Punycode label could not be positively verified.");
84         }
85         if ( !label.startsWith("xn--")) {
86             throw new GigiApiException("Unknown ACE prefix.");
87         }
88         try {
89             String unicode = IDN.toUnicode(label);
90             if (unicode.startsWith("xn--")) {
91                 throw new GigiApiException("Punycode label could not be positively verified.");
92             }
93         } catch (IllegalArgumentException e) {
94             throw new GigiApiException("Punycode label could not be positively verified.");
95         }
96     }
97
98     public static boolean isVaildDomainPart(String s, boolean allowPunycode) {
99         if ( !s.matches("[a-z0-9-]+")) {
100             return false;
101         }
102         if (s.charAt(0) == '-' || s.charAt(s.length() - 1) == '-') {
103             return false;
104         }
105         if (s.length() > 63) {
106             return false;
107         }
108         boolean canBePunycode = s.length() >= 4 && s.charAt(2) == '-' && s.charAt(3) == '-';
109         if (canBePunycode && !allowPunycode) {
110             return false;
111         }
112         return true;
113     }
114
115     private static void checkInsert(String suffix) throws GigiApiException {
116         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");
117         ps.setString(1, suffix);
118         ps.setString(2, suffix);
119         ps.setString(3, suffix);
120         ps.setString(4, suffix);
121         GigiResultSet rs = ps.executeQuery();
122         boolean existed = rs.next();
123         rs.close();
124         if (existed) {
125             throw new GigiApiException("Domain could not be inserted. Domain is already valid.");
126         }
127     }
128
129     public void insert() throws GigiApiException {
130         synchronized (Domain.class) {
131             if (id != 0) {
132                 throw new GigiApiException("already inserted.");
133             }
134             checkInsert(suffix);
135             GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `domains` SET memid=?, domain=?");
136             ps.setInt(1, owner.getId());
137             ps.setString(2, suffix);
138             ps.execute();
139             id = ps.lastInsertId();
140             myCache.put(this);
141         }
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 User 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 `configId` IN (SELECT `id` FROM `pingconfig` WHERE `domainid`=?)");
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` 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 }