ImportSessions.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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. }
  169. else
  170. {
  171. ErrorLabel->Caption = Error;
  172. ErrorPanel->Visible = true;
  173. }
  174. UpdateControls();
  175. }
  176. //---------------------------------------------------------------------------
  177. void __fastcall TImportSessionsDialog::SessionListView2InfoTip(
  178. TObject * /*Sender*/, TListItem * Item, UnicodeString & InfoTip)
  179. {
  180. TSessionData * Data = GetSessionData(Item);
  181. if (SourceComboBox->ItemIndex == KnownHostsIndex)
  182. {
  183. UnicodeString Algs;
  184. UnicodeString HostKeys = Data->HostKey;
  185. while (!HostKeys.IsEmpty())
  186. {
  187. UnicodeString HostKey = CutToChar(HostKeys, L';', true);
  188. UnicodeString Alg = CutToChar(HostKey, L':', true);
  189. AddToList(Algs, Alg, L", ");
  190. }
  191. InfoTip = FMTLOAD(IMPORT_KNOWNHOSTS_INFO_TIP, (Data->HostName, Algs));
  192. }
  193. else
  194. {
  195. InfoTip = Data->InfoTip;
  196. }
  197. }
  198. //---------------------------------------------------------------------------
  199. void __fastcall TImportSessionsDialog::SessionListView2MouseDown(
  200. TObject * /*Sender*/, TMouseButton /*Button*/, TShiftState /*Shift*/,
  201. int /*X*/, int /*Y*/)
  202. {
  203. UpdateControls();
  204. }
  205. //---------------------------------------------------------------------------
  206. void __fastcall TImportSessionsDialog::SessionListView2KeyUp(
  207. TObject * /*Sender*/, WORD & /*Key*/, TShiftState /*Shift*/)
  208. {
  209. UpdateControls();
  210. }
  211. //---------------------------------------------------------------------------
  212. void __fastcall TImportSessionsDialog::FormShow(TObject * /*Sender*/)
  213. {
  214. // Load only now, as earlier loading somehow breaks SessionListView2 layout on initial per-monitor DPI scaling
  215. LoadSessions();
  216. }
  217. //---------------------------------------------------------------------------
  218. void __fastcall TImportSessionsDialog::CheckAllButtonClick(TObject * /*Sender*/)
  219. {
  220. ListViewCheckAll(SessionListView2, caToggle);
  221. UpdateControls();
  222. }
  223. //---------------------------------------------------------------------------
  224. void __fastcall TImportSessionsDialog::HelpButtonClick(TObject * /*Sender*/)
  225. {
  226. FormHelp(this);
  227. }
  228. //---------------------------------------------------------------------------
  229. bool TImportSessionsDialog::ConvertKeyFile(
  230. UnicodeString & KeyFile, TStrings * ConvertedKeyFiles, TStrings * NotConvertedKeyFiles)
  231. {
  232. bool ConvertedSession = false;
  233. if (!KeyFile.IsEmpty() &&
  234. FileExists(ApiPath(KeyFile)))
  235. {
  236. UnicodeString CanonicalPath = GetCanonicalPath(KeyFile);
  237. // Reuses the already converted keys saved under a custom name
  238. // (when saved under the default name they would be captured by the later condition based on GetConvertedKeyFileName)
  239. int CanonicalIndex = ConvertedKeyFiles->IndexOfName(CanonicalPath);
  240. if (CanonicalIndex >= 0)
  241. {
  242. KeyFile = ConvertedKeyFiles->ValueFromIndex[CanonicalIndex];
  243. ConvertedSession = true;
  244. }
  245. // Prevents asking about converting the same key again, when the user refuses the conversion.
  246. else if (NotConvertedKeyFiles->IndexOf(CanonicalPath) >= 0)
  247. {
  248. // noop
  249. }
  250. else
  251. {
  252. UnicodeString ConvertedFilename = GetConvertedKeyFileName(KeyFile);
  253. UnicodeString FileName;
  254. if (FileExists(ApiPath(ConvertedFilename)))
  255. {
  256. FileName = ConvertedFilename;
  257. ConvertedSession = true;
  258. }
  259. else
  260. {
  261. FileName = KeyFile;
  262. TDateTime TimestampBefore, TimestampAfter;
  263. FileAge(FileName, TimestampBefore);
  264. try
  265. {
  266. VerifyAndConvertKey(FileName, true);
  267. FileAge(FileName, TimestampAfter);
  268. if ((KeyFile != FileName) ||
  269. // should never happen as cancelling the saving throws EAbort
  270. DebugAlwaysTrue(TimestampBefore != TimestampAfter))
  271. {
  272. ConvertedSession = true;
  273. }
  274. }
  275. catch (EAbort &)
  276. {
  277. NotConvertedKeyFiles->Add(CanonicalPath);
  278. }
  279. }
  280. if (ConvertedSession)
  281. {
  282. KeyFile = FileName;
  283. ConvertedKeyFiles->Values[CanonicalPath] = FileName;
  284. }
  285. }
  286. }
  287. return ConvertedSession;
  288. }
  289. //---------------------------------------------------------------------------
  290. bool __fastcall TImportSessionsDialog::Execute()
  291. {
  292. bool Result = (ShowModal() == DefaultResult(this));
  293. if (Result)
  294. {
  295. ClearSelections();
  296. SaveSelection();
  297. if (SourceComboBox->ItemIndex == OpensshIndex)
  298. {
  299. std::unique_ptr<TStrings> ConvertedSessions(new TStringList());
  300. std::unique_ptr<TStrings> ConvertedKeyFiles(new TStringList());
  301. std::unique_ptr<TStrings> NotConvertedKeyFiles(CreateSortedStringList());
  302. for (int Index = 0; Index < SessionListView2->Items->Count; Index++)
  303. {
  304. TListItem * Item = SessionListView2->Items->Item[Index];
  305. if (Item->Checked)
  306. {
  307. TSessionData * Data = GetSessionData(Item);
  308. UnicodeString SessionKeys;
  309. UnicodeString PublicKeyFile = Data->PublicKeyFile;
  310. if (ConvertKeyFile(PublicKeyFile, ConvertedKeyFiles.get(), NotConvertedKeyFiles.get()))
  311. {
  312. Data->PublicKeyFile = PublicKeyFile;
  313. SessionKeys = PublicKeyFile;
  314. }
  315. UnicodeString TunnelPublicKeyFile = Data->TunnelPublicKeyFile;
  316. if (ConvertKeyFile(TunnelPublicKeyFile, ConvertedKeyFiles.get(), NotConvertedKeyFiles.get()))
  317. {
  318. Data->TunnelPublicKeyFile = TunnelPublicKeyFile;
  319. if (SessionKeys != TunnelPublicKeyFile)
  320. {
  321. AddToList(SessionKeys, TunnelPublicKeyFile, L", ");
  322. }
  323. }
  324. if (!SessionKeys.IsEmpty())
  325. {
  326. ConvertedSessions->Add(FORMAT(L"%s (%s)", (Data->Name, SessionKeys)));
  327. }
  328. }
  329. }
  330. if (ConvertedSessions->Count > 0)
  331. {
  332. UnicodeString Message = MainInstructions(FMTLOAD(IMPORT_CONVERTED_KEYS, (ConvertedKeyFiles->Count, ConvertedSessions->Count)));
  333. MoreMessageDialog(Message, ConvertedSessions.get(), qtInformation, qaOK, HelpKeyword);
  334. }
  335. }
  336. }
  337. return Result;
  338. }
  339. //---------------------------------------------------------------------------
  340. void __fastcall TImportSessionsDialog::SourceComboBoxSelect(TObject * /*Sender*/)
  341. {
  342. SaveSelection();
  343. LoadSessions();
  344. }
  345. //---------------------------------------------------------------------------
  346. void __fastcall TImportSessionsDialog::CreateHandle()
  347. {
  348. TForm::CreateHandle();
  349. if (DebugAlwaysTrue(HandleAllocated()))
  350. {
  351. HINSTANCE User32Library = LoadLibrary(L"user32.dll");
  352. AddClipboardFormatListenerProc AddClipboardFormatListener =
  353. (AddClipboardFormatListenerProc)GetProcAddress(User32Library, "AddClipboardFormatListener");
  354. if (AddClipboardFormatListener != NULL)
  355. {
  356. AddClipboardFormatListener(Handle);
  357. }
  358. }
  359. }
  360. //---------------------------------------------------------------------------
  361. void __fastcall TImportSessionsDialog::DestroyHandle()
  362. {
  363. if (DebugAlwaysTrue(HandleAllocated()))
  364. {
  365. HINSTANCE User32Library = LoadLibrary(L"user32.dll");
  366. RemoveClipboardFormatListenerProc RemoveClipboardFormatListener =
  367. (RemoveClipboardFormatListenerProc)GetProcAddress(User32Library, "RemoveClipboardFormatListener");
  368. if (RemoveClipboardFormatListener != NULL)
  369. {
  370. RemoveClipboardFormatListener(Handle);
  371. }
  372. }
  373. TForm::DestroyHandle();
  374. }
  375. //---------------------------------------------------------------------------
  376. void __fastcall TImportSessionsDialog::Dispatch(void * Message)
  377. {
  378. TMessage * M = static_cast<TMessage*>(Message);
  379. switch (M->Msg)
  380. {
  381. case WM_CLIPBOARDUPDATE:
  382. UpdateControls();
  383. TForm::Dispatch(Message);
  384. break;
  385. default:
  386. TForm::Dispatch(Message);
  387. break;
  388. }
  389. }
  390. //---------------------------------------------------------------------------
  391. void __fastcall TImportSessionsDialog::PasteButtonClick(TObject * /*Sender*/)
  392. {
  393. UnicodeString Text;
  394. // Proceed even when retrieving from clipboard fails, "no host keys" error will show.
  395. TextFromClipboard(Text, false);
  396. std::unique_ptr<TStrings> Lines(new TStringList());
  397. Lines->Text = Text;
  398. SessionListView2->Items->Clear();
  399. int Index = SourceComboBox->ItemIndex;
  400. UnicodeString Error;
  401. FPastedKnownHosts.reset(Configuration->SelectKnownHostsSessionsForImport(Lines.get(), StoredSessions, Error));
  402. FSessionListsList->Items[Index] = FPastedKnownHosts.get();
  403. FErrors->Strings[Index] = Error;
  404. LoadSessions();
  405. }
  406. //---------------------------------------------------------------------------