1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
|
package catfile
import (
"bufio"
"bytes"
"fmt"
"io"
"strconv"
"strings"
"time"
"gitlab.com/gitlab-org/gitaly/v16/internal/git"
"gitlab.com/gitlab-org/gitaly/v16/internal/helper"
"gitlab.com/gitlab-org/gitaly/v16/proto/go/gitalypb"
"google.golang.org/protobuf/types/known/timestamppb"
)
// Parser parses Git objects into their gitalypb representations.
type Parser interface {
ParseCommit(object git.Object) (*gitalypb.GitCommit, error)
ParseTag(object git.Object) (*gitalypb.Tag, error)
}
type parser struct {
bufferedReader *bufio.Reader
}
// NewParser creates a new parser for Git objects.
func NewParser() Parser {
return newParser()
}
func newParser() *parser {
return &parser{
bufferedReader: bufio.NewReader(nil),
}
}
// ParseCommit parses the commit data from the Reader.
func (p *parser) ParseCommit(object git.Object) (*gitalypb.GitCommit, error) {
commit := &gitalypb.GitCommit{Id: object.ObjectID().String()}
var lastLine bool
p.bufferedReader.Reset(object)
bytesRemaining := object.ObjectSize()
for !lastLine {
line, err := p.bufferedReader.ReadString('\n')
if err == io.EOF {
lastLine = true
} else if err != nil {
return nil, fmt.Errorf("parse raw commit: header: %w", err)
}
bytesRemaining -= int64(len(line))
if len(line) == 0 || line[0] == ' ' {
continue
}
// A blank line indicates the start of the commit body
if line == "\n" {
break
}
// There might not be a final line break if there was an EOF
if line[len(line)-1] == '\n' {
line = line[:len(line)-1]
}
key, value, ok := strings.Cut(line, " ")
if !ok {
continue
}
switch key {
case "parent":
commit.ParentIds = append(commit.ParentIds, value)
case "author":
commit.Author = parseCommitAuthor(value)
case "committer":
commit.Committer = parseCommitAuthor(value)
case "gpgsig":
commit.SignatureType = detectSignatureType(value)
case "tree":
commit.TreeId = value
case "encoding":
commit.Encoding = value
}
}
if !lastLine {
body := make([]byte, bytesRemaining)
if _, err := io.ReadFull(p.bufferedReader, body); err != nil {
return nil, fmt.Errorf("reading commit message: %w", err)
}
// After we have copied the body, we must make sure that there really is no
// additional data. For once, this is to detect bugs in our implementation where we
// would accidentally have truncated the commit message. On the other hand, we also
// need to do this such that we observe the EOF, which we must observe in order to
// unblock reading the next object.
//
// This all feels a bit complicated, where it would be much easier to just read into
// a preallocated `bytes.Buffer`. But this complexity is indeed required to optimize
// allocations. So if you want to change this, please make sure to execute the
// `BenchmarkListAllCommits` benchmark.
if n, err := io.Copy(io.Discard, p.bufferedReader); err != nil {
return nil, fmt.Errorf("reading commit message: %w", err)
} else if n != 0 {
return nil, fmt.Errorf(
"commit message exceeds expected length %v by %v bytes",
object.ObjectSize(), n,
)
}
if len(body) > 0 {
commit.Subject = subjectFromBody(body)
commit.BodySize = int64(len(body))
commit.Body = body
if max := helper.MaxCommitOrTagMessageSize; len(body) > max {
commit.Body = commit.Body[:max]
}
}
}
return commit, nil
}
const maxUnixCommitDate = 1 << 53
// fallbackTimeValue is the value returned in case there is a parse error. It's the maximum
// time value possible in golang. See
// https://gitlab.com/gitlab-org/gitaly/issues/556#note_40289573
var fallbackTimeValue = time.Unix(1<<63-62135596801, 999999999)
func parseCommitAuthor(line string) *gitalypb.CommitAuthor {
author := &gitalypb.CommitAuthor{}
name, line, ok := strings.Cut(line, "<")
author.Name = []byte(strings.TrimSuffix(name, " "))
if !ok {
return author
}
email, line, ok := strings.Cut(line, ">")
if !ok {
return author
}
author.Email = []byte(email)
secSplit := strings.Fields(line)
if len(secSplit) < 1 {
return author
}
sec, err := strconv.ParseInt(secSplit[0], 10, 64)
if err != nil || sec > maxUnixCommitDate || sec < 0 {
sec = fallbackTimeValue.Unix()
}
author.Date = ×tamppb.Timestamp{Seconds: sec}
if len(secSplit) == 2 {
author.Timezone = []byte(secSplit[1])
}
return author
}
func subjectFromBody(body []byte) []byte {
subject, _, _ := bytes.Cut(body, []byte("\n"))
return bytes.TrimRight(subject, "\r\n")
}
func detectSignatureType(line string) gitalypb.SignatureType {
switch strings.TrimSuffix(line, "\n") {
case "-----BEGIN SIGNED MESSAGE-----":
return gitalypb.SignatureType_X509
case "-----BEGIN PGP MESSAGE-----":
return gitalypb.SignatureType_PGP
case "-----BEGIN PGP SIGNATURE-----":
return gitalypb.SignatureType_PGP
case "-----BEGIN SSH SIGNATURE-----":
return gitalypb.SignatureType_SSH
default:
return gitalypb.SignatureType_NONE
}
}
// ParseTag parses the given object, which is expected to refer to a Git tag. The tag's tagged
// commit is not populated. The given object ID shall refer to the tag itself such that the returned
// Tag structure has the correct OID.
func (p *parser) ParseTag(object git.Object) (*gitalypb.Tag, error) {
tag, _, err := p.parseTag(object, nil)
return tag, err
}
type taggedObject struct {
objectID string
objectType string
}
func (p *parser) parseTag(object git.Object, name []byte) (*gitalypb.Tag, taggedObject, error) {
p.bufferedReader.Reset(object)
tag := &gitalypb.Tag{
Id: object.ObjectID().String(),
Name: name,
}
var tagged taggedObject
var lastLine bool
bytesRemaining := object.ObjectSize()
for !lastLine {
line, err := p.bufferedReader.ReadString('\n')
if err == io.EOF {
lastLine = true
} else if err != nil {
return nil, taggedObject{}, fmt.Errorf("reading tag header: %w", err)
}
bytesRemaining -= int64(len(line))
if len(line) == 0 {
continue
}
if line == "\n" {
break
}
if line[len(line)-1] == '\n' {
line = line[:len(line)-1]
}
key, value, ok := strings.Cut(line, " ")
if !ok {
continue
}
switch key {
case "object":
tagged.objectID = value
case "type":
tagged.objectType = value
case "tag":
if len(tag.Name) == 0 {
tag.Name = []byte(value)
}
case "tagger":
tag.Tagger = parseCommitAuthor(value)
}
}
// We only need to try reading the message if we haven't seen an EOF yet, but instead saw
// the "\n\n" separator.
if !lastLine {
message := make([]byte, bytesRemaining)
if _, err := io.ReadFull(p.bufferedReader, message); err != nil {
return nil, taggedObject{}, fmt.Errorf("reading tag message: %w", err)
}
// After we have copied the message, we must make sure that there really is no
// additional data. For once, this is to detect bugs in our implementation where we
// would accidentally have truncated the commit message. On the other hand, we also
// need to do this such that we observe the EOF, which we must observe in order to
// unblock reading the next object.
//
// This all feels a bit complicated, where it would be much easier to just read into
// a preallocated `bytes.Buffer`. But this complexity is indeed required to optimize
// allocations. So if you want to change this, please make sure to execute the
// `BenchmarkFindAllTags` benchmark.
if n, err := io.Copy(io.Discard, p.bufferedReader); err != nil {
return nil, taggedObject{}, fmt.Errorf("reading tag message: %w", err)
} else if n != 0 {
return nil, taggedObject{}, fmt.Errorf(
"tag message exceeds expected length %v by %v bytes",
object.ObjectSize(), n,
)
}
tag.Message = message
tag.MessageSize = int64(len(message))
if signature, _ := ExtractTagSignature(message); signature != nil {
length := bytes.Index(signature, []byte("\n"))
if length > 0 {
signature := string(signature[:length])
tag.SignatureType = detectSignatureType(signature)
}
}
}
return tag, tagged, nil
}
|