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