31#include <wx/translation.h>
70 int refuseAuthentication(
STATE& aState )
74 git_error_set_str( GIT_ERROR_NET,
_(
"Unable to authenticate" ).mbc_str() );
75 aState.handler->SetAuthFailure();
82 extern "C" int probeSignCb( LIBSSH2_SESSION*,
unsigned char**,
size_t*,
const unsigned char*,
size_t,
85 if( !aAbstract || !*aAbstract )
102 int offerSSHKey(
STATE& aState, git_credential** aOut,
const wxString& aUsername )
104 KIGIT_AUTH_ATTEMPT& attempt = aState.handler->AuthAttempt();
105 KIGIT_COMMON* common = aState.Common();
107 if( !aState.agentTried )
109 aState.agentTried =
true;
111 if( git_credential_ssh_key_from_agent( aOut, aUsername.mbc_str() ) == GIT_OK )
120 if( !attempt.
probing.IsEmpty() )
129 if( sshKey.IsEmpty() )
131 wxLogTrace(
traceGit,
"Finished testing all possible ssh keys" );
132 aState.tested |= GIT_CREDENTIAL_SSH_KEY;
133 return GIT_PASSTHROUGH;
143 && git_credential_ssh_custom_new( aOut, aUsername.mbc_str(), blob.data(), blob.size(), probeSignCb,
147 wxLogTrace(
traceGit,
"Asking whether the server takes %s", sshKey );
157 wxLogTrace(
traceGit,
"Testing %s\n", sshKey );
159 if( git_credential_ssh_key_new( aOut, aUsername.mbc_str(), sshPubKey.mbc_str(), sshKey.mbc_str(),
163 wxLogTrace(
traceGit,
"Failed to create SSH key credential for %s: %s", sshKey,
165 return GIT_PASSTHROUGH;
176 extern "C" int credentialsCb( git_credential** aOut,
const char* aUrl,
const char* aUsername,
177 unsigned int aAllowedTypes,
void* aPayload )
179 STATE& state = *
static_cast<STATE*
>( aPayload );
180 KIGIT_REPO_MIXIN* handler = state.handler;
183 state.Common()->SyncRemoteUrl( wxString::FromUTF8( aUrl ) );
188 wxLogTrace(
traceGit,
"Credentials callback for %s, testing %d", safeUrl, aAllowedTypes );
194 wxLogTrace(
traceGit,
"Local repository, no credentials needed" );
195 return GIT_PASSTHROUGH;
198 if( ( aAllowedTypes & GIT_CREDENTIAL_USERNAME ) && !( state.tested & GIT_CREDENTIAL_USERNAME ) )
200 wxString username = handler->
GetUsername().Trim().Trim(
false );
203 wxLogTrace(
traceGit,
"Username credential at %s with allowed type %d", safeUrl, aAllowedTypes );
206 if( username.IsEmpty() )
207 return refuseAuthentication( state );
209 if(
int rc = git_credential_username_new( aOut, username.ToStdString().c_str() ); rc != GIT_OK )
215 state.tested |= GIT_CREDENTIAL_USERNAME;
220 && ( aAllowedTypes & GIT_CREDENTIAL_USERPASS_PLAINTEXT )
221 && !( state.tested & GIT_CREDENTIAL_USERPASS_PLAINTEXT ) && !handler->
GetUsername().IsEmpty() )
223 wxLogTrace(
traceGit,
"Plaintext authentication at %s with allowed type %d", safeUrl, aAllowedTypes );
225 wxString password = state.Common()->GetPassword();
226 int rc = git_credential_userpass_plaintext_new( aOut, handler->
GetUsername().mbc_str(), password.mbc_str() );
228 state.tested |= GIT_CREDENTIAL_USERPASS_PLAINTEXT;
234 && ( aAllowedTypes & GIT_CREDENTIAL_SSH_KEY ) && !( state.tested & GIT_CREDENTIAL_SSH_KEY ) )
237 wxString sshUser = ( aUsername && *aUsername ) ? wxString::FromUTF8( aUsername ) : handler->
GetUsername();
239 int result = offerSSHKey( state, aOut, sshUser );
241 if(
result == GIT_PASSTHROUGH )
242 return refuseAuthentication( state );
247 return refuseAuthentication( state );
251 extern "C" int certificateCb( git_cert* aCert,
int aValid,
const char* aHost,
void* aPayload )
253 if( !aCert || !aHost || !aPayload || aCert->cert_type != GIT_CERT_HOSTKEY_LIBSSH2 )
254 return GIT_PASSTHROUGH;
256 const git_cert_hostkey* cert =
reinterpret_cast<const git_cert_hostkey*
>( aCert );
257 STATE& state = *
static_cast<STATE*
>( aPayload );
258 KIGIT_REPO_MIXIN* handler = state.handler;
260 auto refuse = [&](
const wxString& aReason )
264 return GIT_ECERTIFICATE;
268 auto refuseUnreadable = [&]()
270 wxLogTrace(
traceGit,
"Host key from %s cannot be read, refusing it", aHost );
271 return refuse( wxString::Format(
_(
"KiCad could not read the key %s presented, so the connection was "
272 "not made. Ask your administrator which host key the server uses." ),
273 wxString::FromUTF8( aHost ) ) );
276 if( !( cert->type & GIT_CERT_SSH_RAW ) || !cert->hostkey || cert->hostkey_len == 0 )
277 return refuseUnreadable();
280 key.
rawKey.assign( cert->hostkey, cert->hostkey_len );
281 key.host = wxString::FromUTF8( aHost );
284 if( key.host.StartsWith( wxS(
"[" ) ) && key.host.EndsWith( wxS(
"]" ) ) )
285 key.host = key.host.Mid( 1, key.host.length() - 2 );
287 key.port = state.Common()->SSHPortFor( key.host );
292 wxLogTrace(
traceGit,
"Host %s does not match the synced remote, refusing its key", key.host );
293 return refuse( wxString::Format(
_(
"The address of %s could not be matched to the remote, so its key "
294 "was not checked. Check the remote URL." ),
301 if( key.keyType.IsEmpty() )
302 return refuseUnreadable();
306 wxLogTrace(
traceGit,
"Host key %s SHA256:%s for %s port %d, known_hosts state %d, libgit2 valid %d",
307 key.keyType, key.fingerprint, key.host, key.port,
static_cast<int>( key.state ), aValid );
314 return GIT_ECERTIFICATE;
318 extern "C" int sidebandCb(
const char* aData,
int aLength,
void* aPayload )
320 STATE& state = *
static_cast<STATE*
>( aPayload );
322 if( state.handler->IsThisOperationCancelled() )
324 wxLogTrace(
traceGit,
"Progress CB cancelled" );
328 state.handler->ReceiveSideband( aData, aLength );
333 extern "C" int transferCb(
const git_transfer_progress* aStats,
void* aPayload )
335 STATE& state = *
static_cast<STATE*
>( aPayload );
337 if( state.handler->IsThisOperationCancelled() )
339 wxLogTrace(
traceGit,
"Transfer progress cancelled" );
343 state.handler->UpdateProgress( aStats->received_objects, aStats->total_objects,
344 wxString::Format(
_(
"Received %u of %u objects" ), aStats->received_objects,
345 aStats->total_objects ) );
350 extern "C" int updateTipsCb(
const char* aRefname,
const git_oid* aFirst,
const git_oid* aSecond,
353 constexpr int cstring_len = 8;
354 char a_str[cstring_len + 1];
355 char b_str[cstring_len + 1];
357 STATE& state = *
static_cast<STATE*
>( aPayload );
360 git_oid_tostr( b_str, cstring_len, aSecond );
362#if ( LIBGIT2_VER_MAJOR >= 1 ) || ( LIBGIT2_VER_MINOR >= 99 )
363 if( !git_oid_is_zero( aFirst ) )
365 if( !git_oid_iszero( aFirst ) )
368 git_oid_tostr( a_str, cstring_len, aFirst );
369 status = wxString::Format(
_(
"* [updated] %s..%s %s" ), a_str, b_str, aRefname );
373 status = wxString::Format(
_(
"* [new] %s %s" ), b_str, aRefname );
376 state.handler->UpdateProgress( 0, 0, status );
381 extern "C" int pushTransferCb(
unsigned int aCurrent,
unsigned int aTotal,
size_t aBytes,
void* aPayload )
383 STATE& state = *
static_cast<STATE*
>( aPayload );
385 if( state.handler->IsThisOperationCancelled() )
387 wxLogTrace(
traceGit,
"Push progress cancelled" );
391 long long progress = aTotal ? ( aCurrent * 100ll ) / aTotal : 100;
393 state.handler->UpdateProgress( aCurrent, aTotal,
394 wxString::Format(
_(
"Writing objects: %lld%% (%u/%u), %zu bytes" ), progress,
395 aCurrent, aTotal, aBytes ) );
400 extern "C" int pushUpdateReferenceCb(
const char* aRefname,
const char* aStatus,
void* aPayload )
402 STATE& state = *
static_cast<STATE*
>( aPayload );
404 if( !aStatus || !*aStatus )
406 state.handler->UpdateProgress( 0, 0, wxString::Format(
_(
"[updated] %s" ), aRefname ) );
412 state.handler->SetPushRefusal( wxString::Format( wxS(
"%s: %s" ), aRefname, status ) );
413 state.handler->UpdateProgress( 0, 0, wxString::Format(
_(
"* [rejected] %s (%s)" ), aRefname,
417 git_error_set_str( GIT_ERROR_NET, aStatus );
422 extern "C" void checkoutCb(
const char* aPath,
size_t aDone,
size_t aTotal,
void* aPayload )
424 STATE& state = *
static_cast<STATE*
>( aPayload );
426 state.handler->UpdateProgress( aDone, aTotal, wxString( aPath ) );
432 extern "C" int cloneRemoteCb( git_remote** aOut,
git_repository* aRepo,
const char* aName,
const char* aUrl,
435 if(
int rc = git_remote_create( aOut, aRepo, aName, aUrl ); rc != GIT_OK )
438 if(
const char* url = git_remote_url( *aOut ) )
439 static_cast<STATE*
>( aPayload )->Common()->FollowRewrittenUrl( wxString::FromUTF8( url ) );
445 git_remote_callbacks callbacksFor(
STATE& aState )
447 git_remote_callbacks callbacks;
448 git_remote_init_callbacks( &callbacks, GIT_REMOTE_CALLBACKS_VERSION );
449 callbacks.credentials = credentialsCb;
450 callbacks.certificate_check = certificateCb;
451 callbacks.sideband_progress = sidebandCb;
452 callbacks.transfer_progress = transferCb;
453 callbacks.update_tips = updateTipsCb;
454 callbacks.push_transfer_progress = pushTransferCb;
455 callbacks.push_update_reference = pushUpdateReferenceCb;
456 callbacks.payload = &aState;
462 git_proxy_options autoProxy()
464 git_proxy_options proxy;
465 git_proxy_init_options( &proxy, GIT_PROXY_OPTIONS_VERSION );
466 proxy.type = GIT_PROXY_AUTO;
487#if LIBGIT2_VER_MAJOR > 1 || ( LIBGIT2_VER_MAJOR == 1 && LIBGIT2_VER_MINOR >= 4 )
488 git_remote_connect_options options;
489 git_remote_connect_options_init( &options, GIT_REMOTE_CONNECT_OPTIONS_VERSION );
490 options.callbacks = aCallbacks;
491 options.proxy_opts = autoProxy();
495 options.follow_redirects = GIT_REMOTE_REDIRECT_NONE;
497 if(
int rc = git_remote_connect_ext(
m_remote, aDirection, &options ) )
501 git_proxy_options proxy = autoProxy();
503 if(
int rc = git_remote_connect(
m_remote, aDirection, &aCallbacks, &proxy,
nullptr ) )
508 m_state->handler->RememberWorkingSSHKey();
517 git_fetch_options options;
518 git_fetch_init_options( &options, GIT_FETCH_OPTIONS_VERSION );
519 options.callbacks = callbacksFor( *
m_state );
520 options.proxy_opts = autoProxy();
522 if(
int rc =
connect( GIT_DIRECTION_FETCH, options.callbacks ) )
525 const git_remote_head** heads =
nullptr;
529 if( aBranches && git_remote_ls( &heads, &count,
m_remote ) == GIT_OK )
531 for(
size_t ii = 0; ii < count; ++ii )
533 if( std::strncmp( heads[ii]->
name,
"refs/heads/", 11 ) == 0 )
534 aBranches->push_back( wxString::FromUTF8( heads[ii]->
name + 11 ) );
538 int rc = git_remote_fetch(
m_remote,
nullptr, &options,
nullptr );
552 git_push_options options;
553 git_push_init_options( &options, GIT_PUSH_OPTIONS_VERSION );
554 options.callbacks = callbacksFor( *
m_state );
555 options.proxy_opts = autoProxy();
557#if LIBGIT2_VER_MAJOR > 1 || ( LIBGIT2_VER_MAJOR == 1 && LIBGIT2_VER_MINOR >= 4 )
559 options.follow_redirects = GIT_REMOTE_REDIRECT_NONE;
562 if(
int rc =
connect( GIT_DIRECTION_PUSH, options.callbacks ) )
565 wxString refspec = aConnected();
567 if( refspec.IsEmpty() )
573 std::string refspecUtf8 = refspec.utf8_string();
574 const char* refs[1] = { refspecUtf8.c_str() };
575 const git_strarray refspecs = {
const_cast<char**
>( refs ), 1 };
578 int rc = git_remote_push(
m_remote, &refspecs, &options );
592 if(
int rc =
connect( GIT_DIRECTION_FETCH, callbacksFor( *
m_state ) ) )
604 git_clone_options options;
605 git_clone_init_options( &options, GIT_CLONE_OPTIONS_VERSION );
606 options.checkout_opts.checkout_strategy = GIT_CHECKOUT_SAFE;
607 options.checkout_opts.progress_cb = checkoutCb;
608 options.checkout_opts.progress_payload =
m_state.get();
609 options.fetch_opts.callbacks = callbacksFor( *
m_state );
610 options.fetch_opts.proxy_opts = autoProxy();
611 options.remote_cb = cloneRemoteCb;
612 options.remote_cb_payload =
m_state.get();
614 std::string urlUtf8 = aUrl.utf8_string();
616 if(
int rc = git_clone( aRepo, urlUtf8.c_str(), aPath.mbc_str(), &options ) )
619 m_state->handler->RememberWorkingSSHKey();
std::unique_ptr< STATE > m_state
const KIGIT_ERROR_INFO & Error() const
libgit2's error for the last call that failed, read before anything else could replace it
REMOTE_TRANSPORT(KIGIT_REPO_MIXIN *aHandler, git_remote *aRemote=nullptr, bool aFollowRedirects=true)
aHandler supplies the session and records progress, the credentials offered and why a call failed.
int Fetch(std::vector< wxString > *aBranches=nullptr)
Fetch as git fetch would. aBranches, when given, receives the branches the remote advertised.
int Check()
Connect, which proves the credentials and the host key without transferring anything.
int Clone(const wxString &aUrl, const wxString &aPath, git_repository **aRepo)
Clone aUrl into aPath. The new repository is returned in aRepo for the caller to free.
int Push(const std::function< wxString()> &aConnected)
Connect, then push the refspec aConnected answers, so the caller can check what it pushes after a con...
int connect(git_direction aDirection, const git_remote_callbacks &aCallbacks)
The project's git session.
static KIGIT_ERROR_INFO GetLastGitErrorInfo(int aCode)
The error libgit2 holds for a call that returned aCode.
wxString GetNextPublicKey()
By value, so the caller never holds a pointer into the vector.
static wxString GetLastGitError()
libgit2's last message, without credentials from any URL it quotes, so it is safe to show or trace.
wxString GetPassword()
The secret for the remote, read without ever prompting, so it is safe on a transfer worker.
void SetHostKeyRefusal(const wxString &aReason)
wxString GetUsername() const
Get the username.
KIGIT_AUTH_ATTEMPT & AuthAttempt()
void SetHostKeyFailure(const KIGIT::HOST_KEY_FAILURE &aFailure)
KIGIT_COMMON::GIT_CONN_TYPE GetConnType() const
Get the connection type.
const wxChar *const traceGit
Flag to enable Git debugging output.
The one place a fetch, push, clone or connection check reaches a remote.
bool IsPrivateKeyFileEncrypted(const wxString &aKey)
IsPrivateKeyEncrypted for the key file aKey. A file that cannot be read is reported as unencrypted.
APIEXPORT wxString StripEmbeddedUserinfo(const wxString &aText)
Remove the user and password from every URL quoted in a message, since the remote's can carry a passw...
APIEXPORT wxString PrintableServerText(const wxString &aText)
Text a server sent, made safe to show: no terminal escapes, control or bidi characters,...
@ MATCH
An entry names the host with this key.
APIEXPORT wxString PublicKeyPath(const wxString &aKey)
The public key file to offer with aKey.
APIEXPORT KNOWN_HOST_STATE LookupKnownHost(const wxString &aKnownHostsText, const wxString &aHost, int aPort, const wxString &aKeyType, const std::string &aRawKey)
Classify a server's key against the text of a known_hosts file, as OpenSSH reads it.
APIEXPORT wxString DecodeServerText(const char *aData, size_t aLength)
Bytes a server sent, as UTF-8 or, when they are not valid UTF-8, one character for each byte.
APIEXPORT wxString ReadKnownHosts()
The text of KnownHostsPath(). Empty when it is missing or cannot be read.
APIEXPORT wxString HostKeyType(const std::string &aRawKey)
The type a raw SSH key names for itself, such as ssh-ed25519. Empty when the key is malformed.
APIEXPORT wxString HostKeyFingerprint(const std::string &aRawKey)
SHA256 of a raw key in unpadded base64, as ssh shows it after "SHA256:".
APIEXPORT std::string PublicKeyBlob(const wxString &aKey)
The public key blob from aKey's public key file, as the server sees it, or empty when it cannot be re...
A server key the connection refused, for the UI to offer to trust or to report.
std::string rawKey
The key as the server sent it.
KIGIT_REPO_MIXIN * handler
KIGIT_COMMON * Common() const
void Begin()
Every call offers every credential again and keeps nothing from an earlier failure.
unsigned tested
The git_credential_t kinds this call has offered.
What the credential callback handed out during one operation, kept to explain a rejection.
bool lastKeyRefused
The server refused the last key's public half.
wxString probing
The encrypted key whose public half is out to the server now.
bool passwordGiven
A password went with the last username offered.
KIGIT_COMMON::GIT_CONN_TYPE connType
wxString acceptedKey
An encrypted key whose public half the server accepted.
std::vector< wxString > keysTried
Key files offered, in order.
bool agentTried
The SSH agent was offered before any key file.
bool passphraseGiven
A passphrase went with the last key file offered.
What libgit2 reported for a failed call, read before anything else can replace it.
wxString result
Test unit parsing edge cases and error handling.
wxLogTrace helper definitions.
VIA_CROSS_SECTION_GEOMETRY::STATE STATE