You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PushCertificateIdent.java 8.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. /*
  2. * Copyright (C) 2015, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.transport;
  44. import static java.nio.charset.StandardCharsets.UTF_8;
  45. import static org.eclipse.jgit.util.RawParseUtils.lastIndexOfTrim;
  46. import java.text.SimpleDateFormat;
  47. import java.util.Date;
  48. import java.util.Locale;
  49. import java.util.TimeZone;
  50. import org.eclipse.jgit.lib.PersonIdent;
  51. import org.eclipse.jgit.util.MutableInteger;
  52. import org.eclipse.jgit.util.RawParseUtils;
  53. /**
  54. * Identity in a push certificate.
  55. * <p>
  56. * This is similar to a {@link org.eclipse.jgit.lib.PersonIdent} in that it
  57. * contains a name, timestamp, and timezone offset, but differs in the following
  58. * ways:
  59. * <ul>
  60. * <li>It is always parsed from a UTF-8 string, rather than a raw commit
  61. * buffer.</li>
  62. * <li>It is not guaranteed to contain a name and email portion, since any UTF-8
  63. * string is a valid OpenPGP User ID (RFC4880 5.1.1). The raw User ID is always
  64. * available as {@link #getUserId()}, but {@link #getEmailAddress()} may return
  65. * null.</li>
  66. * <li>The raw text from which the identity was parsed is available with
  67. * {@link #getRaw()}. This is necessary for losslessly reconstructing the signed
  68. * push certificate payload.</li>
  69. * <li>
  70. * </ul>
  71. *
  72. * @since 4.1
  73. */
  74. public class PushCertificateIdent {
  75. /**
  76. * Parse an identity from a string.
  77. * <p>
  78. * Spaces are trimmed when parsing the timestamp and timezone offset, with
  79. * one exception. The timestamp must be preceded by a single space, and the
  80. * rest of the string prior to that space (including any additional
  81. * whitespace) is treated as the OpenPGP User ID.
  82. * <p>
  83. * If either the timestamp or timezone offsets are missing, mimics
  84. * {@link RawParseUtils#parsePersonIdent(String)} behavior and sets them
  85. * both to zero.
  86. *
  87. * @param str
  88. * string to parse.
  89. * @return a {@link org.eclipse.jgit.transport.PushCertificateIdent} object.
  90. */
  91. public static PushCertificateIdent parse(String str) {
  92. MutableInteger p = new MutableInteger();
  93. byte[] raw = str.getBytes(UTF_8);
  94. int tzBegin = raw.length - 1;
  95. tzBegin = lastIndexOfTrim(raw, ' ', tzBegin);
  96. if (tzBegin < 0 || raw[tzBegin] != ' ') {
  97. return new PushCertificateIdent(str, str, 0, 0);
  98. }
  99. int whenBegin = tzBegin++;
  100. int tz = RawParseUtils.parseTimeZoneOffset(raw, tzBegin, p);
  101. boolean hasTz = p.value != tzBegin;
  102. whenBegin = lastIndexOfTrim(raw, ' ', whenBegin);
  103. if (whenBegin < 0 || raw[whenBegin] != ' ') {
  104. return new PushCertificateIdent(str, str, 0, 0);
  105. }
  106. int idEnd = whenBegin++;
  107. long when = RawParseUtils.parseLongBase10(raw, whenBegin, p);
  108. boolean hasWhen = p.value != whenBegin;
  109. if (hasTz && hasWhen) {
  110. idEnd = whenBegin - 1;
  111. } else {
  112. // If either tz or when are non-numeric, mimic parsePersonIdent behavior and
  113. // set them both to zero.
  114. tz = 0;
  115. when = 0;
  116. if (hasTz && !hasWhen) {
  117. // Only one trailing numeric field; assume User ID ends before this
  118. // field, but discard its value.
  119. idEnd = tzBegin - 1;
  120. } else {
  121. // No trailing numeric fields; User ID is whole raw value.
  122. idEnd = raw.length;
  123. }
  124. }
  125. String id = new String(raw, 0, idEnd, UTF_8);
  126. return new PushCertificateIdent(str, id, when * 1000L, tz);
  127. }
  128. private final String raw;
  129. private final String userId;
  130. private final long when;
  131. private final int tzOffset;
  132. /**
  133. * Construct a new identity from an OpenPGP User ID.
  134. *
  135. * @param userId
  136. * OpenPGP User ID; any UTF-8 string.
  137. * @param when
  138. * local time.
  139. * @param tzOffset
  140. * timezone offset; see {@link #getTimeZoneOffset()}.
  141. */
  142. public PushCertificateIdent(String userId, long when, int tzOffset) {
  143. this.userId = userId;
  144. this.when = when;
  145. this.tzOffset = tzOffset;
  146. StringBuilder sb = new StringBuilder(userId).append(' ').append(when / 1000)
  147. .append(' ');
  148. PersonIdent.appendTimezone(sb, tzOffset);
  149. raw = sb.toString();
  150. }
  151. private PushCertificateIdent(String raw, String userId, long when,
  152. int tzOffset) {
  153. this.raw = raw;
  154. this.userId = userId;
  155. this.when = when;
  156. this.tzOffset = tzOffset;
  157. }
  158. /**
  159. * Get the raw string from which this identity was parsed.
  160. * <p>
  161. * If the string was constructed manually, a suitable canonical string is
  162. * returned.
  163. * <p>
  164. * For the purposes of bytewise comparisons with other OpenPGP IDs, the string
  165. * must be encoded as UTF-8.
  166. *
  167. * @return the raw string.
  168. */
  169. public String getRaw() {
  170. return raw;
  171. }
  172. /**
  173. * Get the OpenPGP User ID, which may be any string.
  174. *
  175. * @return the OpenPGP User ID, which may be any string.
  176. */
  177. public String getUserId() {
  178. return userId;
  179. }
  180. /**
  181. * Get the name portion of the User ID.
  182. *
  183. * @return the name portion of the User ID. If no email address would be
  184. * parsed by {@link #getEmailAddress()}, returns the full User ID
  185. * with spaces trimmed.
  186. */
  187. public String getName() {
  188. int nameEnd = userId.indexOf('<');
  189. if (nameEnd < 0 || userId.indexOf('>', nameEnd) < 0) {
  190. nameEnd = userId.length();
  191. }
  192. nameEnd--;
  193. while (nameEnd >= 0 && userId.charAt(nameEnd) == ' ') {
  194. nameEnd--;
  195. }
  196. int nameBegin = 0;
  197. while (nameBegin < nameEnd && userId.charAt(nameBegin) == ' ') {
  198. nameBegin++;
  199. }
  200. return userId.substring(nameBegin, nameEnd + 1);
  201. }
  202. /**
  203. * Get the email portion of the User ID
  204. *
  205. * @return the email portion of the User ID, if one was successfully parsed
  206. * from {@link #getUserId()}, or null.
  207. */
  208. public String getEmailAddress() {
  209. int emailBegin = userId.indexOf('<');
  210. if (emailBegin < 0) {
  211. return null;
  212. }
  213. int emailEnd = userId.indexOf('>', emailBegin);
  214. if (emailEnd < 0) {
  215. return null;
  216. }
  217. return userId.substring(emailBegin + 1, emailEnd);
  218. }
  219. /**
  220. * Get the timestamp of the identity.
  221. *
  222. * @return the timestamp of the identity.
  223. */
  224. public Date getWhen() {
  225. return new Date(when);
  226. }
  227. /**
  228. * Get this person's declared time zone
  229. *
  230. * @return this person's declared time zone; null if the timezone is
  231. * unknown.
  232. */
  233. public TimeZone getTimeZone() {
  234. return PersonIdent.getTimeZone(tzOffset);
  235. }
  236. /**
  237. * Get this person's declared time zone as minutes east of UTC.
  238. *
  239. * @return this person's declared time zone as minutes east of UTC. If the
  240. * timezone is to the west of UTC it is negative.
  241. */
  242. public int getTimeZoneOffset() {
  243. return tzOffset;
  244. }
  245. /** {@inheritDoc} */
  246. @Override
  247. public boolean equals(Object o) {
  248. return (o instanceof PushCertificateIdent)
  249. && raw.equals(((PushCertificateIdent) o).raw);
  250. }
  251. /** {@inheritDoc} */
  252. @Override
  253. public int hashCode() {
  254. return raw.hashCode();
  255. }
  256. /** {@inheritDoc} */
  257. @SuppressWarnings("nls")
  258. @Override
  259. public String toString() {
  260. SimpleDateFormat fmt;
  261. fmt = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy Z", Locale.US);
  262. fmt.setTimeZone(getTimeZone());
  263. return getClass().getSimpleName()
  264. + "[raw=\"" + raw + "\","
  265. + " userId=\"" + userId + "\","
  266. + " " + fmt.format(Long.valueOf(when)) + "]";
  267. }
  268. }