View Javadoc
1   /*
2    * Copyright (C) 2015, Google Inc. and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  
11  package org.eclipse.jgit.transport;
12  
13  import static java.nio.charset.StandardCharsets.UTF_8;
14  import static org.eclipse.jgit.util.RawParseUtils.lastIndexOfTrim;
15  
16  import java.text.SimpleDateFormat;
17  import java.util.Date;
18  import java.util.Locale;
19  import java.util.TimeZone;
20  
21  import org.eclipse.jgit.lib.PersonIdent;
22  import org.eclipse.jgit.util.MutableInteger;
23  import org.eclipse.jgit.util.RawParseUtils;
24  
25  /**
26   * Identity in a push certificate.
27   * <p>
28   * This is similar to a {@link org.eclipse.jgit.lib.PersonIdent} in that it
29   * contains a name, timestamp, and timezone offset, but differs in the following
30   * ways:
31   * <ul>
32   * <li>It is always parsed from a UTF-8 string, rather than a raw commit
33   * buffer.</li>
34   * <li>It is not guaranteed to contain a name and email portion, since any UTF-8
35   * string is a valid OpenPGP User ID (RFC4880 5.1.1). The raw User ID is always
36   * available as {@link #getUserId()}, but {@link #getEmailAddress()} may return
37   * null.</li>
38   * <li>The raw text from which the identity was parsed is available with
39   * {@link #getRaw()}. This is necessary for losslessly reconstructing the signed
40   * push certificate payload.</li>
41   * <li>
42   * </ul>
43   *
44   * @since 4.1
45   */
46  public class PushCertificateIdent {
47  	/**
48  	 * Parse an identity from a string.
49  	 * <p>
50  	 * Spaces are trimmed when parsing the timestamp and timezone offset, with
51  	 * one exception. The timestamp must be preceded by a single space, and the
52  	 * rest of the string prior to that space (including any additional
53  	 * whitespace) is treated as the OpenPGP User ID.
54  	 * <p>
55  	 * If either the timestamp or timezone offsets are missing, mimics
56  	 * {@link RawParseUtils#parsePersonIdent(String)} behavior and sets them
57  	 * both to zero.
58  	 *
59  	 * @param str
60  	 *            string to parse.
61  	 * @return a {@link org.eclipse.jgit.transport.PushCertificateIdent} object.
62  	 */
63  	public static PushCertificateIdent parse(String str) {
64  		MutableInteger p = new MutableInteger();
65  		byte[] raw = str.getBytes(UTF_8);
66  		int tzBegin = raw.length - 1;
67  		tzBegin = lastIndexOfTrim(raw, ' ', tzBegin);
68  		if (tzBegin < 0 || raw[tzBegin] != ' ') {
69  			return new PushCertificateIdent(str, str, 0, 0);
70  		}
71  		int whenBegin = tzBegin++;
72  		int tz = RawParseUtils.parseTimeZoneOffset(raw, tzBegin, p);
73  		boolean hasTz = p.value != tzBegin;
74  
75  		whenBegin = lastIndexOfTrim(raw, ' ', whenBegin);
76  		if (whenBegin < 0 || raw[whenBegin] != ' ') {
77  			return new PushCertificateIdent(str, str, 0, 0);
78  		}
79  		int idEnd = whenBegin++;
80  		long when = RawParseUtils.parseLongBase10(raw, whenBegin, p);
81  		boolean hasWhen = p.value != whenBegin;
82  
83  		if (hasTz && hasWhen) {
84  			idEnd = whenBegin - 1;
85  		} else {
86  			// If either tz or when are non-numeric, mimic parsePersonIdent behavior and
87  			// set them both to zero.
88  			tz = 0;
89  			when = 0;
90  			if (hasTz && !hasWhen) {
91  				// Only one trailing numeric field; assume User ID ends before this
92  				// field, but discard its value.
93  				idEnd = tzBegin - 1;
94  			} else {
95  				// No trailing numeric fields; User ID is whole raw value.
96  				idEnd = raw.length;
97  			}
98  		}
99  		String id = new String(raw, 0, idEnd, UTF_8);
100 
101 		return new PushCertificateIdent(str, id, when * 1000L, tz);
102 	}
103 
104 	private final String raw;
105 	private final String userId;
106 	private final long when;
107 	private final int tzOffset;
108 
109 	/**
110 	 * Construct a new identity from an OpenPGP User ID.
111 	 *
112 	 * @param userId
113 	 *            OpenPGP User ID; any UTF-8 string.
114 	 * @param when
115 	 *            local time.
116 	 * @param tzOffset
117 	 *            timezone offset; see {@link #getTimeZoneOffset()}.
118 	 */
119 	public PushCertificateIdent(String userId, long when, int tzOffset) {
120 		this.userId = userId;
121 		this.when = when;
122 		this.tzOffset = tzOffset;
123 		StringBuilder sb = new StringBuilder(userId).append(' ').append(when / 1000)
124 				.append(' ');
125 		PersonIdent.appendTimezone(sb, tzOffset);
126 		raw = sb.toString();
127 	}
128 
129 	private PushCertificateIdent(String raw, String userId, long when,
130 			int tzOffset) {
131 		this.raw = raw;
132 		this.userId = userId;
133 		this.when = when;
134 		this.tzOffset = tzOffset;
135 	}
136 
137 	/**
138 	 * Get the raw string from which this identity was parsed.
139 	 * <p>
140 	 * If the string was constructed manually, a suitable canonical string is
141 	 * returned.
142 	 * <p>
143 	 * For the purposes of bytewise comparisons with other OpenPGP IDs, the string
144 	 * must be encoded as UTF-8.
145 	 *
146 	 * @return the raw string.
147 	 */
148 	public String getRaw() {
149 		return raw;
150 	}
151 
152 	/**
153 	 * Get the OpenPGP User ID, which may be any string.
154 	 *
155 	 * @return the OpenPGP User ID, which may be any string.
156 	 */
157 	public String getUserId() {
158 		return userId;
159 	}
160 
161 	/**
162 	 * Get the name portion of the User ID.
163 	 *
164 	 * @return the name portion of the User ID. If no email address would be
165 	 *         parsed by {@link #getEmailAddress()}, returns the full User ID
166 	 *         with spaces trimmed.
167 	 */
168 	public String getName() {
169 		int nameEnd = userId.indexOf('<');
170 		if (nameEnd < 0 || userId.indexOf('>', nameEnd) < 0) {
171 			nameEnd = userId.length();
172 		}
173 		nameEnd--;
174 		while (nameEnd >= 0 && userId.charAt(nameEnd) == ' ') {
175 			nameEnd--;
176 		}
177 		int nameBegin = 0;
178 		while (nameBegin < nameEnd && userId.charAt(nameBegin) == ' ') {
179 			nameBegin++;
180 		}
181 		return userId.substring(nameBegin, nameEnd + 1);
182 	}
183 
184 	/**
185 	 * Get the email portion of the User ID
186 	 *
187 	 * @return the email portion of the User ID, if one was successfully parsed
188 	 *         from {@link #getUserId()}, or null.
189 	 */
190 	public String getEmailAddress() {
191 		int emailBegin = userId.indexOf('<');
192 		if (emailBegin < 0) {
193 			return null;
194 		}
195 		int emailEnd = userId.indexOf('>', emailBegin);
196 		if (emailEnd < 0) {
197 			return null;
198 		}
199 		return userId.substring(emailBegin + 1, emailEnd);
200 	}
201 
202 	/**
203 	 * Get the timestamp of the identity.
204 	 *
205 	 * @return the timestamp of the identity.
206 	 */
207 	public Date getWhen() {
208 		return new Date(when);
209 	}
210 
211 	/**
212 	 * Get this person's declared time zone
213 	 *
214 	 * @return this person's declared time zone; null if the timezone is
215 	 *         unknown.
216 	 */
217 	public TimeZone getTimeZone() {
218 		return PersonIdent.getTimeZone(tzOffset);
219 	}
220 
221 	/**
222 	 * Get this person's declared time zone as minutes east of UTC.
223 	 *
224 	 * @return this person's declared time zone as minutes east of UTC. If the
225 	 *         timezone is to the west of UTC it is negative.
226 	 */
227 	public int getTimeZoneOffset() {
228 		return tzOffset;
229 	}
230 
231 	/** {@inheritDoc} */
232 	@Override
233 	public boolean equals(Object o) {
234 		return (o instanceof PushCertificateIdent)
235 			&& raw.equals(((PushCertificateIdent) o).raw);
236 	}
237 
238 	/** {@inheritDoc} */
239 	@Override
240 	public int hashCode() {
241 		return raw.hashCode();
242 	}
243 
244 	/** {@inheritDoc} */
245 	@SuppressWarnings("nls")
246 	@Override
247 	public String toString() {
248 		SimpleDateFormat fmt;
249 		fmt = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy Z", Locale.US);
250 		fmt.setTimeZone(getTimeZone());
251 		return getClass().getSimpleName()
252 			+ "[raw=\"" + raw + "\","
253 			+ " userId=\"" + userId + "\","
254 			+ " " + fmt.format(Long.valueOf(when)) + "]";
255 	}
256 }