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 <git/kigit_transport.h>
30#include <gestfich.h>
31
32#include <cerrno>
33#include <cstring>
34#include <fstream>
35
36#include <wx/clipbrd.h>
37#include <wx/msgdlg.h>
38#include <wx/regex.h>
39#include <wx/stdpaths.h>
40
41
42DIALOG_GIT_REPOSITORY::DIALOG_GIT_REPOSITORY( wxWindow* aParent, git_repository* aRepository, wxString aURL ) :
44 m_repository( aRepository ),
45 m_incomeURL( aURL ),
46 m_tempRepo( false )
47{
48 OptOut( this );
49
50 m_txtURL->SetFocus();
51
52 if( !m_repository )
53 {
54 // Make a temporary repository to test the connection
55 m_tempRepo = true;
56 m_tempPath = wxFileName::CreateTempFileName( "kicadtestrepo" );
57
58 // CreateTempFileName leaves a file at the path, where git cannot make a repository
59 wxRemoveFile( m_tempPath );
60
61 git_repository_init_options options;
62 git_repository_init_init_options( &options, GIT_REPOSITORY_INIT_OPTIONS_VERSION );
63 options.flags = GIT_REPOSITORY_INIT_MKPATH | GIT_REPOSITORY_INIT_NO_REINIT;
64 git_repository_init_ext( &m_repository, m_tempPath.ToStdString().c_str(), &options );
65 }
66
67 // Otherwise the picker opens wherever the last file dialog was, far from any key
68 m_fpSSHKey->SetInitialDirectory( KIGIT::SSHKeyFolder() );
69
70 SetupStandardButtons( { { wxID_HELP, _( "Test Connection" ) } } );
71 Layout();
73
74 m_txtURL->Bind( wxEVT_TEXT,
75 [this]( wxCommandEvent& aEvent )
76 {
79 aEvent.Skip();
80 } );
81}
82
83
85{
86 if( m_tempRepo )
87 {
88 git_repository_free( m_repository );
90 }
91}
92
93
95{
96 wxClipboardLocker lock;
97 if( !lock )
98 return false;
99
100 if( !wxTheClipboard->IsSupported( wxDF_TEXT ) )
101 return false;
102
103 wxTextDataObject textData;
104 if( !wxTheClipboard->GetData( textData ) )
105 return false;
106
107 wxString clipboardText = textData.GetText();
108 if( clipboardText.empty() )
109 return false;
110
112
113 if( parsed.connType != KIGIT_COMMON::GIT_CONN_TYPE::GIT_CONN_LOCAL && !parsed.hostname.IsEmpty()
114 && clipboardText.find_first_of( " \t\r\n" ) == wxString::npos )
115 {
116 m_txtURL->SetValue( clipboardText );
117 return true;
118 }
119
120 return false;
121}
122
123
124void DIALOG_GIT_REPOSITORY::setDefaultSSHKey( const wxString& aHost )
125{
126 std::vector<wxString> keys =
128
129 if( keys.empty() )
130 return;
131
132 // Unticked greys out the picker and passphrase, hiding the key the connection will use
133 m_cbCustom->SetValue( true );
134 m_fpSSHKey->SetFileName( keys.front() );
135
136 wxFileDirPickerEvent evt;
137 evt.SetPath( keys.front() );
138 OnFileUpdated( evt );
139}
140
141
142void DIALOG_GIT_REPOSITORY::onCbCustom( wxCommandEvent& event )
143{
145 event.Skip();
146}
147
148
149void DIALOG_GIT_REPOSITORY::OnUpdateUI( wxUpdateUIEvent& event )
150{
151 // event.Enable( !m_txtName->GetValue().IsEmpty() && !m_txtURL->GetValue().IsEmpty() );
152}
153
154
156{
157 if( aEncrypted )
158 {
159 m_txtPassword->Enable();
160 m_txtPassword->SetToolTip( _( "Enter the password for the SSH key" ) );
161 }
162 else
163 {
164 m_txtPassword->SetValue( wxEmptyString );
165 m_txtPassword->SetToolTip( wxEmptyString );
166 m_txtPassword->Disable();
167 }
168}
169
170
171static wxString get_repo_name( const wxString& aRepoAddr )
172{
173 wxString addr = aRepoAddr;
174
175 // Strip GitHub/GitLab web-UI path suffixes so that pasting a browser URL
176 // (e.g. .../repo/tree/master, .../repo/blob/main/README.md, .../repo/pulls)
177 // still gives the repository name rather than a branch/page name.
178 static wxRegEx webSuffix(
179 R"((/-)?/(tree|blob|commits?|raw|releases|tags|branches|pulls|pull|issues|merge_requests|wiki|actions)/.*$)",
180 wxRE_ADVANCED );
181
182 webSuffix.ReplaceAll( &addr, wxEmptyString );
183
184 while( addr.EndsWith( "/" ) )
185 addr.RemoveLast();
186
187 if( addr.EndsWith( ".git" ) )
188 addr.RemoveLast( 4 );
189
190 size_t last_slash = addr.find_last_of( "/\\" );
191
192 if( last_slash == wxString::npos )
193 return addr.AfterLast( ':' );
194
195 return addr.substr( last_slash + 1 );
196}
197
198
199void DIALOG_GIT_REPOSITORY::OnLocationExit( wxFocusEvent& event )
200{
203 event.Skip();
204}
205
206
208{
209 wxString url = m_txtURL->GetValue();
210
211 if( url.IsEmpty() )
212 return;
213
216 m_ConnType->SetSelection( static_cast<int>( parsed.connType ) );
217
218 if( parsed.connType == KIGIT_COMMON::GIT_CONN_TYPE::GIT_CONN_SSH && !wasSSH && m_fpSSHKey->GetPath().IsEmpty() )
219 setDefaultSSHKey( parsed.hostname );
220
221 if( !parsed.username.IsEmpty() )
222 SetUsername( parsed.username );
223
224 if( !parsed.password.IsEmpty() )
225 SetPassword( parsed.password );
226
227 // Keep the SSH username and port in the address. Passwords belong in the password field.
228 if( parsed.url != url )
229 m_txtURL->ChangeValue( parsed.url );
230
231 m_txtName->SetValue( get_repo_name( parsed.url ) );
232}
233
234
235void DIALOG_GIT_REPOSITORY::OnTestClick( wxCommandEvent& event )
236{
237 wxString url = GetRepoURL();
238
239 if( wxString( url ).Trim().Trim( false ).IsEmpty() || reportUnusableKey() )
240 return;
241
242 wxString error;
243 wxString details;
244 bool success = false;
245 git_remote* remote = nullptr;
246
247 KIGIT_COMMON common( m_repository );
248 common.SetRemote( url );
249
250 // SetUsername clears the fetched-secret flag, so it comes first. The other order tests the
251 // keychain's secret instead of the one just typed.
252 common.SetUsername( GetUsername() );
253 common.SetPassword( m_txtPassword->GetValue() );
254 common.SetSSHKey( GetRepoSSHPath() );
255
256 KIGIT_REPO_MIXIN repoMixin( &common );
257
258 int result = git_remote_create_anonymous( &remote, m_repository, url.utf8_str() );
259 KIGIT::GitRemotePtr remotePtr( remote );
260
261 if( result == GIT_OK )
262 {
263 // url.insteadOf may have rewritten the URL, which would otherwise drop the credentials typed here
264 if( const char* remoteUrl = git_remote_url( remote ) )
265 common.FollowRewrittenUrl( wxString::FromUTF8( remoteUrl ) );
266
267 KIGIT::REMOTE_TRANSPORT transport( &repoMixin, remote );
268 bool retriedAfterTrust = false;
269
270 while( true )
271 {
272 if( transport.Check() == GIT_OK )
273 {
274 success = true;
275 break;
276 }
277
279 wxEmptyString );
280 error = report.summary;
281 details = report.details;
282
283 std::optional<KIGIT::HOST_KEY_FAILURE> hostKey = repoMixin.GetHostKeyFailure();
284
285 if( !hostKey )
286 break;
287
288 // The prompt has told the user why, so a declined key ends the test here
289 if( KIGIT::PromptToTrustHost( this, *hostKey, retriedAfterTrust ) != KIGIT::PROMPT_ANSWER::ACCEPTED )
290 return;
291
292 retriedAfterTrust = true;
293 }
294 }
295 else
296 {
297 KIGIT_FAILURE_CONTEXT context;
299 context.url = url;
300
301 KIGIT_FAILURE_REPORT report =
303 error = report.summary;
304 details = report.details;
305 }
306
307 if( !success )
308 {
309 DisplayErrorMessage( this, error, details );
310 return;
311 }
312
313 auto dlg = KICAD_MESSAGE_DIALOG( this, _( "Connection successful" ), _( "Test Connection" ),
314 wxOK | wxICON_INFORMATION );
315 dlg.ShowModal();
316}
317
318
319// False with aError and aDetails set when aPath is not a private key with its .pub beside it
320static bool checkSSHKey( wxString aPath, wxString& aError, wxString& aDetails, bool& aEncrypted )
321{
322 if( aPath.ends_with( wxS( ".pub" ) ) )
323 aPath = aPath.Left( aPath.size() - 4 );
324
325 std::ifstream ifs( aPath.fn_str() );
326
327 if( !ifs.good() || !ifs.is_open() )
328 {
329 aError = wxString::Format( _( "Could not open private key '%s'" ), aPath );
330 aDetails = wxString::Format( "%s: %d", std::strerror( errno ), errno );
331 return false;
332 }
333
334 std::string keyText( ( std::istreambuf_iterator<char>( ifs ) ), std::istreambuf_iterator<char>() );
335 wxString key = wxString::FromUTF8( keyText );
336
337 if( !key.BeforeFirst( '\n' ).Contains( wxS( "PRIVATE KEY" ) ) )
338 {
339 aError = _( "Invalid SSH Key" );
340 aDetails = _( "The selected file is not a valid SSH private key" );
341 return false;
342 }
343
344 if( KIGIT::EnsurePublicKeyFile( aPath ).IsEmpty() )
345 {
346 aError = wxString::Format( _( "Could not open public key '%s'" ), aPath + wxS( ".pub" ) );
347 aDetails = _( "Put the key's .pub file beside it, or pick a key in OpenSSH format" );
348 return false;
349 }
350
351 aEncrypted = KIGIT::IsPrivateKeyEncrypted( key );
352 return true;
353}
354
355
356void DIALOG_GIT_REPOSITORY::OnFileUpdated( wxFileDirPickerEvent& aEvent )
357{
358 wxString error;
359 wxString details;
360 bool encrypted = false;
361
362 // The picker fires on every keystroke, so a half-typed path is not an error until OK
363 if( checkSSHKey( aEvent.GetPath(), error, details, encrypted ) )
364 SetEncrypted( encrypted );
365}
366
367
369{
371 || GetRepoSSHPath().IsEmpty() )
372 {
373 return false;
374 }
375
376 wxString error;
377 wxString details;
378 bool encrypted = false;
379
380 if( checkSSHKey( GetRepoSSHPath(), error, details, encrypted ) )
381 return false;
382
383 DisplayErrorMessage( this, error, details );
384 return true;
385}
386
387
388// Empty when the address is one git can try; otherwise says what is wrong with it
389static wxString describeUnusableURL( git_repository* aRepo, const wxString& aURL )
390{
391 git_remote* rawRemote = nullptr;
392
393 if( git_remote_create_anonymous( &rawRemote, aRepo, aURL.utf8_str() ) != GIT_OK )
394 return wxString::Format( _( "'%s' is not a repository address." ), aURL );
395
396 KIGIT::GitRemotePtr remote( rawRemote );
397
398 // A url.insteadOf alias is judged by the address it expands to
399 wxString effective = wxString::FromUTF8( git_remote_url( remote.get() ) );
400 wxString checked = effective;
401
402 // The parser has no git:// case, so its server part is checked the way an HTTPS one is
403 if( checked.Lower().StartsWith( wxS( "git://" ) ) )
404 checked = wxS( "https://" ) + checked.Mid( 6 );
405
407
409 {
410 const wxString& host = parsed.hostname;
411 wxString authority = checked.AfterFirst( ':' ).Mid( 2 ).BeforeFirst( '/' );
412
413 // The parser drops an unclosed IPv6 bracket, so look for it in the address itself
414 if( host.IsEmpty() || host.find_first_of( wxS( " \t" ) ) != wxString::npos
415 || ( checked.Contains( wxS( "://" ) ) && authority.Contains( wxS( "[" ) )
416 && !authority.Contains( wxS( "]" ) ) ) )
417 {
418 return wxString::Format( _( "'%s' does not name a server." ), aURL );
419 }
420
421 if( parsed.port < 0 )
422 return wxString::Format( _( "The port in '%s' is not a number." ), aURL );
423
424 return wxEmptyString;
425 }
426
427 wxString lower = effective.Lower();
428
429 if( lower.Contains( wxS( "://" ) ) && !lower.StartsWith( wxS( "file://" ) ) )
430 return wxString::Format( _( "'%s' is not an HTTPS, SSH or folder address." ), aURL );
431
432 return wxEmptyString;
433}
434
435
436void DIALOG_GIT_REPOSITORY::OnOKClick( wxCommandEvent& event )
437{
438 // Save the repository details
439
440 if( m_txtURL->GetValue().IsEmpty() )
441 {
442 DisplayErrorMessage( this, _( "Missing information" ),
443 _( "Please enter a URL for the repository" ) );
444 return;
445 }
446
447 wxString problem = describeUnusableURL( m_repository, GetRepoURL() );
448
449 if( !problem.IsEmpty() )
450 {
451 DisplayErrorMessage( this, problem,
452 _( "Use an address such as https://server/owner/project.git or "
453 "git@server:owner/project.git, or the path of a repository folder." ) );
454 return;
455 }
456
457 if( reportUnusableKey() )
458 return;
459
460 EndModal( wxID_OK );
461}
462
463
465{
466 if( m_ConnType->GetSelection() == static_cast<int>( KIGIT_COMMON::GIT_CONN_TYPE::GIT_CONN_LOCAL ) )
467 {
468 m_panelAuth->Enable( false );
469 }
470 else
471 {
472 m_panelAuth->Enable( true );
473
474 if( m_ConnType->GetSelection() == static_cast<int>( KIGIT_COMMON::GIT_CONN_TYPE::GIT_CONN_SSH ) )
475 {
477 m_cbCustom->Enable( true );
478 m_fpSSHKey->Enable( m_cbCustom->IsChecked() );
479
480 // Edit an embedded SSH username in the address so the two fields cannot disagree.
481 m_txtUsername->Enable( m_cbCustom->IsChecked() && parsed.username.IsEmpty() );
482 m_txtPassword->Enable( m_cbCustom->IsChecked() );
483 m_labelPass1->SetLabel( _( "SSH key password:" ) );
484 }
485 else
486 {
487 m_cbCustom->Enable( false );
488 m_fpSSHKey->Enable( false );
489 m_txtUsername->Enable( true );
490 m_txtPassword->Enable( true );
491 m_labelPass1->SetLabel( _( "Password:" ) );
492 }
493 }
494}
495
496
497void DIALOG_GIT_REPOSITORY::OnSelectConnType( wxCommandEvent& event )
498{
500}
501
503{
504 if( !m_incomeURL.empty() )
505 m_txtURL->SetValue( m_incomeURL );
506 else
508
509 if( !m_txtURL->GetValue().IsEmpty() )
511 else
512 m_ConnType->SetSelection( static_cast<int>( KIGIT_COMMON::GIT_CONN_TYPE::GIT_CONN_LOCAL ) );
513
515
516 return true;
517}
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...
const KIGIT_ERROR_INFO & Error() const
libgit2's error for the last call that failed, read before anything else could replace it
int Check()
Connect, which proves the credentials and the host key without transferring anything.
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 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
The one place a fetch, push, clone or connection check reaches a remote.
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....
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.
PROMPT_ANSWER 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 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.