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.2KB

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