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