Native/Remote.pm

filter: Statementstmt 83.3% 10 / 12 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 4 / 4 Podpod n/a totaltotal 87.5% 14 / 16 CC 1 SCAR 0.7
CC
1
Cov
83%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« Native.pm ↑ Summary
1 # ABSTRACT: A libgit2 remote (fetch / push)
2  
3 package Git::Native::Remote;
4 our $VERSION = '0.006';
5 2 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 0 ▶use Git::Libgit2::FFI ();
Subroutine BEGIN: called CC=1 SCAR=2.6
9 use Git::Libgit2 qw(
10 oid_to_hex GIT_PASSTHROUGH GIT_DIRECTION_FETCH GIT_DIRECTION_PUSH
11 fetch_options_prune_offset cert_hostkey_offsets
12 );
13 use Git::Native::Error qw( check_rc );
14 use FFI::Platypus::Buffer qw( scalar_to_buffer );
15 use FFI::Platypus::Memory qw( memcpy malloc free );
16 use Git::Native::Credential ();
17 use Git::Native::Remote::Result ();
18 use MIME::Base64 qw( encode_base64 decode_base64 );
19 use Digest::SHA qw( sha1 sha256 hmac_sha1 );
20  
21 # Register the per-ref callback types on the shared FFI instance. The types
22 # libgit2 ships (git_credential_acquire_cb, git_transport_certificate_check_cb)
23 # are declared in Git::Libgit2::FFI at module load; these two are new and only
24 # used here, so we register them locally. `->type` errors on duplicate names —
25 # guard with eval so re-entry (test isolation, re-require) is safe.
26 {
27 my $ffi = Git::Libgit2::FFI::ffi();
28 # git_remote_callbacks.update_tips:
29 # int (*)(const char *refname, const git_oid *a, const git_oid *b, void *data)
30 eval {
31 $ffi->type(
32 '(string, opaque, opaque, opaque)->int' => 'git_remote_update_tips_cb',
33 );
34 };
35 # git_remote_callbacks.push_update_reference:
36 # int (*)(const char *refname, const char *status, void *data)
37 eval {
38 $ffi->type(
39 '(string, string, opaque)->int' => 'git_push_update_reference_cb',
40 );
41 };
42 }
43  
44 # libgit2 1.5.x struct layouts (probed). 1.9.x add fields at the end of
45 # git_remote_callbacks but the offsets up through `payload` are stable, so the
46 # callback offsets below hold across releases. What does not hold is a field
47 # sitting *behind* the embedded callbacks struct -- it moves when the struct
48 # grows (120 bytes in 1.5, 128 in 1.9). git_fetch_options.prune is the one such
49 # field we write, so its offset comes from Git::Libgit2::fetch_options_prune_offset
50 # instead of from this block; a stale value here would land on `update_refs`,
51 # which libgit2 1.9 prefers over `update_tips` and calls.
52 # Allocate buffers a bit larger than the C struct for forward-compat.
53 use constant {
54 GIT_REMOTE_CALLBACKS_VERSION => 1,
55 GIT_FETCH_OPTIONS_VERSION => 1,
56 GIT_PUSH_OPTIONS_VERSION => 1,
57  
58 CALLBACKS_SIZE => 256, # actual 1.5: 120; 1.9: ~152
59 FETCH_OPTIONS_SIZE => 384, # actual 1.5: 208
60 PUSH_OPTIONS_SIZE => 384, # actual 1.5: 192
61  
62 # git_remote_callbacks field offsets (1.5.x layout, probed). Fields are
63 # 8-byte fn pointers; the only non-pointer field is `version` (uint32 at
64 # offset 0, padded 4 bytes to align the pointers at offset 8). `update_tips`
65 # and `push_update_reference` are at offsets 48 and 72 respectively; both
66 # sit well before payload (104) so the 256-byte allocation has plenty of
67 # headroom for newer libgit2 that adds more fields after payload.
68 CALLBACKS_CRED_OFFSET => 24, # credentials cb pointer
69 CALLBACKS_CERTCHECK_OFFSET => 32, # certificate_check cb pointer
70 CALLBACKS_UPDATE_TIPS_OFFSET => 48, # update_tips cb pointer
71 CALLBACKS_PUSH_UPDATE_REF_OFFSET => 72, # push_update_reference cb pointer
72 CALLBACKS_PAYLOAD_OFFSET => 104, # payload void*
73  
74 # git_cert_t (cert.cert_type @ offset 0)
75 GIT_CERT_X509 => 1,
76 GIT_CERT_HOSTKEY_LIBSSH2 => 2,
77  
78 # git_cert_ssh_t bits
79 GIT_CERT_SSH_SHA1 => 2,
80 GIT_CERT_SSH_SHA256 => 4,
81  
82 FETCH_OPTS_CALLBACKS_OFFSET => 8, # callbacks struct (embedded)
83  
84 PUSH_OPTS_CALLBACKS_OFFSET => 8,
85  
86 REMOTE_HEAD_NAME_OFFSET => 48,
87 REMOTE_HEAD_SIZE => 64,
88 PTR_SIZE => 8,
89 };
90  
91 has _handle => ( is => 'rw', required => 1 );
92 has _owner => ( is => 'ro', required => 1 ); # Repository
93  
94 sub url { Git::Libgit2::FFI::git_remote_url( $_[0]->_handle ) }
95 sub name { Git::Libgit2::FFI::git_remote_name( $_[0]->_handle ) }
96  
97 # ---------- fetch / push ----------
98  
99 # fetch(refspecs => [...], credentials => sub { ... }, prune => 0|1,
100 # reflog_message => '...')
101 #
102 # Returns a Git::Native::Remote::Result describing the per-ref outcomes.
103 # libgit2 returns 0 even when refs were skipped as non-fast-forward — the
104 # only way to learn about it is via the update_tips callback we install.
105 sub fetch {
106 my ( $self, %args ) = @_;
107 my $refspecs_ref = $args{refspecs};
108  
109 # The update_tips callback records each accepted local ref update.
110 my @updated;
111 my ( $tips_thunk, $tips_keep ) = _make_update_tips_thunk( \@updated );
112  
113 my ( $sa_ptr, $sa_keep ) = _build_strarray( $refspecs_ref );
114  
115 my ( $opts_ptr, $opts_keep ) = _build_fetch_options(
116 $args{credentials}, $args{prune}, $tips_thunk,
117 );
118  
119 my $rc = Git::Libgit2::FFI::git_remote_fetch(
120 $self->_handle, $sa_ptr, $opts_ptr,
121 $args{reflog_message} // 'fetch',
122 );
123 check_rc $rc;
124  
125 return Git::Native::Remote::Result->new( updated => \@updated );
126 }
127  
128 # push(refspecs => [...], credentials => sub { ... }, prune => 0|1)
129 #
130 # Returns a Git::Native::Remote::Result. libgit2 returns 0 even when the
131 # server rejected refs (pre-receive hook, protected ref, non-ff on a
132 # non-forced refspec); the push_update_reference callback carries the
133 # per-ref status the server sent.
134 sub push {
135 my ( $self, %args ) = @_;
136 my $original_refspecs = $args{refspecs} // [];
137 my $refspecs_ref = $self->_expand_push_refspecs($original_refspecs);
138  
139 # --prune: connect, list remote refs in our refspec's destination
140 # namespace, emit delete refspecs for the ones we don't have locally.
141 # Pass ORIGINAL refspecs (still containing wildcards) so we can
142 # recover the namespace pattern.
143 if ( $args{prune} && @$original_refspecs ) {
144 my @delete = $self->_compute_prune_deletes(
145 $original_refspecs, $args{credentials},
146 );
147 CORE::push @$refspecs_ref, @delete;
148 }
149  
150 # Per-ref outcomes from push_update_reference. status == NULL is success,
151 # status == "" is server-reported success with no message, status != ""
152 # is a rejection message. The callback only names the ref, so pair the
153 # expanded refspecs with the local oids they carry first — that is where
154 # an accepted entry's `to` comes from.
155 my @rejected;
156 my @updated;
157 my ( $push_thunk, $push_keep ) = _make_push_update_thunk(
158 \@rejected, \@updated, $self->_push_update_targets($refspecs_ref),
159 );
160  
161 my ( $sa_ptr, $sa_keep ) = _build_strarray( $refspecs_ref );
162  
163 my ( $opts_ptr, $opts_keep ) = _build_push_options(
164 $args{credentials}, $push_thunk,
165 );
166  
167 my $rc = Git::Libgit2::FFI::git_remote_push(
168 $self->_handle, $sa_ptr, $opts_ptr,
169 );
170 check_rc $rc;
171  
172 return Git::Native::Remote::Result->new(
173 updated => \@updated,
174 rejected => \@rejected,
175 );
176 }
177  
178 # List the remote-side refs (requires connecting first). Returns an
179 # arrayref of names. Caller passes credentials cb so private remotes work.
180 sub list_refs {
181 my ( $self, %args ) = @_;
182 $self->_connect( GIT_DIRECTION_FETCH, $args{credentials} );
183 my @names;
184 eval {
185 check_rc Git::Libgit2::FFI::git_remote_ls(
186 \my $heads_arr, \my $count, $self->_handle,
187 );
188 # heads_arr is git_remote_head**: an array of $count pointers,
189 # each pointing to a git_remote_head whose .name (char*) lives at
190 # offset REMOTE_HEAD_NAME_OFFSET.
191 my $ffi = Git::Libgit2::FFI::ffi();
192 for ( my $i = 0; $i < $count; $i++ ) {
193 my $head_ptr = unpack 'J',
194 _peek_bytes( $heads_arr + $i * PTR_SIZE, PTR_SIZE );
195 my $name_ptr = unpack 'J',
196 _peek_bytes( $head_ptr + REMOTE_HEAD_NAME_OFFSET, PTR_SIZE );
197 my $name = $ffi->cast( 'opaque' => 'string', $name_ptr );
198 CORE::push @names, $name;
199 }
200 };
201 my $err = $@;
202 Git::Libgit2::FFI::git_remote_disconnect( $self->_handle );
203 die $err if $err;
204 return \@names;
205 }
206  
207 sub _connect {
208 my ( $self, $direction, $cred_cb ) = @_;
209 # Build a callbacks struct on the stack-ish (Perl-owned buffer).
210 my $cb = "\0" x CALLBACKS_SIZE;
211 my ($cb_ptr) = scalar_to_buffer($cb);
212 check_rc Git::Libgit2::FFI::git_remote_init_callbacks(
213 $cb_ptr, GIT_REMOTE_CALLBACKS_VERSION,
214 );
215 my @keep = ( \$cb );
216 if ($cred_cb) {
217 my ( $thunk, $thunk_keep ) = _make_credential_thunk($cred_cb);
218 CORE::push @keep, $thunk_keep;
219 my $ptr_val = Git::Libgit2::FFI::ffi->cast(
220 'git_credential_acquire_cb' => 'opaque', $thunk,
221 );
222 my $pkt = pack 'J', $ptr_val;
223 my ($pkt_p) = scalar_to_buffer($pkt);
224 memcpy( $cb_ptr + CALLBACKS_CRED_OFFSET, $pkt_p, 8 );
225 CORE::push @keep, \$pkt;
226 }
227 _install_certcheck( $cb_ptr, 0, \@keep );
228 check_rc Git::Libgit2::FFI::git_remote_connect(
229 $self->_handle, $direction, $cb_ptr, 0, 0,
230 );
231 # Hold keepalive on $self so it survives until the next call frees it.
232 $self->{_connect_keep} = \@keep;
233 return $self;
234 }
235  
236 # Compute delete refspecs for `--prune`: for each `[+]src:dst` with `*`,
237 # list remote refs matching the dst pattern, and emit a delete for each
238 # one whose local counterpart no longer exists.
239 sub _compute_prune_deletes {
240 my ( $self, $refspecs, $cred_cb ) = @_;
241 my $remote_names = $self->list_refs( credentials => $cred_cb );
242 my %local;
243 $local{$_} = 1 for @{ $self->_owner->reference_names };
244  
245 my @deletes;
246 my %seen;
247 # Walk *original* user refspecs to figure out the dst-pattern namespace.
248 # We can't recover the dst-pattern from already-expanded specs.
249 for my $rs (@$refspecs) {
250 my ( $force, $src, $dst ) = $rs =~ /\A(\+?)([^:]+):(.+)\z/;
251 next unless defined $src && $dst =~ /\*/;
252 # Map remote ref → expected local name using dst→src.
253 my $dst_re = quotemeta($dst); $dst_re =~ s/\\\*/(.*)/;
254 $dst_re = qr/\A${dst_re}\z/;
255 my $src_template = $src;
256 for my $rname (@$remote_names) {
257 my ($cap) = $rname =~ $dst_re;
258 next unless defined $cap;
259 my $expected_local = $src_template;
260 $expected_local =~ s/\*/$cap/;
261 next if $local{$expected_local};
262 next if $seen{$rname}++;
263 CORE::push @deletes, ":${rname}";
264 }
265 }
266 return @deletes;
267 }
268  
269 # Read N bytes from a raw C address into a Perl scalar.
270 sub _peek_bytes {
271 my ( $addr, $len ) = @_;
272 my $buf = "\0" x $len;
273 my ($bp) = scalar_to_buffer($buf);
274 memcpy( $bp, $addr, $len );
275 return $buf;
276 }
277  
278 # libgit2 git_remote_push does NOT expand wildcard refspecs (unlike CLI
279 # git). We do it here: for each `+?src:dst` refspec containing `*`,
280 # enumerate matching local refs and emit one explicit refspec per ref.
281 sub _expand_push_refspecs {
282 my ( $self, $refspecs ) = @_;
283 $refspecs //= [];
284 my @out;
285 for my $rs (@$refspecs) {
286 my ( $force, $src, $dst ) = $rs =~ /\A(\+?)([^:]+):(.+)\z/;
287 if ( !defined $src || ( index( $src, '*' ) < 0 && index( $dst, '*' ) < 0 ) ) {
288 CORE::push @out, $rs;
289 next;
290 }
291 my $src_re = quotemeta($src);
292 $src_re =~ s/\\\*/(.*)/;
293 $src_re = qr/\A${src_re}\z/;
294  
295 my $names = $self->_owner->reference_names( glob => $src );
296 for my $name (@$names) {
297 my ($cap) = $name =~ $src_re;
298 next unless defined $cap;
299 my $expanded_dst = $dst;
300 $expanded_dst =~ s/\*/$cap/;
301 CORE::push @out, "${force}${name}:${expanded_dst}";
302 }
303 }
304 return \@out;
305 }
306  
307 # ---------- internals ----------
308  
309 # Build a git_strarray pointing into Perl-owned memory. Returns
310 # ($strarray_ptr, $keepalive_scalars_ref). Caller must hold
311 # $keepalive_scalars_ref alive across the C call.
312 sub _build_strarray {
313 my ($refspecs) = @_;
314 $refspecs //= [];
315 Carp::croak "_build_strarray: refspecs must be an arrayref"
316 if ref $refspecs ne 'ARRAY';
317 # Empty list → NULL strarray pointer, which libgit2 reads as
318 # "use configured refspecs from .git/config".
319 return ( 0, [] ) unless @$refspecs;
320  
321 # Copy each string so we have stable storage we control.
322 my @copies = map { "$_" } @$refspecs;
323 my @ptrs;
324 for my $s (@copies) {
325 my ($p) = scalar_to_buffer($s);
326 CORE::push @ptrs, $p;
327 }
328 my $strings_buf = pack 'J*', @ptrs;
329 my ($strings_ptr) = scalar_to_buffer($strings_buf);
330  
331 my $strarray = pack 'JJ', $strings_ptr, scalar(@copies);
332 my ($sa_ptr) = scalar_to_buffer($strarray);
333  
334 # Keep refs to every buffer that owns memory referenced from $strarray.
335 return ( $sa_ptr, [ \@copies, \$strings_buf, \$strarray ] );
336 }
337  
338 sub _build_fetch_options {
339 my ( $cred_cb, $prune, $update_tips_thunk ) = @_;
340  
341 my $opts = "\0" x FETCH_OPTIONS_SIZE;
342 my ($opts_ptr) = scalar_to_buffer($opts);
343 check_rc Git::Libgit2::FFI::git_fetch_options_init(
344 $opts_ptr, GIT_FETCH_OPTIONS_VERSION,
345 );
346  
347 my @keep = ( \$opts );
348  
349 if ($cred_cb) {
350 my ( $cb_thunk, $cb_keep ) = _make_credential_thunk($cred_cb);
351 CORE::push @keep, $cb_keep;
352  
353 # Write the closure's C pointer into callbacks.credentials.
354 my $cb_ptr_val = Git::Libgit2::FFI::ffi->cast(
355 'git_credential_acquire_cb' => 'opaque', $cb_thunk,
356 );
357 my $cb_buf = pack 'J', $cb_ptr_val;
358 my ($cb_buf_ptr) = scalar_to_buffer($cb_buf);
359 memcpy( $opts_ptr + FETCH_OPTS_CALLBACKS_OFFSET + CALLBACKS_CRED_OFFSET,
360 $cb_buf_ptr, 8 );
361 CORE::push @keep, \$cb_buf;
362 }
363  
364 _install_certcheck( $opts_ptr, FETCH_OPTS_CALLBACKS_OFFSET, \@keep );
365  
366 if ($update_tips_thunk) {
367 my $ptr_val = Git::Libgit2::FFI::ffi->cast(
368 'git_remote_update_tips_cb' => 'opaque', $update_tips_thunk,
369 );
370 my $buf = pack 'J', $ptr_val;
371 my ($bp) = scalar_to_buffer($buf);
372 memcpy( $opts_ptr + FETCH_OPTS_CALLBACKS_OFFSET
373 + CALLBACKS_UPDATE_TIPS_OFFSET, $bp, 8 );
374 CORE::push @keep, \$buf;
375 }
376  
377 if ( defined $prune ) {
378 my $val = $prune ? 1 : 2; # 1 = PRUNE, 2 = NO_PRUNE
379 my $pb = pack 'l', $val;
380 my ($pbp) = scalar_to_buffer($pb);
381 memcpy( $opts_ptr + fetch_options_prune_offset, $pbp, 4 );
382 CORE::push @keep, \$pb;
383 }
384  
385 return ( $opts_ptr, \@keep );
386 }
387  
388 sub _build_push_options {
389 my ( $cred_cb, $push_update_thunk ) = @_;
390  
391 my $opts = "\0" x PUSH_OPTIONS_SIZE;
392 my ($opts_ptr) = scalar_to_buffer($opts);
393 check_rc Git::Libgit2::FFI::git_push_options_init(
394 $opts_ptr, GIT_PUSH_OPTIONS_VERSION,
395 );
396  
397 my @keep = ( \$opts );
398  
399 if ($cred_cb) {
400 my ( $cb_thunk, $cb_keep ) = _make_credential_thunk($cred_cb);
401 CORE::push @keep, $cb_keep;
402  
403 my $cb_ptr_val = Git::Libgit2::FFI::ffi->cast(
404 'git_credential_acquire_cb' => 'opaque', $cb_thunk,
405 );
406 my $cb_buf = pack 'J', $cb_ptr_val;
407 my ($cb_buf_ptr) = scalar_to_buffer($cb_buf);
408 memcpy( $opts_ptr + PUSH_OPTS_CALLBACKS_OFFSET + CALLBACKS_CRED_OFFSET,
409 $cb_buf_ptr, 8 );
410 CORE::push @keep, \$cb_buf;
411 }
412  
413 _install_certcheck( $opts_ptr, PUSH_OPTS_CALLBACKS_OFFSET, \@keep );
414  
415 if ($push_update_thunk) {
416 my $ptr_val = Git::Libgit2::FFI::ffi->cast(
417 'git_push_update_reference_cb' => 'opaque', $push_update_thunk,
418 );
419 my $buf = pack 'J', $ptr_val;
420 my ($bp) = scalar_to_buffer($buf);
421 memcpy( $opts_ptr + PUSH_OPTS_CALLBACKS_OFFSET
422 + CALLBACKS_PUSH_UPDATE_REF_OFFSET, $bp, 8 );
423 CORE::push @keep, \$buf;
424 }
425  
426 return ( $opts_ptr, \@keep );
427 }
428  
429 # Wrap a user coderef so it conforms to git_credential_acquire_cb.
430 # Returns ($closure, $keepalive). The closure must outlive the C call —
431 # the keepalive bundle is what the Remote method holds onto.
432 #
433 # NOTHING in here may die: the closure is called from libgit2's C frames,
434 # and a Perl exception unwinding across them is undefined behaviour. Every
435 # failure mode reports via warn and returns a negative rc, which libgit2
436 # propagates out of git_remote_fetch/push for check_rc to throw properly.
437 sub _make_credential_thunk {
438 my ($user_cb) = @_;
439 my $ffi = Git::Libgit2::FFI::ffi();
440  
441 my $closure = $ffi->closure(sub {
442 my ( $out_ptr, $url, $username_from_url, $allowed_types, $payload ) = @_;
443 my $cred = eval {
444 $user_cb->(
445 url => $url,
446 username_from_url => $username_from_url,
447 allowed_types => $allowed_types,
448 );
449 };
450 if ($@) {
451 warn "credential callback died: $@";
452 return -1;
453 }
454 return GIT_PASSTHROUGH unless defined $cred;
455 unless ( Scalar::Util::blessed($cred)
456 && $cred->isa('Git::Native::Credential') ) {
457 warn "credentials callback must return a Git::Native::Credential "
458 . "or undef, got " . _describe_value($cred) . "\n";
459 return -1;
460 }
461  
462 # Disown the wrapper — libgit2 takes ownership on return 0.
463 my $cred_handle = $cred->_disown;
464  
465 # *out_ptr = cred_handle (write 8 bytes of pointer to the address
466 # the caller gave us)
467 my $pkt = pack 'J', $cred_handle;
468 my ($pkt_p) = scalar_to_buffer($pkt);
469 memcpy( $out_ptr, $pkt_p, 8 );
470  
471 return 0;
472 });
473  
474 # `sticky` would survive process-lifetime; we only need until the C
475 # call returns, so just hand the closure to the caller's keepalive.
476 return ( $closure, [ \$closure ] );
477 }
478  
479 # Name a value for a diagnostic without ever dying on it — a blessed object
480 # may carry an overloaded (and throwing) stringifier, so report its class
481 # instead of interpolating it. Only used from inside FFI closures, where a
482 # die is not survivable.
483 sub _describe_value {
484 my ($v) = @_;
485 if ( my $class = Scalar::Util::blessed($v) ) { return "a $class object" }
486 if ( my $type = ref $v ) { return "a $type reference" }
487 my $str = "$v";
488 $str = substr( $str, 0, 60 ) . '...' if length($str) > 63;
489 return "the non-reference value '$str'";
490 }
491  
492 # Build the update_tips closure (git_remote_callbacks.update_tips).
493 # Records each accepted ref update into the caller's $updated arrayref.
494 #
495 # int cb(const char *refname, const git_oid *a, const git_oid *b, void *data)
496 #
497 # a is the old local tip; libgit2 passes a non-NULL pointer even when the
498 # ref didn't exist locally (the bytes are zero-filled — a zero SHA-1).
499 # We translate the all-zero "no previous ref" case to from => undef so
500 # callers can tell new-ref from same-oid updates without a magic constant.
501 # b is the new local tip, and is the all-zero oid when the ref was DELETED
502 # rather than moved — that is how a `prune => 1` fetch reports the refs it
503 # dropped (probed against a file:// remote). Same treatment: to => undef,
504 # which is also what the push side reports for a delete refspec, so
505 # `!defined $_->{to}` means "this ref is gone" on both operations.
506 #
507 # `reason` is always the empty string here: update_tips only fires for
508 # updates libgit2 accepted, and there is no server verdict on a fetch at all.
509 # It exists so a fetch entry and a push entry carry the identical key set —
510 # see Git::Native::Remote::Result.
511 #
512 # Returns 0 on success — returning non-zero aborts the fetch, which is what
513 # we want if libgit2 handed us something we cannot record (a NULL new tip),
514 # because the Result would otherwise lie by omission. Like every FFI closure
515 # here it must not let a die escape into libgit2's C frames, so the body runs
516 # under eval and reports via warn.
517 sub _make_update_tips_thunk {
518 my ($updated) = @_;
519 my $ffi = Git::Libgit2::FFI::ffi();
520 my $closure = $ffi->closure(sub {
521 my ( $refname, $a_ptr, $b_ptr, $payload ) = @_;
522  
523 my $ok = eval {
524 die "update_tips callback got NULL b oid for ref '$refname'\n"
525 unless $b_ptr;
526 my $from = $a_ptr ? _oid_hex_if_nonzero($a_ptr) : undef;
527 my $to = _oid_hex_if_nonzero($b_ptr);
528 CORE::push @$updated, {
529 ref => $refname,
530 from => $from,
531 to => $to,
532 reason => '',
533 };
534 1;
535 };
536 if ( !$ok ) {
537 warn "Git::Native update_tips callback failed: $@";
538 return -1;
539 }
540 return 0;
541 });
542 return ( $closure, [ \$closure ] );
543 }
544  
545 # Read a 20-byte git_oid out of a raw pointer and return its hex form, or
546 # undef when the 20 raw bytes are all zero. libgit2 uses the zero oid as a
547 # sentinel on both sides of update_tips: as the old tip it means "the ref did
548 # not exist here before", as the new tip it means "the ref was deleted".
549 sub _oid_hex_if_nonzero {
550 my ($ptr) = @_;
551 my $raw = _peek_bytes($ptr, 20);
552 return undef if $raw eq "\0" x 20;
553 return oid_to_hex($ptr);
554 }
555  
556 # Build the push_update_reference closure (git_remote_callbacks.push_update_reference).
557 # Records each ref the server accepted (status NULL or "") into $updated and
558 # each rejected ref (status != NULL) into $rejected. status is the literal
559 # message from the server (e.g. "non-fast-forward", "pre-receive hook declined").
560 #
561 # int cb(const char *refname, const char *status, void *data)
562 #
563 # $targets is the destination-refname => oid-hex map from
564 # _push_update_targets, so an accepted push entry carries the same
565 # { ref, from, to, reason } key set a fetch entry does. `from` is always
566 # undef: the previous remote-side oid is only knowable through a
567 # git_remote_ls snapshot taken before the push, and paying for that extra
568 # round trip on every push would be worse than an honest undef.
569 sub _make_push_update_thunk {
570 my ( $rejected, $updated, $targets ) = @_;
571 $targets //= {};
572 my $ffi = Git::Libgit2::FFI::ffi();
573 my $closure = $ffi->closure(sub {
574 my ( $refname, $status, $payload ) = @_;
575 # libgit2 normalises "no rejection" to NULL on the way in; a server that
576 # sent an empty status string means the same thing.
577 if ( !defined $status || $status eq '' ) {
578 CORE::push @$updated, {
579 ref => $refname,
580 from => undef,
581 to => $targets->{$refname},
582 reason => '',
583 };
584 }
585 else {
586 CORE::push @$rejected, { ref => $refname, reason => $status };
587 }
588 return 0;
589 });
590 return ( $closure, [ \$closure ] );
591 }
592  
593 # Map each expanded push refspec's destination refname to the oid the push
594 # puts there, so a push update can report `to` the way a fetch update does.
595 # push_update_reference only hands us a per-ref verdict, but the source side
596 # of the refspec is a local ref we can just look up — no extra network.
597 #
598 # The value is undef for a delete refspec (`:refs/x`, which is what
599 # `prune => 1` emits) — matching the deleted-ref convention on the fetch
600 # side — and also undef for a source that is not a local reference (a raw
601 # oid, a shorthand, a ref that vanished between expansion and push).
602 sub _push_update_targets {
603 my ( $self, $refspecs ) = @_;
604 my %target;
605 for my $rs (@$refspecs) {
606 my ( $src, $dst );
607 if ( index( $rs, ':' ) >= 0 ) {
608 ( $src, $dst ) = $rs =~ /\A\+?([^:]*):(.*)\z/;
609 }
610 else {
611 # A refspec without a colon pushes the source to the same name.
612 ($src) = $rs =~ /\A\+?(.*)\z/;
613 $dst = $src;
614 }
615 next unless defined $dst && length $dst;
616 $target{$dst} = ( defined $src && length $src )
617 ? $self->_local_oid_hex($src)
618 : undef;
619 }
620 return \%target;
621 }
622  
623 # Hex oid a local refname points at, or undef if it does not resolve to
624 # one. Goes through resolve so a symbolic source (`HEAD:refs/heads/main`)
625 # reports the oid it points at rather than nothing. Never dies: an
626 # unresolvable push source is a missing `to`, not a failed push.
627 sub _local_oid_hex {
628 my ( $self, $refname ) = @_;
629 my $oid = eval { $self->_owner->reference($refname)->resolve->target };
630 return undef unless $oid;
631 return $oid->hex;
632 }
633  
634 # ---------- host-key verification (certificate_check callback) ----------
635  
636 # Write a certificate_check closure into a callbacks struct. $cb_base is the
637 # offset of the embedded git_remote_callbacks within $struct_ptr (0 for a
638 # bare callbacks struct, 8 for fetch/push options). Pushes keepalives.
639 #
640 # libgit2 1.5.x + libssh2 has NO built-in known_hosts checking (that landed in
641 # 1.7). Without a certificate_check callback the ssh transport rejects every
642 # host with GIT_ECERTIFICATE (-17) "invalid or unknown remote ssh hostkey".
643 # So we always install one and verify the hostkey against ~/.ssh/known_hosts
644 # ourselves, mirroring what the `git` CLI does via OpenSSH.
645 sub _install_certcheck {
646 my ( $struct_ptr, $cb_base, $keep ) = @_;
647 my ( $thunk, $thunk_keep ) = _make_certcheck_thunk();
648 CORE::push @$keep, @$thunk_keep;
649 my $ptr_val = Git::Libgit2::FFI::ffi->cast(
650 'git_transport_certificate_check_cb' => 'opaque', $thunk,
651 );
652 my $buf = pack 'J', $ptr_val;
653 my ($bp) = scalar_to_buffer($buf);
654 memcpy( $struct_ptr + $cb_base + CALLBACKS_CERTCHECK_OFFSET, $bp, 8 );
655 CORE::push @$keep, \$buf;
656 return;
657 }
658  
659 # Build the certificate_check closure. Returns ($closure, $keepalive).
660 #
661 # int cb(git_cert *cert, int valid, const char *host, void *payload)
662 #
663 # Return 0 to accept, <0 to reject (libgit2 aborts the connection with that
664 # code). For TLS (git_cert_x509) we honour libgit2's own `valid` flag so HTTPS
665 # remotes keep their normal CA validation. For SSH (git_cert_hostkey) we verify
666 # against known_hosts unless GIT_NATIVE_SSH_INSECURE is set (accept-all).
667 sub _make_certcheck_thunk {
668 my $ffi = Git::Libgit2::FFI::ffi();
669 my $closure = $ffi->closure(sub {
670 my ( $cert_ptr, $valid, $host, $payload ) = @_;
671 my $ok = eval {
672 my $cert_type = unpack 'l', _peek_bytes( $cert_ptr, 4 );
673 return $valid ? 1 : 0 if $cert_type == GIT_CERT_X509;
674 if ( $cert_type == GIT_CERT_HOSTKEY_LIBSSH2 ) {
675 return 1 if $ENV{GIT_NATIVE_SSH_INSECURE};
676 return _verify_known_host( $cert_ptr, $host );
677 }
678 # Unknown cert kind — fall back to libgit2's own verdict.
679 return $valid ? 1 : 0;
680 };
681 if ($@) {
682 warn "Git::Native certificate check died: $@";
683 return -1;
684 }
685 return $ok ? 0 : -1;
686 });
687 return ( $closure, [ \$closure ] );
688 }
689  
690 # Verify an ssh hostkey against known_hosts using the SHA256 (preferred) or
691 # SHA1 fingerprint libssh2 computed for the negotiated key. Returns 1 on a
692 # match, 0 otherwise (with an actionable warning).
693 sub _verify_known_host {
694 my ( $cert_ptr, $host ) = @_;
695 # The git_cert_hostkey field offsets come from Git::Libgit2 (derived from
696 # the ABI, karr #30); t/75-cert-hostkey-layout.t cross-checks them against
697 # offsetof() wherever a C compiler is available.
698 my %off = cert_hostkey_offsets();
699 my $bits = unpack 'l', _peek_bytes( $cert_ptr + $off{type}, 4 );
700  
701 my ( $digest, $want );
702 if ( $bits & GIT_CERT_SSH_SHA256 ) {
703 $digest = 'sha256';
704 $want = _peek_bytes( $cert_ptr + $off{sha256}, 32 );
705 }
706 elsif ( $bits & GIT_CERT_SSH_SHA1 ) {
707 $digest = 'sha1';
708 $want = _peek_bytes( $cert_ptr + $off{sha1}, 20 );
709 }
710 else {
711 warn "Git::Native: ssh hostkey for '$host' offers no SHA1/SHA256 "
712 . "fingerprint to verify; rejecting\n";
713 return 0;
714 }
715  
716 my ( $matched, $host_seen ) = _known_hosts_match( $host, $digest, $want );
717 return 1 if $matched;
718  
719 if ($host_seen) {
720 warn "Git::Native: ssh hostkey for '$host' did NOT match the "
721 . "$host_seen known_hosts entr" . ( $host_seen == 1 ? 'y' : 'ies' )
722 . " for it — server offered a key type you have not cached, or the "
723 . "key changed. Run `ssh-keyscan $host >> ~/.ssh/known_hosts`, or set "
724 . "GIT_NATIVE_SSH_INSECURE=1 to bypass.\n";
725 }
726 else {
727 warn "Git::Native: ssh host '$host' is not in known_hosts. Run "
728 . "`ssh-keyscan $host >> ~/.ssh/known_hosts`, or set "
729 . "GIT_NATIVE_SSH_INSECURE=1 to bypass.\n";
730 }
731 return 0;
732 }
733  
734 # Scan the known_hosts files for $host and compare the cached key's digest to
735 # $want. Returns (matched, host_line_count): host_line_count distinguishes
736 # "host unknown" from "host known but key mismatch".
737 sub _known_hosts_match {
738 my ( $host, $digest, $want ) = @_;
739 my $host_seen = 0;
740 for my $file (
741 "$ENV{HOME}/.ssh/known_hosts",
742 "$ENV{HOME}/.ssh/known_hosts2",
743 '/etc/ssh/ssh_known_hosts',
744 ) {
745 next unless -r $file;
746 open my $fh, '<', $file or next;
747 while ( my $line = <$fh> ) {
748 $line =~ s/\A\s+//;
749 next if $line eq '' || $line =~ /\A[#\r\n]/;
750 my @parts = split ' ', $line;
751 my $marker = ( @parts && $parts[0] =~ /\A\@/ ) ? shift @parts : '';
752 next if @parts < 3;
753 next if $marker eq '@cert-authority' || $marker eq '@revoked';
754 my ( $hosts, undef, $key64 ) = @parts;
755 next unless _host_in_field( $host, $hosts );
756 $host_seen++;
757 my $blob = decode_base64($key64);
758 next unless length $blob;
759 my $got = $digest eq 'sha256' ? sha256($blob) : sha1($blob);
760 return ( 1, $host_seen ) if $got eq $want;
761 }
762 close $fh;
763 }
764 return ( 0, $host_seen );
765 }
766  
767 # Does $host match a known_hosts host field? Handles hashed (|1|salt|hash via
768 # HMAC-SHA1), plain comma lists, [host]:port, and * / ? wildcards.
769 sub _host_in_field {
770 my ( $host, $field ) = @_;
771 if ( $field =~ /\A\|1\|([^|]+)\|(.+)\z/ ) {
772 my ( $salt64, $hash64 ) = ( $1, $2 );
773 my $got = encode_base64( hmac_sha1( $host, decode_base64($salt64) ), '' );
774 return $got eq $hash64;
775 }
776 for my $pat ( split /,/, $field ) {
777 next if $pat eq '';
778 $pat = $1 if $pat =~ /\A\[([^\]]+)\](?::\d+)?\z/;
779 return 1 if lc $pat eq lc $host;
780 if ( $pat =~ /[*?]/ ) {
781 my $re = quotemeta $pat;
782 $re =~ s/\\\*/.*/g;
783 $re =~ s/\\\?/./g;
784 return 1 if $host =~ /\A$re\z/i;
785 }
786 }
787 return 0;
788 }
789  
790 sub DEMOLISH {
791 my $self = shift;
792 if ( my $h = $self->{_handle} ) {
793 Git::Libgit2::FFI::git_remote_free($h);
794 }
795 }
796  
797 1;
798  
799 __END__
« Native.pm ↑ Summary