ImportSessions.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. //---------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <Common.h>
  5. #include "ImportSessions.h"
  6. #include <Configuration.h>
  7. #include <CoreMain.h>
  8. #include <VCLCommon.h>
  9. #include <WinInterface.h>
  10. #include <TextsWin.h>
  11. #include <CoreMain.h>
  12. #include <Tools.h>
  13. #include <WinApi.h>
  14. #include <PasTools.hpp>
  15. //---------------------------------------------------------------------
  16. #pragma resource "*.dfm"
  17. //---------------------------------------------------------------------
  18. const int OpensshIndex = 3;
  19. const int KnownHostsIndex = 4;
  20. //---------------------------------------------------------------------
  21. bool __fastcall DoImportSessionsDialog(TList * Imported)
  22. {
  23. std::unique_ptr<TStrings> Errors(new TStringList());
  24. std::unique_ptr<TList> SessionListsList(new TList());
  25. UnicodeString Error;
  26. std::unique_ptr<TStoredSessionList> PuttyImportSessionList(
  27. GUIConfiguration->SelectPuttySessionsForImport(OriginalPuttyRegistryStorageKey, L"PuTTY", StoredSessions, Error));
  28. SessionListsList->Add(PuttyImportSessionList.get());
  29. Errors->Add(Error);
  30. std::unique_ptr<TStoredSessionList> KittyImportSessionList(
  31. GUIConfiguration->SelectPuttySessionsForImport(KittyRegistryStorageKey, L"KiTTY", StoredSessions, Error));
  32. SessionListsList->Add(KittyImportSessionList.get());
  33. Errors->Add(Error);
  34. std::unique_ptr<TStoredSessionList> FilezillaImportSessionList(
  35. Configuration->SelectFilezillaSessionsForImport(StoredSessions, Error));
  36. SessionListsList->Add(FilezillaImportSessionList.get());
  37. Errors->Add(Error);
  38. std::unique_ptr<TStoredSessionList> OpensshImportSessionList(
  39. Configuration->SelectOpensshSessionsForImport(StoredSessions, Error));
  40. SessionListsList->Add(OpensshImportSessionList.get());
  41. Errors->Add(Error);
  42. std::unique_ptr<TStoredSessionList> KnownHostsImportSessionList(
  43. Configuration->SelectKnownHostsSessionsForImport(StoredSessions, Error));
  44. DebugAssert(KnownHostsIndex == SessionListsList->Count);
  45. SessionListsList->Add(KnownHostsImportSessionList.get());
  46. Errors->Add(Error);
  47. DebugAssert(SessionListsList->Count == Errors->Count);
  48. std::unique_ptr<TImportSessionsDialog> ImportSessionsDialog(
  49. SafeFormCreate<TImportSessionsDialog>(Application));
  50. ImportSessionsDialog->Init(SessionListsList.get(), Errors.get());
  51. bool Result = ImportSessionsDialog->Execute();
  52. if (Result)
  53. {
  54. // Particularly when importing known_hosts, there is no feedback.
  55. TInstantOperationVisualizer Visualizer;
  56. UnicodeString PuttyHostKeysSourceKey = OriginalPuttyRegistryStorageKey;
  57. TStoredSessionList * AKnownHostsImportSessionList =
  58. static_cast<TStoredSessionList *>(SessionListsList->Items[KnownHostsIndex]);
  59. StoredSessions->Import(PuttyImportSessionList.get(), true, Imported);
  60. TStoredSessionList::ImportHostKeys(PuttyHostKeysSourceKey, PuttyImportSessionList.get(), true);
  61. StoredSessions->Import(KittyImportSessionList.get(), true, Imported);
  62. TStoredSessionList::ImportHostKeys(KittyRegistryStorageKey, KittyImportSessionList.get(), true);
  63. StoredSessions->Import(FilezillaImportSessionList.get(), true, Imported);
  64. // FileZilla uses PuTTY's host key store
  65. TStoredSessionList::ImportHostKeys(PuttyHostKeysSourceKey, FilezillaImportSessionList.get(), true);
  66. StoredSessions->Import(OpensshImportSessionList.get(), true, Imported);
  67. // The actual import will be done by ImportSelectedKnownHosts
  68. TStoredSessionList::SelectKnownHostsForSelectedSessions(AKnownHostsImportSessionList, OpensshImportSessionList.get());
  69. TStoredSessionList::ImportSelectedKnownHosts(AKnownHostsImportSessionList);
  70. }
  71. return Result;
  72. }
  73. //---------------------------------------------------------------------
  74. __fastcall TImportSessionsDialog::TImportSessionsDialog(TComponent * AOwner) :
  75. TForm(AOwner)
  76. {
  77. UseSystemSettings(this);
  78. // this is loaded from res string to force translation
  79. Caption = LoadStr(IMPORT_CAPTION);
  80. }
  81. //---------------------------------------------------------------------
  82. void __fastcall TImportSessionsDialog::Init(TList * SessionListsList, TStrings * Errors)
  83. {
  84. FSessionListsList = SessionListsList;
  85. FErrors = Errors;
  86. for (int Index = 0; Index < SessionListsList->Count; Index++)
  87. {
  88. if ((SourceComboBox->ItemIndex < 0) && (GetSessionList(Index)->Count > 0))
  89. {
  90. SourceComboBox->ItemIndex = Index;
  91. }
  92. }
  93. if (SourceComboBox->ItemIndex < 0)
  94. {
  95. SourceComboBox->ItemIndex = 0;
  96. }
  97. int Offset = ScaleByTextHeight(this, 8);
  98. ErrorPanel->BoundsRect =
  99. TRect(
  100. SessionListView2->BoundsRect.Left + Offset, SessionListView2->BoundsRect.Top + Offset,
  101. SessionListView2->BoundsRect.Right - Offset, SessionListView2->BoundsRect.Bottom - Offset);
  102. }
  103. //---------------------------------------------------------------------
  104. TStoredSessionList * __fastcall TImportSessionsDialog::GetSessionList(int Index)
  105. {
  106. return reinterpret_cast<TStoredSessionList *>(FSessionListsList->Items[Index]);
  107. }
  108. //---------------------------------------------------------------------
  109. void __fastcall TImportSessionsDialog::UpdateControls()
  110. {
  111. PasteButton->Visible = (SourceComboBox->ItemIndex == KnownHostsIndex);
  112. EnableControl(PasteButton, IsFormatInClipboard(CF_TEXT));
  113. EnableControl(OKButton, ListViewAnyChecked(SessionListView2));
  114. EnableControl(CheckAllButton, SessionListView2->Items->Count > 0);
  115. AutoSizeListColumnsWidth(SessionListView2);
  116. }
  117. //---------------------------------------------------------------------
  118. void __fastcall TImportSessionsDialog::ClearSelections()
  119. {
  120. for (int Index = 0; Index < SourceComboBox->Items->Count; Index++)
  121. {
  122. TStoredSessionList * SessionList = GetSessionList(Index);
  123. for (int Index = 0; Index < SessionList->Count; Index++)
  124. {
  125. SessionList->Sessions[Index]->Selected = false;
  126. }
  127. }
  128. }
  129. //---------------------------------------------------------------------
  130. TSessionData * TImportSessionsDialog::GetSessionData(TListItem * Item)
  131. {
  132. return DebugNotNull(static_cast<TSessionData *>(Item->Data));
  133. }
  134. //---------------------------------------------------------------------
  135. void __fastcall TImportSessionsDialog::SaveSelection()
  136. {
  137. for (int Index = 0; Index < SessionListView2->Items->Count; Index++)
  138. {
  139. TListItem * Item = SessionListView2->Items->Item[Index];
  140. GetSessionData(Item)->Selected = Item->Checked;
  141. }
  142. }
  143. //---------------------------------------------------------------------
  144. void __fastcall TImportSessionsDialog::LoadSessions()
  145. {
  146. TStoredSessionList * SessionList = GetSessionList(SourceComboBox->ItemIndex);
  147. SessionListView2->Items->BeginUpdate();
  148. try
  149. {
  150. SessionListView2->Items->Clear();
  151. for (int Index = 0; Index < SessionList->Count; Index++)
  152. {
  153. TSessionData * Session = SessionList->Sessions[Index];
  154. TListItem * Item = SessionListView2->Items->Add();
  155. Item->Data = Session;
  156. Item->Caption = Session->Name;
  157. Item->Checked = Session->Selected;
  158. }
  159. }
  160. __finally
  161. {
  162. SessionListView2->Items->EndUpdate();
  163. }
  164. UnicodeString Error = FErrors->Strings[SourceComboBox->ItemIndex];
  165. if ((SessionList->Count > 0) || Error.IsEmpty())
  166. {
  167. ErrorPanel->Visible = false;
  168. SessionListView2->TabStop = true;
  169. }
  170. else
  171. {
  172. ErrorLabel->Caption = Error;
  173. ErrorPanel->Visible = true;
  174. SessionListView2->TabStop = false;
  175. }
  176. UpdateControls();
  177. }
  178. //---------------------------------------------------------------------------
  179. void __fastcall TImportSessionsDialog::SessionListView2InfoTip(
  180. TObject * /*Sender*/, TListItem * Item, UnicodeString & InfoTip)
  181. {
  182. TSessionData * Data = GetSessionData(Item);
  183. if (SourceComboBox->ItemIndex == KnownHostsIndex)
  184. {
  185. UnicodeString Algs;
  186. UnicodeString HostKeys = Data->HostKey;
  187. while (!HostKeys.IsEmpty())
  188. {
  189. UnicodeString HostKey = CutToChar(HostKeys, L';', true);
  190. UnicodeString Alg = CutToChar(HostKey, L':', true);
  191. AddToList(Algs, Alg, L", ");
  192. }
  193. InfoTip = FMTLOAD(IMPORT_KNOWNHOSTS_INFO_TIP, (Data->HostName, Algs));
  194. }
  195. else
  196. {
  197. InfoTip = Data->InfoTip;
  198. }
  199. }
  200. //---------------------------------------------------------------------------
  201. void __fastcall TImportSessionsDialog::SessionListView2MouseDown(
  202. TObject * /*Sender*/, TMouseButton /*Button*/, TShiftState /*Shift*/,
  203. int /*X*/, int /*Y*/)
  204. {
  205. UpdateControls();
  206. }
  207. //---------------------------------------------------------------------------
  208. void __fastcall TImportSessionsDialog::SessionListView2KeyUp(
  209. TObject * /*Sender*/, WORD & /*Key*/, TShiftState /*Shift*/)
  210. {
  211. UpdateControls();
  212. }
  213. //---------------------------------------------------------------------------
  214. void __fastcall TImportSessionsDialog::FormShow(TObject * /*Sender*/)
  215. {
  216. // Load only now, as earlier loading somehow breaks SessionListView2 layout on initial per-monitor DPI scaling
  217. LoadSessions();
  218. }
  219. //---------------------------------------------------------------------------
  220. void __fastcall TImportSessionsDialog::CheckAllButtonClick(TObject * /*Sender*/)
  221. {
  222. ListViewCheckAll(SessionListView2, caToggle);
  223. UpdateControls();
  224. }
  225. //---------------------------------------------------------------------------
  226. void __fastcall TImportSessionsDialog::HelpButtonClick(TObject * /*Sender*/)
  227. {
  228. FormHelp(this);
  229. }
  230. //---------------------------------------------------------------------------
  231. bool TImportSessionsDialog::ConvertKeyFile(
  232. UnicodeString & KeyFile, TStrings * ConvertedKeyFiles, TStrings * NotConvertedKeyFiles)
  233. {
  234. bool ConvertedSession = false;
  235. if (!KeyFile.IsEmpty() &&
  236. FileExists(ApiPath(KeyFile)))
  237. {
  238. UnicodeString CanonicalPath = GetCanonicalPath(KeyFile);
  239. // Reuses the already converted keys saved under a custom name
  240. // (when saved under the default name they would be captured by the later condition based on GetConvertedKeyFileName)
  241. int CanonicalIndex = ConvertedKeyFiles->IndexOfName(CanonicalPath);
  242. if (CanonicalIndex >= 0)
  243. {
  244. KeyFile = ConvertedKeyFiles->ValueFromIndex[CanonicalIndex];
  245. ConvertedSession = true;
  246. }
  247. // Prevents asking about converting the same key again, when the user refuses the conversion.
  248. else if (NotConvertedKeyFiles->IndexOf(CanonicalPath) >= 0)
  249. {
  250. // noop
  251. }
  252. else
  253. {
  254. UnicodeString ConvertedFilename = GetConvertedKeyFileName(KeyFile);
  255. UnicodeString FileName;
  256. if (FileExists(ApiPath(ConvertedFilename)))
  257. {
  258. FileName = ConvertedFilename;
  259. ConvertedSession = true;
  260. }
  261. else
  262. {
  263. FileName = KeyFile;
  264. TDateTime TimestampBefore, TimestampAfter;
  265. FileAge(FileName, TimestampBefore);
  266. try
  267. {
  268. VerifyAndConvertKey(FileName, true);
  269. FileAge(FileName, TimestampAfter);
  270. if ((KeyFile != FileName) ||
  271. // should never happen as cancelling the saving throws EAbort
  272. DebugAlwaysTrue(TimestampBefore != TimestampAfter))
  273. {
  274. ConvertedSession = true;
  275. }
  276. }
  277. catch (EAbort &)
  278. {
  279. NotConvertedKeyFiles->Add(CanonicalPath);
  280. }
  281. }
  282. if (ConvertedSession)
  283. {
  284. KeyFile = FileName;
  285. ConvertedKeyFiles->Values[CanonicalPath] = FileName;
  286. }
  287. }
  288. }
  289. return ConvertedSession;
  290. }
  291. //---------------------------------------------------------------------------
  292. bool __fastcall TImportSessionsDialog::Execute()
  293. {
  294. bool Result = (ShowModal() == DefaultResult(this));
  295. if (Result)
  296. {
  297. ClearSelections();
  298. SaveSelection();
  299. if (SourceComboBox->ItemIndex == OpensshIndex)
  300. {
  301. std::unique_ptr<TStrings> ConvertedSessions(new TStringList());
  302. std::unique_ptr<TStrings> ConvertedKeyFiles(new TStringList());
  303. std::unique_ptr<TStrings> NotConvertedKeyFiles(CreateSortedStringList());
  304. for (int Index = 0; Index < SessionListView2->Items->Count; Index++)
  305. {
  306. TListItem * Item = SessionListView2->Items->Item[Index];
  307. if (Item->Checked)
  308. {
  309. TSessionData * Data = GetSessionData(Item);
  310. UnicodeString SessionKeys;
  311. UnicodeString PublicKeyFile = Data->PublicKeyFile;
  312. if (ConvertKeyFile(PublicKeyFile, ConvertedKeyFiles.get(), NotConvertedKeyFiles.get()))
  313. {
  314. Data->PublicKeyFile = PublicKeyFile;
  315. SessionKeys = PublicKeyFile;
  316. }
  317. UnicodeString TunnelPublicKeyFile = Data->TunnelPublicKeyFile;
  318. if (ConvertKeyFile(TunnelPublicKeyFile, ConvertedKeyFiles.get(), NotConvertedKeyFiles.get()))
  319. {
  320. Data->TunnelPublicKeyFile = TunnelPublicKeyFile;
  321. if (SessionKeys != TunnelPublicKeyFile)
  322. {
  323. AddToList(SessionKeys, TunnelPublicKeyFile, L", ");
  324. }
  325. }
  326. if (!SessionKeys.IsEmpty())
  327. {
  328. ConvertedSessions->Add(FORMAT(L"%s (%s)", (Data->Name, SessionKeys)));
  329. }
  330. }
  331. }
  332. if (ConvertedSessions->Count > 0)
  333. {
  334. UnicodeString Message = MainInstructions(FMTLOAD(IMPORT_CONVERTED_KEYS, (ConvertedKeyFiles->Count, ConvertedSessions->Count)));
  335. MoreMessageDialog(Message, ConvertedSessions.get(), qtInformation, qaOK, HelpKeyword);
  336. }
  337. }
  338. }
  339. return Result;
  340. }
  341. //---------------------------------------------------------------------------
  342. void __fastcall TImportSessionsDialog::SourceComboBoxSelect(TObject * /*Sender*/)
  343. {
  344. SaveSelection();
  345. LoadSessions();
  346. }
  347. //---------------------------------------------------------------------------
  348. void __fastcall TImportSessionsDialog::CreateHandle()
  349. {
  350. TForm::CreateHandle();
  351. if (DebugAlwaysTrue(HandleAllocated()))
  352. {
  353. HINSTANCE User32Library = LoadLibrary(L"user32.dll");
  354. AddClipboardFormatListenerProc AddClipboardFormatListener =
  355. (AddClipboardFormatListenerProc)GetProcAddress(User32Library, "AddClipboardFormatListener");
  356. if (AddClipboardFormatListener != NULL)
  357. {
  358. AddClipboardFormatListener(Handle);
  359. }
  360. }
  361. }
  362. //---------------------------------------------------------------------------
  363. void __fastcall TImportSessionsDialog::DestroyHandle()
  364. {
  365. if (DebugAlwaysTrue(HandleAllocated()))
  366. {
  367. HINSTANCE User32Library = LoadLibrary(L"user32.dll");
  368. RemoveClipboardFormatListenerProc RemoveClipboardFormatListener =
  369. (RemoveClipboardFormatListenerProc)GetProcAddress(User32Library, "RemoveClipboardFormatListener");
  370. if (RemoveClipboardFormatListener != NULL)
  371. {
  372. RemoveClipboardFormatListener(Handle);
  373. }
  374. }
  375. TForm::DestroyHandle();
  376. }
  377. //---------------------------------------------------------------------------
  378. void __fastcall TImportSessionsDialog::Dispatch(void * Message)
  379. {
  380. TMessage * M = static_cast<TMessage*>(Message);
  381. switch (M->Msg)
  382. {
  383. case WM_CLIPBOARDUPDATE:
  384. UpdateControls();
  385. TForm::Dispatch(Message);
  386. break;
  387. default:
  388. TForm::Dispatch(Message);
  389. break;
  390. }
  391. }
  392. //---------------------------------------------------------------------------
  393. void __fastcall TImportSessionsDialog::PasteButtonClick(TObject * /*Sender*/)
  394. {
  395. UnicodeString Text;
  396. // Proceed even when retrieving from clipboard fails, "no host keys" error will show.
  397. TextFromClipboard(Text, false);
  398. std::unique_ptr<TStrings> Lines(new TStringList());
  399. Lines->Text = Text;
  400. SessionListView2->Items->Clear();
  401. int Index = SourceComboBox->ItemIndex;
  402. UnicodeString Error;
  403. FPastedKnownHosts.reset(Configuration->SelectKnownHostsSessionsForImport(Lines.get(), StoredSessions, Error));
  404. FSessionListsList->Items[Index] = FPastedKnownHosts.get();
  405. FErrors->Strings[Index] = Error;
  406. LoadSessions();
  407. }
  408. //---------------------------------------------------------------------------