KiCad PCB EDA Suite
Loading...
Searching...
No Matches
dialog_git_repository.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright The KiCad Developers, see AUTHORS.TXT for contributors.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 3
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
21#include <confirm.h>
23
24#include <git2.h>
27#include <git/kigit_ssh_keys.h>
28#include <git/git_repo_mixin.h>
29#include <gestfich.h>
30
31#include <cerrno>
32#include <cstring>
33#include <fstream>
34
35#include <wx/clipbrd.h>
36#include <wx/msgdlg.h>
37#include <wx/regex.h>
38#include <wx/stdpaths.h>
39
40
41DIALOG_GIT_REPOSITORY::DIALOG_GIT_REPOSITORY( wxWindow* aParent, git_repository* aRepository, wxString aURL ) :
43 m_repository( aRepository ),
44 m_incomeURL( aURL ),
45 m_tempRepo( false )
46{
47 OptOut( this );
48
49 m_txtURL->SetFocus();
50
51 if( !m_repository )
52 {
53 // Make a temporary repository to test the connection
54 m_tempRepo = true;
55 m_tempPath = wxFileName::CreateTempFileName( "kicadtestrepo" );
56
57 // CreateTempFileName leaves a file at the path, where git cannot make a repository
58 wxRemoveFile( m_tempPath );
59
60 git_repository_init_options options;
61 git_repository_init_init_options( &options, GIT_REPOSITORY_INIT_OPTIONS_VERSION );
62 options.flags = GIT_REPOSITORY_INIT_MKPATH | GIT_REPOSITORY_INIT_NO_REINIT;
63 git_repository_init_ext( &m_repository, m_tempPath.ToStdString().c_str(), &options );
64 }
65
66 // Otherwise the picker opens wherever the last file dialog was, far from any key
67 m_fpSSHKey->SetInitialDirectory( KIGIT::SSHKeyFolder() );
68
69 SetupStandardButtons( { { wxID_HELP, _( "Test Connection" ) } } );
70 Layout();
72
73 m_txtURL->Bind( wxEVT_TEXT,
74 [this]( wxCommandEvent& aEvent )
75 {
78 aEvent.Skip();
79 } );
80}
81
82
84{
85 if( m_tempRepo )
86 {
87 git_repository_free( m_repository );
89 }
90}
91
92
94{
95 wxClipboardLocker lock;
96 if( !lock )
97 return false;
98
99 if( !wxTheClipboard->IsSupported( wxDF_TEXT ) )
100 return false;
101
102 wxTextDataObject textData;
103 if( !wxTheClipboard->GetData( textData ) )
104 return false;
105
106 wxString clipboardText = textData.GetText();
107 if( clipboardText.empty() )
108 return false;
109
111
112 if( parsed.connType != KIGIT_COMMON::GIT_CONN_TYPE::GIT_CONN_LOCAL && !parsed.hostname.IsEmpty()
113 && clipboardText.find_first_of( " \t\r\n" ) == wxString::npos )
114 {
115 m_txtURL->SetValue( clipboardText );
116 return true;
117 }
118
119 return false;
120}
121
122
123void DIALOG_GIT_REPOSITORY::setDefaultSSHKey( const wxString& aHost )
124{
125 std::vector<wxString> keys =
127
128 if( keys.empty() )
129 return;
130
131 // Unticked greys out the picker and passphrase, hiding the key the connection will use
132 m_cbCustom->SetValue( true );
133 m_fpSSHKey->SetFileName( keys.front() );
134
135 wxFileDirPickerEvent evt;
136 evt.SetPath( keys.front() );
137 OnFileUpdated( evt );
138}
139
140
141void DIALOG_GIT_REPOSITORY::onCbCustom( wxCommandEvent& event )
142{
144 event.Skip();
145}
146
147
148void DIALOG_GIT_REPOSITORY::OnUpdateUI( wxUpdateUIEvent& event )
149{
150 // event.Enable( !m_txtName->GetValue().IsEmpty() && !m_txtURL->GetValue().IsEmpty() );
151}
152
153
155{
156 if( aEncrypted )
157 {
158 m_txtPassword->Enable();
159 m_txtPassword->SetToolTip( _( "Enter the password for the SSH key" ) );
160 }
161 else
162 {
163 m_txtPassword->SetValue( wxEmptyString );
164 m_txtPassword->SetToolTip( wxEmptyString );
165 m_txtPassword->Disable();
166 }
167}
168
169
170static wxString get_repo_name( const wxString& aRepoAddr )
171{
172 wxString addr = aRepoAddr;
173
174 // Strip GitHub/GitLab web-UI path suffixes so that pasting a browser URL
175 // (e.g. .../repo/tree/master, .../repo/blob/main/README.md, .../repo/pulls)
176 // still gives the repository name rather than a branch/page name.
177 static wxRegEx webSuffix(
178 R"((/-)?/(tree|blob|commits?|raw|releases|tags|branches|pulls|pull|issues|merge_requests|wiki|actions)/.*$)",
179 wxRE_ADVANCED );
180
181 webSuffix.ReplaceAll( &addr, wxEmptyString );
182
183 while( addr.EndsWith( "/" ) )
184 addr.RemoveLast();
185
186 if( addr.EndsWith( ".git" ) )
187 addr.RemoveLast( 4 );
188
189 size_t last_slash = addr.find_last_of( "/\\" );
190
191 if( last_slash == wxString::npos )
192 return addr.AfterLast( ':' );
193
194 return addr.substr( last_slash + 1 );
195}
196
197
198void DIALOG_GIT_REPOSITORY::OnLocationExit( wxFocusEvent& event )
199{
202 event.Skip();
203}
204
205
207{
208 wxString url = m_txtURL->GetValue();
209
210 if( url.IsEmpty() )
211 return;
212
215 m_ConnType->SetSelection( static_cast<int>( parsed.connType ) );
216
217 if( parsed.connType == KIGIT_COMMON::GIT_CONN_TYPE::GIT_CONN_SSH && !wasSSH && m_fpSSHKey->GetPath().IsEmpty() )
218 setDefaultSSHKey( parsed.hostname );
219
220 if( !parsed.username.IsEmpty() )
221 SetUsername( parsed.username );
222
223 if( !parsed.password.IsEmpty() )
224 SetPassword( parsed.password );
225
226 // Keep the SSH username and port in the address. Passwords belong in the password field.
227 if( parsed.url != url )
228 m_txtURL->ChangeValue( parsed.url );
229
230 m_txtName->SetValue( get_repo_name( parsed.url ) );
231}
232
233
234void DIALOG_GIT_REPOSITORY::OnTestClick( wxCommandEvent& event )
235{
236 wxString url = GetRepoURL();
237
238 if( wxString( url ).Trim().Trim( false ).IsEmpty() || reportUnusableKey() )
239 return;
240
241 wxString error;
242 wxString details;
243 bool success = false;
244 git_remote* remote = nullptr;
245 git_remote_callbacks callbacks;
246 git_remote_init_callbacks( &callbacks, GIT_REMOTE_CALLBACKS_VERSION );
247
248 // We track if we have already tried to connect.
249 // If we have, the server may come back to offer another connection
250 // type, so we need to keep track of how many times we have tried.
251
252 KIGIT_COMMON common( m_repository );
253 common.SetRemote( url );
254
255 // SetUsername clears the fetched-secret flag, so it comes first. The other order tests the
256 // keychain's secret instead of the one just typed.
257 common.SetUsername( GetUsername() );
258 common.SetPassword( m_txtPassword->GetValue() );
259 common.SetSSHKey( GetRepoSSHPath() );
260
261 KIGIT_REPO_MIXIN repoMixin( &common );
262 callbacks.payload = &repoMixin;
263 callbacks.credentials = credentials_cb;
264 callbacks.certificate_check = certificate_check_cb;
265
266 git_proxy_options proxyOpts;
267 git_proxy_init_options( &proxyOpts, GIT_PROXY_OPTIONS_VERSION );
268 proxyOpts.type = GIT_PROXY_AUTO;
269 proxyOpts.url = "";
270
271 int result = git_remote_create_anonymous( &remote, m_repository, url.utf8_str() );
272 KIGIT::GitRemotePtr remotePtr( remote );
273
274 if( result == GIT_OK )
275 {
276 // url.insteadOf may have rewritten the URL, which would otherwise drop the credentials typed here
277 if( const char* remoteUrl = git_remote_url( remote ) )
278 common.FollowRewrittenUrl( wxString::FromUTF8( remoteUrl ) );
279
280 bool retriedAfterTrust = false;
281
282 while( true )
283 {
284 repoMixin.ResetTransferState();
285 result = git_remote_connect( remote, GIT_DIRECTION_FETCH, &callbacks, &proxyOpts, nullptr );
286
287 if( result == GIT_OK )
288 {
289 repoMixin.RememberWorkingSSHKey();
290 git_remote_disconnect( remote );
291 success = true;
292 break;
293 }
294
296 KIGIT_OPERATION::CONNECT, wxEmptyString );
297 git_remote_disconnect( remote );
298 error = report.summary;
299 details = report.details;
300
301 std::optional<KIGIT::HOST_KEY_FAILURE> hostKey = repoMixin.GetHostKeyFailure();
302
303 if( !hostKey )
304 break;
305
306 // The prompt has told the user why, so a declined key ends the test here
307 if( !KIGIT::PromptToTrustHost( this, *hostKey, retriedAfterTrust ) )
308 return;
309
310 retriedAfterTrust = true;
311 }
312 }
313 else
314 {
315 KIGIT_FAILURE_CONTEXT context;
317 context.url = url;
318
319 KIGIT_FAILURE_REPORT report =
321 error = report.summary;
322 details = report.details;
323 }
324
325 if( !success )
326 {
327 DisplayErrorMessage( this, error, details );
328 return;
329 }
330
331 auto dlg = KICAD_MESSAGE_DIALOG( this, _( "Connection successful" ), _( "Test Connection" ),
332 wxOK | wxICON_INFORMATION );
333 dlg.ShowModal();
334}
335
336
337// False with aError and aDetails set when aPath is not a private key with its .pub beside it
338static bool checkSSHKey( wxString aPath, wxString& aError, wxString& aDetails, bool& aEncrypted )
339{
340 if( aPath.ends_with( wxS( ".pub" ) ) )
341 aPath = aPath.Left( aPath.size() - 4 );
342
343 std::ifstream ifs( aPath.fn_str() );
344
345 if( !ifs.good() || !ifs.is_open() )
346 {
347 aError = wxString::Format( _( "Could not open private key '%s'" ), aPath );
348 aDetails = wxString::Format( "%s: %d", std::strerror( errno ), errno );
349 return false;
350 }
351
352 std::string keyText( ( std::istreambuf_iterator<char>( ifs ) ), std::istreambuf_iterator<char>() );
353 wxString key = wxString::FromUTF8( keyText );
354
355 if( !key.BeforeFirst( '\n' ).Contains( wxS( "PRIVATE KEY" ) ) )
356 {
357 aError = _( "Invalid SSH Key" );
358 aDetails = _( "The selected file is not a valid SSH private key" );
359 return false;
360 }
361
362 if( KIGIT::EnsurePublicKeyFile( aPath ).IsEmpty() )
363 {
364 aError = wxString::Format( _( "Could not open public key '%s'" ), aPath + wxS( ".pub" ) );
365 aDetails = _( "Put the key's .pub file beside it, or pick a key in OpenSSH format" );
366 return false;
367 }
368
369 aEncrypted = KIGIT::IsPrivateKeyEncrypted( key );
370 return true;
371}
372
373
374void DIALOG_GIT_REPOSITORY::OnFileUpdated( wxFileDirPickerEvent& aEvent )
375{
376 wxString error;
377 wxString details;
378 bool encrypted = false;
379
380 // The picker fires on every keystroke, so a half-typed path is not an error until OK
381 if( checkSSHKey( aEvent.GetPath(), error, details, encrypted ) )
382 SetEncrypted( encrypted );
383}
384
385
387{
389 || GetRepoSSHPath().IsEmpty() )
390 {
391 return false;
392 }
393
394 wxString error;
395 wxString details;
396 bool encrypted = false;
397
398 if( checkSSHKey( GetRepoSSHPath(), error, details, encrypted ) )
399 return false;
400
401 DisplayErrorMessage( this, error, details );
402 return true;
403}
404
405
406// Empty when the address is one git can try; otherwise says what is wrong with it
407static wxString describeUnusableURL( git_repository* aRepo, const wxString& aURL )
408{
409 git_remote* rawRemote = nullptr;
410
411 if( git_remote_create_anonymous( &rawRemote, aRepo, aURL.utf8_str() ) != GIT_OK )
412 return wxString::Format( _( "'%s' is not a repository address." ), aURL );
413
414 KIGIT::GitRemotePtr remote( rawRemote );
415
416 // A url.insteadOf alias is judged by the address it expands to
417 wxString effective = wxString::FromUTF8( git_remote_url( remote.get() ) );
418 wxString checked = effective;
419
420 // The parser has no git:// case, so its server part is checked the way an HTTPS one is
421 if( checked.Lower().StartsWith( wxS( "git://" ) ) )
422 checked = wxS( "https://" ) + checked.Mid( 6 );
423
425
427 {
428 const wxString& host = parsed.hostname;
429 wxString authority = checked.AfterFirst( ':' ).Mid( 2 ).BeforeFirst( '/' );
430
431 // The parser drops an unclosed IPv6 bracket, so look for it in the address itself
432 if( host.IsEmpty() || host.find_first_of( wxS( " \t" ) ) != wxString::npos
433 || ( checked.Contains( wxS( "://" ) ) && authority.Contains( wxS( "[" ) )
434 && !authority.Contains( wxS( "]" ) ) ) )
435 {
436 return wxString::Format( _( "'%s' does not name a server." ), aURL );
437 }
438
439 if( parsed.port < 0 )
440 return wxString::Format( _( "The port in '%s' is not a number." ), aURL );
441
442 return wxEmptyString;
443 }
444
445 wxString lower = effective.Lower();
446
447 if( lower.Contains( wxS( "://" ) ) && !lower.StartsWith( wxS( "file://" ) ) )
448 return wxString::Format( _( "'%s' is not an HTTPS, SSH or folder address." ), aURL );
449
450 return wxEmptyString;
451}
452
453
454void DIALOG_GIT_REPOSITORY::OnOKClick( wxCommandEvent& event )
455{
456 // Save the repository details
457
458 if( m_txtURL->GetValue().IsEmpty() )
459 {
460 DisplayErrorMessage( this, _( "Missing information" ),
461 _( "Please enter a URL for the repository" ) );
462 return;
463 }
464
465 wxString problem = describeUnusableURL( m_repository, GetRepoURL() );
466
467 if( !problem.IsEmpty() )
468 {
469 DisplayErrorMessage( this, problem,
470 _( "Use an address such as https://server/owner/project.git or "
471 "git@server:owner/project.git, or the path of a repository folder." ) );
472 return;
473 }
474
475 if( reportUnusableKey() )
476 return;
477
478 EndModal( wxID_OK );
479}
480
481
483{
484 if( m_ConnType->GetSelection() == static_cast<int>( KIGIT_COMMON::GIT_CONN_TYPE::GIT_CONN_LOCAL ) )
485 {
486 m_panelAuth->Enable( false );
487 }
488 else
489 {
490 m_panelAuth->Enable( true );
491
492 if( m_ConnType->GetSelection() == static_cast<int>( KIGIT_COMMON::GIT_CONN_TYPE::GIT_CONN_SSH ) )
493 {
495 m_cbCustom->Enable( true );
496 m_fpSSHKey->Enable( m_cbCustom->IsChecked() );
497
498 // Edit an embedded SSH username in the address so the two fields cannot disagree.
499 m_txtUsername->Enable( m_cbCustom->IsChecked() && parsed.username.IsEmpty() );
500 m_txtPassword->Enable( m_cbCustom->IsChecked() );
501 m_labelPass1->SetLabel( _( "SSH key password:" ) );
502 }
503 else
504 {
505 m_cbCustom->Enable( false );
506 m_fpSSHKey->Enable( false );
507 m_txtUsername->Enable( true );
508 m_txtPassword->Enable( true );
509 m_labelPass1->SetLabel( _( "Password:" ) );
510 }
511 }
512}
513
514
515void DIALOG_GIT_REPOSITORY::OnSelectConnType( wxCommandEvent& event )
516{
518}
519
521{
522 if( !m_incomeURL.empty() )
523 m_txtURL->SetValue( m_incomeURL );
524 else
526
527 if( !m_txtURL->GetValue().IsEmpty() )
529 else
530 m_ConnType->SetSelection( static_cast<int>( KIGIT_COMMON::GIT_CONN_TYPE::GIT_CONN_LOCAL ) );
531
533
534 return true;
535}
DIALOG_GIT_REPOSITORY_BASE(wxWindow *parent, wxWindowID id=wxID_ANY, const wxString &title=_("Git Repository"), const wxPoint &pos=wxDefaultPosition, const wxSize &size=wxSize(-1,-1), long style=wxCAPTION|wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER)
void OnSelectConnType(wxCommandEvent &event) override
KIGIT_COMMON::GIT_CONN_TYPE GetRepoType() const
void OnFileUpdated(wxFileDirPickerEvent &event) override
void SetPassword(const wxString &aPassword)
void onCbCustom(wxCommandEvent &event) override
wxString GetRepoSSHPath() const
The private key, also when its .pub was picked.
void SetEncrypted(bool aEncrypted=true)
void OnLocationExit(wxFocusEvent &event) override
bool reportUnusableKey()
Show why the chosen SSH key cannot be used. False when there is no such problem.
DIALOG_GIT_REPOSITORY(wxWindow *aParent, git_repository *aRepository, wxString aURL=wxEmptyString)
void setDefaultSSHKey(const wxString &aHost)
void OnTestClick(wxCommandEvent &event) override
void OnOKClick(wxCommandEvent &event) override
void SetUsername(const wxString &aUsername)
virtual bool TransferDataToWindow() override
void OnUpdateUI(wxUpdateUIEvent &event) override
void OptOut(wxWindow *aWindow)
Opt out of control state saving.
void SetupStandardButtons(std::map< int, wxString > aLabels={})
void finishDialogSettings()
In all dialogs, we must call the same functions to fix minimal dlg size, the default position and per...
The project's git session.
void FollowRewrittenUrl(const wxString &aRawUrl)
Bind the session to a URL that url.insteadOf rewrote, keeping the username, password and key entered ...
void SetSSHKey(const wxString &aSSHKey)
void SetUsername(const wxString &aUsername)
static KIGIT_ERROR_INFO GetLastGitErrorInfo(int aCode)
The error libgit2 holds for a call that returned aCode.
static REMOTE_URL ParseRemoteURL(const wxString &aURL)
void SetPassword(const wxString &aPassword)
void SetRemote(const wxString &aRemote)
std::optional< KIGIT::HOST_KEY_FAILURE > GetHostKeyFailure() const
The host key this operation's transfer refused, for the UI to offer to trust or to report.
KIGIT_FAILURE_REPORT ReportTransferFailure(const KIGIT_ERROR_INFO &aError, KIGIT_OPERATION aOperation, const wxString &aRemoteName)
Classify a failed libgit2 transfer call and queue its summary and details.
void RememberWorkingSSHKey()
Call once the transfer has connected, so the key that worked is offered first next time.
void ResetTransferState()
Start a transfer with nothing left from an earlier one on this handler or session: no keys or methods...
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition confirm.cpp:217
This file is part of the common library.
#define KICAD_MESSAGE_DIALOG
Definition confirm.h:48
static bool checkSSHKey(wxString aPath, wxString &aError, wxString &aDetails, bool &aEncrypted)
static wxString get_repo_name(const wxString &aRepoAddr)
static wxString describeUnusableURL(git_repository *aRepo, const wxString &aURL)
#define _(s)
bool RmDirRecursive(const wxString &aFileName, wxString *aErrors)
Remove the directory aDirName and all its contents including subdirectories and their files.
Definition gestfich.cpp:512
int certificate_check_cb(git_cert *aCert, int aValid, const char *aHost, void *aPayload)
Check an SSH host key against known_hosts, which decides alone.
int credentials_cb(git_cred **aOut, const char *aUrl, const char *aUsername, unsigned int aAllowedTypes, void *aPayload)
bool IsPrivateKeyEncrypted(const wxString &aKeyText)
Report whether an SSH private key is protected by a passphrase.
APIEXPORT wxString EnsurePublicKeyFile(const wxString &aKey)
PublicKeyPath for aKey, first writing a public key file to KiCad's cache when the key has no ....
wxString ConfiguredSSHCommand(git_repository *aRepo)
git's core.sshCommand for aRepo, or from the user's git config when aRepo is null....
bool PromptToTrustHost(wxWindow *aParent, const HOST_KEY_FAILURE &aFailure, bool aRetriedAfterTrust)
Ask whether to trust a server seen for the first time, and remember its key when the user agrees.
APIEXPORT std::vector< wxString > DefaultSSHKeyCandidates(const wxString &aHomeDir, const wxString &aHost, const wxString &aSSHCommand=wxEmptyString)
Private keys to offer aHost, best first.
APIEXPORT wxString HomeDir()
The user's home folder, where ssh looks for its config and default keys: the first candidate with a ....
APIEXPORT wxString SSHKeyFolder()
The folder ssh keeps keys in, for a file picker to open at. Empty when the home folder is unknown.
APIEXPORT KIGIT_FAILURE_REPORT DescribeGitFailure(const KIGIT_ERROR_INFO &aError, const KIGIT_AUTH_ATTEMPT &aAuth, const KIGIT_FAILURE_CONTEXT &aContext)
Turn a failed transfer into a message the user can act on.
std::unique_ptr< git_remote, decltype([](git_remote *aRemote) { git_remote_free(aRemote); })> GitRemotePtr
A unique pointer for git_remote objects with automatic cleanup.
A transport address with any embedded credentials extracted.
int port
0 when the address names none.
wxString url
Keeps the SSH username, scheme and port, but never a password.
What the failed operation was doing, as far as the message needs it.
KIGIT_OPERATION operation
wxString url
The address connected to. Messages show only its host and its stripped form.
wxString summary
What happened and what to do next, in the user's terms. Never raw text.
wxString details
The raw error, the server's text and the address without its password.
wxString result
Test unit parsing edge cases and error handling.